Debian Codegraph @

sieve_contract_test.go

raw
1 // sieve_contract_test.go - construction error paths, hand fidelity after
2 // Delete, and eviction progress under sustained read load (whitebox)
3 //
4 // (c) 2024 Sudhi Herle <[email protected]>
5 //
6 // Copyright 2024- Sudhi Herle <sw-at-herle-dot-net>
7 // License: BSD-2-Clause
8 //
9 // If you need a commercial license for this work, please contact
10 // the author.
11 //
12 // This software does not come with any express or implied
13 // warranty; it is provided "as is". No claim is made to its
14 // suitability for any purpose.
15
16 package sieve
17
18 import (
19 "errors"
20 "sync"
21 "testing"
22 "time"
23 )
24
25 // TestNew_Errors exercises every construction error path.
26 func TestNew_Errors(t *testing.T) {
27 cases := []struct {
28 name string
29 cap int
30 opts []Option
31 wantErr error
32 }{
33 {"zero capacity", 0, nil, ErrInvalidCapacity},
34 {"negative capacity", -1, nil, ErrInvalidCapacity},
35 {"capacity above max", MaxCapacity + 1, nil, ErrInvalidCapacity},
36 {"clamp above max", 8, []Option{WithVisitClamp(MaxVisitClamp + 1)}, ErrInvalidVisitClamp},
37 {"clamp far above max", 8, []Option{WithVisitClamp(255)}, ErrInvalidVisitClamp},
38 }
39
40 for _, tc := range cases {
41 t.Run(tc.name, func(t *testing.T) {
42 s, err := New[int, int](tc.cap, tc.opts...)
43 if s != nil {
44 t.Fatalf("expected nil cache, got %v", s)
45 }
46 if !errors.Is(err, tc.wantErr) {
47 t.Fatalf("expected %v, got %v", tc.wantErr, err)
48 }
49 })
50 }
51 }
52
53 // TestNew_ValidBoundaries exercises the accepted edges of the input range.
54 func TestNew_ValidBoundaries(t *testing.T) {
55 if _, err := New[int, int](1); err != nil {
56 t.Fatalf("capacity 1: unexpected error %v", err)
57 }
58 if _, err := New[int, int](8, WithVisitClamp(MaxVisitClamp)); err != nil {
59 t.Fatalf("clamp at MaxVisitClamp: unexpected error %v", err)
60 }
61 // Values below 1 are silently rounded up to 1.
62 if _, err := New[int, int](8, WithVisitClamp(0)); err != nil {
63 t.Fatalf("clamp 0: unexpected error %v", err)
64 }
65 if _, err := New[int, int](8, WithVisitClamp(-3)); err != nil {
66 t.Fatalf("clamp -3: unexpected error %v", err)
67 }
68 }
69
70 // TestMust_PanicsOnError verifies the Must helper contract.
71 func TestMust_PanicsOnError(t *testing.T) {
72 defer func() {
73 if recover() == nil {
74 t.Fatal("Must did not panic on construction error")
75 }
76 }()
77 Must(New[int, int](0))
78 }
79
80 // TestInternal_HandFidelity_DeleteHand verifies that Delete() of the node
81 // the eviction hand points to advances the hand to its predecessor instead
82 // of leaving it dangling on a freed slot. Without the fix, the freed slot
83 // is reused at the head of the list and the hand teleports there, evicting
84 // the newest entry instead of continuing the scan from where it stopped.
85 //
86 // Keys are 1-based: the zero key is reserved (see Sieve doc).
87 func TestInternal_HandFidelity_DeleteHand(t *testing.T) {
88 const capacity = 4
89 s := Must(New[int, int](capacity))
90
91 // Fill: list head→tail is 4,3,2,1.
92 for i := 1; i <= capacity; i++ {
93 s.Add(i, i*10)
94 }
95
96 // First eviction: nothing visited, so the tail (key 1) is evicted and
97 // the hand lands on key 2's node. Key 5 reuses the freed slot at head.
98 ev, r := s.Add(5, 50)
99 if !r.Evicted() || ev.Key != 1 {
100 t.Fatalf("expected eviction of key 1, got evicted=%v key=%v", r.Evicted(), ev.Key)
101 }
102 if s.hand == sentinelIdx {
103 t.Fatal("hand not set after eviction")
104 }
105 handKey := s.allocator.nodes[s.hand].key
106 if handKey != 2 {
107 t.Fatalf("expected hand on key 2, got key %v", handKey)
108 }
109
110 // Delete the hand node. The hand must advance to key 2's predecessor
111 // (key 3) rather than dangle on the freed slot.
112 if !s.Delete(2) {
113 t.Fatal("Delete(2) failed")
114 }
115 checkInvariants(t, s, "after Delete of hand node")
116 if got := s.allocator.nodes[s.hand].key; got != 3 {
117 t.Fatalf("expected hand on key 3 after Delete of hand node, got key %v", got)
118 }
119
120 // Refill (key 6 reuses key 2's slot, inserted at head) and force an
121 // eviction. The scan must continue at key 3 — not at the newest entry.
122 s.Add(6, 60)
123 ev, r = s.Add(7, 70)
124 if !r.Evicted() {
125 t.Fatal("expected eviction when adding key 7")
126 }
127 if ev.Key != 3 {
128 t.Fatalf("expected eviction of key 3 (hand position), got key %v", ev.Key)
129 }
130 if _, ok := s.Get(6); !ok {
131 t.Fatal("newest entry (key 6) was evicted — hand teleported to head")
132 }
133 checkInvariants(t, s, "after eviction past deleted hand")
134 }
135
136 // TestEvictionProgress_UnderGetLoad verifies that the eviction scan makes
137 // progress while concurrent lock-free Gets continuously re-mark visited
138 // bits behind the hand (theoretical livelock scenario).
139 func TestEvictionProgress_UnderGetLoad(t *testing.T) {
140 const (
141 capacity = 64
142 readers = 8
143 adds = 5000
144 )
145 s := Must(New[int, int](capacity))
146 for i := 1; i <= capacity; i++ {
147 s.Add(i, i)
148 }
149
150 done := make(chan struct{})
151 var wg sync.WaitGroup
152 for r := 0; r < readers; r++ {
153 wg.Add(1)
154 go func() {
155 defer wg.Done()
156 for {
157 select {
158 case <-done:
159 return
160 default:
161 }
162 for k := 1; k <= capacity; k++ {
163 s.Get(k)
164 }
165 }
166 }()
167 }
168
169 start := time.Now()
170 deadline := start.Add(30 * time.Second)
171 for i := 0; i < adds; i++ {
172 s.Add(capacity+1+i, i)
173 if time.Now().After(deadline) {
174 close(done)
175 wg.Wait()
176 t.Fatalf("eviction stalled: only %d/%d Adds completed in 30s", i, adds)
177 }
178 }
179 close(done)
180 wg.Wait()
181
182 if got := s.Len(); got != capacity {
183 t.Fatalf("expected size %d after churn, got %d", capacity, got)
184 }
185 }