| 1 |
# go-sieve - SIEVE cache eviction for Go |
| 2 |
|
| 3 |
[](https://pkg.go.dev/github.com/opencoff/go-sieve) |
| 4 |
[](https://goreportcard.com/report/github.com/opencoff/go-sieve) |
| 5 |
[](https://github.com/opencoff/go-sieve/releases) |
| 6 |
|
| 7 |
A Go implementation of the |
| 8 |
[SIEVE](https://yazhuozhang.com/assets/pdf/nsdi24-sieve.pdf) cache eviction |
| 9 |
algorithm (NSDI'24, Zhang et al.), **engineered from the ground up for highly |
| 10 |
concurrent, read-heavy workloads**. Generic over key and value types. |
| 11 |
|
| 12 |
The read path (`Get()`) is fully **lock-free** — a single atomic load on the |
| 13 |
key→index map plus a single atomic bit update on a shared visited bitfield. |
| 14 |
No mutex, no pointer chasing, no per-entry allocations, zero GC traffic on |
| 15 |
hits. Under concurrent read load this is **13–55x faster** than |
| 16 |
`hashicorp/golang-lru` per trace on real-world cache traces (warm cache, |
| 17 |
10 cores), and the gap grows with core count: SIEVE's aggregate |
| 18 |
throughput improves as cores are added while mutex-bound LRU/ARC |
| 19 |
throughput *degrades below its own single-core line*. Under a cold-cache |
| 20 |
mixed read/write replay, SIEVE is 2–6x faster. The write path uses a |
| 21 |
single short-held mutex and a pre-allocated node pool, so |
| 22 |
`Add()`/`Probe()`/`ProbeFunc()` also avoid per-operation heap allocation in |
| 23 |
steady state. |
| 24 |
|
| 25 |
If you need a cache that many goroutines hit simultaneously on the read |
| 26 |
path — an HTTP response cache, a DNS resolver cache, an authz decision |
| 27 |
cache, a hot-path object lookup — this implementation is built for that |
| 28 |
shape. On a single goroutine the two are comparable (SIEVE replays most |
| 29 |
traces faster sequentially, LRU wins a few); under any concurrency, |
| 30 |
Sieve wins decisively. |
| 31 |
|
| 32 |
SIEVE uses a FIFO queue with a roving "hand" pointer: cache hits set a |
| 33 |
visited bit (lazy promotion), and eviction scans from the hand clearing |
| 34 |
visited bits until it finds an unvisited node (quick demotion). It matches |
| 35 |
or exceeds LRU/ARC hit ratios with far less bookkeeping — validated here on |
| 36 |
~300M requests from the MSR Cambridge and Meta Storage trace repositories. |
| 37 |
|
| 38 |
## Key Design Elements |
| 39 |
|
| 40 |
**Array-backed indexed list.** [Marc Brooker observed](https://brooker.co.za/blog/2023/12/15/sieve.html) |
| 41 |
that SIEVE's mid-list removal prevents a simple circular buffer. Rather than |
| 42 |
Tobin Baker's "swap tail into hole" workaround, this implementation uses a |
| 43 |
doubly-linked list with `int32` indices into a pre-allocated backing array. |
| 44 |
This preserves SIEVE's exact eviction semantics while eliminating all interior |
| 45 |
pointers — the GC sees a flat `[]node` with no pointers to trace (for |
| 46 |
non-pointer `K`, `V` types). |
| 47 |
|
| 48 |
**xsync.MapOf for concurrent access.** The key→index map uses |
| 49 |
[puzpuzpuz/xsync.MapOf](https://github.com/puzpuzpuz/xsync) which stores |
| 50 |
`int32` values inline in cache-line-padded buckets — no traced pointers per |
| 51 |
entry. `Get()` is fully lock-free; only `Add()`/`Probe()`/`ProbeFunc()` (on miss) |
| 52 |
and `Delete()` take the global mutex. |
| 53 |
|
| 54 |
**Columnar slot state (`slotState`).** Each node's lock and visited |
| 55 |
counter are hoisted out of the `node` struct into a separate contiguous |
| 56 |
`[]uint64` — one word per slot, laid out as a column alongside the |
| 57 |
`[]node` array. This columnar split has three effects: |
| 58 |
|
| 59 |
1. the eviction hand scans `IsVisited` by walking a dense `[]uint64` sequentially — |
| 60 |
8 slots per cache line, hardware-prefetch friendly — without pulling in |
| 61 |
key/val data it doesn't need; |
| 62 |
2. `Get()`'s `LockAndMark` writes only to the `slotState` word for that slot, |
| 63 |
so it never dirties the cache line holding the node's key/val — no false |
| 64 |
sharing with concurrent readers of adjacent nodes |
| 65 |
3. `[]uint64` contains no pointers, so the GC never traces it, unlike node fields |
| 66 |
that may hold pointer-typed K/V. |
| 67 |
|
| 68 |
Within each word, bit 63 is a spinlock and the low bits are a |
| 69 |
saturating visited counter (1 bit at k=1, ⌈log₂(k+1)⌉ bits for higher k). |
| 70 |
|
| 71 |
**Pre-allocated node pool.** All nodes are allocated once at cache creation in |
| 72 |
a contiguous array. A bump allocator + intrusive freelist (reusing `node.next`) |
| 73 |
provides O(1) alloc/free with zero heap allocations during steady-state operation. |
| 74 |
|
| 75 |
**TOCTOU-safe concurrent writes.** `Add()` and `Probe()` use a double-check |
| 76 |
pattern: fast-path `Load()` outside the lock, re-check under `mu.Lock()` before |
| 77 |
inserting. This prevents duplicate nodes from concurrent writers racing on the |
| 78 |
same key. `ProbeFunc()` calls its constructor between the fast-path miss and |
| 79 |
the lock, so the constructor never runs under the mutex; concurrent misses on |
| 80 |
the same key may each construct a value, but only one is stored and the other |
| 81 |
callers receive it with `CacheHit`. |
| 82 |
|
| 83 |
## Benchmark Results |
| 84 |
|
| 85 |
Benchmarked against [hashicorp/golang-lru v2.0.7](https://github.com/hashicorp/golang-lru) |
| 86 |
(LRU and ARC) on an Apple M4 (10 cores: 4 performance + 6 efficiency): |
| 87 |
|
| 88 |
- macOS (Darwin 25.5.0, arm64) |
| 89 |
- `go1.26.3` |
| 90 |
- `GOMAXPROCS=10` |
| 91 |
|
| 92 |
Benchmarks live in `bench/` as a separate module to avoid polluting `go.mod`. |
| 93 |
Every table below is generated by `bench/cmd/mktables` from the raw |
| 94 |
results files — including derived claims, which are computed rather than |
| 95 |
hand-counted. |
| 96 |
|
| 97 |
Commands used (no name filter — every benchmark in every package runs): |
| 98 |
|
| 99 |
``` |
| 100 |
cd bench && make bench # synthetic comparison, count=3 |
| 101 |
cd bench && make trace # trace replay + miss ratio + GC, count=1 |
| 102 |
cd bench && make sweep SWEEP_PROCS="1 2 4 8 10" # core-scaling sweep |
| 103 |
``` |
| 104 |
|
| 105 |
Full raw results: [`bench-results.md`](bench-results.md). |
| 106 |
|
| 107 |
### Reading the parallel ns/op numbers |
| 108 |
|
| 109 |
The single-digit ns/op numbers in the parallel tables below are real but |
| 110 |
need context: they are **aggregate throughput**. |
| 111 |
|
| 112 |
Go's `b.RunParallel` distributes `b.N` total operations across |
| 113 |
`GOMAXPROCS` goroutines and reports `ns/op = wall_clock / b.N`. When 10 |
| 114 |
goroutines complete Get()s at 5.8 ns/op aggregate, the system produces |
| 115 |
one completed Get every ~5.8 ns; the **per-core latency** is ~58 ns |
| 116 |
(5.8 × 10 cores), consistent with two L1/L2-hot atomic operations plus |
| 117 |
the surrounding map lookup. |
| 118 |
|
| 119 |
LRU/ARC report ~140–390 ns/op under the same conditions — not because a |
| 120 |
single Get is that much slower, but because every Get takes a mutex. |
| 121 |
All goroutines serialize through one lock, so adding cores makes |
| 122 |
aggregate throughput *worse* (see the core-scaling table below: LRU |
| 123 |
goes from 31 ns/op at 1 core to 182 ns/op at 10 — lock handoff costs |
| 124 |
grow with contention). On a single goroutine, SIEVE and LRU are in the |
| 125 |
same league — the **gap is a concurrency-scaling story**. |
| 126 |
|
| 127 |
After warmup, the working data structures (map buckets, node array, |
| 128 |
visited bitfield) are resident in CPU cache — L1/L2 for small traces, |
| 129 |
L3 for larger ones. Real workloads with lower temporal locality will |
| 130 |
see higher per-core latency, but the relative advantage over |
| 131 |
mutex-bound LRU/ARC holds whenever there is any parallelism at all. |
| 132 |
|
| 133 |
### Parallel Micro-Benchmarks (`count=3`, medians) |
| 134 |
|
| 135 |
| Benchmark | Sieve | LRU | ARC | |
| 136 |
|-----------|-------|-----|-----| |
| 137 |
| `Get_Parallel` | **5.76 ns/op, 0 B** | 144.2 ns/op, 0 B | 144.9 ns/op, 0 B | |
| 138 |
| `Add_Parallel` | **89.8 ns/op, 8 B** | 212.0 ns/op, 40 B | 273.3 ns/op, 74 B | |
| 139 |
| `Probe_Parallel` | **91.2 ns/op, 8 B** | — | — | |
| 140 |
| `Delete_Parallel` | 81.2 ns/op, 0 B | **69.5 ns/op, 0 B** | 88.3 ns/op, 0 B | |
| 141 |
| `Mixed_Parallel` (60/30/10) | **71.0 ns/op, 2 B** | 162.2 ns/op, 12 B | 211.8 ns/op, 23 B | |
| 142 |
| `Zipf_Get_Parallel` (s=1.01) | **24.7 ns/op** | 127.7 ns/op | 133.1 ns/op | |
| 143 |
| `Zipf_Get_Parallel` (s=1.50) | **94.2 ns/op** | 100.4 ns/op | 112.6 ns/op | |
| 144 |
| Memory @ 1M fill | **78.4 MB** | 112.4 MB | 112.3 MB | |
| 145 |
| `GCImpact` (1M entries) | **4.37 ms/iter**, 18.1 µs pause | 9.46 ms/iter, 22.4 µs | 9.93 ms/iter, 23.5 µs | |
| 146 |
|
| 147 |
`Probe_Parallel` is SIEVE-only — LRU's `PeekOrAdd` and `ContainsOrAdd` |
| 148 |
skip recency promotion and are not semantic equivalents. `Delete_Parallel` |
| 149 |
is the one micro where SIEVE loses: LRU's single-lock linked-list unlink |
| 150 |
edges out SIEVE's slot-state clear (69.5 vs 81.2 ns/op). At extreme |
| 151 |
Zipf skew (s=1.50) SIEVE's advantage narrows to ~6%: most requests hit |
| 152 |
a handful of keys, so readers contend on the same per-slot word. |
| 153 |
|
| 154 |
### Core scaling (`Get_Parallel`, median ns/op) |
| 155 |
|
| 156 |
| GOMAXPROCS | Sieve | LRU | ARC | |
| 157 |
|-----------:|------:|----:|----:| |
| 158 |
| 1 | 14.9 | 31.4 | 33.8 | |
| 159 |
| 2 | 8.9 | 74.3 | 77.0 | |
| 160 |
| 4 | 5.5 | 121.1 | 146.0 | |
| 161 |
| 8 | 8.0 | 178.7 | 182.0 | |
| 162 |
| 10 | 7.5 | 182.1 | 193.4 | |
| 163 |
|
| 164 |
SIEVE's aggregate throughput improves with cores (the 8–10 core numbers |
| 165 |
include the M4's efficiency cores); LRU/ARC throughput **degrades** |
| 166 |
with every added core because all readers fight over one mutex — at 10 |
| 167 |
cores LRU is ~6x slower per completed Get than at 1 core. |
| 168 |
|
| 169 |
## Trace Replay Results |
| 170 |
|
| 171 |
This implementation is benchmarked against real-world cache traces from the |
| 172 |
[libCacheSim](https://cachelib.org/) trace repository — 13 MSR Cambridge |
| 173 |
enterprise block I/O traces + 5 Meta Storage (Tectonic) block traces |
| 174 |
totalling ~300M requests. Each trace was replayed with a cache sized at |
| 175 |
10% of unique keys, comparing SIEVE (k=1, k=2, k=3) against |
| 176 |
hashicorp/golang-lru (LRU and ARC). Parallel benchmarks walk the trace |
| 177 |
as a ring with per-goroutine **staggered start offsets** (see |
| 178 |
[`bench/README.md`](bench/README.md)). |
| 179 |
|
| 180 |
### Parallel Get throughput (warm cache, 10 goroutines, ns/op, zero allocs) |
| 181 |
|
| 182 |
SIEVE's lock-free `Get()` is **13–55x faster** than the better of |
| 183 |
LRU/ARC on every trace under concurrent read load: |
| 184 |
|
| 185 |
| Trace | SIEVE k=1 | SIEVE k=3 | LRU | ARC | |
| 186 |
|-------|---------:|---------:|----:|----:| |
| 187 |
| msr_2007/msr_web_2 | **2.24** | 2.05 | 105.7 | 150.4 | |
| 188 |
| msr_2007/msr_proj_4 | **2.84** | 3.87 | 157.4 | 220.8 | |
| 189 |
| msr_2007/msr_prxy_0 | **3.28** | 3.15 | 106.3 | 133.3 | |
| 190 |
| msr_2007/msr_prn_1 | **3.51** | 3.37 | 135.9 | 185.8 | |
| 191 |
| meta_storage/block_traces_2 | **4.01** | 4.31 | 129.4 | 211.4 | |
| 192 |
| meta_storage/block_traces_1 | **4.03** | 4.34 | 132.5 | 197.9 | |
| 193 |
| msr_2007/msr_usr_2 | **4.62** | 4.79 | 209.4 | 268.5 | |
| 194 |
| meta_storage/block_traces_4 | **4.88** | 4.87 | 159.2 | 250.5 | |
| 195 |
| meta_storage/block_traces_3 | **4.95** | 4.56 | 147.2 | 224.8 | |
| 196 |
| meta_storage/block_traces_5 | **5.00** | 4.92 | 152.2 | 222.5 | |
| 197 |
| msr_2007/msr_src1_0 | **5.65** | 5.60 | 157.4 | 384.9 | |
| 198 |
| msr_2007/msr_usr_1 | **6.39** | 7.73 | 252.6 | 308.0 | |
| 199 |
| msr_2007/msr_src1_1 | **7.04** | 7.20 | 165.9 | 276.9 | |
| 200 |
| msr_2007/msr_proj_1 | **7.31** | 7.21 | 255.1 | 307.3 | |
| 201 |
| msr_2007/msr_proj_0 | **8.15** | 8.55 | 110.4 | 136.9 | |
| 202 |
| msr_2007/msr_hm_0 | **9.12** | 9.38 | 117.6 | 141.8 | |
| 203 |
| msr_2007/msr_proj_2 | **10.09** | 7.96 | 260.1 | 299.6 | |
| 204 |
| msr_2007/msr_prn_0 | **12.20** | 12.34 | 173.2 | 154.2 | |
| 205 |
|
| 206 |
The k=3 saturating counter adds little to no overhead on the read path. |
| 207 |
This benchmark pre-warms the cache with a full trace replay, then hammers |
| 208 |
`Get()` only — the ideal scenario for a read-heavy cache in steady state. |
| 209 |
|
| 210 |
### Parallel Replay throughput (cold cache, mixed read+write, 10 goroutines, ns/op) |
| 211 |
|
| 212 |
This is `Probe()` for SIEVE and `Get+Add` for LRU/ARC, hammered in |
| 213 |
parallel with **no warmup**. It measures the steady-state workload a real |
| 214 |
cache faces: reads and writes interleaved, evictions happening live. The |
| 215 |
previous table's numbers reflect the best-case read ceiling; this table |
| 216 |
reflects what throughput you actually get when your cache is doing work. |
| 217 |
|
| 218 |
| Trace | SIEVE k=1 | SIEVE k=3 | LRU | ARC | |
| 219 |
|-------|---------:|---------:|----:|----:| |
| 220 |
| msr_2007/msr_prxy_0 | **37.4** | 36.6 | 229.3 | 251.1 | |
| 221 |
| msr_2007/msr_hm_0 | **58.7** | 61.0 | 228.9 | 297.9 | |
| 222 |
| msr_2007/msr_prn_0 | **62.2** | 67.6 | 251.6 | 322.3 | |
| 223 |
| msr_2007/msr_proj_0 | **63.0** | 58.6 | 236.2 | 312.2 | |
| 224 |
| msr_2007/msr_usr_1 | **73.6** | 80.4 | 376.8 | 391.2 | |
| 225 |
| msr_2007/msr_prn_1 | **90.4** | 91.5 | 351.7 | 390.4 | |
| 226 |
| msr_2007/msr_proj_4 | **110.0** | 113.5 | 425.1 | 563.9 | |
| 227 |
| msr_2007/msr_proj_1 | **118.6** | 121.3 | 447.0 | 505.6 | |
| 228 |
| meta_storage/block_traces_1 | **134.2** | 160.0 | 277.2 | 351.6 | |
| 229 |
| meta_storage/block_traces_2 | **137.9** | 179.4 | 300.5 | 374.9 | |
| 230 |
| msr_2007/msr_web_2 | **155.5** | 145.4 | 478.4 | 513.7 | |
| 231 |
| meta_storage/block_traces_4 | **156.2** | 179.2 | 371.8 | 384.8 | |
| 232 |
| meta_storage/block_traces_5 | **157.4** | 178.1 | 336.2 | 377.9 | |
| 233 |
| meta_storage/block_traces_3 | **158.4** | 178.6 | 312.7 | 380.4 | |
| 234 |
| msr_2007/msr_src1_0 | **219.3** | 200.8 | 628.9 | 588.3 | |
| 235 |
| msr_2007/msr_usr_2 | **222.3** | 215.6 | 627.7 | 579.9 | |
| 236 |
| msr_2007/msr_proj_2 | **252.3** | 265.0 | 528.3 | 527.5 | |
| 237 |
| msr_2007/msr_src1_1 | **274.7** | 274.2 | 652.3 | 633.4 | |
| 238 |
|
| 239 |
Under concurrent cold-cache replay, SIEVE is **2–6x faster** than the |
| 240 |
better of LRU/ARC on every trace. The margin is smaller than the warm |
| 241 |
table because every miss serializes through the same write mutex in |
| 242 |
all three caches — SIEVE's edge here comes entirely from its lock-free |
| 243 |
hit path. The best case is `msr_prxy_0` (95% hits, 6.1x); the worst |
| 244 |
cases are the high-miss-ratio traces (`msr_src1_1`, 98% misses, 2.3x). |
| 245 |
|
| 246 |
(An earlier revision of this table claimed 18–62x. That number was an |
| 247 |
artifact of all goroutines walking the trace from offset 0 in lockstep, |
| 248 |
which inflated hit ratios; the staggered-offset harness fixes it.) |
| 249 |
|
| 250 |
### Miss ratio (every trace) |
| 251 |
|
| 252 |
Cache sized at 10% of unique keys. **Bold** = best in row. |
| 253 |
|
| 254 |
| Trace | SIEVE k=1 | SIEVE k=2 | SIEVE k=3 | LRU | ARC | |
| 255 |
|-------|----------:|----------:|----------:|----:|----:| |
| 256 |
| meta_storage/block_traces_1 | 0.4632 | 0.4651 | 0.4672 | **0.4602** | 0.4667 | |
| 257 |
| meta_storage/block_traces_2 | 0.4719 | 0.4743 | 0.4754 | **0.4676** | 0.4755 | |
| 258 |
| meta_storage/block_traces_3 | 0.4908 | 0.4928 | 0.4948 | **0.4885** | 0.4947 | |
| 259 |
| meta_storage/block_traces_4 | 0.4841 | 0.4870 | 0.4888 | **0.4812** | 0.4887 | |
| 260 |
| meta_storage/block_traces_5 | 0.4959 | 0.4984 | 0.4998 | **0.4927** | 0.5003 | |
| 261 |
| msr_2007/msr_hm_0 | 0.2991 | 0.3025 | 0.3025 | 0.3188 | **0.2923** | |
| 262 |
| msr_2007/msr_prn_0 | 0.2156 | 0.2194 | 0.2208 | 0.2310 | **0.2145** | |
| 263 |
| msr_2007/msr_prn_1 | 0.3908 | 0.3837 | **0.3796** | 0.4341 | 0.4148 | |
| 264 |
| msr_2007/msr_proj_0 | 0.2537 | 0.2660 | 0.2745 | 0.2375 | **0.2242** | |
| 265 |
| msr_2007/msr_proj_1 | 0.6794 | 0.6794 | 0.6794 | 0.7215 | **0.6788** | |
| 266 |
| msr_2007/msr_proj_2 | 0.8231 | 0.8231 | 0.8231 | 0.8548 | **0.8125** | |
| 267 |
| msr_2007/msr_proj_4 | 0.8463 | 0.8463 | 0.8463 | 0.8140 | **0.7173** | |
| 268 |
| msr_2007/msr_prxy_0 | 0.0512 | 0.0572 | 0.0594 | 0.0476 | **0.0468** | |
| 269 |
| msr_2007/msr_src1_0 | 0.7845 | 0.7845 | 0.7845 | 0.9132 | **0.7811** | |
| 270 |
| msr_2007/msr_src1_1 | 0.7939 | 0.7934 | **0.7934** | 0.8129 | 0.8231 | |
| 271 |
| msr_2007/msr_usr_1 | 0.3558 | 0.3558 | 0.3558 | 0.4007 | **0.3513** | |
| 272 |
| msr_2007/msr_usr_2 | 0.7216 | 0.7216 | 0.7216 | 0.7533 | **0.7199** | |
| 273 |
| msr_2007/msr_web_2 | 0.9786 | 0.9786 | 0.9786 | 0.9929 | **0.9785** | |
| 274 |
|
| 275 |
**Overall best (bold, computed by `mktables`):** ARC has the lowest |
| 276 |
miss ratio in 11 of 18 rows, LRU in 5 (all meta_storage), SIEVE |
| 277 |
k-variants in 2 — msr_prn_1 (k=3 outright) and msr_src1_1 (k=2 and k=3 |
| 278 |
tied at 0.7934). SIEVE k=1 is never the overall best. |
| 279 |
|
| 280 |
**Head-to-head, SIEVE k=1 vs LRU** (the typical deployment choice): |
| 281 |
SIEVE k=1 has lower miss ratio on 10 of 18 traces, LRU on 8. When |
| 282 |
SIEVE is better the margins are large (msr_src1_0: 12.9 points, |
| 283 |
msr_usr_1: 4.5, msr_prn_1: 4.3). When LRU is better the margins are |
| 284 |
narrow (all 5 meta_storage: 2–3 points each). |
| 285 |
|
| 286 |
**SIEVE's case rests on throughput.** Miss ratios are competitive |
| 287 |
(SIEVE is never dramatically worse than LRU), and SIEVE is 2–6x faster |
| 288 |
on a cold mixed workload and 13–55x faster on warm reads, with the gap |
| 289 |
widening as cores are added. SIEVE k=3 produces the single-best entry |
| 290 |
in the entire table on msr_prn_1 (0.3796 vs LRU 0.4341, ARC 0.4148). |
| 291 |
|
| 292 |
### Memory during replay |
| 293 |
|
| 294 |
On the 13.2M-request `meta_storage/block_traces_1` trace (601K-entry cache), |
| 295 |
`TestGCPressure` reports: |
| 296 |
|
| 297 |
| Variant | TotalAlloc | |
| 298 |
|---------|-----------:| |
| 299 |
| **SIEVE k=1** | **135 MB** | |
| 300 |
| SIEVE k=3 | 135 MB | |
| 301 |
| LRU | 418 MB | |
| 302 |
| ARC | 997 MB | |
| 303 |
|
| 304 |
SIEVE allocates **3.1x less** than LRU and **7.4x less** than ARC during |
| 305 |
replay — the array-backed node pool and inline-int32 `xsync.MapOf` are |
| 306 |
structural wins. |
| 307 |
|
| 308 |
Full per-trace tables (sequential replay ns/op, B/op, miss ratio for every |
| 309 |
trace) are in [`bench-results.md`](bench-results.md). Methodology and |
| 310 |
trace-loading details are in [`bench/README.md`](bench/README.md). |
| 311 |
|
| 312 |
## Usage |
| 313 |
|
| 314 |
```go |
| 315 |
import "github.com/opencoff/go-sieve" |
| 316 |
|
| 317 |
// Create a cache mapping string keys to int values, capacity 1000. |
| 318 |
c, err := sieve.New[string, int](1000) |
| 319 |
if err != nil { |
| 320 |
log.Fatal(err) // ErrInvalidCapacity or ErrInvalidVisitClamp |
| 321 |
} |
| 322 |
|
| 323 |
// Or, for constant arguments, use Must to get a one-liner: |
| 324 |
c := sieve.Must(sieve.New[string, int](1000)) |
| 325 |
|
| 326 |
c.Add("foo", 42) |
| 327 |
|
| 328 |
if val, ok := c.Get("foo"); ok { |
| 329 |
fmt.Println(val) // 42 |
| 330 |
} |
| 331 |
|
| 332 |
// Probe inserts only if absent; returns the cached value if present. |
| 333 |
val, _, r := c.Probe("foo", 99) |
| 334 |
// val == 42, r.Hit() == true |
| 335 |
|
| 336 |
// ProbeFunc is Probe with lazy construction: mk runs only on a miss. |
| 337 |
val, _, r = c.ProbeFunc("bar", func(k string) int { return len(k) }) |
| 338 |
// val == 3, r.Hit() == false |
| 339 |
|
| 340 |
c.Delete("foo") |
| 341 |
c.Purge() // reset entire cache |
| 342 |
``` |
| 343 |
|
| 344 |
### SIEVE-k |
| 345 |
|
| 346 |
`WithVisitClamp(k)` creates a SIEVE-k cache where each entry uses a |
| 347 |
saturating counter instead of a single visited bit. An item accessed k+1 |
| 348 |
times survives k eviction passes before being evicted. `k=1` is equivalent |
| 349 |
to classic SIEVE (the default). Use `k=2` or `k=3` for workloads with |
| 350 |
repeated access patterns where extra eviction resistance is beneficial. |
| 351 |
|
| 352 |
```go |
| 353 |
// Classic SIEVE (k=1, the default) |
| 354 |
c, err := sieve.New[string, int](1000) |
| 355 |
|
| 356 |
// SIEVE-k=3: items survive up to 3 eviction passes |
| 357 |
c, err := sieve.New[string, int](1000, sieve.WithVisitClamp(3)) |
| 358 |
``` |
| 359 |
|
| 360 |
`New` returns an error for `capacity <= 0` (`ErrInvalidCapacity`) and for |
| 361 |
`WithVisitClamp(k)` with `k > sieve.MaxVisitClamp` (7 — `ErrInvalidVisitClamp`). |
| 362 |
Clamp values below 1 are silently rounded up to 1. |
| 363 |
|
| 364 |
### Eviction Handling |
| 365 |
|
| 366 |
`Add()`, `Probe()` and `ProbeFunc()` return the evicted entry (if any) along with a |
| 367 |
`CacheResult` bitmask. This allows callers to handle evictions |
| 368 |
synchronously without channels, goroutines, or lifecycle management. |
| 369 |
|
| 370 |
```go |
| 371 |
c := sieve.Must(sieve.New[string, int](1000)) |
| 372 |
|
| 373 |
ev, r := c.Add("foo", 42) |
| 374 |
if r.Evicted() { |
| 375 |
cleanupDisk(ev.Key, ev.Val) |
| 376 |
} |
| 377 |
|
| 378 |
// CacheResult bitmask: |
| 379 |
// CacheHit — key was already present (value updated, no eviction) |
| 380 |
// CacheEvict — an entry was evicted to make room (mutually exclusive with CacheHit) |
| 381 |
``` |
| 382 |
|
| 383 |
`Purge()` and `Delete()` do not report evictions. |
| 384 |
|
| 385 |
### Iteration |
| 386 |
|
| 387 |
`All()` returns a Go 1.23+ `iter.Seq2[K, V]` over the cache contents. |
| 388 |
Iteration is weakly consistent and safe to call concurrently with |
| 389 |
`Get`/`Add`/`Probe`/`ProbeFunc`/`Delete` (including from inside the loop body): |
| 390 |
|
| 391 |
```go |
| 392 |
for k, v := range c.All() { |
| 393 |
fmt.Println(k, v) |
| 394 |
} |
| 395 |
``` |
| 396 |
|
| 397 |
- Order is unspecified — it does **not** follow SIEVE FIFO order. |
| 398 |
- Entries inserted during the walk may or may not be observed; entries |
| 399 |
evicted or deleted during the walk are skipped. |
| 400 |
- Walking the cache does **not** mark entries as visited, so iteration |
| 401 |
does not protect entries from eviction (unlike `Get`). |
| 402 |
- No cache lock is held across the loop body, so re-entrant |
| 403 |
`Get`/`Add`/`Delete` calls from inside `range` are safe. |
| 404 |
|
| 405 |
## API |
| 406 |
|
| 407 |
| Function / Method | Description | |
| 408 |
|-------------------|-------------| |
| 409 |
| `New[K, V](capacity, ...Option) (*Sieve[K,V], error)` | Create a cache with fixed capacity. Returns `ErrInvalidCapacity` or `ErrInvalidVisitClamp` on bad input. | |
| 410 |
| `Must[K, V](*Sieve[K,V], error) *Sieve[K,V]` | Helper that panics on error; useful with constant arguments. | |
| 411 |
| `Get(key) (V, bool)` | Look up a key (lock-free, zero-alloc). | |
| 412 |
| `Add(key, val) (Evicted[K,V], CacheResult)` | Insert or update; returns evicted entry and result bitmask. | |
| 413 |
| `Probe(key, val) (V, Evicted[K,V], CacheResult)` | Insert-if-absent; returns cached/inserted value, evicted entry, and result bitmask. | |
| 414 |
| `ProbeFunc(key, mk func(K) V) (V, Evicted[K,V], CacheResult)` | Like `Probe`, but `mk(key)` is called only on a miss, with no locks held. Concurrent misses may each call `mk`; one result is stored. | |
| 415 |
| `Delete(key) bool` | Remove a key. | |
| 416 |
| `Purge()` | Clear the entire cache. | |
| 417 |
| `Len() int` | Current number of entries (lock-free atomic load). | |
| 418 |
| `Cap() int` | Maximum capacity. | |
| 419 |
| `All() iter.Seq2[K, V]` | Weakly-consistent range iterator over current entries; does not mark visited. | |
| 420 |
|
| 421 |
### Options |
| 422 |
|
| 423 |
| Option | Description | |
| 424 |
|--------|-------------| |
| 425 |
| `WithVisitClamp(k)` | Use k-level saturating counters (default k=1 = classic SIEVE). `k` is capped at `MaxVisitClamp` (7); `k < 1` is silently rounded to 1. | |
| 426 |
|
| 427 |
## Key Constraints |
| 428 |
|
| 429 |
**The zero value of `K` is reserved — do not use it as a key** (`""` for |
| 430 |
string keys, `0` for integer keys, the zero struct for struct keys). |
| 431 |
|
| 432 |
This is by design: when an entry is evicted or deleted, its slot's key |
| 433 |
is zeroed in place, and the lock-free read path relies on a zeroed key |
| 434 |
never matching a live lookup. If you store the zero key, a `Get` racing |
| 435 |
with that key's eviction can observe the zeroed slot and return a |
| 436 |
spurious hit with a zero value. In single-threaded use the zero key |
| 437 |
appears to work, but the contract is: keys must be non-zero. |
| 438 |
|
| 439 |
If your natural key space includes the zero value, wrap it (e.g. offset |
| 440 |
integer keys by 1, or prefix string keys). |
| 441 |
|
| 442 |
## GC Note |
| 443 |
|
| 444 |
When `K` or `V` is a pointer type (including `string`, which contains an |
| 445 |
internal pointer in Go), the node array will still contain GC-traced pointers. |
| 446 |
The GC pressure reduction is most dramatic for scalar key/value types (`int`, |
| 447 |
`[16]byte`, fixed-size structs). |
| 448 |
|
| 449 |
## License |
| 450 |
|
| 451 |
BSD-2-Clause. See the source files for the full license text. |