Debian Codegraph @

bench/replay_test.go

raw
1 //go:build trace
2
3 package bench_test
4
5 import (
6 "os"
7 "path/filepath"
8 "runtime"
9 "strings"
10 "sync"
11 "sync/atomic"
12 "testing"
13
14 sieve "github.com/opencoff/go-sieve"
15
16 "github.com/opencoff/go-sieve/bench"
17
18 arc "github.com/hashicorp/golang-lru/arc/v2"
19 lru "github.com/hashicorp/golang-lru/v2"
20 )
21
22 // --- Trace discovery and caching ---
23
24 // traceEntry holds a loaded trace keyed by its relative path.
25 type traceEntry struct {
26 name string // relative path from data/, e.g. "msr_2007/msr_hm_0"
27 trace *bench.Trace[uint64]
28 }
29
30 var (
31 traceOnce sync.Once
32 traceEntries []traceEntry
33 )
34
35 func dataDir() string {
36 return filepath.Join("..", "data")
37 }
38
39 func isOracleGeneral(name string) bool {
40 return strings.HasSuffix(name, ".oracleGeneral") || strings.HasSuffix(name, ".oracleGeneral.bin")
41 }
42
43 // discoverTraces finds and loads all oracleGeneral traces under data/.
44 // Results are cached via sync.Once.
45 func discoverTraces(tb testing.TB) []traceEntry {
46 traceOnce.Do(func() {
47 root := dataDir()
48 filepath.WalkDir(root, func(path string, d os.DirEntry, err error) error {
49 if err != nil || d.IsDir() {
50 return nil
51 }
52 if !isOracleGeneral(d.Name()) {
53 return nil
54 }
55 // Skip very large files (>2GB) to keep benchmarks tractable
56 info, err := d.Info()
57 if err != nil {
58 return nil
59 }
60 if info.Size() > 2*1024*1024*1024 {
61 return nil
62 }
63
64 trace, err := bench.LoadOracleGeneral(path)
65 if err != nil {
66 return nil
67 }
68
69 rel, _ := filepath.Rel(root, path)
70 // Clean up the name: strip extension, use / as separator
71 name := strings.TrimSuffix(rel, ".bin")
72 name = strings.TrimSuffix(name, ".oracleGeneral")
73 traceEntries = append(traceEntries, traceEntry{name: name, trace: trace})
74 return nil
75 })
76 })
77 if len(traceEntries) == 0 {
78 tb.Skip("no oracleGeneral traces found in data/")
79 }
80 return traceEntries
81 }
82
83 // --- Miss Ratio Test ---
84
85 func TestMissRatio(t *testing.T) {
86 entries := discoverTraces(t)
87
88 for _, e := range entries {
89 trace := e.trace
90 capacity := trace.Unique / 10
91 if capacity < 1 {
92 capacity = 1
93 }
94
95 t.Run(e.name, func(t *testing.T) {
96 t.Logf("%d requests, %d unique, cache size %d (10%%)", len(trace.Requests), trace.Unique, capacity)
97
98 type variant struct {
99 name string
100 run func() int
101 }
102 variants := []variant{
103 {"sieve-k1", func() int {
104 c := sieve.Must(sieve.New[uint64, struct{}](capacity))
105 return replayMisses(c, trace)
106 }},
107 {"sieve-k2", func() int {
108 c := sieve.Must(sieve.New[uint64, struct{}](capacity, sieve.WithVisitClamp(2)))
109 return replayMisses(c, trace)
110 }},
111 {"sieve-k3", func() int {
112 c := sieve.Must(sieve.New[uint64, struct{}](capacity, sieve.WithVisitClamp(3)))
113 return replayMisses(c, trace)
114 }},
115 {"LRU", func() int {
116 c, _ := lru.New[uint64, struct{}](capacity)
117 return replayMissesLRU(c, trace)
118 }},
119 {"ARC", func() int {
120 c, _ := arc.NewARC[uint64, struct{}](capacity)
121 return replayMissesARC(c, trace)
122 }},
123 }
124
125 for _, v := range variants {
126 misses := v.run()
127 ratio := float64(misses) / float64(len(trace.Requests))
128 t.Logf(" %-12s miss ratio: %.4f (%d/%d)", v.name, ratio, misses, len(trace.Requests))
129 }
130 })
131 }
132 }
133
134 // --- Sequential Replay Benchmarks ---
135
136 func BenchmarkReplay(b *testing.B) {
137 entries := discoverTraces(b)
138
139 for _, e := range entries {
140 trace := e.trace
141 capacity := trace.Unique / 10
142 if capacity < 1 {
143 capacity = 1
144 }
145
146 b.Run(e.name+"/SieveK1", func(b *testing.B) {
147 for range b.N {
148 c := sieve.Must(sieve.New[uint64, struct{}](capacity))
149 misses := replayMisses(c, trace)
150 b.ReportMetric(float64(misses)/float64(len(trace.Requests)), "miss-ratio")
151 }
152 })
153
154 b.Run(e.name+"/SieveK3", func(b *testing.B) {
155 for range b.N {
156 c := sieve.Must(sieve.New[uint64, struct{}](capacity, sieve.WithVisitClamp(3)))
157 misses := replayMisses(c, trace)
158 b.ReportMetric(float64(misses)/float64(len(trace.Requests)), "miss-ratio")
159 }
160 })
161
162 b.Run(e.name+"/LRU", func(b *testing.B) {
163 for range b.N {
164 c, _ := lru.New[uint64, struct{}](capacity)
165 misses := replayMissesLRU(c, trace)
166 b.ReportMetric(float64(misses)/float64(len(trace.Requests)), "miss-ratio")
167 }
168 })
169
170 b.Run(e.name+"/ARC", func(b *testing.B) {
171 for range b.N {
172 c, _ := arc.NewARC[uint64, struct{}](capacity)
173 misses := replayMissesARC(c, trace)
174 b.ReportMetric(float64(misses)/float64(len(trace.Requests)), "miss-ratio")
175 }
176 })
177 }
178 }
179
180 // --- Parallel Get Benchmarks ---
181
182 // staggerStart returns an evenly spaced starting offset into a ring of n
183 // requests for each successive worker. Without it, every goroutine walks
184 // the trace from offset 0 in near-lockstep: each key is requested by all
185 // goroutines almost simultaneously, inflating the hit ratio relative to
186 // a real replay.
187 func staggerStart(worker *atomic.Int64, n int) int {
188 g := runtime.GOMAXPROCS(0)
189 if g < 1 {
190 g = 1
191 }
192 w := int(worker.Add(1)-1) % g
193 return w * (n / g)
194 }
195
196 func BenchmarkParallelGet(b *testing.B) {
197 entries := discoverTraces(b)
198
199 for _, e := range entries {
200 trace := e.trace
201 capacity := trace.Unique / 10
202 if capacity < 1 {
203 capacity = 1
204 }
205
206 b.Run(e.name+"/SieveK1", func(b *testing.B) {
207 c := sieve.Must(sieve.New[uint64, struct{}](capacity))
208 warmup(c, trace)
209 var worker atomic.Int64
210 b.ResetTimer()
211 b.RunParallel(func(pb *testing.PB) {
212 n := len(trace.Requests)
213 i := staggerStart(&worker, n)
214 for pb.Next() {
215 c.Get(trace.Requests[i%n].Key)
216 i++
217 }
218 })
219 })
220
221 b.Run(e.name+"/SieveK3", func(b *testing.B) {
222 c := sieve.Must(sieve.New[uint64, struct{}](capacity, sieve.WithVisitClamp(3)))
223 warmup(c, trace)
224 var worker atomic.Int64
225 b.ResetTimer()
226 b.RunParallel(func(pb *testing.PB) {
227 n := len(trace.Requests)
228 i := staggerStart(&worker, n)
229 for pb.Next() {
230 c.Get(trace.Requests[i%n].Key)
231 i++
232 }
233 })
234 })
235
236 b.Run(e.name+"/LRU", func(b *testing.B) {
237 c, _ := lru.New[uint64, struct{}](capacity)
238 warmupLRU(c, trace)
239 var worker atomic.Int64
240 b.ResetTimer()
241 b.RunParallel(func(pb *testing.PB) {
242 n := len(trace.Requests)
243 i := staggerStart(&worker, n)
244 for pb.Next() {
245 c.Get(trace.Requests[i%n].Key)
246 i++
247 }
248 })
249 })
250
251 b.Run(e.name+"/ARC", func(b *testing.B) {
252 c, _ := arc.NewARC[uint64, struct{}](capacity)
253 warmupARC(c, trace)
254 var worker atomic.Int64
255 b.ResetTimer()
256 b.RunParallel(func(pb *testing.PB) {
257 n := len(trace.Requests)
258 i := staggerStart(&worker, n)
259 for pb.Next() {
260 c.Get(trace.Requests[i%n].Key)
261 i++
262 }
263 })
264 })
265 }
266 }
267
268 // --- Parallel Replay Benchmarks ---
269 //
270 // BenchmarkParallelReplay measures the full get-or-insert path on a cold
271 // cache with no warmup. Each goroutine walks a trace-indexed ring.
272 // Complements BenchmarkParallelGet (warm-cache read-only): together they
273 // bracket the steady-state mix of read and write traffic.
274 //
275 // SIEVE uses Probe; LRU/ARC use the Get+Add idiom (see the helpers comment
276 // for why PeekOrAdd is the wrong fit for LRU).
277
278 func BenchmarkParallelReplay(b *testing.B) {
279 entries := discoverTraces(b)
280
281 for _, e := range entries {
282 trace := e.trace
283 capacity := trace.Unique / 10
284 if capacity < 1 {
285 capacity = 1
286 }
287
288 b.Run(e.name+"/SieveK1", func(b *testing.B) {
289 c := sieve.Must(sieve.New[uint64, struct{}](capacity))
290 var worker atomic.Int64
291 b.ResetTimer()
292 b.RunParallel(func(pb *testing.PB) {
293 n := len(trace.Requests)
294 i := staggerStart(&worker, n)
295 for pb.Next() {
296 c.Probe(trace.Requests[i%n].Key, struct{}{})
297 i++
298 }
299 })
300 })
301
302 b.Run(e.name+"/SieveK3", func(b *testing.B) {
303 c := sieve.Must(sieve.New[uint64, struct{}](capacity, sieve.WithVisitClamp(3)))
304 var worker atomic.Int64
305 b.ResetTimer()
306 b.RunParallel(func(pb *testing.PB) {
307 n := len(trace.Requests)
308 i := staggerStart(&worker, n)
309 for pb.Next() {
310 c.Probe(trace.Requests[i%n].Key, struct{}{})
311 i++
312 }
313 })
314 })
315
316 b.Run(e.name+"/LRU", func(b *testing.B) {
317 c, _ := lru.New[uint64, struct{}](capacity)
318 var worker atomic.Int64
319 b.ResetTimer()
320 b.RunParallel(func(pb *testing.PB) {
321 n := len(trace.Requests)
322 i := staggerStart(&worker, n)
323 for pb.Next() {
324 k := trace.Requests[i%n].Key
325 if _, ok := c.Get(k); !ok {
326 c.Add(k, struct{}{})
327 }
328 i++
329 }
330 })
331 })
332
333 b.Run(e.name+"/ARC", func(b *testing.B) {
334 c, _ := arc.NewARC[uint64, struct{}](capacity)
335 var worker atomic.Int64
336 b.ResetTimer()
337 b.RunParallel(func(pb *testing.PB) {
338 n := len(trace.Requests)
339 i := staggerStart(&worker, n)
340 for pb.Next() {
341 k := trace.Requests[i%n].Key
342 if _, ok := c.Get(k); !ok {
343 c.Add(k, struct{}{})
344 }
345 i++
346 }
347 })
348 })
349 }
350 }
351
352 // --- GC Pressure Test ---
353
354 func TestGCPressure(t *testing.T) {
355 entries := discoverTraces(t)
356 // Use first trace for GC test
357 trace := entries[0].trace
358 capacity := trace.Unique / 10
359 if capacity < 1 {
360 capacity = 1
361 }
362
363 type result struct {
364 name string
365 numGC uint32
366 pauseNs uint64
367 totalAlloc uint64
368 heapObjects uint64
369 }
370
371 runGCTest := func(name string, replay func()) result {
372 runtime.GC()
373 var before runtime.MemStats
374 runtime.ReadMemStats(&before)
375 replay()
376 runtime.GC()
377 var after runtime.MemStats
378 runtime.ReadMemStats(&after)
379 return result{
380 name: name,
381 numGC: after.NumGC - before.NumGC,
382 pauseNs: after.PauseTotalNs - before.PauseTotalNs,
383 totalAlloc: after.TotalAlloc - before.TotalAlloc,
384 heapObjects: after.HeapObjects,
385 }
386 }
387
388 t.Logf("Using trace: %s (%d requests, %d unique, cache %d)",
389 entries[0].name, len(trace.Requests), trace.Unique, capacity)
390
391 results := []result{
392 runGCTest("sieve-k1", func() {
393 c := sieve.Must(sieve.New[uint64, struct{}](capacity))
394 replayMisses(c, trace)
395 }),
396 runGCTest("sieve-k3", func() {
397 c := sieve.Must(sieve.New[uint64, struct{}](capacity, sieve.WithVisitClamp(3)))
398 replayMisses(c, trace)
399 }),
400 runGCTest("LRU", func() {
401 c, _ := lru.New[uint64, struct{}](capacity)
402 replayMissesLRU(c, trace)
403 }),
404 runGCTest("ARC", func() {
405 c, _ := arc.NewARC[uint64, struct{}](capacity)
406 replayMissesARC(c, trace)
407 }),
408 }
409
410 t.Logf("%-12s %8s %12s %14s %12s", "Variant", "NumGC", "PauseTotal", "TotalAlloc", "HeapObjects")
411 for _, r := range results {
412 t.Logf("%-12s %8d %10d us %12d KB %12d",
413 r.name, r.numGC, r.pauseNs/1000, r.totalAlloc/1024, r.heapObjects)
414 }
415 }
416
417 // --- Helpers ---
418 //
419 // SIEVE replay uses Probe() — a single call that inserts on miss and
420 // marks the visited bit on hit. It's the idiomatic API for the
421 // get-or-insert pattern a trace replay exercises.
422 //
423 // LRU and ARC use the Get+Add pattern. Their lookalikes (PeekOrAdd,
424 // ContainsOrAdd) deliberately skip the recency update on hit and would
425 // corrupt eviction order — so they are the wrong fit for a replay that
426 // preserves semantics.
427
428 func replayMisses(c *sieve.Sieve[uint64, struct{}], trace *bench.Trace[uint64]) int {
429 misses := 0
430 for _, r := range trace.Requests {
431 if _, _, res := c.Probe(r.Key, struct{}{}); !res.Hit() {
432 misses++
433 }
434 }
435 return misses
436 }
437
438 func replayMissesLRU(c *lru.Cache[uint64, struct{}], trace *bench.Trace[uint64]) int {
439 misses := 0
440 for _, r := range trace.Requests {
441 if _, ok := c.Get(r.Key); !ok {
442 c.Add(r.Key, struct{}{})
443 misses++
444 }
445 }
446 return misses
447 }
448
449 func replayMissesARC(c *arc.ARCCache[uint64, struct{}], trace *bench.Trace[uint64]) int {
450 misses := 0
451 for _, r := range trace.Requests {
452 if _, ok := c.Get(r.Key); !ok {
453 c.Add(r.Key, struct{}{})
454 misses++
455 }
456 }
457 return misses
458 }
459
460 func warmup(c *sieve.Sieve[uint64, struct{}], trace *bench.Trace[uint64]) {
461 for _, r := range trace.Requests {
462 c.Probe(r.Key, struct{}{})
463 }
464 }
465
466 func warmupLRU(c *lru.Cache[uint64, struct{}], trace *bench.Trace[uint64]) {
467 for _, r := range trace.Requests {
468 if _, ok := c.Get(r.Key); !ok {
469 c.Add(r.Key, struct{}{})
470 }
471 }
472 }
473
474 func warmupARC(c *arc.ARCCache[uint64, struct{}], trace *bench.Trace[uint64]) {
475 for _, r := range trace.Requests {
476 if _, ok := c.Get(r.Key); !ok {
477 c.Add(r.Key, struct{}{})
478 }
479 }
480 }