Debian Codegraph @

invariants_test.go

raw
1 // invariants_test.go - deep structural invariant checker (whitebox)
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
16
17 import (
18 "fmt"
19 "testing"
20 )
21
22 // checkInvariants verifies all structural invariants of a Sieve cache.
23 // Caller must ensure no concurrent operations are in progress.
24 func checkInvariants[K comparable, V any](t *testing.T, s *Sieve[K, V], context string) {
25 t.Helper()
26
27 s.mu.Lock()
28 defer s.mu.Unlock()
29
30 nodes := s.allocator.nodes
31 cap := s.allocator.cap
32 size := int(s.size.Load())
33
34 // 1. Forward walk: sentinel.next → ... → sentinel
35 fwdCount := 0
36 seen := make(map[int32]bool)
37 for idx := nodes[sentinelIdx].next; idx != sentinelIdx; idx = nodes[idx].next {
38 fwdCount++
39 if fwdCount > int(cap)+1 {
40 t.Fatalf("%s: forward walk exceeded capacity — cycle detected", context)
41 }
42 if idx < 1 || idx > cap {
43 t.Fatalf("%s: forward walk hit invalid index %d (valid range: 1..%d)", context, idx, cap)
44 }
45 // 5. No duplicates
46 if seen[idx] {
47 t.Fatalf("%s: duplicate index %d in forward walk", context, idx)
48 }
49 seen[idx] = true
50 }
51 if fwdCount != size {
52 t.Fatalf("%s: forward walk count %d != size %d", context, fwdCount, size)
53 }
54
55 // 2. Reverse walk: sentinel.prev → ... → sentinel
56 revCount := 0
57 for idx := nodes[sentinelIdx].prev; idx != sentinelIdx; idx = nodes[idx].prev {
58 revCount++
59 if revCount > int(cap)+1 {
60 t.Fatalf("%s: reverse walk exceeded capacity — cycle detected", context)
61 }
62 }
63 if revCount != size {
64 t.Fatalf("%s: reverse walk count %d != size %d (fwd was %d)", context, revCount, size, fwdCount)
65 }
66
67 // 3a. Every list node's key exists in the map with the correct index
68 for idx := nodes[sentinelIdx].next; idx != sentinelIdx; idx = nodes[idx].next {
69 n := &nodes[idx]
70 mapIdx, ok := s.cache.Load(n.key)
71 if !ok {
72 t.Fatalf("%s: list node %d (key=%v) not found in map", context, idx, n.key)
73 }
74 if mapIdx != idx {
75 t.Fatalf("%s: map[%v]=%d but node is at index %d", context, n.key, mapIdx, idx)
76 }
77 }
78
79 // 3b. Map size == list size
80 mapSize := 0
81 s.cache.Range(func(_ K, _ int32) bool {
82 mapSize++
83 return true
84 })
85 if mapSize != size {
86 t.Fatalf("%s: map size %d != list size %d", context, mapSize, size)
87 }
88
89 // 4. Hand validity: must be sentinelIdx or a valid slot index (1..cap).
90 // remove() advances the hand to the predecessor when the hand node
91 // itself is removed, so the hand never dangles on a freed slot.
92 if s.hand != sentinelIdx {
93 if s.hand < 1 || s.hand > cap {
94 t.Fatalf("%s: hand=%d out of valid range [sentinelIdx, 1..%d]", context, s.hand, cap)
95 }
96 }
97
98 // 6. Allocator accounting: size + freelistLen == bumpAllocated
99 freelistLen := 0
100 for idx := s.allocator.next; idx != nullIdx; idx = nodes[idx].next {
101 freelistLen++
102 if freelistLen > int(cap)+1 {
103 t.Fatalf("%s: freelist cycle detected", context)
104 }
105 }
106 bumpAllocated := int(s.allocator.cur - 1)
107 if size+freelistLen != bumpAllocated {
108 t.Fatalf("%s: accounting: size(%d) + freelist(%d) = %d, want bump_allocated(%d)",
109 context, size, freelistLen, size+freelistLen, bumpAllocated)
110 }
111 }
112
113 // =========================================================================
114 // Tests using the deep invariant checker
115 // =========================================================================
116
117 // TestInternalInvariants mirrors TestInvariants but uses the deep checker.
118 func TestInternalInvariants(t *testing.T) {
119 const cap = 8
120 s := Must(New[int, int](cap))
121 checkInvariants(t, s, "empty cache")
122
123 // Fill to capacity
124 for i := 0; i < cap; i++ {
125 s.Add(i, i*10)
126 checkInvariants(t, s, fmt.Sprintf("after Add(%d)", i))
127 }
128
129 // Visit all
130 for i := 0; i < cap; i++ {
131 v, ok := s.Get(i)
132 if !ok || v != i*10 {
133 t.Fatalf("Get(%d) = (%d, %v), want (%d, true)", i, v, ok, i*10)
134 }
135 checkInvariants(t, s, fmt.Sprintf("after Get(%d)", i))
136 }
137
138 // Eviction
139 for i := cap; i < cap*2; i++ {
140 s.Add(i, i*10)
141 checkInvariants(t, s, fmt.Sprintf("after eviction Add(%d)", i))
142 }
143
144 // Update
145 for i := cap; i < cap*2; i++ {
146 s.Add(i, i*100)
147 checkInvariants(t, s, fmt.Sprintf("after update Add(%d)", i))
148 }
149
150 // Delete
151 for i := cap; i < cap+4; i++ {
152 s.Delete(i)
153 checkInvariants(t, s, fmt.Sprintf("after Delete(%d)", i))
154 }
155
156 // Probe miss (insert)
157 for i := 0; i < 4; i++ {
158 key := cap*2 + i
159 s.Probe(key, key*10)
160 checkInvariants(t, s, fmt.Sprintf("after Probe(%d) miss", key))
161 }
162
163 // Probe hit
164 for i := 0; i < 4; i++ {
165 key := cap*2 + i
166 v, _, r := s.Probe(key, -1)
167 if !r.Hit() || v != key*10 {
168 t.Fatalf("Probe(%d) hit = (%d, %v), want (%d, true)", key, v, r.Hit(), key*10)
169 }
170 }
171
172 // Purge
173 s.Purge()
174 checkInvariants(t, s, "after Purge")
175
176 // 7. Post-Purge state
177 s.mu.Lock()
178 if sz := s.size.Load(); sz != 0 {
179 t.Fatalf("post-Purge: size=%d, want 0", sz)
180 }
181 if s.hand != sentinelIdx {
182 t.Fatalf("post-Purge: hand=%d, want sentinelIdx", s.hand)
183 }
184 nodes := s.allocator.nodes
185 if nodes[sentinelIdx].next != sentinelIdx || nodes[sentinelIdx].prev != sentinelIdx {
186 t.Fatalf("post-Purge: sentinel not self-linked: next=%d prev=%d",
187 nodes[sentinelIdx].next, nodes[sentinelIdx].prev)
188 }
189 if s.allocator.cur != 1 || s.allocator.next != nullIdx {
190 t.Fatalf("post-Purge: allocator not reset: cur=%d next=%d",
191 s.allocator.cur, s.allocator.next)
192 }
193 s.mu.Unlock()
194
195 // Re-add after Purge
196 for i := 0; i < cap; i++ {
197 s.Add(i, i)
198 checkInvariants(t, s, fmt.Sprintf("after re-Add(%d) post-purge", i))
199 }
200
201 // Heavy churn
202 for i := 0; i < cap*5; i++ {
203 s.Add(cap+i, cap+i)
204 checkInvariants(t, s, fmt.Sprintf("after churn Add(%d)", cap+i))
205 }
206 }
207
208 // TestInternal_EvictionAllVisited verifies that eviction works when every
209 // node in the list is visited. The hand must scan the entire list clearing
210 // all visited bits, wrap around, and evict the first node found unvisited.
211 //
212 // We trace the eviction deterministically:
213 // - List after fill: sentinel → 7 → 6 → 5 → 4 → 3 → 2 → 1 → 0 → sentinel
214 // (each Add inserts at head, so key 7 is head, key 0 is tail)
215 // - hand == sentinelIdx (unset), so eviction starts from tail (key 0)
216 // - All nodes visited → hand scans backward clearing bits:
217 // 0(clear)→7(clear)→6(clear)→5(clear)→4(clear)→3(clear)→2(clear)→1(clear)
218 // → wraps to tail → 0(now unvisited) → evict 0.
219 // - Result: key 0 evicted, keys 1-7 + 8 present, all visited bits cleared.
220 func TestInternal_EvictionAllVisited(t *testing.T) {
221 const cap = 8
222 s := Must(New[int, int](cap))
223
224 // Fill: keys 0..7
225 for i := 0; i < cap; i++ {
226 s.Add(i, i*10)
227 }
228
229 // Verify list order: head should be key 7 (last inserted), tail key 0
230 s.mu.Lock()
231 nodes := s.allocator.nodes
232 headKey := nodes[nodes[sentinelIdx].next].key
233 tailKey := nodes[nodes[sentinelIdx].prev].key
234 s.mu.Unlock()
235 if headKey != cap-1 {
236 t.Fatalf("head key=%d, want %d (last inserted)", headKey, cap-1)
237 }
238 if tailKey != 0 {
239 t.Fatalf("tail key=%d, want 0 (first inserted)", tailKey)
240 }
241
242 // Visit ALL nodes
243 for i := 0; i < cap; i++ {
244 s.Get(i)
245 }
246
247 // Verify all visited
248 s.mu.Lock()
249 nodes = s.allocator.nodes
250 for idx := nodes[sentinelIdx].next; idx != sentinelIdx; idx = nodes[idx].next {
251 if !s.slots.IsVisited(idx) {
252 t.Fatalf("node %d (key=%v) should be visited", idx, nodes[idx].key)
253 }
254 }
255 s.mu.Unlock()
256
257 // Add key 8 — triggers eviction with 100% visited list.
258 // Expected: key 0 (tail) evicted after full scan + wrap.
259 s.Add(cap, cap*10)
260 checkInvariants(t, s, "after eviction with all visited")
261
262 // Key 0 should be evicted (it's the tail, first node reached after wrap)
263 if _, ok := s.Get(0); ok {
264 t.Fatal("expected key 0 to be evicted (tail, first unvisited after scan)")
265 }
266
267 // Key 8 (new) and keys 1..7 should all be present
268 for i := 1; i <= cap; i++ {
269 v, ok := s.Get(i)
270 if !ok {
271 t.Fatalf("key %d should be present", i)
272 }
273 if v != i*10 {
274 t.Fatalf("Get(%d) = %d, want %d", i, v, i*10)
275 }
276 }
277
278 // After all-visited eviction, all visited bits should have been cleared
279 // during the scan. The only visited nodes are the ones we just Get'd above.
280 // Verify the data structure is consistent.
281 checkInvariants(t, s, "after verifying all keys")
282 }
283
284 // TestInternal_EvictionAllVisited_Repeated verifies that the all-visited
285 // eviction path works across multiple consecutive evictions.
286 func TestInternal_EvictionAllVisited_Repeated(t *testing.T) {
287 const cap = 16
288 s := Must(New[int, int](cap))
289
290 for round := 0; round < 5; round++ {
291 // Fill cache
292 base := round * cap * 2
293 for s.Len() < cap {
294 k := base + s.Len()
295 s.Add(k, k)
296 }
297
298 // Visit everything
299 s.mu.Lock()
300 nodes := s.allocator.nodes
301 for idx := nodes[sentinelIdx].next; idx != sentinelIdx; idx = nodes[idx].next {
302 // Use Get (which takes and releases lock) — must unlock first
303 key := nodes[idx].key
304 s.mu.Unlock()
305 s.Get(key)
306 s.mu.Lock()
307 nodes = s.allocator.nodes // re-read after re-lock
308 }
309 s.mu.Unlock()
310
311 // Force evictions — each one faces an all-visited list
312 for i := 0; i < cap/2; i++ {
313 newKey := base + cap*2 + i
314 s.Add(newKey, newKey)
315 checkInvariants(t, s, fmt.Sprintf("round %d, eviction %d", round, i))
316 }
317 }
318 }
319
320 // TestInternal_DeleteThenEvict verifies that deleting the node the hand
321 // points to doesn't corrupt the cache when a subsequent eviction occurs.
322 func TestInternal_DeleteThenEvict(t *testing.T) {
323 const cap = 8
324 s := Must(New[int, int](cap))
325
326 // Fill: keys 0..7
327 for i := 0; i < cap; i++ {
328 s.Add(i, i*10)
329 }
330
331 // Trigger one eviction to set hand to a known position
332 // Visit keys 0..6 but NOT key 0 (tail). Key 0 will be evicted.
333 // Actually, with sentinel list, insertion at head means:
334 // List: sentinel → 7 → 6 → 5 → 4 → 3 → 2 → 1 → 0 → sentinel
335 // Tail is key 0 (index 1). Don't visit it.
336 for i := 1; i < cap; i++ {
337 s.Get(i)
338 }
339
340 // Add key 8: evicts tail (key 0), hand moves to prev of evicted node
341 s.Add(cap, cap*10)
342 checkInvariants(t, s, "after first eviction")
343
344 // Record what the hand points to
345 s.mu.Lock()
346 handIdx := s.hand
347 handKey := s.allocator.nodes[handIdx].key
348 s.mu.Unlock()
349
350 // Delete the node that hand points to
351 ok := s.Delete(handKey)
352 if !ok {
353 t.Fatalf("Delete(%d): expected true", handKey)
354 }
355 // hand is now stale (points to a freed node) but the cache should
356 // still be consistent for subsequent operations.
357
358 // Fill back up and force more evictions
359 for i := 0; i < cap*2; i++ {
360 key := cap*10 + i
361 s.Add(key, key)
362 checkInvariants(t, s, fmt.Sprintf("after post-delete Add(%d)", key))
363 }
364 }
365
366 // TestInternal_AllocatorAccounting verifies freelist/bump accounting
367 // across many add/delete cycles.
368 func TestInternal_AllocatorAccounting(t *testing.T) {
369 const cap = 32
370 s := Must(New[int, int](cap))
371
372 // Phase 1: fill
373 for i := 0; i < cap; i++ {
374 s.Add(i, i)
375 checkInvariants(t, s, fmt.Sprintf("fill Add(%d)", i))
376 }
377
378 // Phase 2: delete half
379 for i := 0; i < cap/2; i++ {
380 s.Delete(i)
381 checkInvariants(t, s, fmt.Sprintf("Delete(%d)", i))
382 }
383
384 // Phase 3: re-add (reuses freelist slots)
385 for i := 0; i < cap/2; i++ {
386 key := cap + i
387 s.Add(key, key)
388 checkInvariants(t, s, fmt.Sprintf("re-add Add(%d)", key))
389 }
390
391 // Phase 4: eviction churn (all slots now bump-allocated + recycled)
392 for i := 0; i < cap*3; i++ {
393 key := cap*2 + i
394 s.Add(key, key)
395 checkInvariants(t, s, fmt.Sprintf("churn Add(%d)", key))
396 }
397
398 // Phase 5: delete all, verify accounting
399 for s.Len() > 0 {
400 // Find a key to delete by walking the list
401 s.mu.Lock()
402 nodes := s.allocator.nodes
403 firstIdx := nodes[sentinelIdx].next
404 key := nodes[firstIdx].key
405 s.mu.Unlock()
406
407 s.Delete(key)
408 }
409 checkInvariants(t, s, "after delete all")
410
411 s.mu.Lock()
412 if sz := s.size.Load(); sz != 0 {
413 t.Fatalf("size=%d after deleting all, want 0", sz)
414 }
415 // All allocated slots should be on freelist
416 freelistLen := 0
417 nodes := s.allocator.nodes
418 for idx := s.allocator.next; idx != nullIdx; idx = nodes[idx].next {
419 freelistLen++
420 }
421 bumpAllocated := int(s.allocator.cur - 1)
422 if freelistLen != bumpAllocated {
423 t.Fatalf("after delete all: freelist(%d) != bump_allocated(%d)", freelistLen, bumpAllocated)
424 }
425 s.mu.Unlock()
426 }
427
428 // TestInternal_StaleIndex_ABA deterministically verifies the n.key == key guard
429 // (sieve.go lines 175, 197, 232) that detects stale indices after eviction+reuse.
430 //
431 // Sequence:
432 // 1. Fill a 4-entry cache with keys 10,20,30,40
433 // 2. Evict key 10 (unvisited tail) by adding key 50
434 // 3. The freed index is reused for the next Add (LIFO freelist)
435 // 4. Verify the old index now holds a different key — the guard catches this
436 func TestInternal_StaleIndex_ABA(t *testing.T) {
437 const cap = 4
438 s := Must(New[int, int](cap))
439
440 // Fill: keys 10, 20, 30, 40 (non-zero to avoid zero-value ambiguity)
441 for _, k := range []int{10, 20, 30, 40} {
442 s.Add(k, k*1000)
443 }
444 checkInvariants(t, s, "after fill")
445
446 // Record the index for key 10 (tail — first inserted, will be evicted first)
447 targetIdx, ok := s.cache.Load(10)
448 if !ok {
449 t.Fatal("key 10 not in cache map")
450 }
451
452 // Visit keys 20, 30, 40 so they survive eviction. Do NOT visit key 10.
453 for _, k := range []int{20, 30, 40} {
454 if _, ok := s.Get(k); !ok {
455 t.Fatalf("Get(%d) should hit", k)
456 }
457 }
458
459 // Add key 50: triggers eviction. Key 10 is unvisited tail → evicted.
460 // remove() frees targetIdx to LIFO freelist.
461 s.Add(50, 50*1000)
462 checkInvariants(t, s, "after eviction of key 10")
463
464 // Verify key 10 is gone from the map
465 if _, ok := s.cache.Load(10); ok {
466 t.Fatal("key 10 should have been evicted from map")
467 }
468
469 // Verify key 10 is gone via public API
470 if _, ok := s.Get(10); ok {
471 t.Fatal("Get(10) should miss after eviction")
472 }
473
474 // Add key 60: LIFO freelist returns targetIdx — reused for a different key
475 s.Add(60, 60*1000)
476 checkInvariants(t, s, "after reuse of freed index")
477
478 // Verify the freed index was reused for key 60
479 reusedIdx, ok := s.cache.Load(60)
480 if !ok {
481 t.Fatal("key 60 not in cache map")
482 }
483 if reusedIdx != targetIdx {
484 t.Fatalf("expected LIFO reuse: key 60 at idx %d, but key 10 was at idx %d", reusedIdx, targetIdx)
485 }
486
487 // Verify the node at targetIdx now holds key 60, not key 10
488 s.slots.Lock(targetIdx)
489 keyAtIdx := s.allocator.nodes[targetIdx].key
490 valAtIdx := s.allocator.nodes[targetIdx].val
491 s.slots.Unlock(targetIdx)
492
493 if keyAtIdx != 60 {
494 t.Fatalf("node[%d].key = %d, want 60 (proves stale index would mismatch)", targetIdx, keyAtIdx)
495 }
496 if valAtIdx != 60*1000 {
497 t.Fatalf("node[%d].val = %d, want %d", targetIdx, valAtIdx, 60*1000)
498 }
499
500 // Verify public API works correctly for both keys
501 if v, ok := s.Get(60); !ok || v != 60*1000 {
502 t.Fatalf("Get(60) = (%d, %v), want (%d, true)", v, ok, 60*1000)
503 }
504 if _, ok := s.Get(10); ok {
505 t.Fatal("Get(10) should still miss — key guard would catch stale index")
506 }
507
508 checkInvariants(t, s, "final")
509 }
510
511 // TestInternal_LargerScale runs the deep invariant checker at larger scale
512 // (less frequently to keep test time reasonable).
513 func TestInternal_LargerScale(t *testing.T) {
514 const cap = 256
515 s := Must(New[int, int](cap))
516
517 // Bulk fill with eviction
518 for i := 0; i < cap*4; i++ {
519 s.Add(i, i)
520 }
521 checkInvariants(t, s, "after bulk fill")
522
523 // Delete every other key, then refill
524 for i := cap * 3; i < cap*4; i += 2 {
525 s.Delete(i)
526 }
527 checkInvariants(t, s, "after alternating deletes")
528
529 for i := cap * 4; i < cap*5; i++ {
530 s.Add(i, i)
531 }
532 checkInvariants(t, s, "after refill")
533
534 // Purge and restart
535 s.Purge()
536 checkInvariants(t, s, "after Purge")
537
538 for i := 0; i < cap; i++ {
539 s.Add(i, i)
540 }
541 checkInvariants(t, s, "after re-fill post-purge")
542 }