Debian Codegraph @

sieve.go

raw
1 // sieve.go - SIEVE - a simple and efficient cache
2 //
3 // (c) 2024 Sudhi Herle <[email protected]>
4 //
5 // Copyright 2024- Sudhi Herle <sw-at-herle-dot-net>
6 // License: BSD-2-Clause
7 //
8 // If you need a commercial license for this work, please contact
9 // the author.
10 //
11 // This software does not come with any express or implied
12 // warranty; it is provided "as is". No claim is made to its
13 // suitability for any purpose.
14
15 // Package sieve implements the SIEVE cache eviction algorithm (NSDI'24, Zhang et al.).
16 // https://yazhuozhang.com/assets/pdf/nsdi24-sieve.pdf
17 //
18 // SIEVE uses a FIFO queue with a roving "hand" pointer. On cache hit, only a
19 // visited bit is set (lazy promotion). On miss, the hand scans toward the head,
20 // clearing visited bits until it finds an unvisited node to evict (quick demotion).
21 //
22 // This implementation is optimized for low GC overhead and high concurrency:
23 // an array-backed doubly-linked list with int32 indices (no interior pointers),
24 // a combined per-node lock+visited word (one uint64 per node), and xsync.Map
25 // for lock-free reads.
26 package sieve
27
28 import (
29 "errors"
30 "fmt"
31 "iter"
32 "math"
33 "strings"
34 "sync"
35 "sync/atomic"
36
37 "github.com/puzpuzpuz/xsync/v4"
38 )
39
40 // MaxCapacity is the largest value accepted by New for the cache capacity.
41 // Node indices are stored as int32 (to keep the node struct compact and to
42 // let xsync.Map pack values inline); the bump allocator advances to
43 // capacity+1 after the last fill, so the upper bound is math.MaxInt32 - 1.
44 const MaxCapacity = math.MaxInt32 - 1
45
46 // MaxVisitClamp is the maximum value accepted by WithVisitClamp. Values above
47 // this are rejected by New with ErrInvalidVisitClamp. The limit is one byte
48 // because no published SIEVE-k workload benefits from counters larger than a
49 // few units.
50 const MaxVisitClamp = 7
51
52 // Construction errors returned by New.
53 var (
54 // ErrInvalidCapacity is returned by New when capacity is outside the
55 // valid range [1, MaxCapacity].
56 ErrInvalidCapacity = errors.New("sieve: capacity out of range [1, MaxCapacity]")
57
58 // ErrInvalidVisitClamp is returned by New when WithVisitClamp receives
59 // a value greater than MaxVisitClamp. Values below 1 are silently
60 // clamped up to 1 (classic SIEVE).
61 ErrInvalidVisitClamp = errors.New("sieve: visit clamp must be <= MaxVisitClamp")
62 )
63
64 const (
65 nullIdx = int32(-1)
66 sentinelIdx = int32(0) // index 0 is always the sentinel node
67 )
68
69 // node contains the <key, val> tuple as a node in a linked list.
70 // Synchronization is external: the per-node slotState word protects
71 // val reads/writes via its embedded spinlock.
72 type node[K comparable, V any] struct {
73 key K
74 val V
75 next int32 // index into backing array
76 prev int32
77 }
78
79 // allocator manages a fixed pool of pre-allocated nodes using bump allocation
80 // and an index-based freelist. Index 0 is reserved for the sentinel node and
81 // is never allocated or freed.
82 type allocator[K comparable, V any] struct {
83 nodes []node[K, V] // the full backing array (never resliced), index 0 = sentinel
84 cur int32 // bump allocator cursor (starts at 1, skipping sentinel)
85 next int32 // head of freelist (nullIdx = empty)
86 cap int32 // user-requested capacity (excludes sentinel)
87 }
88
89 // initAllocator initializes an allocator with capacity usable nodes.
90 // Allocates capacity+1 slots (index 0 is the sentinel).
91 func initAllocator[K comparable, V any](a *allocator[K, V], capacity int) {
92 a.nodes = make([]node[K, V], capacity+1) // +1 for sentinel
93 a.cur = 1 // skip sentinel at index 0
94 a.next = nullIdx
95 a.cap = int32(capacity) // #nosec G115 — New() validates capacity in [1, MaxCapacity = MaxInt32-1]
96 // Initialize sentinel: circular self-links
97 a.nodes[sentinelIdx].next = sentinelIdx
98 a.nodes[sentinelIdx].prev = sentinelIdx
99 }
100
101 // alloc retrieves a node index from the allocator.
102 // It first tries the freelist, then falls back to bump allocation.
103 // Returns nullIdx if no nodes are available.
104 func (a *allocator[K, V]) alloc() int32 {
105 // Try freelist first
106 if a.next != nullIdx {
107 idx := a.next
108 a.next = a.nodes[idx].next
109 return idx
110 }
111
112 // Bump allocate (total array length = cap + 1 for sentinel)
113 if a.cur > a.cap {
114 return nullIdx
115 }
116
117 idx := a.cur
118 a.cur++
119 return idx
120 }
121
122 // free returns a node at idx to the freelist.
123 // Caller must have already zeroed key/val (done in remove() under slot lock).
124 func (a *allocator[K, V]) free(idx int32) {
125 a.nodes[idx].next = a.next
126 a.next = idx
127 }
128
129 // reset resets the allocator to its initial state and re-initializes
130 // the sentinel's circular self-links.
131 //
132 // Note: key/val fields are NOT zeroed here to avoid racing with concurrent
133 // Get() calls that may hold a stale index. Instead, newNode() overwrites
134 // key/val under the slot lock, and remove() zeroes them under the slot lock.
135 // After Purge, stale key/val references are retained until slots are reused;
136 // this is an acceptable GC trade-off for a rare operation.
137 func (a *allocator[K, V]) reset() {
138 a.cur = 1 // skip sentinel
139 a.next = nullIdx
140 a.nodes[sentinelIdx].next = sentinelIdx
141 a.nodes[sentinelIdx].prev = sentinelIdx
142 }
143
144 // capacity returns the user-visible capacity (excludes sentinel)
145 func (a *allocator[K, V]) capacity() int32 {
146 return a.cap
147 }
148
149 // Evicted represents a key-value pair that was evicted from the cache.
150 type Evicted[K comparable, V any] struct {
151 Key K
152 Val V
153 }
154
155 // CacheResult is a bitmask indicating what happened during an Add or Probe operation.
156 type CacheResult uint8
157
158 const (
159 // CacheHit indicates the key was already present in the cache.
160 CacheHit CacheResult = 1 << iota
161
162 // CacheEvict indicates an entry was evicted to make room for the new key.
163 CacheEvict
164 )
165
166 // Hit reports whether the key was already present in the cache.
167 func (r CacheResult) Hit() bool { return r&CacheHit != 0 }
168
169 // Evicted reports whether an entry was evicted during the operation.
170 func (r CacheResult) Evicted() bool { return r&CacheEvict != 0 }
171
172 // Sieve represents a cache mapping the key of type 'K' with
173 // a value of type 'V'. The type 'K' must implement the
174 // comparable trait. An instance of Sieve has a fixed max capacity;
175 // new additions to the cache beyond the capacity will cause cache
176 // eviction of other entries - as determined by the SIEVE algorithm.
177 //
178 // The zero value of K is reserved and must not be used as a key
179 // (e.g. "" for string keys, 0 for integer keys). Internally, freed
180 // slots have their key zeroed; the lock-free read path relies on a
181 // zero key never matching a live lookup. Storing the zero key
182 // "works" in single-threaded use but can return a stale (zero-value)
183 // hit under concurrent eviction.
184 type Sieve[K comparable, V any] struct {
185 mu sync.Mutex
186 cache *xsync.Map[K, int32]
187 slots slotState // combined per-node lock + visited counter
188 hand int32 // eviction hand; sentinelIdx means "unset, start from tail"
189 size atomic.Int32 // lock-free Len(); writes happen under s.mu
190
191 allocator allocator[K, V] // embedded by value — one fewer GC-traced pointer
192 }
193
194 // New creates a new cache of size 'capacity' mapping key 'K' to value 'V'.
195 // Without options, this creates a classic SIEVE with a single visited bit (k=1).
196 // Use WithVisitClamp to create a SIEVE-k cache.
197 //
198 // Returns ErrInvalidCapacity if capacity is outside [1, MaxCapacity] and
199 // ErrInvalidVisitClamp if the visit-clamp option exceeds MaxVisitClamp.
200 // Clamp values below 1 are silently rounded up to 1 for backwards
201 // compatibility with callers that pass a zero default.
202 func New[K comparable, V any](capacity int, opts ...Option) (*Sieve[K, V], error) {
203 if capacity <= 0 || capacity > MaxCapacity {
204 return nil, fmt.Errorf("%w: got %d, max %d", ErrInvalidCapacity, capacity, MaxCapacity)
205 }
206
207 cfg := config{k: 1}
208 for _, o := range opts {
209 o(&cfg)
210 }
211 if cfg.k < 1 {
212 cfg.k = 1
213 }
214 if cfg.k > MaxVisitClamp {
215 return nil, fmt.Errorf("%w: got %d, max %d", ErrInvalidVisitClamp, cfg.k, MaxVisitClamp)
216 }
217
218 // +1 for sentinel in slot array to keep indexing aligned
219 total := capacity + 1
220 s := &Sieve[K, V]{
221 cache: xsync.NewMap[K, int32](xsync.WithPresize(capacity)),
222 hand: sentinelIdx,
223 slots: newSlotState(total, cfg.k),
224 }
225 initAllocator(&s.allocator, capacity)
226 return s, nil
227 }
228
229 // Must is a helper that wraps a call to New and panics if the error is
230 // non-nil. It is intended for use in tests and top-level variable
231 // initializers where construction arguments are known constants:
232 //
233 // var cache = sieve.Must(sieve.New[string, int](1000))
234 func Must[K comparable, V any](s *Sieve[K, V], err error) *Sieve[K, V] {
235 if err != nil {
236 panic(err)
237 }
238 return s
239 }
240
241 // Get fetches the value for a given key in the cache.
242 // It returns true if the key is in the cache, false otherwise.
243 // The zero value for 'V' is returned when key is not in the cache.
244 // The zero value of K must not be used as a key (see Sieve).
245 func (s *Sieve[K, V]) Get(key K) (V, bool) {
246 if idx, ok := s.cache.Load(key); ok {
247 slots := &s.slots
248 slots.LockAndMark(idx)
249 n := &s.allocator.nodes[idx]
250 if n.key == key {
251 val := n.val
252 slots.Unlock(idx)
253 return val, true
254 }
255 // Stale idx: node was evicted and reused for a different key.
256 slots.Unlock(idx)
257 }
258
259 var x V
260 return x, false
261 }
262
263 // Add adds a new element to the cache or overwrites one if it exists.
264 // Returns the evicted entry (if any) and a CacheResult bitmask:
265 // - CacheHit is set when the key was already present (value updated).
266 // - CacheEvict is set when an entry was evicted to make room.
267 //
268 // CacheHit and CacheEvict are mutually exclusive: updating an existing
269 // key never triggers eviction.
270 //
271 // The zero value of K must not be used as a key (see Sieve).
272 func (s *Sieve[K, V]) Add(key K, val V) (Evicted[K, V], CacheResult) {
273 nodes := s.allocator.nodes
274 slots := &s.slots
275
276 // Fast path: key exists, just update
277 if idx, ok := s.cache.Load(key); ok {
278 n := &nodes[idx]
279 slots.LockAndMark(idx)
280 if n.key == key {
281 n.val = val
282 slots.Unlock(idx)
283 return Evicted[K, V]{}, CacheHit
284 }
285 // Stale idx: node was evicted and reused. Fall through to slow path.
286 slots.Unlock(idx)
287 }
288
289 mu := &s.mu
290 mu.Lock()
291 // Re-check under lock to prevent double-insert (TOCTOU fix)
292 if idx, ok := s.cache.Load(key); ok {
293 slots.LockAndMark(idx)
294 nodes[idx].val = val
295 slots.Unlock(idx)
296 mu.Unlock()
297 return Evicted[K, V]{}, CacheHit
298 }
299 ev, evicted := s.add(key, val)
300 mu.Unlock()
301
302 if evicted {
303 return ev, CacheEvict
304 }
305 return Evicted[K, V]{}, 0
306 }
307
308 // Probe adds <key, val> if not present in the cache.
309 // Returns:
310 // - The cached value (on hit) or val (on miss)
311 // - The evicted entry, if any
312 // - A CacheResult bitmask: CacheHit if key was present, CacheEvict if an
313 // entry was evicted. CacheHit and CacheEvict are mutually exclusive.
314 //
315 // The zero value of K must not be used as a key (see Sieve).
316 func (s *Sieve[K, V]) Probe(key K, val V) (V, Evicted[K, V], CacheResult) {
317 nodes := s.allocator.nodes
318 slots := &s.slots
319
320 // Fast path: key exists
321 if idx, ok := s.cache.Load(key); ok {
322 n := &nodes[idx]
323 slots.LockAndMark(idx)
324 if n.key == key {
325 v := n.val
326 slots.Unlock(idx)
327 return v, Evicted[K, V]{}, CacheHit
328 }
329 // Stale idx: node was evicted and reused. Fall through to slow path.
330 slots.Unlock(idx)
331 }
332
333 mu := &s.mu
334 mu.Lock()
335 // Re-check under lock to prevent double-insert (TOCTOU fix)
336 if idx, ok := s.cache.Load(key); ok {
337 slots.LockAndMark(idx)
338 v := nodes[idx].val
339 slots.Unlock(idx)
340 mu.Unlock()
341 return v, Evicted[K, V]{}, CacheHit
342 }
343 ev, evicted := s.add(key, val)
344 mu.Unlock()
345
346 if evicted {
347 return val, ev, CacheEvict
348 }
349 return val, Evicted[K, V]{}, 0
350 }
351
352 // ProbeFunc adds <key, mk(key)> if key is not present in the cache.
353 // mk is called only on a miss, with no locks held; so it may safely
354 // call any method on the cache. Concurrent misses on the same key may
355 // each call mk; only one result is stored and the other callers
356 // receive the stored value with CacheHit set.
357 //
358 // Returns:
359 // - The cached value (on hit) or mk(key) (on miss)
360 // - The evicted entry, if any
361 // - A CacheResult bitmask: CacheHit if key was present, CacheEvict if an
362 // entry was evicted. CacheHit and CacheEvict are mutually exclusive.
363 //
364 // The zero value of K must not be used as a key (see Sieve).
365 func (s *Sieve[K, V]) ProbeFunc(key K, mk func(K) V) (V, Evicted[K, V], CacheResult) {
366 if v, ok := s.Get(key); ok {
367 return v, Evicted[K, V]{}, CacheHit
368 }
369
370 return s.Probe(key, mk(key))
371 }
372
373 // Delete deletes the named key from the cache
374 // It returns true if the item was in the cache and false otherwise
375 func (s *Sieve[K, V]) Delete(key K) bool {
376 s.mu.Lock()
377 if idx, ok := s.cache.LoadAndDelete(key); ok {
378 s.remove(idx)
379 s.mu.Unlock()
380 return true
381 }
382 s.mu.Unlock()
383 return false
384 }
385
386 // Purge resets the cache. Concurrent Get/Add/Probe calls that loaded
387 // an index before Purge may return a stale result; this is inherent to
388 // any concurrent purge operation.
389 //
390 // We intentionally do NOT call slots.ResetAll() here. Visited bits for
391 // reused slots are cleared by newNode() via LockAndReset(), which safely
392 // spins until any concurrent fast-path holder releases the slot lock.
393 // An unconditional ResetAll(Store→0) would destroy locks held by stale
394 // fast-path goroutines, causing two goroutines to "hold" the same lock.
395 func (s *Sieve[K, V]) Purge() {
396 s.mu.Lock()
397 s.hand = sentinelIdx
398 s.cache.Clear()
399 s.allocator.reset()
400 s.size.Store(0)
401 s.mu.Unlock()
402 }
403
404 // Len returns the current cache utilization. It is lock-free (atomic
405 // load) and may observe in-flight updates from concurrent Add/Delete/Purge
406 // callers, so treat the result as a point-in-time estimate under
407 // concurrent use.
408 func (s *Sieve[K, V]) Len() int {
409 return int(s.size.Load())
410 }
411
412 // Cap returns the max cache capacity
413 func (s *Sieve[K, V]) Cap() int {
414 return int(s.allocator.capacity())
415 }
416
417 // All returns a weakly-consistent iterator over the (key, value) pairs
418 // currently in the cache. It is safe to call concurrently with Get, Add,
419 // Probe, Delete, and other All callers.
420 //
421 // Semantics:
422 //
423 // - Iteration order is unspecified and does NOT follow SIEVE FIFO order.
424 // - Entries inserted during iteration may or may not be observed.
425 // - Entries evicted or deleted during iteration are skipped.
426 // - Iteration does not mark entries visited, so walking the cache
427 // does not protect entries from eviction (unlike Get).
428 // - The iterator yields each surviving entry at most once in the common
429 // case, but the underlying xsync map's relaxed scan may rarely re-yield
430 // an entry that migrated buckets during a concurrent resize. Callers
431 // that must see each key exactly once should deduplicate.
432 //
433 // It is safe to call Get, Add, Probe, or Delete on the cache from inside
434 // the iterator body. No cache lock is held across the yield.
435 func (s *Sieve[K, V]) All() iter.Seq2[K, V] {
436 return func(yield func(K, V) bool) {
437 nodes := s.allocator.nodes
438 slots := &s.slots
439 for k, idx := range s.cache.AllRelaxed() {
440 slots.Lock(idx)
441 n := &nodes[idx]
442 if n.key != k {
443 // Stale idx: slot was evicted and reused for a different key.
444 slots.Unlock(idx)
445 continue
446 }
447 kk, vv := n.key, n.val
448 slots.Unlock(idx)
449 if !yield(kk, vv) {
450 return
451 }
452 }
453 }
454 }
455
456 // String returns a string description of the sieve cache
457 func (s *Sieve[K, V]) String() string {
458 s.mu.Lock()
459 m := s.desc()
460 s.mu.Unlock()
461 return m
462 }
463
464 // Dump dumps all the cache contents as a newline delimited
465 // string.
466 func (s *Sieve[K, V]) Dump() string {
467 var b strings.Builder
468
469 s.mu.Lock()
470 b.WriteString(s.desc())
471 b.WriteRune('\n')
472 nodes := s.allocator.nodes
473 for idx := nodes[sentinelIdx].next; idx != sentinelIdx; idx = nodes[idx].next {
474 h := " "
475 if idx == s.hand {
476 h = ">>"
477 }
478 n := &nodes[idx]
479 fmt.Fprintf(&b, "%svisited=%v, key=%v, val=%v\n", h, s.slots.IsVisited(idx), n.key, n.val)
480 }
481 s.mu.Unlock()
482 return b.String()
483 }
484
485 // -- internal methods --
486
487 // add a new tuple to the cache and evict as necessary.
488 // Returns the evicted entry (if any) so the caller can return it.
489 // Caller must hold lock.
490 func (s *Sieve[K, V]) add(key K, val V) (Evicted[K, V], bool) {
491 var ev Evicted[K, V]
492 var evicted bool
493
494 // cache miss; we evict and find a new node
495 if s.size.Load() == s.allocator.capacity() {
496 ev, evicted = s.evict()
497 }
498
499 idx := s.newNode(key, val)
500
501 // Eviction is guaranteed to remove one node; so this should never happen.
502 if idx == nullIdx {
503 msg := fmt.Sprintf("%T: add <%v>: objpool empty after eviction", s, key)
504 panic(msg)
505 }
506
507 s.cache.Store(key, idx)
508
509 nodes := s.allocator.nodes
510
511 // Insert after sentinel (at head of list). Branch-free.
512 n := &nodes[idx]
513 sen := &nodes[sentinelIdx]
514 head := sen.next
515
516 n.next, n.prev = head, sentinelIdx
517 sen.next, nodes[head].prev = idx, idx
518
519 s.size.Add(1)
520 return ev, evicted
521 }
522
523 // evict removes one item from the cache and returns its key/value.
524 // Caller must hold the lock.
525 //
526 // Termination: each step either evicts (returns) or decrements one
527 // visited counter, so a quiescent scan finishes in at most k*size
528 // steps. Concurrent lock-free Get()s can re-mark nodes behind the
529 // hand, so the scan is not strictly bounded under adversarial read
530 // load; in practice readers cannot keep every node perpetually
531 // marked and the scan converges.
532 func (s *Sieve[K, V]) evict() (Evicted[K, V], bool) {
533 hand := s.hand
534 nodes := s.allocator.nodes
535 sen := &nodes[sentinelIdx]
536
537 if hand == sentinelIdx {
538 // Start from tail (sentinel.prev)
539 hand = sen.prev
540 }
541
542 for hand != sentinelIdx {
543 n := &nodes[hand]
544 if !s.slots.IsVisited(hand) {
545 s.cache.Delete(n.key)
546 s.hand = n.prev
547 ev := s.remove(hand)
548 return ev, true
549 }
550 s.slots.Clear(hand)
551 hand = n.prev
552 // Wrap around: if we hit sentinel, go to tail
553 if hand == sentinelIdx {
554 hand = sen.prev
555 }
556 }
557 s.hand = hand
558 var ev Evicted[K, V]
559 return ev, false
560 }
561
562 // remove removes the node at idx from the linked list and frees it.
563 // It captures and returns the node's key/val before zeroing them,
564 // so callers (evict) can return eviction info.
565 // Caller must hold s.mu. Key/val are captured and zeroed under the
566 // slot lock to serialize with concurrent fast-path reads and to
567 // release GC references. Branch-free: sentinel eliminates null checks.
568 func (s *Sieve[K, V]) remove(idx int32) Evicted[K, V] {
569 s.size.Add(-1)
570
571 nodes := s.allocator.nodes
572 n := &nodes[idx]
573
574 // If the eviction hand points at the node being removed, advance it
575 // to the predecessor before unlinking. Otherwise a Delete() of the
576 // hand node leaves the hand on a freed slot; when that slot is
577 // reused it is inserted at the head, teleporting the hand there and
578 // making the next eviction scan start at the newest entry.
579 if s.hand == idx {
580 s.hand = n.prev
581 }
582
583 // Unlink — no branches needed thanks to sentinel
584 nodes[n.prev].next = n.next
585 nodes[n.next].prev = n.prev
586
587 // Capture key/val and zero them under the slot lock to serialize
588 // with concurrent fast-path reads (which write val under slot lock)
589 // and allow GC to collect pointed-to objects.
590 s.slots.Lock(idx)
591 ev := Evicted[K, V]{Key: n.key, Val: n.val}
592 var zk K
593 var zv V
594 n.key = zk
595 n.val = zv
596 s.slots.Unlock(idx)
597
598 // Return the node to the allocator's freelist
599 s.allocator.free(idx)
600 return ev
601 }
602
603 // newNode allocates a node and initializes it with key and val.
604 // Returns nullIdx if no nodes are available.
605 //
606 // Field writes are performed under the slot lock to serialize with
607 // concurrent fast-path reads (Get/Add/Probe) that may hold a stale
608 // index from before eviction. The Lock/Unlock on the slot establishes
609 // a happens-before edge so the fast path sees the new key/val.
610 func (s *Sieve[K, V]) newNode(key K, val V) int32 {
611 idx := s.allocator.alloc()
612 if idx == nullIdx {
613 return nullIdx
614 }
615
616 s.slots.LockAndReset(idx)
617
618 n := &s.allocator.nodes[idx]
619 n.key = key
620 n.val = val
621 n.next = nullIdx
622 n.prev = nullIdx
623
624 s.slots.Unlock(idx)
625 return idx
626 }
627
628 // desc describes the properties of the sieve
629 func (s *Sieve[K, V]) desc() string {
630 nodes := s.allocator.nodes
631 m := fmt.Sprintf("cache<%T>: size %d, cap %d, head=%d, tail=%d, hand=%d",
632 s, s.size.Load(), int(s.allocator.capacity()),
633 nodes[sentinelIdx].next, nodes[sentinelIdx].prev, s.hand)
634 return m
635 }