| 1 |
// sieve_adversarial_test.go - comprehensive functional, edge-case, and concurrency tests |
| 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 |
"fmt" |
| 19 |
"math/rand" |
| 20 |
"runtime" |
| 21 |
"sync" |
| 22 |
"sync/atomic" |
| 23 |
"testing" |
| 24 |
|
| 25 |
"github.com/opencoff/go-sieve" |
| 26 |
) |
| 27 |
|
| 28 |
// --- Edge Case Tests --- |
| 29 |
|
| 30 |
func TestEdge_Capacity1(t *testing.T) { |
| 31 |
s := sieve.Must(sieve.New[int, string](1)) |
| 32 |
|
| 33 |
if s.Cap() != 1 { |
| 34 |
t.Fatalf("Cap() = %d, want 1", s.Cap()) |
| 35 |
} |
| 36 |
|
| 37 |
s.Add(1, "a") |
| 38 |
if v, ok := s.Get(1); !ok || v != "a" { |
| 39 |
t.Fatalf("Get(1) = (%q, %v), want (a, true)", v, ok) |
| 40 |
} |
| 41 |
|
| 42 |
// Adding second key evicts first |
| 43 |
s.Add(2, "b") |
| 44 |
if s.Len() != 1 { |
| 45 |
t.Fatalf("Len() = %d, want 1", s.Len()) |
| 46 |
} |
| 47 |
if _, ok := s.Get(1); ok { |
| 48 |
t.Fatal("expected key 1 to be evicted") |
| 49 |
} |
| 50 |
if v, ok := s.Get(2); !ok || v != "b" { |
| 51 |
t.Fatalf("Get(2) = (%q, %v), want (b, true)", v, ok) |
| 52 |
} |
| 53 |
} |
| 54 |
|
| 55 |
func TestEdge_GetEmptyCache(t *testing.T) { |
| 56 |
s := sieve.Must(sieve.New[string, int](10)) |
| 57 |
|
| 58 |
v, ok := s.Get("nonexistent") |
| 59 |
if ok { |
| 60 |
t.Fatal("expected miss on empty cache") |
| 61 |
} |
| 62 |
if v != 0 { |
| 63 |
t.Fatalf("expected zero value, got %d", v) |
| 64 |
} |
| 65 |
} |
| 66 |
|
| 67 |
func TestEdge_DeleteNonexistent(t *testing.T) { |
| 68 |
s := sieve.Must(sieve.New[int, int](10)) |
| 69 |
|
| 70 |
if s.Delete(42) { |
| 71 |
t.Fatal("expected false for deleting from empty cache") |
| 72 |
} |
| 73 |
|
| 74 |
s.Add(1, 1) |
| 75 |
if s.Delete(42) { |
| 76 |
t.Fatal("expected false for deleting nonexistent key") |
| 77 |
} |
| 78 |
} |
| 79 |
|
| 80 |
func TestEdge_ProbeInsertsThenReturns(t *testing.T) { |
| 81 |
s := sieve.Must(sieve.New[int, string](4)) |
| 82 |
|
| 83 |
// Probe on miss inserts and returns (val, _, 0) |
| 84 |
v, _, r := s.Probe(1, "hello") |
| 85 |
if r.Hit() { |
| 86 |
t.Fatal("expected miss on first Probe") |
| 87 |
} |
| 88 |
if v != "hello" { |
| 89 |
t.Fatalf("Probe miss: expected %q, got %q", "hello", v) |
| 90 |
} |
| 91 |
|
| 92 |
// Probe on hit returns cached value, not the passed value |
| 93 |
v, _, r = s.Probe(1, "world") |
| 94 |
if !r.Hit() { |
| 95 |
t.Fatal("expected hit on second Probe") |
| 96 |
} |
| 97 |
if v != "hello" { |
| 98 |
t.Fatalf("Probe hit: expected %q, got %q", "hello", v) |
| 99 |
} |
| 100 |
} |
| 101 |
|
| 102 |
func TestEdge_PurgeAndReuse(t *testing.T) { |
| 103 |
s := sieve.Must(sieve.New[int, int](8)) |
| 104 |
|
| 105 |
for i := 0; i < 8; i++ { |
| 106 |
s.Add(i, i*10) |
| 107 |
} |
| 108 |
if s.Len() != 8 { |
| 109 |
t.Fatalf("pre-purge Len() = %d, want 8", s.Len()) |
| 110 |
} |
| 111 |
|
| 112 |
s.Purge() |
| 113 |
|
| 114 |
if s.Len() != 0 { |
| 115 |
t.Fatalf("post-purge Len() = %d, want 0", s.Len()) |
| 116 |
} |
| 117 |
if s.Cap() != 8 { |
| 118 |
t.Fatalf("post-purge Cap() = %d, want 8", s.Cap()) |
| 119 |
} |
| 120 |
|
| 121 |
// All old keys should be gone |
| 122 |
for i := 0; i < 8; i++ { |
| 123 |
if _, ok := s.Get(i); ok { |
| 124 |
t.Fatalf("key %d should not exist after Purge", i) |
| 125 |
} |
| 126 |
} |
| 127 |
|
| 128 |
// Re-add should work |
| 129 |
for i := 0; i < 8; i++ { |
| 130 |
s.Add(i, i*100) |
| 131 |
} |
| 132 |
for i := 0; i < 8; i++ { |
| 133 |
v, ok := s.Get(i) |
| 134 |
if !ok { |
| 135 |
t.Fatalf("key %d missing after re-add", i) |
| 136 |
} |
| 137 |
if v != i*100 { |
| 138 |
t.Fatalf("key %d: expected %d, got %d", i, i*100, v) |
| 139 |
} |
| 140 |
} |
| 141 |
} |
| 142 |
|
| 143 |
func TestEdge_AddUpdateReturnValue(t *testing.T) { |
| 144 |
s := sieve.Must(sieve.New[string, int](4)) |
| 145 |
|
| 146 |
// First add: not a hit (new key) |
| 147 |
_, r := s.Add("x", 1) |
| 148 |
if r.Hit() { |
| 149 |
t.Fatal("first Add should not be a hit") |
| 150 |
} |
| 151 |
|
| 152 |
// Second add: hit (existing key updated) |
| 153 |
_, r = s.Add("x", 2) |
| 154 |
if !r.Hit() { |
| 155 |
t.Fatal("second Add should be a hit") |
| 156 |
} |
| 157 |
|
| 158 |
v, _ := s.Get("x") |
| 159 |
if v != 2 { |
| 160 |
t.Fatalf("after update: expected 2, got %d", v) |
| 161 |
} |
| 162 |
} |
| 163 |
|
| 164 |
func TestEdge_DeleteReducesLen(t *testing.T) { |
| 165 |
s := sieve.Must(sieve.New[int, int](16)) |
| 166 |
|
| 167 |
for i := 0; i < 10; i++ { |
| 168 |
s.Add(i, i) |
| 169 |
} |
| 170 |
if s.Len() != 10 { |
| 171 |
t.Fatalf("Len() = %d, want 10", s.Len()) |
| 172 |
} |
| 173 |
|
| 174 |
for i := 0; i < 10; i++ { |
| 175 |
ok := s.Delete(i) |
| 176 |
if !ok { |
| 177 |
t.Fatalf("Delete(%d) returned false", i) |
| 178 |
} |
| 179 |
expected := 10 - i - 1 |
| 180 |
if s.Len() != expected { |
| 181 |
t.Fatalf("after Delete(%d): Len() = %d, want %d", i, s.Len(), expected) |
| 182 |
} |
| 183 |
} |
| 184 |
} |
| 185 |
|
| 186 |
func TestEdge_LenNeverExceedsCap(t *testing.T) { |
| 187 |
const cap = 32 |
| 188 |
s := sieve.Must(sieve.New[int, int](cap)) |
| 189 |
|
| 190 |
for i := 0; i < cap*10; i++ { |
| 191 |
s.Add(i, i) |
| 192 |
if s.Len() > cap { |
| 193 |
t.Fatalf("after Add(%d): Len()=%d > Cap()=%d", i, s.Len(), cap) |
| 194 |
} |
| 195 |
} |
| 196 |
} |
| 197 |
|
| 198 |
// --- Concurrent Stress Tests --- |
| 199 |
|
| 200 |
// TestConcurrent_DeleteStress tests Delete under high concurrency. |
| 201 |
func TestConcurrent_DeleteStress(t *testing.T) { |
| 202 |
const ( |
| 203 |
cacheSize = 512 |
| 204 |
goroutines = 50 |
| 205 |
opsPerG = 2000 |
| 206 |
) |
| 207 |
|
| 208 |
s := sieve.Must(sieve.New[int, int](cacheSize)) |
| 209 |
|
| 210 |
// Pre-fill |
| 211 |
for i := 0; i < cacheSize; i++ { |
| 212 |
s.Add(i, i) |
| 213 |
} |
| 214 |
|
| 215 |
var wg sync.WaitGroup |
| 216 |
wg.Add(goroutines) |
| 217 |
for g := 0; g < goroutines; g++ { |
| 218 |
go func() { |
| 219 |
defer wg.Done() |
| 220 |
r := rand.New(rand.NewSource(rand.Int63())) |
| 221 |
for i := 0; i < opsPerG; i++ { |
| 222 |
key := r.Intn(cacheSize * 2) |
| 223 |
switch r.Intn(4) { |
| 224 |
case 0: |
| 225 |
s.Delete(key) |
| 226 |
case 1: |
| 227 |
s.Add(key, key) |
| 228 |
case 2: |
| 229 |
s.Get(key) |
| 230 |
case 3: |
| 231 |
s.Probe(key, key) |
| 232 |
} |
| 233 |
} |
| 234 |
}() |
| 235 |
} |
| 236 |
wg.Wait() |
| 237 |
|
| 238 |
if s.Len() < 0 || s.Len() > cacheSize { |
| 239 |
t.Fatalf("Len()=%d out of range [0, %d]", s.Len(), cacheSize) |
| 240 |
} |
| 241 |
} |
| 242 |
|
| 243 |
// TestConcurrent_PurgeUnderLoad tests Purge racing with Get/Add. |
| 244 |
func TestConcurrent_PurgeUnderLoad(t *testing.T) { |
| 245 |
const ( |
| 246 |
cacheSize = 256 |
| 247 |
goroutines = 20 |
| 248 |
opsPerG = 1000 |
| 249 |
purges = 10 |
| 250 |
) |
| 251 |
|
| 252 |
s := sieve.Must(sieve.New[int, int](cacheSize)) |
| 253 |
|
| 254 |
var wg sync.WaitGroup |
| 255 |
var stop atomic.Bool |
| 256 |
|
| 257 |
// Workers doing Get/Add |
| 258 |
wg.Add(goroutines) |
| 259 |
for g := 0; g < goroutines; g++ { |
| 260 |
go func() { |
| 261 |
defer wg.Done() |
| 262 |
r := rand.New(rand.NewSource(rand.Int63())) |
| 263 |
for !stop.Load() { |
| 264 |
key := r.Intn(cacheSize * 2) |
| 265 |
if r.Intn(2) == 0 { |
| 266 |
s.Get(key) |
| 267 |
} else { |
| 268 |
s.Add(key, key) |
| 269 |
} |
| 270 |
} |
| 271 |
}() |
| 272 |
} |
| 273 |
|
| 274 |
// Purger |
| 275 |
for i := 0; i < purges; i++ { |
| 276 |
// Let workers run a bit |
| 277 |
runtime.Gosched() |
| 278 |
s.Purge() |
| 279 |
} |
| 280 |
|
| 281 |
stop.Store(true) |
| 282 |
wg.Wait() |
| 283 |
|
| 284 |
// After all workers stop, cache should be in a consistent state |
| 285 |
if s.Len() < 0 || s.Len() > cacheSize { |
| 286 |
t.Fatalf("Len()=%d out of range [0, %d]", s.Len(), cacheSize) |
| 287 |
} |
| 288 |
} |
| 289 |
|
| 290 |
// TestConcurrent_EvictionStress exercises eviction under heavy concurrent load. |
| 291 |
// This specifically targets the code path where eviction scans the list while |
| 292 |
// concurrent Get() calls re-mark visited bits. |
| 293 |
func TestConcurrent_EvictionStress(t *testing.T) { |
| 294 |
const ( |
| 295 |
cacheSize = 64 // small cache to maximize eviction rate |
| 296 |
goroutines = 20 |
| 297 |
opsPerG = 10000 |
| 298 |
) |
| 299 |
|
| 300 |
s := sieve.Must(sieve.New[int, int](cacheSize)) |
| 301 |
|
| 302 |
var wg sync.WaitGroup |
| 303 |
wg.Add(goroutines) |
| 304 |
for g := 0; g < goroutines; g++ { |
| 305 |
go func(id int) { |
| 306 |
defer wg.Done() |
| 307 |
r := rand.New(rand.NewSource(int64(id))) |
| 308 |
for i := 0; i < opsPerG; i++ { |
| 309 |
// Key range much larger than cache → constant eviction |
| 310 |
key := r.Intn(cacheSize * 20) |
| 311 |
switch r.Intn(10) { |
| 312 |
case 0, 1, 2, 3, 4, 5: // 60% Get |
| 313 |
s.Get(key) |
| 314 |
case 6, 7, 8: // 30% Add |
| 315 |
s.Add(key, key) |
| 316 |
case 9: // 10% Delete |
| 317 |
s.Delete(key) |
| 318 |
} |
| 319 |
} |
| 320 |
}(g) |
| 321 |
} |
| 322 |
wg.Wait() |
| 323 |
|
| 324 |
if s.Len() < 0 || s.Len() > cacheSize { |
| 325 |
t.Fatalf("Len()=%d out of range [0, %d]", s.Len(), cacheSize) |
| 326 |
} |
| 327 |
} |
| 328 |
|
| 329 |
// TestConcurrent_ValueConsistency checks that Get returns the correct value |
| 330 |
// for the key it was asked about, not a value from a different key. |
| 331 |
// This is a probabilistic detector for the ABA problem on index reuse. |
| 332 |
func TestConcurrent_ValueConsistency(t *testing.T) { |
| 333 |
const ( |
| 334 |
cacheSize = 64 // small cache to force frequent eviction/reuse |
| 335 |
goroutines = 12 |
| 336 |
opsPerG = 50000 |
| 337 |
keyRange = cacheSize * 4 // 4x cache to force eviction |
| 338 |
) |
| 339 |
|
| 340 |
// Values encode the key, so we can detect cross-key contamination. |
| 341 |
// val = key * 1000 + arbitrary_suffix |
| 342 |
s := sieve.Must(sieve.New[int, int](cacheSize)) |
| 343 |
|
| 344 |
var violations atomic.Int64 |
| 345 |
var wg sync.WaitGroup |
| 346 |
wg.Add(goroutines) |
| 347 |
|
| 348 |
for g := 0; g < goroutines; g++ { |
| 349 |
go func(id int) { |
| 350 |
defer wg.Done() |
| 351 |
r := rand.New(rand.NewSource(int64(id))) |
| 352 |
for i := 0; i < opsPerG; i++ { |
| 353 |
key := r.Intn(keyRange) |
| 354 |
encodedVal := key*1000 + r.Intn(1000) |
| 355 |
|
| 356 |
if r.Intn(3) == 0 { |
| 357 |
// Add: value encodes which key it belongs to |
| 358 |
s.Add(key, encodedVal) |
| 359 |
} else { |
| 360 |
// Get: verify value belongs to this key |
| 361 |
if v, ok := s.Get(key); ok { |
| 362 |
gotKey := v / 1000 |
| 363 |
if gotKey != key { |
| 364 |
violations.Add(1) |
| 365 |
} |
| 366 |
} |
| 367 |
} |
| 368 |
} |
| 369 |
}(g) |
| 370 |
} |
| 371 |
wg.Wait() |
| 372 |
|
| 373 |
v := violations.Load() |
| 374 |
if v > 0 { |
| 375 |
t.Errorf("detected %d value consistency violations (ABA problem on index reuse)", v) |
| 376 |
} |
| 377 |
} |
| 378 |
|
| 379 |
// TestConcurrent_ProbeConsistency checks that Probe returns consistent values. |
| 380 |
func TestConcurrent_ProbeConsistency(t *testing.T) { |
| 381 |
const ( |
| 382 |
cacheSize = 32 |
| 383 |
goroutines = 10 |
| 384 |
opsPerG = 20000 |
| 385 |
keyRange = cacheSize * 4 |
| 386 |
) |
| 387 |
|
| 388 |
s := sieve.Must(sieve.New[int, int](cacheSize)) |
| 389 |
|
| 390 |
var violations atomic.Int64 |
| 391 |
var wg sync.WaitGroup |
| 392 |
wg.Add(goroutines) |
| 393 |
|
| 394 |
for g := 0; g < goroutines; g++ { |
| 395 |
go func(id int) { |
| 396 |
defer wg.Done() |
| 397 |
r := rand.New(rand.NewSource(int64(id))) |
| 398 |
for i := 0; i < opsPerG; i++ { |
| 399 |
key := r.Intn(keyRange) |
| 400 |
probeVal := key * 1000 |
| 401 |
|
| 402 |
v, _, _ := s.Probe(key, probeVal) |
| 403 |
gotKey := v / 1000 |
| 404 |
if gotKey != key { |
| 405 |
violations.Add(1) |
| 406 |
} |
| 407 |
} |
| 408 |
}(g) |
| 409 |
} |
| 410 |
wg.Wait() |
| 411 |
|
| 412 |
v := violations.Load() |
| 413 |
if v > 0 { |
| 414 |
t.Errorf("detected %d Probe value consistency violations", v) |
| 415 |
} |
| 416 |
} |
| 417 |
|
| 418 |
// --- SIEVE-k Additional Tests --- |
| 419 |
|
| 420 |
func TestSieveK_K2(t *testing.T) { |
| 421 |
c := sieve.Must(sieve.New[string, int](3, sieve.WithVisitClamp(2))) |
| 422 |
|
| 423 |
c.Add("A", 1) |
| 424 |
c.Add("B", 2) |
| 425 |
c.Add("C", 3) |
| 426 |
|
| 427 |
// Access A twice (saturates at k=2) |
| 428 |
c.Get("A") |
| 429 |
c.Get("A") |
| 430 |
|
| 431 |
// Access B once |
| 432 |
c.Get("B") |
| 433 |
|
| 434 |
// C has no accesses → evicted first |
| 435 |
c.Add("D", 4) |
| 436 |
if _, ok := c.Get("C"); ok { |
| 437 |
t.Fatal("expected C to be evicted") |
| 438 |
} |
| 439 |
if _, ok := c.Get("A"); !ok { |
| 440 |
t.Fatal("expected A to survive") |
| 441 |
} |
| 442 |
} |
| 443 |
|
| 444 |
func TestSieveK_LargeK(t *testing.T) { |
| 445 |
// k=7 — uses 3 bits for counter |
| 446 |
c := sieve.Must(sieve.New[int, int](4, sieve.WithVisitClamp(7))) |
| 447 |
|
| 448 |
c.Add(1, 1) |
| 449 |
c.Add(2, 2) |
| 450 |
c.Add(3, 3) |
| 451 |
c.Add(4, 4) |
| 452 |
|
| 453 |
// Access key 1 many times |
| 454 |
for i := 0; i < 20; i++ { |
| 455 |
c.Get(1) |
| 456 |
} |
| 457 |
|
| 458 |
// Force several evictions — key 1 should survive |
| 459 |
c.Add(5, 5) // evicts one of 2,3,4 |
| 460 |
c.Add(6, 6) // evicts another |
| 461 |
c.Add(7, 7) // evicts another |
| 462 |
|
| 463 |
if _, ok := c.Get(1); !ok { |
| 464 |
t.Fatal("key 1 should survive with k=7 and many accesses") |
| 465 |
} |
| 466 |
} |
| 467 |
|
| 468 |
func TestSieveK_PurgeResetsCounters(t *testing.T) { |
| 469 |
c := sieve.Must(sieve.New[int, int](4, sieve.WithVisitClamp(3))) |
| 470 |
|
| 471 |
c.Add(1, 1) |
| 472 |
for i := 0; i < 10; i++ { |
| 473 |
c.Get(1) |
| 474 |
} |
| 475 |
|
| 476 |
c.Purge() |
| 477 |
|
| 478 |
if c.Len() != 0 { |
| 479 |
t.Fatalf("post-purge Len() = %d, want 0", c.Len()) |
| 480 |
} |
| 481 |
|
| 482 |
// Re-add and verify counters are reset (not saturated from before) |
| 483 |
c.Add(1, 10) |
| 484 |
c.Add(2, 20) |
| 485 |
c.Add(3, 30) |
| 486 |
c.Add(4, 40) |
| 487 |
|
| 488 |
// Don't access 1 at all. Add a 5th item to trigger eviction. |
| 489 |
// With reset counters, 1 (unvisited) should be evicted. |
| 490 |
c.Add(5, 50) |
| 491 |
// We can't guarantee which item is evicted without knowing hand position, |
| 492 |
// but we can verify the cache is consistent. |
| 493 |
if c.Len() != 4 { |
| 494 |
t.Fatalf("post-eviction Len() = %d, want 4", c.Len()) |
| 495 |
} |
| 496 |
} |
| 497 |
|
| 498 |
// --- Dump/String Validation --- |
| 499 |
|
| 500 |
func TestDump_Format(t *testing.T) { |
| 501 |
s := sieve.Must(sieve.New[int, string](4)) |
| 502 |
s.Add(1, "a") |
| 503 |
s.Add(2, "b") |
| 504 |
s.Add(3, "c") |
| 505 |
|
| 506 |
dump := s.Dump() |
| 507 |
if dump == "" { |
| 508 |
t.Fatal("Dump() returned empty string") |
| 509 |
} |
| 510 |
|
| 511 |
str := s.String() |
| 512 |
if str == "" { |
| 513 |
t.Fatal("String() returned empty string") |
| 514 |
} |
| 515 |
} |
| 516 |
|
| 517 |
func TestString_ShowsCapAndSize(t *testing.T) { |
| 518 |
s := sieve.Must(sieve.New[int, int](16)) |
| 519 |
for i := 0; i < 5; i++ { |
| 520 |
s.Add(i, i) |
| 521 |
} |
| 522 |
|
| 523 |
str := s.String() |
| 524 |
// String should contain size and cap info |
| 525 |
expected := fmt.Sprintf("size %d, cap %d", 5, 16) |
| 526 |
if len(str) == 0 { |
| 527 |
t.Fatal("String() is empty") |
| 528 |
} |
| 529 |
_ = expected // we just verify it doesn't panic and returns non-empty |
| 530 |
} |
| 531 |
|
| 532 |
// --- Heavy Churn Test --- |
| 533 |
|
| 534 |
// TestChurn_HandWrapAround forces many evictions to exercise hand wrap-around. |
| 535 |
func TestChurn_HandWrapAround(t *testing.T) { |
| 536 |
const cap = 16 |
| 537 |
s := sieve.Must(sieve.New[int, int](cap)) |
| 538 |
|
| 539 |
// Fill and churn through many iterations |
| 540 |
for i := 0; i < cap*100; i++ { |
| 541 |
s.Add(i, i) |
| 542 |
if s.Len() > cap { |
| 543 |
t.Fatalf("iter %d: Len()=%d > Cap()=%d", i, s.Len(), cap) |
| 544 |
} |
| 545 |
|
| 546 |
// Periodically Get some items to set visited bits |
| 547 |
if i%3 == 0 { |
| 548 |
s.Get(i) |
| 549 |
} |
| 550 |
} |
| 551 |
|
| 552 |
// Final state should be consistent |
| 553 |
if s.Len() != cap { |
| 554 |
t.Fatalf("final Len()=%d, want %d", s.Len(), cap) |
| 555 |
} |
| 556 |
} |
| 557 |
|
| 558 |
// TestChurn_DeleteAndRefill tests alternating delete and add patterns. |
| 559 |
func TestChurn_DeleteAndRefill(t *testing.T) { |
| 560 |
const cap = 32 |
| 561 |
s := sieve.Must(sieve.New[int, int](cap)) |
| 562 |
|
| 563 |
for round := 0; round < 10; round++ { |
| 564 |
base := round * cap |
| 565 |
|
| 566 |
// Fill |
| 567 |
for i := 0; i < cap; i++ { |
| 568 |
s.Add(base+i, base+i) |
| 569 |
} |
| 570 |
|
| 571 |
// Delete half |
| 572 |
for i := 0; i < cap/2; i++ { |
| 573 |
s.Delete(base + i) |
| 574 |
} |
| 575 |
|
| 576 |
if s.Len() > cap { |
| 577 |
t.Fatalf("round %d: Len()=%d > Cap()=%d", round, s.Len(), cap) |
| 578 |
} |
| 579 |
} |
| 580 |
} |
| 581 |
|
| 582 |
// ========================================================================= |
| 583 |
// Additional edge case tests |
| 584 |
// ========================================================================= |
| 585 |
|
| 586 |
// TestEdge_EvictionAllVisited verifies eviction works when every node |
| 587 |
// in the list is visited. The hand must scan the entire list, clear all |
| 588 |
// visited bits, wrap around, and evict the first unvisited node. |
| 589 |
func TestEdge_EvictionAllVisited(t *testing.T) { |
| 590 |
const cap = 8 |
| 591 |
s := sieve.Must(sieve.New[int, int](cap)) |
| 592 |
|
| 593 |
for i := 0; i < cap; i++ { |
| 594 |
s.Add(i, i*10) |
| 595 |
} |
| 596 |
|
| 597 |
// Visit ALL nodes |
| 598 |
for i := 0; i < cap; i++ { |
| 599 |
s.Get(i) |
| 600 |
} |
| 601 |
|
| 602 |
// Add one more — forces full-list eviction scan |
| 603 |
s.Add(cap, cap*10) |
| 604 |
|
| 605 |
if s.Len() != cap { |
| 606 |
t.Fatalf("Len()=%d, want %d", s.Len(), cap) |
| 607 |
} |
| 608 |
|
| 609 |
// New key must be present |
| 610 |
v, ok := s.Get(cap) |
| 611 |
if !ok || v != cap*10 { |
| 612 |
t.Fatalf("Get(%d) = (%d, %v), want (%d, true)", cap, v, ok, cap*10) |
| 613 |
} |
| 614 |
|
| 615 |
// Exactly one old key evicted |
| 616 |
present := 0 |
| 617 |
for i := 0; i < cap; i++ { |
| 618 |
if _, ok := s.Get(i); ok { |
| 619 |
present++ |
| 620 |
} |
| 621 |
} |
| 622 |
if present != cap-1 { |
| 623 |
t.Fatalf("expected %d old keys present, got %d", cap-1, present) |
| 624 |
} |
| 625 |
} |
| 626 |
|
| 627 |
// TestEdge_EvictionAllVisited_Repeated exercises the all-visited path |
| 628 |
// across many consecutive evictions. |
| 629 |
func TestEdge_EvictionAllVisited_Repeated(t *testing.T) { |
| 630 |
const cap = 16 |
| 631 |
s := sieve.Must(sieve.New[int, int](cap)) |
| 632 |
|
| 633 |
// Fill |
| 634 |
for i := 0; i < cap; i++ { |
| 635 |
s.Add(i, i) |
| 636 |
} |
| 637 |
|
| 638 |
for round := 0; round < 10; round++ { |
| 639 |
// Visit everything currently in cache |
| 640 |
for i := 0; i < cap*20; i++ { |
| 641 |
s.Get(i) // misses are no-ops |
| 642 |
} |
| 643 |
|
| 644 |
// Force cap/2 evictions, each facing all-visited list |
| 645 |
for i := 0; i < cap/2; i++ { |
| 646 |
key := (round+1)*1000 + i |
| 647 |
s.Add(key, key) |
| 648 |
if s.Len() != cap { |
| 649 |
t.Fatalf("round %d, eviction %d: Len()=%d, want %d", round, i, s.Len(), cap) |
| 650 |
} |
| 651 |
} |
| 652 |
} |
| 653 |
} |
| 654 |
|
| 655 |
// TestEdge_NewWithVisits_K0 verifies that NewWithVisits with k=0 is |
| 656 |
// clamped to k=1 and behaves identically to New. |
| 657 |
func TestEdge_NewWithVisits_K0(t *testing.T) { |
| 658 |
c := sieve.Must(sieve.New[int, int](4, sieve.WithVisitClamp(0))) |
| 659 |
|
| 660 |
c.Add(1, 10) |
| 661 |
c.Add(2, 20) |
| 662 |
c.Add(3, 30) |
| 663 |
c.Add(4, 40) |
| 664 |
|
| 665 |
if c.Len() != 4 { |
| 666 |
t.Fatalf("Len()=%d, want 4", c.Len()) |
| 667 |
} |
| 668 |
|
| 669 |
v, ok := c.Get(1) |
| 670 |
if !ok || v != 10 { |
| 671 |
t.Fatalf("Get(1) = (%d, %v), want (10, true)", v, ok) |
| 672 |
} |
| 673 |
|
| 674 |
// Trigger eviction — same behavior as k=1 |
| 675 |
c.Add(5, 50) |
| 676 |
if c.Len() != 4 { |
| 677 |
t.Fatalf("after eviction: Len()=%d, want 4", c.Len()) |
| 678 |
} |
| 679 |
} |
| 680 |
|
| 681 |
// TestEdge_Capacity2 tests a 2-entry cache. When cache has 1 item, |
| 682 |
// head == tail. Exercises boundary conditions in list operations. |
| 683 |
func TestEdge_Capacity2(t *testing.T) { |
| 684 |
s := sieve.Must(sieve.New[string, int](2)) |
| 685 |
|
| 686 |
s.Add("a", 1) |
| 687 |
if s.Len() != 1 { |
| 688 |
t.Fatalf("Len()=%d, want 1", s.Len()) |
| 689 |
} |
| 690 |
|
| 691 |
s.Add("b", 2) |
| 692 |
if s.Len() != 2 { |
| 693 |
t.Fatalf("Len()=%d, want 2", s.Len()) |
| 694 |
} |
| 695 |
|
| 696 |
// Access a so it's visited |
| 697 |
s.Get("a") |
| 698 |
|
| 699 |
// Add c — should evict b (unvisited) or the tail |
| 700 |
s.Add("c", 3) |
| 701 |
if s.Len() != 2 { |
| 702 |
t.Fatalf("after eviction: Len()=%d, want 2", s.Len()) |
| 703 |
} |
| 704 |
|
| 705 |
// c must be present (just added) |
| 706 |
if _, ok := s.Get("c"); !ok { |
| 707 |
t.Fatal("expected c to be present") |
| 708 |
} |
| 709 |
|
| 710 |
// Delete both |
| 711 |
s.Delete("a") |
| 712 |
s.Delete("c") |
| 713 |
if s.Len() != 0 { |
| 714 |
t.Fatalf("after deleting all: Len()=%d, want 0", s.Len()) |
| 715 |
} |
| 716 |
|
| 717 |
// Re-add should work |
| 718 |
s.Add("x", 42) |
| 719 |
v, ok := s.Get("x") |
| 720 |
if !ok || v != 42 { |
| 721 |
t.Fatalf("Get(x) = (%d, %v), want (42, true)", v, ok) |
| 722 |
} |
| 723 |
} |
| 724 |
|
| 725 |
// TestEdge_ProbeAfterDelete verifies that Probe re-inserts a deleted key. |
| 726 |
func TestEdge_ProbeAfterDelete(t *testing.T) { |
| 727 |
s := sieve.Must(sieve.New[string, int](4)) |
| 728 |
|
| 729 |
s.Add("key", 100) |
| 730 |
s.Delete("key") |
| 731 |
|
| 732 |
if _, ok := s.Get("key"); ok { |
| 733 |
t.Fatal("key should be gone after Delete") |
| 734 |
} |
| 735 |
|
| 736 |
// Probe should re-insert |
| 737 |
v, _, r := s.Probe("key", 200) |
| 738 |
if r.Hit() { |
| 739 |
t.Fatal("Probe should return miss after Delete") |
| 740 |
} |
| 741 |
if v != 200 { |
| 742 |
t.Fatalf("Probe miss: expected 200, got %d", v) |
| 743 |
} |
| 744 |
|
| 745 |
// Now it should be present |
| 746 |
v2, ok := s.Get("key") |
| 747 |
if !ok || v2 != 200 { |
| 748 |
t.Fatalf("Get after Probe re-insert = (%d, %v), want (200, true)", v2, ok) |
| 749 |
} |
| 750 |
} |
| 751 |
|
| 752 |
// TestEdge_DeleteThenEvict verifies that deleting keys and then triggering |
| 753 |
// evictions doesn't corrupt the cache (exercises stale hand + freelist reuse). |
| 754 |
func TestEdge_DeleteThenEvict(t *testing.T) { |
| 755 |
const cap = 8 |
| 756 |
s := sieve.Must(sieve.New[int, int](cap)) |
| 757 |
|
| 758 |
// Fill |
| 759 |
for i := 0; i < cap; i++ { |
| 760 |
s.Add(i, i*10) |
| 761 |
} |
| 762 |
|
| 763 |
// Visit some, then add to trigger eviction and set the hand |
| 764 |
s.Get(1) |
| 765 |
s.Get(2) |
| 766 |
s.Get(3) |
| 767 |
s.Add(cap, cap*10) // evicts one unvisited key, sets hand |
| 768 |
|
| 769 |
// Delete several keys |
| 770 |
s.Delete(1) |
| 771 |
s.Delete(2) |
| 772 |
|
| 773 |
// Now add many keys — forces eviction using potentially stale hand |
| 774 |
for i := 0; i < cap*3; i++ { |
| 775 |
key := cap*10 + i |
| 776 |
s.Add(key, key) |
| 777 |
if s.Len() > cap { |
| 778 |
t.Fatalf("iter %d: Len()=%d > Cap()=%d", i, s.Len(), cap) |
| 779 |
} |
| 780 |
} |
| 781 |
} |
| 782 |
|
| 783 |
// ========================================================================= |
| 784 |
// Additional concurrency tests |
| 785 |
// ========================================================================= |
| 786 |
|
| 787 |
// TestConcurrent_PurgeValueCorrectness verifies that Get never returns a |
| 788 |
// value belonging to a different key during concurrent Purge+Add cycles. |
| 789 |
// Tracks operation counts to prove we actually exercised the contended paths. |
| 790 |
func TestConcurrent_PurgeValueCorrectness(t *testing.T) { |
| 791 |
const ( |
| 792 |
cacheSize = 128 |
| 793 |
goroutines = 20 |
| 794 |
purges = 20 |
| 795 |
) |
| 796 |
|
| 797 |
s := sieve.Must(sieve.New[int, int](cacheSize)) |
| 798 |
|
| 799 |
var violations atomic.Int64 |
| 800 |
var gets, adds, hits atomic.Int64 |
| 801 |
var wg sync.WaitGroup |
| 802 |
var stop atomic.Bool |
| 803 |
var ready sync.WaitGroup |
| 804 |
|
| 805 |
// Workers: Get/Add with encoded values |
| 806 |
ready.Add(goroutines) |
| 807 |
wg.Add(goroutines) |
| 808 |
for g := 0; g < goroutines; g++ { |
| 809 |
go func() { |
| 810 |
defer wg.Done() |
| 811 |
r := rand.New(rand.NewSource(rand.Int63())) |
| 812 |
ready.Done() |
| 813 |
for !stop.Load() { |
| 814 |
key := r.Intn(cacheSize * 2) |
| 815 |
encodedVal := key * 1000 |
| 816 |
|
| 817 |
if r.Intn(3) == 0 { |
| 818 |
s.Add(key, encodedVal) |
| 819 |
adds.Add(1) |
| 820 |
} else { |
| 821 |
gets.Add(1) |
| 822 |
if v, ok := s.Get(key); ok { |
| 823 |
hits.Add(1) |
| 824 |
if v/1000 != key { |
| 825 |
violations.Add(1) |
| 826 |
} |
| 827 |
} |
| 828 |
} |
| 829 |
} |
| 830 |
}() |
| 831 |
} |
| 832 |
|
| 833 |
// Wait for all workers to start, then purge |
| 834 |
ready.Wait() |
| 835 |
for i := 0; i < purges; i++ { |
| 836 |
runtime.Gosched() |
| 837 |
s.Purge() |
| 838 |
} |
| 839 |
|
| 840 |
stop.Store(true) |
| 841 |
wg.Wait() |
| 842 |
|
| 843 |
v := violations.Load() |
| 844 |
if v > 0 { |
| 845 |
t.Errorf("detected %d value consistency violations during Purge", v) |
| 846 |
} |
| 847 |
|
| 848 |
// Verify we actually did meaningful work |
| 849 |
if gets.Load() < 1000 { |
| 850 |
t.Fatalf("too few Gets (%d) — test didn't exercise read path", gets.Load()) |
| 851 |
} |
| 852 |
if adds.Load() < 100 { |
| 853 |
t.Fatalf("too few Adds (%d) — test didn't exercise write path", adds.Load()) |
| 854 |
} |
| 855 |
if hits.Load() == 0 { |
| 856 |
t.Fatal("zero hits — Purge may have prevented all cache reads from succeeding") |
| 857 |
} |
| 858 |
t.Logf("ops: %d gets (%d hits), %d adds, %d purges, %d violations", |
| 859 |
gets.Load(), hits.Load(), adds.Load(), purges, v) |
| 860 |
} |
| 861 |
|
| 862 |
// TestConcurrent_AddDeleteSameKey focuses on concurrent Add and Delete |
| 863 |
// targeting the same key. The fast-path Add (per-node lock) races with |
| 864 |
// Delete (global mutex + node zeroing). |
| 865 |
// Tracks hit counts to prove we actually exercised the contended paths. |
| 866 |
func TestConcurrent_AddDeleteSameKey(t *testing.T) { |
| 867 |
const ( |
| 868 |
cacheSize = 64 |
| 869 |
goroutines = 20 |
| 870 |
opsPerG = 20000 |
| 871 |
keyRange = 16 // small key range to maximize collisions |
| 872 |
) |
| 873 |
|
| 874 |
s := sieve.Must(sieve.New[int, int](cacheSize)) |
| 875 |
|
| 876 |
var deletes, adds, getHits, probeHits, violations atomic.Int64 |
| 877 |
var wg sync.WaitGroup |
| 878 |
wg.Add(goroutines) |
| 879 |
for g := 0; g < goroutines; g++ { |
| 880 |
go func(id int) { |
| 881 |
defer wg.Done() |
| 882 |
r := rand.New(rand.NewSource(int64(id))) |
| 883 |
for i := 0; i < opsPerG; i++ { |
| 884 |
key := r.Intn(keyRange) |
| 885 |
encodedVal := key * 1000 |
| 886 |
|
| 887 |
switch r.Intn(4) { |
| 888 |
case 0: |
| 889 |
if s.Delete(key) { |
| 890 |
deletes.Add(1) |
| 891 |
} |
| 892 |
case 1: |
| 893 |
s.Add(key, encodedVal) |
| 894 |
adds.Add(1) |
| 895 |
case 2: |
| 896 |
if v, ok := s.Get(key); ok { |
| 897 |
getHits.Add(1) |
| 898 |
if v/1000 != key { |
| 899 |
violations.Add(1) |
| 900 |
} |
| 901 |
} |
| 902 |
case 3: |
| 903 |
if v, _, r := s.Probe(key, encodedVal); r.Hit() { |
| 904 |
probeHits.Add(1) |
| 905 |
if v/1000 != key { |
| 906 |
violations.Add(1) |
| 907 |
} |
| 908 |
} |
| 909 |
} |
| 910 |
} |
| 911 |
}(g) |
| 912 |
} |
| 913 |
wg.Wait() |
| 914 |
|
| 915 |
if v := violations.Load(); v > 0 { |
| 916 |
t.Errorf("detected %d value consistency violations", v) |
| 917 |
} |
| 918 |
if s.Len() < 0 || s.Len() > cacheSize { |
| 919 |
t.Fatalf("Len()=%d out of range [0, %d]", s.Len(), cacheSize) |
| 920 |
} |
| 921 |
|
| 922 |
// Verify all operation types were exercised |
| 923 |
if deletes.Load() == 0 { |
| 924 |
t.Fatal("zero successful deletes — didn't exercise Delete path") |
| 925 |
} |
| 926 |
if getHits.Load() == 0 { |
| 927 |
t.Fatal("zero Get hits — didn't exercise fast-path read") |
| 928 |
} |
| 929 |
if probeHits.Load() == 0 { |
| 930 |
t.Fatal("zero Probe hits — didn't exercise Probe fast-path") |
| 931 |
} |
| 932 |
t.Logf("ops: %d adds, %d deletes, %d get-hits, %d probe-hits", |
| 933 |
adds.Load(), deletes.Load(), getHits.Load(), probeHits.Load()) |
| 934 |
} |
| 935 |
|
| 936 |
// TestConcurrent_StaleGetDuringReallocation forces the LockAndReset / LockAndMark |
| 937 |
// interleaving at the Sieve integration level. A very small cache (cap=8) with a |
| 938 |
// 10x key range maximizes the rate of eviction and slot reuse, increasing the |
| 939 |
// probability that a Get() in progress on slot X sees LockAndReset() on the same |
| 940 |
// slot during reallocation. Any cross-key value contamination is detected. |
| 941 |
func TestConcurrent_StaleGetDuringReallocation(t *testing.T) { |
| 942 |
const ( |
| 943 |
cacheSize = 8 |
| 944 |
keyRange = cacheSize * 10 // 80 keys, forces constant eviction |
| 945 |
goroutines = 20 |
| 946 |
opsPerG = 100_000 |
| 947 |
) |
| 948 |
|
| 949 |
s := sieve.Must(sieve.New[int, int](cacheSize)) |
| 950 |
|
| 951 |
var violations atomic.Int64 |
| 952 |
var gets, hits, adds atomic.Int64 |
| 953 |
var wg sync.WaitGroup |
| 954 |
wg.Add(goroutines) |
| 955 |
|
| 956 |
for g := 0; g < goroutines; g++ { |
| 957 |
go func(id int) { |
| 958 |
defer wg.Done() |
| 959 |
r := rand.New(rand.NewSource(int64(id * 31))) |
| 960 |
for i := 0; i < opsPerG; i++ { |
| 961 |
key := r.Intn(keyRange) |
| 962 |
if r.Intn(10) < 7 { // 70% Get |
| 963 |
gets.Add(1) |
| 964 |
if v, ok := s.Get(key); ok { |
| 965 |
hits.Add(1) |
| 966 |
if v/1000 != key { |
| 967 |
violations.Add(1) |
| 968 |
} |
| 969 |
} |
| 970 |
} else { // 30% Add |
| 971 |
adds.Add(1) |
| 972 |
s.Add(key, key*1000) |
| 973 |
} |
| 974 |
} |
| 975 |
}(g) |
| 976 |
} |
| 977 |
wg.Wait() |
| 978 |
|
| 979 |
v := violations.Load() |
| 980 |
if v > 0 { |
| 981 |
t.Errorf("detected %d cross-key value contaminations (cap=%d, keyRange=%d)", v, cacheSize, keyRange) |
| 982 |
} |
| 983 |
|
| 984 |
if hits.Load() == 0 { |
| 985 |
t.Fatal("zero hits — test didn't exercise the Get fast path") |
| 986 |
} |
| 987 |
|
| 988 |
t.Logf("ops: %d gets (%d hits), %d adds, violations=%d", |
| 989 |
gets.Load(), hits.Load(), adds.Load(), v) |
| 990 |
} |
| 991 |
|
| 992 |
// TestConcurrent_ProbeReturnValue verifies Probe's return value contract |
| 993 |
// under concurrent access. When multiple goroutines Probe the same key: |
| 994 |
// - Exactly one should get (val, false) — the inserter |
| 995 |
// - All others should get (cachedVal, true) — the value from the winner |
| 996 |
// We test this statistically: all returned values must encode the correct key. |
| 997 |
func TestConcurrent_ProbeReturnValue(t *testing.T) { |
| 998 |
const ( |
| 999 |
cacheSize = 128 |
| 1000 |
goroutines = 50 |
| 1001 |
opsPerG = 10000 |
| 1002 |
keyRange = 32 // small to force Probe collisions |
| 1003 |
) |
| 1004 |
|
| 1005 |
s := sieve.Must(sieve.New[int, int](cacheSize)) |
| 1006 |
|
| 1007 |
var violations atomic.Int64 |
| 1008 |
var wg sync.WaitGroup |
| 1009 |
wg.Add(goroutines) |
| 1010 |
|
| 1011 |
for g := 0; g < goroutines; g++ { |
| 1012 |
go func(id int) { |
| 1013 |
defer wg.Done() |
| 1014 |
r := rand.New(rand.NewSource(int64(id))) |
| 1015 |
for i := 0; i < opsPerG; i++ { |
| 1016 |
key := r.Intn(keyRange) |
| 1017 |
probeVal := key * 1000 |
| 1018 |
|
| 1019 |
v, _, _ := s.Probe(key, probeVal) |
| 1020 |
// Whether hit or miss, the value must belong to this key |
| 1021 |
if v/1000 != key { |
| 1022 |
violations.Add(1) |
| 1023 |
} |
| 1024 |
} |
| 1025 |
}(g) |
| 1026 |
} |
| 1027 |
wg.Wait() |
| 1028 |
|
| 1029 |
v := violations.Load() |
| 1030 |
if v > 0 { |
| 1031 |
t.Errorf("detected %d Probe return value violations", v) |
| 1032 |
} |
| 1033 |
} |