Debian Codegraph @

sieve_iter_test.go

raw
1 // sieve_iter_test.go - tests for the All() range iterator
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_test
16
17 import (
18 "math/rand"
19 "runtime"
20 "sync"
21 "sync/atomic"
22 "testing"
23 "time"
24
25 "github.com/opencoff/go-sieve"
26 )
27
28 // TestAll_Basic fills a cache below capacity and verifies that All()
29 // yields every inserted (key, value) pair exactly once.
30 func TestAll_Basic(t *testing.T) {
31 assert := newAsserter(t)
32
33 s := sieve.Must(sieve.New[int, int](64))
34 want := make(map[int]int, 32)
35 for i := 1; i <= 32; i++ {
36 s.Add(i, i*10)
37 want[i] = i * 10
38 }
39
40 got := make(map[int]int, 32)
41 for k, v := range s.All() {
42 _, dup := got[k]
43 assert(!dup, "duplicate key %d yielded", k)
44 got[k] = v
45 }
46
47 assert(len(got) == len(want), "yielded %d entries, want %d", len(got), len(want))
48 for k, v := range want {
49 gv, ok := got[k]
50 assert(ok, "missing key %d", k)
51 assert(gv == v, "key %d: got %d, want %d", k, gv, v)
52 }
53 }
54
55 // TestAll_Empty verifies iteration over an empty cache yields nothing.
56 func TestAll_Empty(t *testing.T) {
57 assert := newAsserter(t)
58
59 s := sieve.Must(sieve.New[int, int](16))
60 n := 0
61 for range s.All() {
62 n++
63 }
64 assert(n == 0, "empty cache yielded %d entries", n)
65 }
66
67 // TestAll_EarlyBreak verifies that breaking out of the range loop
68 // terminates iteration cleanly.
69 func TestAll_EarlyBreak(t *testing.T) {
70 assert := newAsserter(t)
71
72 s := sieve.Must(sieve.New[int, int](128))
73 for i := 1; i <= 100; i++ {
74 s.Add(i, i)
75 }
76
77 n := 0
78 for k, v := range s.All() {
79 assert(k == v, "k/v mismatch: %d != %d", k, v)
80 n++
81 if n == 3 {
82 break
83 }
84 }
85 assert(n == 3, "expected to break after 3 entries, got %d", n)
86 }
87
88 // TestAll_DoesNotPromote verifies that iterating over the cache does not
89 // set visited bits on entries. After a full walk, the next eviction
90 // should still target the SIEVE FIFO tail.
91 func TestAll_DoesNotPromote(t *testing.T) {
92 assert := newAsserter(t)
93
94 s := sieve.Must(sieve.New[int, string](4))
95 s.Add(1, "one")
96 s.Add(2, "two")
97 s.Add(3, "three")
98 s.Add(4, "four")
99
100 // Full walk — must not mark any entry visited.
101 n := 0
102 for range s.All() {
103 n++
104 }
105 assert(n == 4, "expected 4 entries, got %d", n)
106
107 // Adding a 5th item should still evict the oldest (key 1).
108 // If iteration had marked entries visited, the hand would skip key 1
109 // and evict something else (or scan multiple times).
110 ev, r := s.Add(5, "five")
111 assert(r.Evicted(), "expected eviction on 5th add")
112 assert(ev.Key == 1, "iteration leaked visited bit: evicted %d, want 1", ev.Key)
113 }
114
115 // TestAll_ReentrantOps verifies that Get/Add/Delete called from inside
116 // the iterator body do not deadlock and behave correctly.
117 func TestAll_ReentrantOps(t *testing.T) {
118 assert := newAsserter(t)
119
120 s := sieve.Must(sieve.New[int, int](128))
121 for i := 1; i <= 50; i++ {
122 s.Add(i, i)
123 }
124
125 seen := 0
126 for k, v := range s.All() {
127 assert(k == v, "k/v mismatch: %d != %d", k, v)
128 seen++
129
130 // Re-entrant Get — must not deadlock.
131 gv, ok := s.Get(k)
132 assert(ok, "Get(%d) missing during iteration", k)
133 assert(gv == v, "Get(%d): got %d, want %d", k, gv, v)
134
135 // Re-entrant Delete on an unrelated key.
136 if k == 25 {
137 s.Delete(1)
138 }
139
140 // Re-entrant Add of a new key.
141 if k == 30 {
142 s.Add(1000, 1000)
143 }
144 }
145 // We expect to see at least the originals minus the one we deleted
146 // before reaching it, but xsync's relaxed scan can surface new
147 // inserts non-deterministically, so we just sanity-check the bound.
148 assert(seen >= 49 && seen <= 52, "unexpected yield count: %d", seen)
149 }
150
151 // TestAll_ConcurrentReaders verifies that multiple concurrent iterators
152 // over the same cache do not deadlock or report data races.
153 func TestAll_ConcurrentReaders(t *testing.T) {
154 assert := newAsserter(t)
155
156 s := sieve.Must(sieve.New[int, int](1024))
157 for i := 1; i <= 500; i++ {
158 s.Add(i, i*7)
159 }
160
161 const readers = 8
162 var wg sync.WaitGroup
163 wg.Add(readers)
164 for r := 0; r < readers; r++ {
165 go func() {
166 defer wg.Done()
167 for j := 0; j < 20; j++ {
168 count := 0
169 for k, v := range s.All() {
170 if v != k*7 {
171 t.Errorf("concurrent reader: bad pair (%d, %d)", k, v)
172 return
173 }
174 count++
175 }
176 if count == 0 {
177 t.Errorf("concurrent reader saw empty cache")
178 return
179 }
180 }
181 }()
182 }
183 wg.Wait()
184 assert(true, "no deadlock")
185 }
186
187 // TestAll_ConcurrentWritersAndIterator runs writers (Add / Probe / Delete /
188 // Get) in parallel with an iterator goroutine and verifies invariants:
189 // - no yielded pair has the zero key/value sentinel from an evicted slot
190 // - the (k, v) pair satisfies our test invariant (v == k*1000)
191 // - no panics, no -race report
192 //
193 // This is the primary race-detector test: run with `go test -race`.
194 func TestAll_ConcurrentWritersAndIterator(t *testing.T) {
195 assert := newAsserter(t)
196
197 const (
198 capacity = 256
199 keyspace = 4096
200 workers = 8
201 duration = 750 * time.Millisecond
202 )
203
204 s := sieve.Must(sieve.New[int, int](capacity))
205
206 // Pre-warm so the iterator has something to chew on immediately.
207 for i := 1; i <= capacity/2; i++ {
208 s.Add(i, i*1000)
209 }
210
211 stop := make(chan struct{})
212 var wg sync.WaitGroup
213
214 // Writers
215 for w := 0; w < workers; w++ {
216 wg.Add(1)
217 go func(seed int64) {
218 defer wg.Done()
219 rng := rand.New(rand.NewSource(seed))
220 for {
221 select {
222 case <-stop:
223 return
224 default:
225 }
226 k := 1 + rng.Intn(keyspace)
227 switch rng.Intn(4) {
228 case 0:
229 s.Add(k, k*1000)
230 case 1:
231 s.Probe(k, k*1000)
232 case 2:
233 s.Get(k)
234 case 3:
235 s.Delete(k)
236 }
237 }
238 }(int64(w) + 1)
239 }
240
241 // Iterator
242 var iterations, yielded uint64
243 wg.Add(1)
244 go func() {
245 defer wg.Done()
246 for {
247 select {
248 case <-stop:
249 return
250 default:
251 }
252 n := 0
253 for k, v := range s.All() {
254 // Invariant 1: no zero sentinel — every inserted value is k*1000 with k >= 1.
255 if k == 0 || v == 0 {
256 t.Errorf("iterator yielded zero sentinel: (%d, %d)", k, v)
257 return
258 }
259 // Invariant 2: (k, v) is internally consistent.
260 if v != k*1000 {
261 t.Errorf("iterator yielded inconsistent pair: (%d, %d)", k, v)
262 return
263 }
264 n++
265 // Bound iteration so we cycle quickly under churn.
266 if n > capacity*4 {
267 break
268 }
269 }
270 atomic.AddUint64(&yielded, uint64(n))
271 atomic.AddUint64(&iterations, 1)
272 runtime.Gosched()
273 }
274 }()
275
276 time.Sleep(duration)
277 close(stop)
278 wg.Wait()
279
280 assert(atomic.LoadUint64(&iterations) > 0, "iterator never ran")
281 t.Logf("iterations=%d total-yielded=%d", iterations, yielded)
282 }
283
284 // TestAll_HighChurn drives extreme eviction pressure (tiny cache, large
285 // keyspace) while iterating, to maximize the chance of a stale-idx race.
286 func TestAll_HighChurn(t *testing.T) {
287 assert := newAsserter(t)
288
289 const (
290 capacity = 32
291 keyspace = 8192
292 workers = 8
293 duration = 750 * time.Millisecond
294 )
295
296 s := sieve.Must(sieve.New[int, int](capacity))
297
298 stop := make(chan struct{})
299 var wg sync.WaitGroup
300
301 for w := 0; w < workers; w++ {
302 wg.Add(1)
303 go func(seed int64) {
304 defer wg.Done()
305 rng := rand.New(rand.NewSource(seed))
306 for {
307 select {
308 case <-stop:
309 return
310 default:
311 }
312 k := 1 + rng.Intn(keyspace)
313 s.Add(k, k*1000)
314 if rng.Intn(8) == 0 {
315 s.Delete(k)
316 }
317 }
318 }(int64(w) + 100)
319 }
320
321 var iterations uint64
322 wg.Add(1)
323 go func() {
324 defer wg.Done()
325 for {
326 select {
327 case <-stop:
328 return
329 default:
330 }
331 for k, v := range s.All() {
332 if k == 0 || v == 0 {
333 t.Errorf("high-churn iterator yielded zero sentinel: (%d, %d)", k, v)
334 return
335 }
336 if v != k*1000 {
337 t.Errorf("high-churn iterator yielded inconsistent pair: (%d, %d)", k, v)
338 return
339 }
340 }
341 atomic.AddUint64(&iterations, 1)
342 }
343 }()
344
345 time.Sleep(duration)
346 close(stop)
347 wg.Wait()
348
349 assert(atomic.LoadUint64(&iterations) > 0, "high-churn iterator never completed a pass")
350 t.Logf("high-churn iterations=%d", iterations)
351 }
352
353 // TestAll_StringKeyValue exercises the iterator with pointer-typed K/V to
354 // confirm slot zeroing under remove() doesn't leak into yielded values.
355 func TestAll_StringKeyValue(t *testing.T) {
356 assert := newAsserter(t)
357
358 const (
359 capacity = 64
360 keyspace = 1024
361 workers = 4
362 duration = 500 * time.Millisecond
363 )
364
365 s := sieve.Must(sieve.New[string, string](capacity))
366
367 stop := make(chan struct{})
368 var wg sync.WaitGroup
369
370 mk := func(i int) (string, string) {
371 k := "key-" + itoa(i)
372 return k, "val-" + itoa(i)
373 }
374
375 for w := 0; w < workers; w++ {
376 wg.Add(1)
377 go func(seed int64) {
378 defer wg.Done()
379 rng := rand.New(rand.NewSource(seed))
380 for {
381 select {
382 case <-stop:
383 return
384 default:
385 }
386 k, v := mk(1 + rng.Intn(keyspace))
387 s.Add(k, v)
388 }
389 }(int64(w) + 200)
390 }
391
392 wg.Add(1)
393 go func() {
394 defer wg.Done()
395 for {
396 select {
397 case <-stop:
398 return
399 default:
400 }
401 for k, v := range s.All() {
402 // Invariant: yielded key must not be the empty string
403 // (the zero-value sentinel that remove() writes), and
404 // value's suffix must match key's suffix.
405 if k == "" || v == "" {
406 t.Errorf("yielded empty sentinel: (%q, %q)", k, v)
407 return
408 }
409 if k[:4] != "key-" || v[:4] != "val-" || k[4:] != v[4:] {
410 t.Errorf("inconsistent pair: (%q, %q)", k, v)
411 return
412 }
413 }
414 }
415 }()
416
417 time.Sleep(duration)
418 close(stop)
419 wg.Wait()
420 assert(true, "no panic, no race")
421 }
422
423 // itoa is a tiny dependency-free int-to-string for test keys.
424 func itoa(n int) string {
425 if n == 0 {
426 return "0"
427 }
428 neg := n < 0
429 if neg {
430 n = -n
431 }
432 var buf [20]byte
433 i := len(buf)
434 for n > 0 {
435 i--
436 buf[i] = byte('0' + n%10)
437 n /= 10
438 }
439 if neg {
440 i--
441 buf[i] = '-'
442 }
443 return string(buf[i:])
444 }