forked from RoaringBitmap/roaring
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsmat.go
More file actions
717 lines (638 loc) · 21.7 KB
/
smat.go
File metadata and controls
717 lines (638 loc) · 21.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
/*
# Instructions for smat testing for roaring
[smat](https://github.com/mschoch/smat) is a framework that provides
state machine assisted fuzz testing.
To run the smat tests for roaring...
## Prerequisites
Go 1.18 or later (for native fuzzing support).
## Steps
1. Generate initial smat corpus:
```
go test -tags=gofuzz -run=TestGenerateSmatCorpus
```
You should see a directory `workdir` created with initial corpus files.
2. Run the fuzz test:
```
go test -run='^$' -fuzz=FuzzSmat -fuzztime=300s -timeout=60s
```
Adjust `-fuzztime` as needed for longer or shorter runs. If crashes are found,
check the test output and the reproducer files in the `workdir` directory.
You may copy the reproducers to roaring_tests.go
*/
package roaring
import (
"encoding/base64"
"fmt"
"os"
"path/filepath"
"runtime/debug"
"slices"
"strings"
"time"
"github.com/bits-and-blooms/bitset"
"github.com/mschoch/smat"
)
// The native fuzz entry point lives in a _test.go file so the go test
// fuzz engine discovers it. See smat_fuzz_test.go for the fuzz wrapper.
var smatDebug = true
const max_value = 1048576
const max_pairs = 10
func smatLog(prefix, format string, args ...interface{}) {
if smatDebug {
fmt.Print(prefix)
fmt.Printf(format, args...)
}
}
type smatContext struct {
pairs []*smatPair
// Two registers, x & y.
x int
y int
actions int
// per-context last action for this fuzz worker
lastAction *actionRecord
}
// actionRecord stores a snapshot of the state just before an action runs.
type actionRecord struct {
Name string
X, Y int
PairSnapshots []string // base64-encoded MarshalBinary of each pair's Bitmap
}
type smatPair struct {
bm *Bitmap
bs *bitset.BitSet
// parent context (nil if unknown)
ctx *smatContext
}
// ------------------------------------------------------------------
var smatActionMap = smat.ActionMap{
smat.ActionID('X'): smatAction("x++", smatWrap(func(c *smatContext) { c.x = (c.x + 1) % max_value })),
smat.ActionID('x'): smatAction("x--", smatWrap(func(c *smatContext) { c.x = (c.x - 1 + max_value) % max_value })),
smat.ActionID('Y'): smatAction("y++", smatWrap(func(c *smatContext) { c.y = (c.y + 1) % max_value })),
smat.ActionID('y'): smatAction("y--", smatWrap(func(c *smatContext) { c.y = (c.y - 1 + max_value) % max_value })),
smat.ActionID('*'): smatAction("x*y", smatWrap(func(c *smatContext) { c.x = (c.x * c.y) % max_value })),
smat.ActionID('<'): smatAction("x<<", smatWrap(func(c *smatContext) { c.x = (c.x << 1) % max_value })),
smat.ActionID('^'): smatAction("swap", smatWrap(func(c *smatContext) { c.x, c.y = c.y, c.x })),
smat.ActionID('['): smatAction(" pushPair", smatWrap(smatPushPair)),
smat.ActionID(']'): smatAction(" popPair", smatWrap(smatPopPair)),
smat.ActionID('B'): smatAction(" setBit", smatWrap(smatSetBit)),
smat.ActionID('b'): smatAction(" removeBit", smatWrap(smatRemoveBit)),
smat.ActionID('o'): smatAction(" or", smatWrap(smatOr)),
smat.ActionID('a'): smatAction(" and", smatWrap(smatAnd)),
smat.ActionID('z'): smatAction(" xor", smatWrap(smatXor)),
smat.ActionID('#'): smatAction(" cardinality", smatWrap(smatCardinality)),
smat.ActionID('O'): smatAction(" orCardinality", smatWrap(smatOrCardinality)),
smat.ActionID('A'): smatAction(" andCardinality", smatWrap(smatAndCardinality)),
smat.ActionID('Z'): smatAction(" xorCardinality", smatWrap(smatXorCardinality)),
smat.ActionID('c'): smatAction(" clear", smatWrap(smatClear)),
smat.ActionID('r'): smatAction(" runOptimize", smatWrap(smatRunOptimize)),
smat.ActionID('e'): smatAction(" isEmpty", smatWrap(smatIsEmpty)),
smat.ActionID('i'): smatAction(" intersects", smatWrap(smatIntersects)),
smat.ActionID('f'): smatAction(" flip", smatWrap(smatFlip)),
smat.ActionID('-'): smatAction(" difference", smatWrap(smatDifference)),
}
var smatRunningPercentActions []smat.PercentAction
func init() {
var ids []int
for actionId := range smatActionMap {
ids = append(ids, int(actionId))
}
slices.Sort(ids)
pct := 100 / len(smatActionMap)
for _, actionId := range ids {
smatRunningPercentActions = append(smatRunningPercentActions,
smat.PercentAction{Percent: pct, Action: smat.ActionID(actionId)})
}
smatActionMap[smat.ActionID('S')] = smatAction("SETUP", smatSetupFunc)
smatActionMap[smat.ActionID('T')] = smatAction("TEARDOWN", smatTeardownFunc)
}
// We only have one smat state: running.
func smatRunning(next byte) smat.ActionID {
return smat.PercentExecute(next, smatRunningPercentActions...)
}
func smatAction(name string, f func(ctx smat.Context) (smat.State, error)) func(smat.Context) (smat.State, error) {
return func(ctx smat.Context) (smat.State, error) {
c := ctx.(*smatContext)
// Snapshot all pairs' bitmaps (base64 of MarshalBinary) before action
rec := actionRecord{Name: name, X: c.x, Y: c.y}
if len(c.pairs) > 0 {
rec.PairSnapshots = make([]string, 0, len(c.pairs))
for _, pair := range c.pairs {
if pair == nil || pair.bm == nil {
rec.PairSnapshots = append(rec.PairSnapshots, "<nil>")
continue
}
b, err := pair.bm.MarshalBinary()
if err != nil {
rec.PairSnapshots = append(rec.PairSnapshots, "<marshal-error:"+err.Error()+">")
} else {
rec.PairSnapshots = append(rec.PairSnapshots, base64.StdEncoding.EncodeToString(b))
}
}
}
// record per-context last action (no global mutex required)
if c != nil {
c.lastAction = &rec
}
// catch panics inside action to dump a repro and stack before re-panicking
defer func() {
if r := recover(); r != nil {
// best-effort: write quick repro with lastAction from context
var lastAction *actionRecord
if c != nil {
lastAction = c.lastAction
}
ts := time.Now().UnixNano()
repro := "// Reproducer generated by smat (panic)\n"
repro += "package roaring\n\n"
repro += "import (\n\t\"encoding/base64\"\n\t\"testing\"\n)\n\n"
repro += fmt.Sprintf("func TestFuzzerPanicRepro_%d(t *testing.T) {\n", ts)
// similar to checkEquals repro
if lastAction != nil && len(lastAction.PairSnapshots) > 0 {
pairIndex := lastAction.X % len(lastAction.PairSnapshots)
if pairIndex < len(lastAction.PairSnapshots) {
snapshot := lastAction.PairSnapshots[pairIndex]
if snapshot != "<nil>" && !strings.HasPrefix(snapshot, "<") {
repro += fmt.Sprintf("\tb, _ := base64.StdEncoding.DecodeString(\"%s\")\n", snapshot)
repro += "\tbm := NewBitmap()\n"
repro += "\tbm.UnmarshalBinary(b)\n"
// perform the action that caused panic
if strings.Contains(lastAction.Name, "setBit") {
repro += fmt.Sprintf("\tbm.AddInt(%d)\n", lastAction.Y)
} else if strings.Contains(lastAction.Name, "removeBit") {
repro += fmt.Sprintf("\tbm.Remove(%d)\n", lastAction.Y)
} else if strings.Contains(lastAction.Name, "flip") {
repro += fmt.Sprintf("\tbm.Flip(uint64(%d), uint64(%d)+1)\n", lastAction.Y, lastAction.Y)
} else if strings.Contains(lastAction.Name, "runOptimize") {
repro += "\tbm.RunOptimize()\n"
} else if strings.Contains(lastAction.Name, "clear") {
repro += "\tbm.Clear()\n"
} else if lastAction.Name == " or" {
pairIndexY := lastAction.Y % len(lastAction.PairSnapshots)
if pairIndexY < len(lastAction.PairSnapshots) {
snapshotY := lastAction.PairSnapshots[pairIndexY]
if snapshotY != "<nil>" && !strings.HasPrefix(snapshotY, "<") {
repro += fmt.Sprintf("\tb2, _ := base64.StdEncoding.DecodeString(\"%s\")\n", snapshotY)
repro += "\tbm2 := NewBitmap()\n"
repro += "\tbm2.UnmarshalBinary(b2)\n"
repro += "\tbm.Or(bm2)\n"
}
}
} else if lastAction.Name == " and" {
pairIndexY := lastAction.Y % len(lastAction.PairSnapshots)
if pairIndexY < len(lastAction.PairSnapshots) {
snapshotY := lastAction.PairSnapshots[pairIndexY]
if snapshotY != "<nil>" && !strings.HasPrefix(snapshotY, "<") {
repro += fmt.Sprintf("\tb2, _ := base64.StdEncoding.DecodeString(\"%s\")\n", snapshotY)
repro += "\tbm2 := NewBitmap()\n"
repro += "\tbm2.UnmarshalBinary(b2)\n"
repro += "\tbm.And(bm2)\n"
}
}
} else if lastAction.Name == " difference" {
pairIndexY := lastAction.Y % len(lastAction.PairSnapshots)
if pairIndexY < len(lastAction.PairSnapshots) {
snapshotY := lastAction.PairSnapshots[pairIndexY]
if snapshotY != "<nil>" && !strings.HasPrefix(snapshotY, "<") {
repro += fmt.Sprintf("\tb2, _ := base64.StdEncoding.DecodeString(\"%s\")\n", snapshotY)
repro += "\tbm2 := NewBitmap()\n"
repro += "\tbm2.UnmarshalBinary(b2)\n"
repro += "\tbm.AndNot(bm2)\n"
}
}
} else if lastAction.Name == " xor" {
pairIndexY := lastAction.Y % len(lastAction.PairSnapshots)
if pairIndexY < len(lastAction.PairSnapshots) {
snapshotY := lastAction.PairSnapshots[pairIndexY]
if snapshotY != "<nil>" && !strings.HasPrefix(snapshotY, "<") {
repro += fmt.Sprintf("\tb2, _ := base64.StdEncoding.DecodeString(\"%s\")\n", snapshotY)
repro += "\tbm2 := NewBitmap()\n"
repro += "\tbm2.UnmarshalBinary(b2)\n"
repro += "\tbm.Xor(bm2)\n"
}
}
} else {
repro += fmt.Sprintf("\t// Unhandled action: %s\n", lastAction.Name)
}
} else {
repro += "\t// invalid snapshot\n"
}
}
}
repro += "}\n"
if path, werr := saveReproFile("smat_panic_repro", ts, repro); werr == nil {
fmt.Printf("wrote panic repro to %s\n", path)
} else {
fmt.Printf("failed writing panic repro: %v\n", werr)
}
fmt.Printf("PANIC in action %s: %v\n", rec.Name, r)
fmt.Printf("stack:\n%s\n", debug.Stack())
panic(r)
}
}()
c.actions++
return f(ctx)
}
}
// saveReproFile writes the given repro content to workdir/<prefix>_<ts>_test.go
// or falls back to the OS temp dir. Returns full path or error.
func saveReproFile(prefix string, ts int64, content string) (string, error) {
// try workdir
if err := os.MkdirAll("workdir", 0o755); err == nil {
fname := fmt.Sprintf("workdir/%s_%d_test.go", prefix, ts)
if err := os.WriteFile(fname, []byte(content), 0o644); err == nil {
return fname, nil
}
}
// fallback to temp
tmp := os.TempDir()
fname := fmt.Sprintf("%s_%d_test.go", prefix, ts)
full := filepath.Join(tmp, fname)
if err := os.WriteFile(full, []byte(content), 0o644); err == nil {
return full, nil
} else {
return "", err
}
}
// Creates an smat action func based on a simple callback.
func smatWrap(cb func(c *smatContext)) func(smat.Context) (next smat.State, err error) {
return func(ctx smat.Context) (next smat.State, err error) {
c := ctx.(*smatContext)
cb(c)
return smatRunning, nil
}
}
// Invokes a callback function with the input v bounded to len(c.pairs).
func (c *smatContext) withPair(v int, cb func(*smatPair)) {
if len(c.pairs) > 0 {
if v < 0 {
v = -v
}
v = v % len(c.pairs)
cb(c.pairs[v])
}
}
// ------------------------------------------------------------------
func smatSetupFunc(ctx smat.Context) (next smat.State, err error) {
return smatRunning, nil
}
func smatTeardownFunc(ctx smat.Context) (next smat.State, err error) {
return nil, err
}
// ------------------------------------------------------------------
func smatPushPair(c *smatContext) {
if len(c.pairs) >= max_pairs {
return
}
p := &smatPair{
bm: NewBitmap(),
bs: bitset.New(100),
ctx: c,
}
c.pairs = append(c.pairs, p)
}
func smatPopPair(c *smatContext) {
if len(c.pairs) > 0 {
c.pairs = c.pairs[0 : len(c.pairs)-1]
}
}
func smatSetBit(c *smatContext) {
c.withPair(c.x, func(p *smatPair) {
p.Validate()
y := uint32(c.y)
p.bm.AddInt(int(y))
p.bs.Set(uint(y))
p.checkEquals()
})
}
func smatRemoveBit(c *smatContext) {
c.withPair(c.x, func(p *smatPair) {
p.Validate()
y := uint32(c.y)
p.bm.Remove(y)
p.bs.Clear(uint(y))
p.checkEquals()
})
}
func smatAnd(c *smatContext) {
c.withPair(c.x, func(px *smatPair) {
c.withPair(c.y, func(py *smatPair) {
px.Validate()
py.Validate()
px.bm.And(py.bm)
px.bs = px.bs.Intersection(py.bs)
px.checkEquals()
py.checkEquals()
})
})
}
func smatOr(c *smatContext) {
c.withPair(c.x, func(px *smatPair) {
c.withPair(c.y, func(py *smatPair) {
px.Validate()
py.Validate()
px.bm.Or(py.bm)
px.bs = px.bs.Union(py.bs)
px.checkEquals()
py.checkEquals()
})
})
}
func smatXor(c *smatContext) {
c.withPair(c.x, func(px *smatPair) {
c.withPair(c.y, func(py *smatPair) {
px.Validate()
py.Validate()
px.bm.Xor(py.bm)
px.bs = px.bs.SymmetricDifference(py.bs)
px.checkEquals()
py.checkEquals()
})
})
}
func smatAndCardinality(c *smatContext) {
c.withPair(c.x, func(px *smatPair) {
c.withPair(c.y, func(py *smatPair) {
px.Validate()
py.Validate()
c0 := px.bm.AndCardinality(py.bm)
c1 := px.bs.IntersectionCardinality(py.bs)
if c0 != uint64(c1) {
panic("expected same add cardinality")
}
px.checkEquals()
py.checkEquals()
})
})
}
func smatOrCardinality(c *smatContext) {
c.withPair(c.x, func(px *smatPair) {
c.withPair(c.y, func(py *smatPair) {
px.Validate()
py.Validate()
c0 := px.bm.OrCardinality(py.bm)
c1 := px.bs.UnionCardinality(py.bs)
if c0 != uint64(c1) {
panic("expected same or cardinality")
}
px.checkEquals()
py.checkEquals()
})
})
}
func smatXorCardinality(c *smatContext) {
c.withPair(c.x, func(px *smatPair) {
c.withPair(c.y, func(py *smatPair) {
px.Validate()
py.Validate()
c0 := px.bm.OrCardinality(py.bm) - px.bm.AndCardinality(py.bm)
c1 := px.bs.SymmetricDifferenceCardinality(py.bs)
if c0 != uint64(c1) {
panic("expected same xor cardinality")
}
px.checkEquals()
py.checkEquals()
})
})
}
func smatRunOptimize(c *smatContext) {
c.withPair(c.x, func(px *smatPair) {
px.Validate()
px.bm.RunOptimize()
px.checkEquals()
})
}
func smatClear(c *smatContext) {
c.withPair(c.x, func(px *smatPair) {
px.Validate()
px.bm.Clear()
px.bs = px.bs.ClearAll()
px.checkEquals()
})
}
func smatCardinality(c *smatContext) {
c.withPair(c.x, func(px *smatPair) {
c0 := px.bm.GetCardinality()
c1 := px.bs.Count()
if c0 != uint64(c1) {
panic("expected same cardinality")
}
})
}
func smatIsEmpty(c *smatContext) {
c.withPair(c.x, func(px *smatPair) {
c0 := px.bm.IsEmpty()
c1 := px.bs.None()
if c0 != c1 {
panic("expected same is empty")
}
})
}
func smatIntersects(c *smatContext) {
c.withPair(c.x, func(px *smatPair) {
c.withPair(c.y, func(py *smatPair) {
px.Validate()
py.Validate()
v0 := px.bm.Intersects(py.bm)
v1 := px.bs.IntersectionCardinality(py.bs) > 0
if v0 != v1 {
panic("intersects not equal")
}
px.checkEquals()
py.checkEquals()
})
})
}
func smatFlip(c *smatContext) {
c.withPair(c.x, func(p *smatPair) {
p.Validate()
y := uint32(c.y)
p.bm.Flip(uint64(y), uint64(y)+1)
p.bs = p.bs.Flip(uint(y))
p.checkEquals()
})
}
func smatDifference(c *smatContext) {
c.withPair(c.x, func(px *smatPair) {
c.withPair(c.y, func(py *smatPair) {
px.Validate()
py.Validate()
px.bm.AndNot(py.bm)
px.bs = px.bs.Difference(py.bs)
px.checkEquals()
py.checkEquals()
})
})
}
func (p *smatPair) checkEquals() {
valid := p.bm.Validate()
if valid != nil {
// marshal current bitmap
var curSnap string
if p != nil && p.bm != nil {
if b, err := p.bm.MarshalBinary(); err == nil {
curSnap = base64.StdEncoding.EncodeToString(b)
} else {
curSnap = "<marshal-error:" + err.Error() + ">"
}
} else {
curSnap = "<nil>"
}
// collect last action summary from context (per-worker)
last := "<none>"
if p != nil && p.ctx != nil {
c := p.ctx
if c.lastAction != nil {
last = fmt.Sprintf("action=%s x=%d y=%d pairs=%d", c.lastAction.Name, c.lastAction.X, c.lastAction.Y, len(c.lastAction.PairSnapshots))
}
}
// If debugging enabled, log extra info
smatLog("ERROR: ", "bitmap invalid: %v\n", valid)
// build a reproducible test snippet that reconstructs the bitmap and replays the failing action
ts := time.Now().UnixNano()
testName := fmt.Sprintf("TestFuzzerRepro_%d", ts)
repro := "// Reproducer generated by smat\n"
repro += "package roaring\n\n"
repro += "import (\n\t\"encoding/base64\"\n\t\"testing\"\n)\n\n"
repro += fmt.Sprintf("func %s(t *testing.T) {\n", testName)
var lastAction *actionRecord
if p != nil && p.ctx != nil {
lastAction = p.ctx.lastAction
}
// use the snapshot of the modified pair
if lastAction != nil && len(lastAction.PairSnapshots) > 0 {
// assume the modified pair is x % len(pairs), but since pairs are in order, and x is lastAction.X
pairIndex := lastAction.X % len(lastAction.PairSnapshots)
if pairIndex < len(lastAction.PairSnapshots) {
snapshot := lastAction.PairSnapshots[pairIndex]
if snapshot != "<nil>" && !strings.HasPrefix(snapshot, "<") {
repro += fmt.Sprintf("\tb, _ := base64.StdEncoding.DecodeString(\"%s\")\n", snapshot)
repro += "\tbm := NewBitmap()\n"
repro += "\tbm.UnmarshalBinary(b)\n"
repro += "\tif err := bm.Validate(); err != nil {\n"
repro += "\t\tt.Errorf(\"Initial Validate failed: %v\", err)\n"
repro += "\t}\n"
// perform the action
if strings.Contains(lastAction.Name, "setBit") {
repro += fmt.Sprintf("\tbm.AddInt(%d)\n", lastAction.Y)
} else if strings.Contains(lastAction.Name, "removeBit") {
repro += fmt.Sprintf("\tbm.Remove(%d)\n", lastAction.Y)
} else if strings.Contains(lastAction.Name, "flip") {
repro += fmt.Sprintf("\tbm.Flip(uint64(%d), uint64(%d)+1)\n", lastAction.Y, lastAction.Y)
} else if strings.Contains(lastAction.Name, "runOptimize") {
repro += "\tbm.RunOptimize()\n"
} else if strings.Contains(lastAction.Name, "clear") {
repro += "\tbm.Clear()\n"
} else if lastAction.Name == " or" {
pairIndexY := lastAction.Y % len(lastAction.PairSnapshots)
if pairIndexY < len(lastAction.PairSnapshots) {
snapshotY := lastAction.PairSnapshots[pairIndexY]
if snapshotY != "<nil>" && !strings.HasPrefix(snapshotY, "<") {
repro += fmt.Sprintf("\tb2, _ := base64.StdEncoding.DecodeString(\"%s\")\n", snapshotY)
repro += "\tbm2 := NewBitmap()\n"
repro += "\tbm2.UnmarshalBinary(b2)\n"
repro += "\tbm.Or(bm2)\n"
}
}
} else if lastAction.Name == " and" {
pairIndexY := lastAction.Y % len(lastAction.PairSnapshots)
if pairIndexY < len(lastAction.PairSnapshots) {
snapshotY := lastAction.PairSnapshots[pairIndexY]
if snapshotY != "<nil>" && !strings.HasPrefix(snapshotY, "<") {
repro += fmt.Sprintf("\tb2, _ := base64.StdEncoding.DecodeString(\"%s\")\n", snapshotY)
repro += "\tbm2 := NewBitmap()\n"
repro += "\tbm2.UnmarshalBinary(b2)\n"
repro += "\tbm.And(bm2)\n"
}
}
} else if lastAction.Name == " difference" {
pairIndexY := lastAction.Y % len(lastAction.PairSnapshots)
if pairIndexY < len(lastAction.PairSnapshots) {
snapshotY := lastAction.PairSnapshots[pairIndexY]
if snapshotY != "<nil>" && !strings.HasPrefix(snapshotY, "<") {
repro += fmt.Sprintf("\tb2, _ := base64.StdEncoding.DecodeString(\"%s\")\n", snapshotY)
repro += "\tbm2 := NewBitmap()\n"
repro += "\tbm2.UnmarshalBinary(b2)\n"
repro += "\tbm.AndNot(bm2)\n"
}
}
} else if lastAction.Name == " xor" {
pairIndexY := lastAction.Y % len(lastAction.PairSnapshots)
if pairIndexY < len(lastAction.PairSnapshots) {
snapshotY := lastAction.PairSnapshots[pairIndexY]
if snapshotY != "<nil>" && !strings.HasPrefix(snapshotY, "<") {
repro += fmt.Sprintf("\tb2, _ := base64.StdEncoding.DecodeString(\"%s\")\n", snapshotY)
repro += "\tbm2 := NewBitmap()\n"
repro += "\tbm2.UnmarshalBinary(b2)\n"
repro += "\tbm.Xor(bm2)\n"
}
}
} else {
repro += fmt.Sprintf("\t// Unhandled action: %s\n", lastAction.Name)
}
repro += "\tif err := bm.Validate(); err != nil {\n"
repro += "\t\tt.Errorf(\"Validate failed: %v\", err)\n"
repro += "\t} else {\n"
repro += "\t\tt.Logf(\"Validate succeeded\")\n"
repro += "\t}\n"
} else {
repro += "\t// invalid snapshot\n"
}
}
}
repro += "}\n"
// print the repro snippet for the developer
fmt.Println()
fmt.Println("=== SMAT REPRODUCER SNIPPET ===")
if len(repro) > 10000 {
fmt.Println("// Reproducer too large, skipping full print")
} else {
fmt.Println(repro)
}
// also write the repro snippet to a timestamped file in workdir/
if len(repro) > 10000 {
repro = "// Reproducer too large, skipping\n"
}
if err := os.MkdirAll("workdir", 0o755); err == nil {
fname := fmt.Sprintf("workdir/smat_repro_%d_test.go", ts)
if werr := os.WriteFile(fname, []byte(repro), 0o644); werr == nil {
fmt.Printf("Wrote repro to %s\n", fname)
} else {
fmt.Printf("Failed writing repro file: %v\n", werr)
}
} else {
fmt.Printf("Failed creating workdir: %v\n", err)
}
panic(fmt.Sprintf("[checkEquals] bitmap invalid: %v\ncurrentBase64:%s\nlastAction:%s\n", valid, curSnap, last))
}
if !p.equalsBitSet(p.bs, p.bm) {
panic("bitset mismatch")
}
}
func (p *smatPair) Validate() {
valid := p.bm.Validate()
if valid != nil {
panic(fmt.Sprintf("[Validate] bitmap invalid: %v", valid))
}
}
func (p *smatPair) equalsBitSet(a *bitset.BitSet, b *Bitmap) bool {
for i, e := a.NextSet(0); e; i, e = a.NextSet(i + 1) {
if !b.ContainsInt(int(i)) {
fmt.Printf("in a bitset, not b bitmap, i: %d\n", i)
fmt.Printf(" a bitset: %s\n b bitmap: %s\n",
a.String(), b.String())
return false
}
}
i := b.Iterator()
for i.HasNext() {
v := i.Next()
if !a.Test(uint(v)) {
fmt.Printf("in b bitmap, not a bitset, v: %d\n", v)
fmt.Printf(" a bitset: %s\n b bitmap: %s\n",
a.String(), b.String())
return false
}
}
return true
}