skl.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  1. /*
  2. * SPDX-FileCopyrightText: © Hypermode Inc. <hello@hypermode.com>
  3. * SPDX-License-Identifier: Apache-2.0
  4. */
  5. /*
  6. Adapted from RocksDB inline skiplist.
  7. Key differences:
  8. - No optimization for sequential inserts (no "prev").
  9. - No custom comparator.
  10. - Support overwrites. This requires care when we see the same key when inserting.
  11. For RocksDB or LevelDB, overwrites are implemented as a newer sequence number in the key, so
  12. there is no need for values. We don't intend to support versioning. In-place updates of values
  13. would be more efficient.
  14. - We discard all non-concurrent code.
  15. - We do not support Splices. This simplifies the code a lot.
  16. - No AllocateNode or other pointer arithmetic.
  17. - We combine the findLessThan, findGreaterOrEqual, etc into one function.
  18. */
  19. package skl
  20. import (
  21. "math"
  22. "sync/atomic"
  23. "unsafe"
  24. "github.com/dgraph-io/badger/v4/y"
  25. "github.com/dgraph-io/ristretto/v2/z"
  26. )
  27. const (
  28. maxHeight = 20
  29. heightIncrease = math.MaxUint32 / 3
  30. )
  31. // MaxNodeSize is the memory footprint of a node of maximum height.
  32. const MaxNodeSize = int(unsafe.Sizeof(node{}))
  33. type node struct {
  34. // Multiple parts of the value are encoded as a single uint64 so that it
  35. // can be atomically loaded and stored:
  36. // value offset: uint32 (bits 0-31)
  37. // value size : uint16 (bits 32-63)
  38. value atomic.Uint64
  39. // A byte slice is 24 bytes. We are trying to save space here.
  40. keyOffset uint32 // Immutable. No need to lock to access key.
  41. keySize uint16 // Immutable. No need to lock to access key.
  42. // Height of the tower.
  43. height uint16
  44. // Most nodes do not need to use the full height of the tower, since the
  45. // probability of each successive level decreases exponentially. Because
  46. // these elements are never accessed, they do not need to be allocated.
  47. // Therefore, when a node is allocated in the arena, its memory footprint
  48. // is deliberately truncated to not include unneeded tower elements.
  49. //
  50. // All accesses to elements should use CAS operations, with no need to lock.
  51. tower [maxHeight]atomic.Uint32
  52. }
  53. type Skiplist struct {
  54. height atomic.Int32 // Current height. 1 <= height <= kMaxHeight. CAS.
  55. head *node
  56. ref atomic.Int32
  57. arena *Arena
  58. OnClose func()
  59. }
  60. // IncrRef increases the refcount
  61. func (s *Skiplist) IncrRef() {
  62. s.ref.Add(1)
  63. }
  64. // DecrRef decrements the refcount, deallocating the Skiplist when done using it
  65. func (s *Skiplist) DecrRef() {
  66. newRef := s.ref.Add(-1)
  67. if newRef > 0 {
  68. return
  69. }
  70. if s.OnClose != nil {
  71. s.OnClose()
  72. }
  73. // Indicate we are closed. Good for testing. Also, lets GC reclaim memory. Race condition
  74. // here would suggest we are accessing skiplist when we are supposed to have no reference!
  75. s.arena = nil
  76. // Since the head references the arena's buf, as long as the head is kept around
  77. // GC can't release the buf.
  78. s.head = nil
  79. }
  80. func newNode(arena *Arena, key []byte, v y.ValueStruct, height int) *node {
  81. // The base level is already allocated in the node struct.
  82. offset := arena.putNode(height)
  83. node := arena.getNode(offset)
  84. node.keyOffset = arena.putKey(key)
  85. node.keySize = uint16(len(key))
  86. node.height = uint16(height)
  87. node.value.Store(encodeValue(arena.putVal(v), v.EncodedSize()))
  88. return node
  89. }
  90. func encodeValue(valOffset uint32, valSize uint32) uint64 {
  91. return uint64(valSize)<<32 | uint64(valOffset)
  92. }
  93. func decodeValue(value uint64) (valOffset uint32, valSize uint32) {
  94. valOffset = uint32(value)
  95. valSize = uint32(value >> 32)
  96. return
  97. }
  98. // NewSkiplist makes a new empty skiplist, with a given arena size
  99. func NewSkiplist(arenaSize int64) *Skiplist {
  100. arena := newArena(arenaSize)
  101. head := newNode(arena, nil, y.ValueStruct{}, maxHeight)
  102. s := &Skiplist{head: head, arena: arena}
  103. s.height.Store(1)
  104. s.ref.Store(1)
  105. return s
  106. }
  107. func (s *node) getValueOffset() (uint32, uint32) {
  108. value := s.value.Load()
  109. return decodeValue(value)
  110. }
  111. func (s *node) key(arena *Arena) []byte {
  112. return arena.getKey(s.keyOffset, s.keySize)
  113. }
  114. func (s *node) setValue(arena *Arena, v y.ValueStruct) {
  115. valOffset := arena.putVal(v)
  116. value := encodeValue(valOffset, v.EncodedSize())
  117. s.value.Store(value)
  118. }
  119. func (s *node) getNextOffset(h int) uint32 {
  120. return s.tower[h].Load()
  121. }
  122. func (s *node) casNextOffset(h int, old, val uint32) bool {
  123. return s.tower[h].CompareAndSwap(old, val)
  124. }
  125. // Returns true if key is strictly > n.key.
  126. // If n is nil, this is an "end" marker and we return false.
  127. //func (s *Skiplist) keyIsAfterNode(key []byte, n *node) bool {
  128. // y.AssertTrue(n != s.head)
  129. // return n != nil && y.CompareKeys(key, n.key) > 0
  130. //}
  131. func (s *Skiplist) randomHeight() int {
  132. h := 1
  133. for h < maxHeight && z.FastRand() <= heightIncrease {
  134. h++
  135. }
  136. return h
  137. }
  138. func (s *Skiplist) getNext(nd *node, height int) *node {
  139. return s.arena.getNode(nd.getNextOffset(height))
  140. }
  141. // findNear finds the node near to key.
  142. // If less=true, it finds rightmost node such that node.key < key (if allowEqual=false) or
  143. // node.key <= key (if allowEqual=true).
  144. // If less=false, it finds leftmost node such that node.key > key (if allowEqual=false) or
  145. // node.key >= key (if allowEqual=true).
  146. // Returns the node found. The bool returned is true if the node has key equal to given key.
  147. func (s *Skiplist) findNear(key []byte, less bool, allowEqual bool) (*node, bool) {
  148. x := s.head
  149. level := int(s.getHeight() - 1)
  150. for {
  151. // Assume x.key < key.
  152. next := s.getNext(x, level)
  153. if next == nil {
  154. // x.key < key < END OF LIST
  155. if level > 0 {
  156. // Can descend further to iterate closer to the end.
  157. level--
  158. continue
  159. }
  160. // Level=0. Cannot descend further. Let's return something that makes sense.
  161. if !less {
  162. return nil, false
  163. }
  164. // Try to return x. Make sure it is not a head node.
  165. if x == s.head {
  166. return nil, false
  167. }
  168. return x, false
  169. }
  170. nextKey := next.key(s.arena)
  171. cmp := y.CompareKeys(key, nextKey)
  172. if cmp > 0 {
  173. // x.key < next.key < key. We can continue to move right.
  174. x = next
  175. continue
  176. }
  177. if cmp == 0 {
  178. // x.key < key == next.key.
  179. if allowEqual {
  180. return next, true
  181. }
  182. if !less {
  183. // We want >, so go to base level to grab the next bigger note.
  184. return s.getNext(next, 0), false
  185. }
  186. // We want <. If not base level, we should go closer in the next level.
  187. if level > 0 {
  188. level--
  189. continue
  190. }
  191. // On base level. Return x.
  192. if x == s.head {
  193. return nil, false
  194. }
  195. return x, false
  196. }
  197. // cmp < 0. In other words, x.key < key < next.
  198. if level > 0 {
  199. level--
  200. continue
  201. }
  202. // At base level. Need to return something.
  203. if !less {
  204. return next, false
  205. }
  206. // Try to return x. Make sure it is not a head node.
  207. if x == s.head {
  208. return nil, false
  209. }
  210. return x, false
  211. }
  212. }
  213. // findSpliceForLevel returns (outBefore, outAfter) with outBefore.key <= key <= outAfter.key.
  214. // The input "before" tells us where to start looking.
  215. // If we found a node with the same key, then we return outBefore = outAfter.
  216. // Otherwise, outBefore.key < key < outAfter.key.
  217. func (s *Skiplist) findSpliceForLevel(key []byte, before *node, level int) (*node, *node) {
  218. for {
  219. // Assume before.key < key.
  220. next := s.getNext(before, level)
  221. if next == nil {
  222. return before, next
  223. }
  224. nextKey := next.key(s.arena)
  225. cmp := y.CompareKeys(key, nextKey)
  226. if cmp == 0 {
  227. // Equality case.
  228. return next, next
  229. }
  230. if cmp < 0 {
  231. // before.key < key < next.key. We are done for this level.
  232. return before, next
  233. }
  234. before = next // Keep moving right on this level.
  235. }
  236. }
  237. func (s *Skiplist) getHeight() int32 {
  238. return s.height.Load()
  239. }
  240. // Put inserts the key-value pair.
  241. func (s *Skiplist) Put(key []byte, v y.ValueStruct) {
  242. // Since we allow overwrite, we may not need to create a new node. We might not even need to
  243. // increase the height. Let's defer these actions.
  244. listHeight := s.getHeight()
  245. var prev [maxHeight + 1]*node
  246. var next [maxHeight + 1]*node
  247. prev[listHeight] = s.head
  248. next[listHeight] = nil
  249. for i := int(listHeight) - 1; i >= 0; i-- {
  250. // Use higher level to speed up for current level.
  251. prev[i], next[i] = s.findSpliceForLevel(key, prev[i+1], i)
  252. if prev[i] == next[i] {
  253. prev[i].setValue(s.arena, v)
  254. return
  255. }
  256. }
  257. // We do need to create a new node.
  258. height := s.randomHeight()
  259. x := newNode(s.arena, key, v, height)
  260. // Try to increase s.height via CAS.
  261. listHeight = s.getHeight()
  262. for height > int(listHeight) {
  263. if s.height.CompareAndSwap(listHeight, int32(height)) {
  264. // Successfully increased skiplist.height.
  265. break
  266. }
  267. listHeight = s.getHeight()
  268. }
  269. // We always insert from the base level and up. After you add a node in base level, we cannot
  270. // create a node in the level above because it would have discovered the node in the base level.
  271. for i := 0; i < height; i++ {
  272. for {
  273. if prev[i] == nil {
  274. y.AssertTrue(i > 1) // This cannot happen in base level.
  275. // We haven't computed prev, next for this level because height exceeds old listHeight.
  276. // For these levels, we expect the lists to be sparse, so we can just search from head.
  277. prev[i], next[i] = s.findSpliceForLevel(key, s.head, i)
  278. // Someone adds the exact same key before we are able to do so. This can only happen on
  279. // the base level. But we know we are not on the base level.
  280. y.AssertTrue(prev[i] != next[i])
  281. }
  282. nextOffset := s.arena.getNodeOffset(next[i])
  283. x.tower[i].Store(nextOffset)
  284. if prev[i].casNextOffset(i, nextOffset, s.arena.getNodeOffset(x)) {
  285. // Managed to insert x between prev[i] and next[i]. Go to the next level.
  286. break
  287. }
  288. // CAS failed. We need to recompute prev and next.
  289. // It is unlikely to be helpful to try to use a different level as we redo the search,
  290. // because it is unlikely that lots of nodes are inserted between prev[i] and next[i].
  291. prev[i], next[i] = s.findSpliceForLevel(key, prev[i], i)
  292. if prev[i] == next[i] {
  293. y.AssertTruef(i == 0, "Equality can happen only on base level: %d", i)
  294. prev[i].setValue(s.arena, v)
  295. return
  296. }
  297. }
  298. }
  299. }
  300. // Empty returns if the Skiplist is empty.
  301. func (s *Skiplist) Empty() bool {
  302. return s.findLast() == nil
  303. }
  304. // findLast returns the last element. If head (empty list), we return nil. All the find functions
  305. // will NEVER return the head nodes.
  306. func (s *Skiplist) findLast() *node {
  307. n := s.head
  308. level := int(s.getHeight()) - 1
  309. for {
  310. next := s.getNext(n, level)
  311. if next != nil {
  312. n = next
  313. continue
  314. }
  315. if level == 0 {
  316. if n == s.head {
  317. return nil
  318. }
  319. return n
  320. }
  321. level--
  322. }
  323. }
  324. // Get gets the value associated with the key. It returns a valid value if it finds equal or earlier
  325. // version of the same key.
  326. func (s *Skiplist) Get(key []byte) y.ValueStruct {
  327. n, _ := s.findNear(key, false, true) // findGreaterOrEqual.
  328. if n == nil {
  329. return y.ValueStruct{}
  330. }
  331. nextKey := s.arena.getKey(n.keyOffset, n.keySize)
  332. if !y.SameKey(key, nextKey) {
  333. return y.ValueStruct{}
  334. }
  335. valOffset, valSize := n.getValueOffset()
  336. vs := s.arena.getVal(valOffset, valSize)
  337. vs.Version = y.ParseTs(nextKey)
  338. return vs
  339. }
  340. // NewIterator returns a skiplist iterator. You have to Close() the iterator.
  341. func (s *Skiplist) NewIterator() *Iterator {
  342. s.IncrRef()
  343. return &Iterator{list: s}
  344. }
  345. // MemSize returns the size of the Skiplist in terms of how much memory is used within its internal
  346. // arena.
  347. func (s *Skiplist) MemSize() int64 { return s.arena.size() }
  348. // Iterator is an iterator over skiplist object. For new objects, you just
  349. // need to initialize Iterator.list.
  350. type Iterator struct {
  351. list *Skiplist
  352. n *node
  353. }
  354. // Close frees the resources held by the iterator
  355. func (s *Iterator) Close() error {
  356. s.list.DecrRef()
  357. return nil
  358. }
  359. // Valid returns true iff the iterator is positioned at a valid node.
  360. func (s *Iterator) Valid() bool { return s.n != nil }
  361. // Key returns the key at the current position.
  362. func (s *Iterator) Key() []byte {
  363. return s.list.arena.getKey(s.n.keyOffset, s.n.keySize)
  364. }
  365. // Value returns value.
  366. func (s *Iterator) Value() y.ValueStruct {
  367. valOffset, valSize := s.n.getValueOffset()
  368. return s.list.arena.getVal(valOffset, valSize)
  369. }
  370. // ValueUint64 returns the uint64 value of the current node.
  371. func (s *Iterator) ValueUint64() uint64 {
  372. return s.n.value.Load()
  373. }
  374. // Next advances to the next position.
  375. func (s *Iterator) Next() {
  376. y.AssertTrue(s.Valid())
  377. s.n = s.list.getNext(s.n, 0)
  378. }
  379. // Prev advances to the previous position.
  380. func (s *Iterator) Prev() {
  381. y.AssertTrue(s.Valid())
  382. s.n, _ = s.list.findNear(s.Key(), true, false) // find <. No equality allowed.
  383. }
  384. // Seek advances to the first entry with a key >= target.
  385. func (s *Iterator) Seek(target []byte) {
  386. s.n, _ = s.list.findNear(target, false, true) // find >=.
  387. }
  388. // SeekForPrev finds an entry with key <= target.
  389. func (s *Iterator) SeekForPrev(target []byte) {
  390. s.n, _ = s.list.findNear(target, true, true) // find <=.
  391. }
  392. // SeekToFirst seeks position at the first entry in list.
  393. // Final state of iterator is Valid() iff list is not empty.
  394. func (s *Iterator) SeekToFirst() {
  395. s.n = s.list.getNext(s.list.head, 0)
  396. }
  397. // SeekToLast seeks position at the last entry in list.
  398. // Final state of iterator is Valid() iff list is not empty.
  399. func (s *Iterator) SeekToLast() {
  400. s.n = s.list.findLast()
  401. }
  402. // UniIterator is a unidirectional memtable iterator. It is a thin wrapper around
  403. // Iterator. We like to keep Iterator as before, because it is more powerful and
  404. // we might support bidirectional iterators in the future.
  405. type UniIterator struct {
  406. iter *Iterator
  407. reversed bool
  408. }
  409. // NewUniIterator returns a UniIterator.
  410. func (s *Skiplist) NewUniIterator(reversed bool) *UniIterator {
  411. return &UniIterator{
  412. iter: s.NewIterator(),
  413. reversed: reversed,
  414. }
  415. }
  416. // Next implements y.Interface
  417. func (s *UniIterator) Next() {
  418. if !s.reversed {
  419. s.iter.Next()
  420. } else {
  421. s.iter.Prev()
  422. }
  423. }
  424. // Rewind implements y.Interface
  425. func (s *UniIterator) Rewind() {
  426. if !s.reversed {
  427. s.iter.SeekToFirst()
  428. } else {
  429. s.iter.SeekToLast()
  430. }
  431. }
  432. // Seek implements y.Interface
  433. func (s *UniIterator) Seek(key []byte) {
  434. if !s.reversed {
  435. s.iter.Seek(key)
  436. } else {
  437. s.iter.SeekForPrev(key)
  438. }
  439. }
  440. // Key implements y.Interface
  441. func (s *UniIterator) Key() []byte { return s.iter.Key() }
  442. // Value implements y.Interface
  443. func (s *UniIterator) Value() y.ValueStruct { return s.iter.Value() }
  444. // Valid implements y.Interface
  445. func (s *UniIterator) Valid() bool { return s.iter.Valid() }
  446. // Close implements y.Interface (and frees up the iter's resources)
  447. func (s *UniIterator) Close() error { return s.iter.Close() }