storage: track WAL materialization geometry

This commit is contained in:
pingqiu committed 2026-07-30 05:01:00 -07:00
1 parent eb03eae474
commit f230748599
12 files changed
+1037 -24

No files matched your search

+26 -7
View File
@@ -3,10 +3,11 @@ package storage
import "sync"
// dirtyEntry tracks where a single LBA's most recent value lives in
// the WAL — used by readers to fetch unflushed data and by the
// flusher to apply WAL records to the extent region.
// the WAL. recordSize is the exact encoded record geometry reconstructed
// from the append or recovery path; on-disk bytes remain authoritative.
type dirtyEntry struct {
walOffset uint64
recordSize uint64
dataOffset uint32
lsn uint64
length uint32
@@ -44,14 +45,26 @@ func newDirtyMap(numShards int) *dirtyMap {
func (d *dirtyMap) shard(lba uint64) *dirtyShard { return &d.shards[lba&d.mask] }
func (d *dirtyMap) put(lba, walOffset, lsn uint64, length uint32) {
d.putAt(lba, walOffset, 0, lsn, length)
func (d *dirtyMap) put(lba, walOffset, lsn uint64, length uint32, recordSize uint64) {
d.putAt(lba, walOffset, 0, lsn, length, recordSize)
}
func (d *dirtyMap) putAt(lba, walOffset uint64, dataOffset uint32, lsn uint64, length uint32) {
func (d *dirtyMap) putAt(
lba, walOffset uint64,
dataOffset uint32,
lsn uint64,
length uint32,
recordSize uint64,
) {
s := d.shard(lba)
s.mu.Lock()
s.m[lba] = dirtyEntry{walOffset: walOffset, dataOffset: dataOffset, lsn: lsn, length: length}
s.m[lba] = dirtyEntry{
walOffset: walOffset,
recordSize: recordSize,
dataOffset: dataOffset,
lsn: lsn,
length: length,
}
s.mu.Unlock()
}
@@ -102,6 +115,7 @@ func (d *dirtyMap) compareAndDelete(lba, expectedLSN uint64) bool {
type snapshotEntry struct {
LBA uint64
WALOffset uint64
RecordSize uint64
DataOffset uint32
LSN uint64
Length uint32
@@ -118,7 +132,12 @@ func (d *dirtyMap) snapshot() []snapshotEntry {
s.mu.RLock()
for lba, e := range s.m {
out = append(out, snapshotEntry{
LBA: lba, WALOffset: e.walOffset, DataOffset: e.dataOffset, LSN: e.lsn, Length: e.length,
LBA: lba,
WALOffset: e.walOffset,
RecordSize: e.recordSize,
DataOffset: e.dataOffset,
LSN: e.lsn,
Length: e.length,
})
}
s.mu.RUnlock()
+17 -2
View File
@@ -339,8 +339,23 @@ func (f *flusher) readDirtyRecord(e snapshotEntry) (data []byte, entrySize uint6
}
return entry.Data[start:end], entrySize, nil
case walEntryTrim:
if entry.LSN != e.LSN || entry.LBA != e.LBA || e.DataOffset != 0 ||
e.Length != blockSize {
trimBlocks := uint64(1)
if entry.Length > 0 {
if entry.Length%blockSize != 0 {
return nil, 0, fmt.Errorf(
"flusher: invalid dirty WAL trim LBA %d offset %d length %d",
e.LBA, e.WALOffset, entry.Length)
}
trimBlocks = uint64(entry.Length / blockSize)
}
if e.DataOffset%blockSize != 0 || e.Length != blockSize {
return nil, 0, fmt.Errorf(
"flusher: invalid dirty WAL trim LBA %d offset %d",
e.LBA, e.WALOffset)
}
blockIndex := uint64(e.DataOffset / blockSize)
if entry.LSN != e.LSN || blockIndex >= trimBlocks ||
entry.LBA+blockIndex != e.LBA {
return nil, 0, fmt.Errorf(
"flusher: WAL slot mismatch trim LBA %d offset %d dirty LSN %d record LSN %d",
e.LBA, e.WALOffset, e.LSN, entry.LSN)
@@ -18,6 +18,8 @@ type FlusherInstrumentationStatus struct {
CycleDurationNanos uint64
CycleMaxDurationNanos uint64
SnapshotEntries uint64
SnapshotUniqueWALRecords uint64
SnapshotRecordReuseCandidates uint64
SnapshotDurationNanos uint64
OpportunityAnalysisNanos uint64
SnapshotBoundedWriteMinimum uint64
@@ -41,6 +43,9 @@ type FlusherInstrumentationStatus struct {
WALRecordReadFailures uint64
WALRecordReadBytes uint64
WALRecordReadDurationNanos uint64
MaterializationReadOps uint64
MaterializationReadBytes uint64
MaterializationRecordReuseHits uint64
ExtentWriteOps uint64
ExtentWriteFailures uint64
ExtentWriteBytes uint64
@@ -65,6 +70,8 @@ type flusherInstrumentation struct {
cycleDurationNanos atomic.Uint64
cycleMaxDurationNanos atomic.Uint64
snapshotEntries atomic.Uint64
snapshotUniqueWALRecords atomic.Uint64
snapshotRecordReuseCandidates atomic.Uint64
snapshotDurationNanos atomic.Uint64
opportunityAnalysisNanos atomic.Uint64
snapshotBoundedWriteMinimum atomic.Uint64
@@ -88,6 +95,7 @@ type flusherInstrumentation struct {
walRecordReadFailures atomic.Uint64
walRecordReadBytes atomic.Uint64
walRecordReadDurationNanos atomic.Uint64
materializationRecordReuseHits atomic.Uint64
extentWriteOps atomic.Uint64
extentWriteFailures atomic.Uint64
extentWriteBytes atomic.Uint64
@@ -116,7 +124,10 @@ func (i *flusherInstrumentation) recordCycle(
i.snapshotDurationNanos.Add(storageDurationNanos(snapshotDuration))
opportunityStart := time.Now()
opportunity := boundedExtentWriteOpportunity(entries, blockSize)
recordShape := walRecordMaterializationShape(entries)
i.opportunityAnalysisNanos.Add(storageDurationNanos(time.Since(opportunityStart)))
i.snapshotUniqueWALRecords.Add(recordShape.uniqueRecords)
i.snapshotRecordReuseCandidates.Add(recordShape.reuseCandidates)
i.snapshotBoundedWriteMinimum.Add(opportunity.minimumOps)
i.snapshotRunCount.Add(opportunity.runCount)
i.snapshotSingletonRuns.Add(opportunity.singletonRuns)
@@ -134,6 +145,27 @@ func (i *flusherInstrumentation) recordCycle(
}
}
type walRecordShape struct {
uniqueRecords uint64
reuseCandidates uint64
}
func walRecordMaterializationShape(entries []snapshotEntry) walRecordShape {
type identity struct {
offset uint64
size uint64
}
records := make(map[identity]struct{}, len(entries))
for _, entry := range entries {
records[identity{offset: entry.WALOffset, size: entry.RecordSize}] = struct{}{}
}
uniqueRecords := uint64(len(records))
return walRecordShape{
uniqueRecords: uniqueRecords,
reuseCandidates: uint64(len(entries)) - uniqueRecords,
}
}
func (i *flusherInstrumentation) recordWrittenOpportunity(entries []snapshotEntry, blockSize uint32) {
opportunityStart := time.Now()
opportunity := boundedExtentWriteOpportunity(entries, blockSize)
@@ -218,6 +250,10 @@ func (i *flusherInstrumentation) recordSupersededEntry() {
i.supersededEntries.Add(1)
}
func (i *flusherInstrumentation) recordMaterializationReuseHit() {
i.materializationRecordReuseHits.Add(1)
}
func (i *flusherInstrumentation) recordExtentWrite(bytes int, duration time.Duration, err error) {
value := uint64(bytes)
i.extentWriteOps.Add(1)
@@ -266,6 +302,10 @@ func updateAtomicMax(target *atomic.Uint64, value uint64) {
}
func (i *flusherInstrumentation) snapshot() FlusherInstrumentationStatus {
walHeaderReadOps := i.walHeaderReadOps.Load()
walHeaderReadBytes := i.walHeaderReadBytes.Load()
walRecordReadOps := i.walRecordReadOps.Load()
walRecordReadBytes := i.walRecordReadBytes.Load()
return FlusherInstrumentationStatus{
CyclesStarted: i.cyclesStarted.Load(),
CyclesSucceeded: i.cyclesSucceeded.Load(),
@@ -273,6 +313,8 @@ func (i *flusherInstrumentation) snapshot() FlusherInstrumentationStatus {
CycleDurationNanos: i.cycleDurationNanos.Load(),
CycleMaxDurationNanos: i.cycleMaxDurationNanos.Load(),
SnapshotEntries: i.snapshotEntries.Load(),
SnapshotUniqueWALRecords: i.snapshotUniqueWALRecords.Load(),
SnapshotRecordReuseCandidates: i.snapshotRecordReuseCandidates.Load(),
SnapshotDurationNanos: i.snapshotDurationNanos.Load(),
OpportunityAnalysisNanos: i.opportunityAnalysisNanos.Load(),
SnapshotBoundedWriteMinimum: i.snapshotBoundedWriteMinimum.Load(),
@@ -288,14 +330,17 @@ func (i *flusherInstrumentation) snapshot() FlusherInstrumentationStatus {
ValidatedRecords: i.validatedRecords.Load(),
ValidationFailures: i.validationFailures.Load(),
SupersededEntries: i.supersededEntries.Load(),
WALHeaderReadOps: i.walHeaderReadOps.Load(),
WALHeaderReadOps: walHeaderReadOps,
WALHeaderReadFailures: i.walHeaderReadFailures.Load(),
WALHeaderReadBytes: i.walHeaderReadBytes.Load(),
WALHeaderReadBytes: walHeaderReadBytes,
WALHeaderReadDurationNanos: i.walHeaderReadDurationNanos.Load(),
WALRecordReadOps: i.walRecordReadOps.Load(),
WALRecordReadOps: walRecordReadOps,
WALRecordReadFailures: i.walRecordReadFailures.Load(),
WALRecordReadBytes: i.walRecordReadBytes.Load(),
WALRecordReadBytes: walRecordReadBytes,
WALRecordReadDurationNanos: i.walRecordReadDurationNanos.Load(),
MaterializationReadOps: walHeaderReadOps + walRecordReadOps,
MaterializationReadBytes: walHeaderReadBytes + walRecordReadBytes,
MaterializationRecordReuseHits: i.materializationRecordReuseHits.Load(),
ExtentWriteOps: i.extentWriteOps.Load(),
ExtentWriteFailures: i.extentWriteFailures.Load(),
ExtentWriteBytes: i.extentWriteBytes.Load(),
@@ -61,10 +61,24 @@ func TestFlusherInstrumentationCountsCompleteCycle(t *testing.T) {
t.Fatalf("snapshot/validated/superseded=%d/%d/%d want 4/4/0",
got.SnapshotEntries, got.ValidatedRecords, got.SupersededEntries)
}
if got.SnapshotUniqueWALRecords != 4 || got.SnapshotRecordReuseCandidates != 0 {
t.Fatalf("unique/reuse-opportunities=%d/%d want 4/0",
got.SnapshotUniqueWALRecords, got.SnapshotRecordReuseCandidates)
}
if got.WALHeaderReadOps != 4 || got.WALRecordReadOps != 4 {
t.Fatalf("header/record reads=%d/%d want 4/4",
got.WALHeaderReadOps, got.WALRecordReadOps)
}
if got.MaterializationReadOps != 8 ||
got.MaterializationReadBytes != 4*walEntryHeaderSize+4*(walEntryHeaderSize+4096) {
t.Fatalf("materialization reads/bytes=%d/%d want 8/%d",
got.MaterializationReadOps, got.MaterializationReadBytes,
4*walEntryHeaderSize+4*(walEntryHeaderSize+4096))
}
if got.MaterializationRecordReuseHits != 0 {
t.Fatalf("materialization reuse hits=%d want 0 on default path",
got.MaterializationRecordReuseHits)
}
if got.ExtentWriteOps != 4 || got.ExtentWriteBytes != 4*4096 ||
got.ExtentWriteMaxBytes != 4096 || got.ExtentWriteFailures != 0 {
t.Fatalf("extent ops/bytes/max/failures=%d/%d/%d/%d want 4/%d/4096/0",
@@ -139,6 +153,82 @@ func TestFlusherInstrumentationSeparatesSnapshotAndWrittenOpportunity(t *testing
}
}
func TestFlusherInstrumentationCountsWALRecordMaterializationShape(t *testing.T) {
entries := []snapshotEntry{
{LBA: 0, WALOffset: 100, RecordSize: 8230},
{LBA: 1, WALOffset: 100, RecordSize: 8230},
{LBA: 2, WALOffset: 100, RecordSize: 8230},
{LBA: 9, WALOffset: 900, RecordSize: 4134},
}
var instr flusherInstrumentation
finish := instr.recordCycle(time.Now(), time.Nanosecond, entries, 4096)
instr.recordWALHeaderRead(walEntryHeaderSize, time.Nanosecond, nil)
instr.recordWALRecordRead(4134, time.Nanosecond, nil)
instr.recordMaterializationReuseHit()
finish(true)
got := instr.snapshot()
if got.SnapshotEntries != 4 ||
got.SnapshotUniqueWALRecords != 2 ||
got.SnapshotRecordReuseCandidates != 2 {
t.Fatalf("entries/unique/reuse-opportunities=%d/%d/%d want 4/2/2",
got.SnapshotEntries, got.SnapshotUniqueWALRecords,
got.SnapshotRecordReuseCandidates)
}
if got.MaterializationReadOps != 2 ||
got.MaterializationReadBytes != walEntryHeaderSize+4134 {
t.Fatalf("materialization reads/bytes=%d/%d want 2/%d",
got.MaterializationReadOps, got.MaterializationReadBytes,
walEntryHeaderSize+4134)
}
if got.MaterializationRecordReuseHits != 1 {
t.Fatalf("materialization reuse hits=%d want 1", got.MaterializationRecordReuseHits)
}
}
func TestFlusherInstrumentationExposesCurrentDuplicateReadsForSharedRecord(t *testing.T) {
s, err := CreateWALStore(filepath.Join(t.TempDir(), "store.bin"), 16, 4096)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = s.Close() })
s.DisableAutoFlushForRecoveryTest()
s.enableMultiBlockRecordsForTest(true)
if _, err := s.WriteBatch(3, [][]byte{
makeBlock(4096, 0x81),
makeBlock(4096, 0x82),
makeBlock(4096, 0x83),
}); err != nil {
t.Fatal(err)
}
if _, err := s.Sync(); err != nil {
t.Fatal(err)
}
if err := s.flusher.flushOnce(); err != nil {
t.Fatal(err)
}
got := s.FlusherInstrumentation()
if got.SnapshotEntries != 3 ||
got.SnapshotUniqueWALRecords != 1 ||
got.SnapshotRecordReuseCandidates != 2 {
t.Fatalf("entries/unique/reuse-opportunities=%d/%d/%d want 3/1/2",
got.SnapshotEntries, got.SnapshotUniqueWALRecords,
got.SnapshotRecordReuseCandidates)
}
if got.WALHeaderReadOps != 3 || got.WALRecordReadOps != 3 ||
got.MaterializationReadOps != 6 {
t.Fatalf("header/record/materialization reads=%d/%d/%d want 3/3/6",
got.WALHeaderReadOps, got.WALRecordReadOps,
got.MaterializationReadOps)
}
if got.MaterializationRecordReuseHits != 0 {
t.Fatalf("materialization reuse hits=%d want 0 before D3",
got.MaterializationRecordReuseHits)
}
}
func TestFlusherInstrumentationCountsCheckpointFailure(t *testing.T) {
tests := []struct {
name string
+12 -3
View File
@@ -119,7 +119,10 @@ func recoverWAL(fd *os.File, sb *superblock, dm *dirtyMap) (recoveryResult, erro
case walEntryWrite:
blocks := entry.Length / sb.BlockSize
for i := uint32(0); i < blocks; i++ {
dm.putAt(entry.LBA+uint64(i), pos, i*sb.BlockSize, entry.LSN, sb.BlockSize)
dm.putAt(
entry.LBA+uint64(i), pos, i*sb.BlockSize,
entry.LSN, sb.BlockSize, entrySize,
)
}
result.EntriesReplayed++
case walEntryWriteBatch:
@@ -133,7 +136,10 @@ func recoverWAL(fd *os.File, sb *superblock, dm *dirtyMap) (recoveryResult, erro
if lsn <= checkpointLSN {
continue
}
dm.putAt(entry.LBA+uint64(i), pos, i*sb.BlockSize, lsn, sb.BlockSize)
dm.putAt(
entry.LBA+uint64(i), pos, i*sb.BlockSize,
lsn, sb.BlockSize, entrySize,
)
}
result.EntriesReplayed++
case walEntryTrim:
@@ -142,7 +148,10 @@ func recoverWAL(fd *os.File, sb *superblock, dm *dirtyMap) (recoveryResult, erro
blocks = 1
}
for i := uint32(0); i < blocks; i++ {
dm.put(entry.LBA+uint64(i), pos, entry.LSN, sb.BlockSize)
dm.putAt(
entry.LBA+uint64(i), pos, i*sb.BlockSize,
entry.LSN, sb.BlockSize, entrySize,
)
}
result.EntriesReplayed++
case walEntryBarrier:
+15 -6
View File
@@ -470,7 +470,10 @@ func (s *WALStore) Write(lba uint32, data []byte) (uint64, error) {
return 0, fmt.Errorf("storage: WAL append: %w", err)
}
dirtyStart := time.Now()
s.dm.put(uint64(lba), walRelOff, lsn, uint32(len(data)))
s.dm.put(
uint64(lba), walRelOff, lsn, uint32(len(data)),
uint64(walEntryHeaderSize+len(data)),
)
s.instr.recordDirtyMapUpdate(1, time.Since(dirtyStart))
s.nextLSN++
@@ -543,7 +546,10 @@ func (s *WALStore) WriteBatch(startLBA uint32, blocks [][]byte) ([]uint64, error
}
dirtyStart := time.Now()
for i, walRelOff := range offsets {
s.dm.put(uint64(startLBA+uint32(i)), walRelOff, lsns[i], uint32(len(blocks[i])))
s.dm.put(
uint64(startLBA+uint32(i)), walRelOff, lsns[i], uint32(len(blocks[i])),
uint64(walEntryHeaderSize+len(blocks[i])),
)
}
s.instr.recordDirtyMapUpdate(len(offsets), time.Since(dirtyStart))
@@ -594,6 +600,7 @@ func (s *WALStore) writeBatchMultiBlockLocked(startLBA uint32, blocks [][]byte,
uint32(i*int(s.sb.BlockSize)),
lsn,
uint32(len(data)),
uint64(walEntryHeaderSize+len(payload)),
)
}
s.instr.recordDirtyMapUpdate(len(blocks), time.Since(dirtyStart))
@@ -642,11 +649,10 @@ func (s *WALStore) readFromWAL(walRelOff uint64, dataOffset uint32) ([]byte, err
if _, err := s.fd.ReadAt(headerBuf, absOff); err != nil {
return nil, fmt.Errorf("storage: WAL read header: %w", err)
}
length := parseLengthFromHeader(headerBuf)
if length == 0 {
// Trim entry — return zeros, same as a never-written LBA.
if headerBuf[16] == walEntryTrim {
return make([]byte, s.sb.BlockSize), nil
}
length := parseLengthFromHeader(headerBuf)
if dataOffset >= length {
return nil, fmt.Errorf("storage: WAL read data offset %d >= length %d", dataOffset, length)
}
@@ -932,7 +938,10 @@ func (s *WALStore) ApplyEntry(lba uint32, data []byte, lsn uint64) error {
if err != nil {
return fmt.Errorf("storage: WAL append (apply): %w", err)
}
s.dm.put(uint64(lba), walRelOff, lsn, uint32(len(dataCopy)))
s.dm.put(
uint64(lba), walRelOff, lsn, uint32(len(dataCopy)),
uint64(walEntryHeaderSize+len(dataCopy)),
)
s.mu.Lock()
defer s.mu.Unlock()
@@ -131,12 +131,21 @@ func benchmarkWALStoreContention(b *testing.B, lbaForIndex func(int, int) uint32
b, s, status, flusherStatus, uint64(b.N), 1,
foregroundDuration, syncDuration, drainDuration,
)
b.ReportMetric(0, "multi_block_records")
b.ReportMetric(float64(b.N)/foregroundDuration.Seconds(), "write_ops/s")
})
}
}
func BenchmarkPhase170WALStoreBatchContention(b *testing.B) {
benchmarkWALStoreBatchContention(b, false)
}
func BenchmarkPhase172WALStoreMultiBlockContention(b *testing.B) {
benchmarkWALStoreBatchContention(b, true)
}
func benchmarkWALStoreBatchContention(b *testing.B, multiBlockRecords bool) {
const (
blockSize = 4096
numBlocks = 16384
@@ -149,6 +158,7 @@ func BenchmarkPhase170WALStoreBatchContention(b *testing.B) {
b.Fatal(err)
}
b.Cleanup(func() { _ = s.Close() })
s.enableMultiBlockRecordsForTest(multiBlockRecords)
b.ReportAllocs()
data := make([][][]byte, writers)
@@ -223,6 +233,11 @@ func BenchmarkPhase170WALStoreBatchContention(b *testing.B) {
foregroundDuration, syncDuration, drainDuration,
)
b.ReportMetric(batchBlocks, "batch_blocks")
if multiBlockRecords {
b.ReportMetric(1, "multi_block_records")
} else {
b.ReportMetric(0, "multi_block_records")
}
b.ReportMetric(float64(logicalEntries)/foregroundDuration.Seconds(), "block_ops/s")
})
}
@@ -252,6 +267,18 @@ func reportWALStoreContentionMetrics(
}
return float64(total) / float64(logicalEntries)
}
perValidatedRecord := func(total uint64) float64 {
if flusherStatus.ValidatedRecords == 0 {
return 0
}
return float64(total) / float64(flusherStatus.ValidatedRecords)
}
perSnapshotEntry := func(total uint64) float64 {
if flusherStatus.SnapshotEntries == 0 {
return 0
}
return float64(total) / float64(flusherStatus.SnapshotEntries)
}
_, _, headLSN := s.Boundaries()
checkpointLSN := s.CheckpointLSN()
@@ -279,19 +306,29 @@ func reportWALStoreContentionMetrics(
b.ReportMetric(float64(syncDuration.Nanoseconds()), "final_sync_ns")
b.ReportMetric(float64(drainDuration.Nanoseconds()), "final_drain_ns")
b.ReportMetric(perEntry(flusherStatus.SnapshotEntries), "flush_snapshot_entries/entry")
b.ReportMetric(perEntry(flusherStatus.SnapshotUniqueWALRecords), "flush_unique_wal_records/entry")
b.ReportMetric(perEntry(flusherStatus.SnapshotRecordReuseCandidates), "flush_record_reuse_opportunities/entry")
b.ReportMetric(perSnapshotEntry(flusherStatus.SnapshotUniqueWALRecords), "flush_unique_wal_records/snapshot_entry")
b.ReportMetric(perSnapshotEntry(flusherStatus.SnapshotRecordReuseCandidates), "flush_record_reuse_opportunities/snapshot_entry")
b.ReportMetric(perEntry(flusherStatus.SnapshotDurationNanos), "flush_snapshot_ns/entry")
b.ReportMetric(perEntry(flusherStatus.OpportunityAnalysisNanos), "flush_opportunity_ns/entry")
b.ReportMetric(perEntry(flusherStatus.ValidatedRecords), "flush_validated_records/entry")
b.ReportMetric(float64(flusherStatus.ValidationFailures), "flush_validation_failures")
b.ReportMetric(perEntry(flusherStatus.SupersededEntries), "flush_superseded_entries/entry")
b.ReportMetric(perEntry(flusherStatus.WALHeaderReadOps), "flush_header_reads/entry")
b.ReportMetric(perValidatedRecord(flusherStatus.WALHeaderReadOps), "flush_header_reads/validated_record")
b.ReportMetric(float64(flusherStatus.WALHeaderReadFailures), "flush_header_read_failures")
b.ReportMetric(perEntry(flusherStatus.WALHeaderReadBytes), "flush_header_read_bytes/entry")
b.ReportMetric(perEntry(flusherStatus.WALHeaderReadDurationNanos), "flush_header_read_ns/entry")
b.ReportMetric(perEntry(flusherStatus.WALRecordReadOps), "flush_record_reads/entry")
b.ReportMetric(perValidatedRecord(flusherStatus.WALRecordReadOps), "flush_record_reads/validated_record")
b.ReportMetric(float64(flusherStatus.WALRecordReadFailures), "flush_record_read_failures")
b.ReportMetric(perEntry(flusherStatus.WALRecordReadBytes), "flush_record_read_bytes/entry")
b.ReportMetric(perEntry(flusherStatus.WALRecordReadDurationNanos), "flush_record_read_ns/entry")
b.ReportMetric(perEntry(flusherStatus.MaterializationReadOps), "flush_materialization_reads/entry")
b.ReportMetric(perValidatedRecord(flusherStatus.MaterializationReadOps), "flush_materialization_reads/validated_record")
b.ReportMetric(perEntry(flusherStatus.MaterializationReadBytes), "flush_materialization_read_bytes/entry")
b.ReportMetric(perValidatedRecord(flusherStatus.MaterializationRecordReuseHits), "flush_record_reuse_hits/validated_record")
b.ReportMetric(perEntry(flusherStatus.ExtentWriteOps), "extent_write_ops/entry")
b.ReportMetric(float64(flusherStatus.ExtentWriteFailures), "extent_write_failures")
b.ReportMetric(perEntry(flusherStatus.ExtentWriteBytes), "extent_write_bytes/entry")
@@ -113,10 +113,10 @@ func (r *WALStoreReader) readFromWAL(walRelOff uint64, dataOffset uint32) ([]byt
if _, err := r.fd.ReadAt(headerBuf, absOff); err != nil {
return nil, fmt.Errorf("storage: OpenReadOnly WAL header: %w", err)
}
length := parseLengthFromHeader(headerBuf)
if length == 0 {
if headerBuf[16] == walEntryTrim {
return make([]byte, r.sb.BlockSize), nil
}
length := parseLengthFromHeader(headerBuf)
if dataOffset >= length {
return nil, fmt.Errorf("storage: OpenReadOnly WAL data offset %d >= length %d", dataOffset, length)
}
@@ -0,0 +1,400 @@
package storage
import (
"bytes"
"os"
"path/filepath"
"testing"
)
func TestDirtyMapSnapshotCarriesRecordGeometry(t *testing.T) {
dm := newDirtyMap(4)
dm.put(7, 91, 12, 4096, 4134)
dm.putAt(8, 200, 4096, 20, 4096, 8230)
entries := snapshotEntriesByLBA(dm.snapshot())
if got := entries[7].RecordSize; got != 4134 {
t.Fatalf("ordinary record size=%d want 4134", got)
}
if got := entries[8].RecordSize; got != 8230 {
t.Fatalf("shared record size=%d want 8230", got)
}
}
func TestWALStoreDirtyRecordGeometryAppendPaths(t *testing.T) {
const blockSize = 4096
const ordinaryRecordSize = uint64(walEntryHeaderSize + blockSize)
t.Run("ordinary", func(t *testing.T) {
s := createGeometryTestStore(t)
if _, err := s.Write(3, makeBlock(blockSize, 0x31)); err != nil {
t.Fatal(err)
}
entry := snapshotEntriesByLBA(s.dm.snapshot())[3]
if entry.RecordSize != ordinaryRecordSize {
t.Fatalf("record size=%d want %d", entry.RecordSize, ordinaryRecordSize)
}
})
t.Run("independent batch", func(t *testing.T) {
s := createGeometryTestStore(t)
if _, err := s.WriteBatch(4, [][]byte{
makeBlock(blockSize, 0x41),
makeBlock(blockSize, 0x42),
makeBlock(blockSize, 0x43),
}); err != nil {
t.Fatal(err)
}
entries := snapshotEntriesByLBA(s.dm.snapshot())
offsets := make(map[uint64]struct{})
for lba := uint64(4); lba < 7; lba++ {
entry := entries[lba]
if entry.RecordSize != ordinaryRecordSize {
t.Fatalf("LBA %d record size=%d want %d", lba, entry.RecordSize, ordinaryRecordSize)
}
offsets[entry.WALOffset] = struct{}{}
}
if len(offsets) != 3 {
t.Fatalf("independent batch unique offsets=%d want 3", len(offsets))
}
})
t.Run("multi block", func(t *testing.T) {
s := createGeometryTestStore(t)
s.enableMultiBlockRecordsForTest(true)
if _, err := s.WriteBatch(8, [][]byte{
makeBlock(blockSize, 0x51),
makeBlock(blockSize, 0x52),
makeBlock(blockSize, 0x53),
}); err != nil {
t.Fatal(err)
}
entries := snapshotEntriesByLBA(s.dm.snapshot())
wantSize := uint64(walEntryHeaderSize + 3*blockSize)
wantOffset := entries[8].WALOffset
for index, lba := range []uint64{8, 9, 10} {
entry := entries[lba]
if entry.WALOffset != wantOffset || entry.RecordSize != wantSize {
t.Fatalf("LBA %d identity=(%d,%d) want=(%d,%d)",
lba, entry.WALOffset, entry.RecordSize, wantOffset, wantSize)
}
if wantDataOffset := uint32(index * blockSize); entry.DataOffset != wantDataOffset {
t.Fatalf("LBA %d data offset=%d want %d", lba, entry.DataOffset, wantDataOffset)
}
}
})
t.Run("apply entry", func(t *testing.T) {
s := createGeometryTestStore(t)
if err := s.ApplyEntry(12, makeBlock(blockSize, 0x61), 41); err != nil {
t.Fatal(err)
}
entry := snapshotEntriesByLBA(s.dm.snapshot())[12]
if entry.RecordSize != ordinaryRecordSize {
t.Fatalf("record size=%d want %d", entry.RecordSize, ordinaryRecordSize)
}
})
}
func TestWALStoreRecoverReconstructsRecordGeometry(t *testing.T) {
const blockSize = 4096
path := filepath.Join(t.TempDir(), "store.bin")
func() {
s, err := CreateWALStore(path, 32, blockSize)
if err != nil {
t.Fatal(err)
}
s.DisableAutoFlushForRecoveryTest()
if _, err := s.Write(1, makeBlock(blockSize, 0x71)); err != nil {
t.Fatal(err)
}
s.enableMultiBlockRecordsForTest(true)
if _, err := s.WriteBatch(4, [][]byte{
makeBlock(blockSize, 0x72),
makeBlock(blockSize, 0x73),
makeBlock(blockSize, 0x74),
}); err != nil {
t.Fatal(err)
}
if stable, err := s.Sync(); err != nil || stable != 4 {
t.Fatalf("Sync stable=%d err=%v want 4,nil", stable, err)
}
crashGeometryTestStore(t, s)
}()
s, err := OpenWALStore(path)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = s.Close() })
s.DisableAutoFlushForRecoveryTest()
if recovered, err := s.Recover(); err != nil || recovered != 4 {
t.Fatalf("Recover=%d err=%v want 4,nil", recovered, err)
}
entries := snapshotEntriesByLBA(s.dm.snapshot())
if got, want := entries[1].RecordSize, uint64(walEntryHeaderSize+blockSize); got != want {
t.Fatalf("ordinary recovered record size=%d want %d", got, want)
}
wantMultiSize := uint64(walEntryHeaderSize + 3*blockSize)
wantMultiOffset := entries[4].WALOffset
for _, lba := range []uint64{4, 5, 6} {
entry := entries[lba]
if entry.WALOffset != wantMultiOffset || entry.RecordSize != wantMultiSize {
t.Fatalf("LBA %d recovered identity=(%d,%d) want=(%d,%d)",
lba, entry.WALOffset, entry.RecordSize, wantMultiOffset, wantMultiSize)
}
}
}
func TestWALStoreRecoverReconstructsLegacyTrimRecordGeometry(t *testing.T) {
const (
blockSize = 4096
trimBlocks = 3
)
path := filepath.Join(t.TempDir(), "store.bin")
func() {
s, err := CreateWALStore(path, 16, blockSize)
if err != nil {
t.Fatal(err)
}
s.DisableAutoFlushForRecoveryTest()
for lba := uint32(3); lba < 3+trimBlocks; lba++ {
if err := s.WriteExtentDirect(lba, makeBlock(blockSize, 0xA5)); err != nil {
t.Fatal(err)
}
}
if stable, err := s.Sync(); err != nil || stable != 0 {
t.Fatalf("base Sync stable=%d err=%v want 0,nil", stable, err)
}
trim := &walEntry{
LSN: 1,
Type: walEntryTrim,
LBA: 3,
Length: trimBlocks * blockSize,
}
if _, err := s.wal.append(trim); err != nil {
t.Fatal(err)
}
s.mu.Lock()
s.nextLSN = 2
s.walHead = 1
s.walTail = 1
s.mu.Unlock()
if stable, err := s.Sync(); err != nil || stable != 1 {
t.Fatalf("Sync stable=%d err=%v want 1,nil", stable, err)
}
crashGeometryTestStore(t, s)
}()
reader, err := OpenReadOnly(path)
if err != nil {
t.Fatal(err)
}
for lba := uint32(3); lba < 3+trimBlocks; lba++ {
got, err := reader.Read(lba)
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(got, make([]byte, blockSize)) {
t.Fatalf("read-only trim LBA %d did not return zeros", lba)
}
}
if err := reader.Close(); err != nil {
t.Fatal(err)
}
s, err := OpenWALStore(path)
if err != nil {
t.Fatal(err)
}
s.DisableAutoFlushForRecoveryTest()
if recovered, err := s.Recover(); err != nil || recovered != 1 {
t.Fatalf("Recover=%d err=%v want 1,nil", recovered, err)
}
entries := snapshotEntriesByLBA(s.dm.snapshot())
if len(entries) != trimBlocks {
t.Fatalf("trim dirty entries=%d want %d", len(entries), trimBlocks)
}
wantOffset := entries[3].WALOffset
for index, lba := range []uint64{3, 4, 5} {
entry := entries[lba]
if entry.WALOffset != wantOffset ||
entry.RecordSize != uint64(walEntryHeaderSize) ||
entry.DataOffset != uint32(index*blockSize) {
t.Fatalf("trim LBA %d identity=(%d,%d,%d) want=(%d,%d,%d)",
lba, entry.WALOffset, entry.RecordSize, entry.DataOffset,
wantOffset, walEntryHeaderSize, index*blockSize)
}
got, err := s.Read(uint32(lba))
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(got, make([]byte, blockSize)) {
t.Fatalf("dirty trim LBA %d did not return zeros", lba)
}
}
if err := s.flusher.flushOnce(); err != nil {
t.Fatal(err)
}
if got := s.dm.len(); got != 0 {
t.Fatalf("trim dirty entries after flush=%d want 0", got)
}
if got := s.CheckpointLSN(); got != 1 {
t.Fatalf("trim checkpoint=%d want 1", got)
}
for lba := uint32(3); lba < 3+trimBlocks; lba++ {
got, err := s.readFromExtent(lba)
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(got, make([]byte, blockSize)) {
t.Fatalf("flushed trim LBA %d did not zero extent", lba)
}
}
if err := s.Close(); err != nil {
t.Fatal(err)
}
}
func TestWALStoreRecordGeometrySurvivesRingWrap(t *testing.T) {
const (
blockSize = 4096
walSize = 16 * 1024
)
path := filepath.Join(t.TempDir(), "store.bin")
s := createWALStoreWithWALSizeForTest(t, path, 16, blockSize, walSize)
s.DisableAutoFlushForRecoveryTest()
for lba := uint32(0); lba < 3; lba++ {
if _, err := s.Write(lba, makeBlock(blockSize, byte(0x90+lba))); err != nil {
t.Fatal(err)
}
}
if _, err := s.Sync(); err != nil {
t.Fatal(err)
}
if err := s.flusher.flushOnce(); err != nil {
t.Fatal(err)
}
if got := s.dm.len(); got != 0 {
t.Fatalf("dirty entries after first flush=%d want 0", got)
}
if _, err := s.Write(7, makeBlock(blockSize, 0x99)); err != nil {
t.Fatal(err)
}
entry := snapshotEntriesByLBA(s.dm.snapshot())[7]
if entry.WALOffset != 0 {
t.Fatalf("wrapped WAL offset=%d want 0", entry.WALOffset)
}
if got, want := entry.RecordSize, uint64(walEntryHeaderSize+blockSize); got != want {
t.Fatalf("wrapped record size=%d want %d", got, want)
}
if got := s.WriteInstrumentation().WALAppendWrapCount; got != 1 {
t.Fatalf("WAL wraps=%d want 1", got)
}
if stable, err := s.Sync(); err != nil || stable != 4 {
t.Fatalf("wrapped Sync stable=%d err=%v want 4,nil", stable, err)
}
crashGeometryTestStore(t, s)
reopened, err := OpenWALStore(path)
if err != nil {
t.Fatal(err)
}
reopened.DisableAutoFlushForRecoveryTest()
if recovered, err := reopened.Recover(); err != nil || recovered != 4 {
t.Fatalf("wrapped Recover=%d err=%v want 4,nil", recovered, err)
}
recoveredEntry := snapshotEntriesByLBA(reopened.dm.snapshot())[7]
if recoveredEntry.WALOffset != entry.WALOffset ||
recoveredEntry.RecordSize != entry.RecordSize {
t.Fatalf("recovered wrapped identity=(%d,%d) want=(%d,%d)",
recoveredEntry.WALOffset, recoveredEntry.RecordSize,
entry.WALOffset, entry.RecordSize)
}
if err := reopened.Close(); err != nil {
t.Fatal(err)
}
}
func TestPhase172ScopedMaterializationProbe(t *testing.T) {
path := os.Getenv("SW_BLOCK_PHASE172_SCOPED_PROBE_PATH")
if path == "" {
t.Skip("set SW_BLOCK_PHASE172_SCOPED_PROBE_PATH to run the syscall probe")
}
const (
blockSize = 4096
records = 1024
)
if err := os.Remove(path); err != nil && !os.IsNotExist(err) {
t.Fatal(err)
}
s, err := CreateWALStore(path, records, blockSize)
if err != nil {
t.Fatal(err)
}
s.DisableAutoFlushForRecoveryTest()
t.Cleanup(func() { _ = s.Close() })
for lba := uint32(0); lba < records; lba++ {
if _, err := s.Write(lba, makeBlock(blockSize, byte(lba%251+1))); err != nil {
t.Fatal(err)
}
}
if _, err := s.Sync(); err != nil {
t.Fatal(err)
}
if err := s.flusher.flushOnce(); err != nil {
t.Fatal(err)
}
got := s.FlusherInstrumentation()
t.Logf("phase172_probe_validated_records=%d", got.ValidatedRecords)
t.Logf("phase172_probe_header_read_ops=%d", got.WALHeaderReadOps)
t.Logf("phase172_probe_record_read_ops=%d", got.WALRecordReadOps)
t.Logf("phase172_probe_materialization_read_ops=%d", got.MaterializationReadOps)
if got.ValidatedRecords != records ||
got.WALHeaderReadOps != records ||
got.WALRecordReadOps != records ||
got.MaterializationReadOps != 2*records {
t.Fatalf("validated/header/record/materialization=%d/%d/%d/%d want %d/%d/%d/%d",
got.ValidatedRecords, got.WALHeaderReadOps, got.WALRecordReadOps,
got.MaterializationReadOps, records, records, records, 2*records)
}
}
func createGeometryTestStore(t *testing.T) *WALStore {
t.Helper()
s, err := CreateWALStore(filepath.Join(t.TempDir(), "store.bin"), 32, 4096)
if err != nil {
t.Fatal(err)
}
s.DisableAutoFlushForRecoveryTest()
t.Cleanup(func() { _ = s.Close() })
return s
}
func crashGeometryTestStore(t *testing.T, s *WALStore) {
t.Helper()
s.committer.Stop()
if err := s.fd.Close(); err != nil {
t.Fatal(err)
}
}
func snapshotEntriesByLBA(entries []snapshotEntry) map[uint64]snapshotEntry {
result := make(map[uint64]snapshotEntry, len(entries))
for _, entry := range entries {
result[entry.LBA] = entry
}
return result
}
@@ -94,6 +94,8 @@ Build one disabled-by-default comparison path for the shipped `WALStore` that:
### D1. Record Geometry And Baseline Contract
Implementation status: complete locally; exact-commit Linux admission pending.
- Extend the dirty-entry in-memory contract with only the geometry needed to
size one record read. Populate it at ordinary append, trim, WriteBatch,
multi-block append, and recovery replay.
@@ -113,6 +115,13 @@ Build one disabled-by-default comparison path for the shipped `WALStore` that:
counter shape. Whole-process counts may be reported as qualitative context
but cannot satisfy admission.
The D1 review exposed and fixed a pre-existing legacy range-trim inconsistency:
recovery expanded the record per block, while dirty reads treated trim length
as payload and the flusher accepted only the base LBA. The corrected fixture
starts from nonzero extents and proves read-only, dirty-read, writeback,
checkpoint, crash/reopen, and explicit-close behavior for a three-block trim.
This changes no disk format or default materialization mode.
### D2. Single-Read Fail-Closed Materialization
- Add one internal disabled-by-default comparison mode.
@@ -0,0 +1,86 @@
# Phase 172 D1 WAL Materialization Baseline QA
Validate exact in-memory WAL record geometry and reproduce the shipped
flusher's duplicate-read shape before D2 changes materialization behavior.
## Source
Run the exact assigned commit from a clean Linux worktree. Record the full
commit, dirty state, kernel, Go version, artifact path, and archive SHA-256.
Do not use a shared development tree.
## Command
```bash
bash scripts/run-phase172-wal-materialization-baseline-gate.sh
```
Do not reduce the five repetitions, one-second benchmark time, normal
checkpoint behavior, final Sync, final drain, 20 geometry repetitions, or
1024-record scoped syscall probe.
## Required Evidence
The gate must report:
```text
phase172_wal_materialization_baseline_status=ok
storage_regression=pass
record_geometry_repeat_20=pass
legacy_trim_recovery_fixture=pass
ring_wrap_geometry_fixture=pass
all_samples_checkpoint_coverage_complete=true
all_samples_failed_cycles_zero=true
sequential_duplicate_read_pass_count=<0..5>
scattered_duplicate_read_pass_count=<0..5>
sequential_wrap_pass_count=<0..5>
strace_available=true
scoped_strace_matches_product_counter=true
d2_single_read_candidate_admitted=<true|false>
next_recommendation=<implement_disabled_single_read_materialization|stop_before_single_read_materialization>
```
Inspect all five samples for sequential 4 KiB, scattered 4 KiB, explicit
16-block batch, and disabled-by-default multi-block opt-in workloads. Confirm:
- ordinary append, independent batch, multi-block append, replicated
`ApplyEntry`, crash/reopen recovery, legacy trim recovery, and ring wrap all
carry exact encoded `RecordSize`;
- no disk-format or default materialization selector changed;
- sequential and scattered samples each report one header read plus one full
record read per validated dirty record;
- at least four of five samples in each ordinary workload satisfy the
predeclared `[0.95,1.05]`, `[0.95,1.05]`, and `>=1.90` thresholds;
- explicit batch records remain independent, while multi-block snapshots show
fewer unique records than logical entries and nonzero reuse opportunity;
- actual materialization reuse hits remain zero on the unchanged D1 path;
- all cycles finish, checkpoint equals head, and validation/read/write/sync
failure counters stay zero;
- `strace -P <exact-store-file>` reports the same `pread64` call count as the
product's `MaterializationReadOps`; whole-process syscall counts do not
satisfy this gate;
- D2 admission follows the gate output without changing thresholds after the
run.
If the gate reports `d2_single_read_candidate_admitted=false`, treat that as a
valid D1 result and stop before D2.
## Additional Linux Checks
```bash
go test -race ./core/storage \
-run 'Test(DirtyMapSnapshotCarriesRecordGeometry|WALStoreDirtyRecordGeometryAppendPaths|WALStoreRecoverReconstructsRecordGeometry|WALStoreRecoverReconstructsLegacyTrimRecordGeometry|WALStoreRecordGeometrySurvivesRingWrap|FlusherInstrumentationCountsWALRecordMaterializationShape|FlusherInstrumentationExposesCurrentDuplicateReadsForSharedRecord)$' \
-count=20
go vet ./core/storage
```
## Deliverable
Write:
```text
internal/docs/qa-assignments/phase172-d1-wal-materialization-baseline-qa-signoff.md
```
Include exact summary keys, the scoped product/`strace` read counts, all four
workload medians, artifact checksum, review findings, and cleanup status.
@@ -0,0 +1,294 @@
#!/usr/bin/env bash
set -euo pipefail
ROOT="${1:-$(pwd)}"
ARTIFACT_DIR="${SW_BLOCK_ARTIFACT_DIR:-${ROOT}/results/phase172-wal-materialization-baseline-gate}"
SUMMARY="${ARTIFACT_DIR}/phase172-wal-materialization-baseline-summary.txt"
BENCHTIME="${SW_BLOCK_PHASE172_BENCHTIME:-1s}"
REPETITIONS="${SW_BLOCK_PHASE172_REPETITIONS:-5}"
WORKLOADS=(sequential scattered batch multiblock)
mkdir -p "${ARTIFACT_DIR}"
: >"${SUMMARY}"
write_summary() {
echo "$*" | tee -a "${SUMMARY}" >/dev/null
}
benchmark_for_workload() {
case "$1" in
sequential) echo "BenchmarkPhase167WALStoreContention" ;;
scattered) echo "BenchmarkPhase171WALStoreScatteredContention" ;;
batch) echo "BenchmarkPhase170WALStoreBatchContention" ;;
multiblock) echo "BenchmarkPhase172WALStoreMultiBlockContention" ;;
*) return 1 ;;
esac
}
metric_from_log() {
local file="$1"
local benchmark="$2"
local metric="$3"
awk -v prefix="${benchmark}/writers_4-" -v metric="${metric}" '
index($1, prefix) == 1 {
for (i = 2; i < NF; i++) {
if ($(i + 1) == metric) {
print $i
exit
}
}
}
' "${file}"
}
metric_from_test_log() {
local file="$1"
local key="$2"
awk -F= -v key="${key}" '$1 ~ key "$" { print $2; exit }' "${file}"
}
equal_values() {
awk -v left="$1" -v right="$2" 'BEGIN {
print (left + 0 == right + 0) ? "true" : "false"
}'
}
value_in_range() {
awk -v value="$1" -v minimum="$2" -v maximum="$3" 'BEGIN {
print (value >= minimum && value <= maximum) ? "true" : "false"
}'
}
value_at_least() {
awk -v value="$1" -v minimum="$2" 'BEGIN {
print (value >= minimum) ? "true" : "false"
}'
}
sum_file() {
awk '{ total += $1 } END { print total + 0 }' "$1"
}
median_file() {
sort -n "$1" | awk 'NR == 3 { print; exit }'
}
values_csv() {
paste -sd, "$1"
}
if [[ "${REPETITIONS}" != "5" ]]; then
echo "SW_BLOCK_PHASE172_REPETITIONS must be exactly 5" >&2
exit 1
fi
if [[ "${BENCHTIME}" != "1s" ]]; then
echo "SW_BLOCK_PHASE172_BENCHTIME must be exactly 1s" >&2
exit 1
fi
cd "${ROOT}"
write_summary "phase172_wal_materialization_baseline_status=running"
write_summary "git_sha=$(git rev-parse HEAD)"
write_summary "git_dirty=$([[ -n "$(git status --porcelain)" ]] && echo true || echo false)"
write_summary "go_version=$(go version | tr ' ' '_')"
write_summary "kernel=$(uname -srvmo | tr ' ' '_')"
write_summary "benchmark_time=${BENCHTIME}"
write_summary "repetitions=${REPETITIONS}"
write_summary "writers=4"
write_summary "workloads=sequential_4k,scattered_4k,explicit_16x4k_batch,multiblock_16x4k_opt_in"
write_summary "d2_admission=4_of_5_sequential_and_scattered_samples_each_header_and_record_reads_per_validated_record_in_0.95_to_1.05_and_combined_at_least_1.90"
write_summary "strace_scope=exact_store_file_path"
go test ./core/storage -count=1 >"${ARTIFACT_DIR}/storage-regression.log" 2>&1
write_summary "storage_regression=pass"
go test ./core/storage \
-run 'Test(DirtyMapSnapshotCarriesRecordGeometry|WALStoreDirtyRecordGeometryAppendPaths|WALStoreRecoverReconstructsRecordGeometry|WALStoreRecoverReconstructsLegacyTrimRecordGeometry|WALStoreRecordGeometrySurvivesRingWrap)$' \
-count=20 >"${ARTIFACT_DIR}/record-geometry-repeat.log" 2>&1
write_summary "record_geometry_repeat_20=pass"
write_summary "legacy_trim_recovery_fixture=pass"
write_summary "ring_wrap_geometry_fixture=pass"
metrics=(
"MB/s:mibps"
"p99_ns:p99_ns"
"flush_snapshot_entries/entry:snapshot_entries_per_entry"
"flush_unique_wal_records/snapshot_entry:unique_records_per_snapshot_entry"
"flush_record_reuse_opportunities/snapshot_entry:reuse_opportunities_per_snapshot_entry"
"flush_validated_records/entry:validated_records_per_entry"
"flush_header_reads/validated_record:header_reads_per_validated_record"
"flush_record_reads/validated_record:record_reads_per_validated_record"
"flush_materialization_reads/validated_record:materialization_reads_per_validated_record"
"flush_materialization_read_bytes/entry:materialization_read_bytes_per_entry"
"flush_record_reuse_hits/validated_record:record_reuse_hits_per_validated_record"
"wal_wraps:wal_wraps"
"checkpoint_coverage:checkpoint_coverage"
"flush_cycles_started:cycles_started"
"flush_cycles_succeeded:cycles_succeeded"
"multi_block_records:multi_block_records"
)
failure_metrics=(
flush_validation_failures
flush_header_read_failures
flush_record_read_failures
extent_write_failures
extent_sync_failures
checkpoint_write_failures
checkpoint_sync_failures
flush_cycles_failed
)
for workload in "${WORKLOADS[@]}"; do
for pair in "${metrics[@]}"; do
: >"${ARTIFACT_DIR}/${workload}-${pair#*:}.values"
done
: >"${ARTIFACT_DIR}/${workload}-admission.values"
done
for repetition in 1 2 3 4 5; do
case "${repetition}" in
1) order=(sequential scattered batch multiblock) ;;
2) order=(multiblock batch scattered sequential) ;;
3) order=(scattered sequential multiblock batch) ;;
4) order=(batch multiblock sequential scattered) ;;
5) order=(sequential batch scattered multiblock) ;;
esac
write_summary "repetition_${repetition}_order=${order[*]}"
for workload in "${order[@]}"; do
benchmark="$(benchmark_for_workload "${workload}")"
log="${ARTIFACT_DIR}/${repetition}-${workload}.log"
go test ./core/storage -run '^$' \
-bench "^${benchmark}/writers_4$" \
-benchtime="${BENCHTIME}" -count=1 >"${log}" 2>&1
for pair in "${metrics[@]}"; do
metric="${pair%%:*}"
alias="${pair#*:}"
value="$(metric_from_log "${log}" "${benchmark}" "${metric}")"
if [[ -z "${value}" ]]; then
echo "missing workload=${workload} metric=${metric} in ${log}" >&2
exit 1
fi
echo "${value}" >>"${ARTIFACT_DIR}/${workload}-${alias}.values"
done
for metric in "${failure_metrics[@]}"; do
value="$(metric_from_log "${log}" "${benchmark}" "${metric}")"
if [[ -z "${value}" || "$(equal_values "${value}" 0)" != "true" ]]; then
echo "nonzero or missing workload=${workload} ${metric}=${value:-missing}" >&2
exit 1
fi
done
checkpoint="$(metric_from_log "${log}" "${benchmark}" checkpoint_coverage)"
cycles_started="$(metric_from_log "${log}" "${benchmark}" flush_cycles_started)"
cycles_succeeded="$(metric_from_log "${log}" "${benchmark}" flush_cycles_succeeded)"
if [[ "$(equal_values "${checkpoint}" 1)" != "true" ||
"$(equal_values "${cycles_started}" "${cycles_succeeded}")" != "true" ]]; then
echo "incomplete checkpoint workload=${workload} repetition=${repetition}" >&2
exit 1
fi
reuse_hits="$(
metric_from_log "${log}" "${benchmark}" \
flush_record_reuse_hits/validated_record
)"
if [[ "$(equal_values "${reuse_hits}" 0)" != "true" ]]; then
echo "unexpected materialization reuse workload=${workload} hits=${reuse_hits}" >&2
exit 1
fi
mode="$(metric_from_log "${log}" "${benchmark}" multi_block_records)"
if [[ "${workload}" == "multiblock" ]]; then
expected_mode=1
else
expected_mode=0
fi
if [[ "$(equal_values "${mode}" "${expected_mode}")" != "true" ]]; then
echo "wrong multi-block mode workload=${workload} got=${mode}" >&2
exit 1
fi
header="$(metric_from_log "${log}" "${benchmark}" flush_header_reads/validated_record)"
record="$(metric_from_log "${log}" "${benchmark}" flush_record_reads/validated_record)"
combined="$(metric_from_log "${log}" "${benchmark}" flush_materialization_reads/validated_record)"
admitted=0
if [[ "$(value_in_range "${header}" 0.95 1.05)" == "true" &&
"$(value_in_range "${record}" 0.95 1.05)" == "true" &&
"$(value_at_least "${combined}" 1.90)" == "true" ]]; then
admitted=1
fi
echo "${admitted}" >>"${ARTIFACT_DIR}/${workload}-admission.values"
done
done
write_summary "all_samples_checkpoint_coverage_complete=true"
write_summary "all_samples_failed_cycles_zero=true"
for workload in "${WORKLOADS[@]}"; do
for alias in \
mibps p99_ns unique_records_per_snapshot_entry \
reuse_opportunities_per_snapshot_entry header_reads_per_validated_record \
record_reads_per_validated_record materialization_reads_per_validated_record \
materialization_read_bytes_per_entry record_reuse_hits_per_validated_record \
wal_wraps; do
values="${ARTIFACT_DIR}/${workload}-${alias}.values"
write_summary "${workload}_${alias}_samples=$(values_csv "${values}")"
write_summary "${workload}_${alias}_median=$(median_file "${values}")"
done
done
sequential_pass_count="$(sum_file "${ARTIFACT_DIR}/sequential-admission.values")"
scattered_pass_count="$(sum_file "${ARTIFACT_DIR}/scattered-admission.values")"
sequential_wrap_count="$(
awk '$1 >= 1 { count++ } END { print count + 0 }' \
"${ARTIFACT_DIR}/sequential-wal_wraps.values"
)"
write_summary "sequential_duplicate_read_pass_count=${sequential_pass_count}"
write_summary "scattered_duplicate_read_pass_count=${scattered_pass_count}"
write_summary "sequential_wrap_pass_count=${sequential_wrap_count}"
scoped_path="${ARTIFACT_DIR}/phase172-scoped-probe.store"
scoped_log="${ARTIFACT_DIR}/phase172-scoped-probe.log"
strace_log="${ARTIFACT_DIR}/phase172-scoped-probe.strace.txt"
scoped_match=false
if command -v strace >/dev/null 2>&1; then
go test -c ./core/storage -o "${ARTIFACT_DIR}/storage.test"
if SW_BLOCK_PHASE172_SCOPED_PROBE_PATH="${scoped_path}" \
strace -f -c -e trace=pread64 -P "${scoped_path}" -o "${strace_log}" \
"${ARTIFACT_DIR}/storage.test" \
-test.run '^TestPhase172ScopedMaterializationProbe$' \
-test.count=1 -test.v >"${scoped_log}" 2>&1; then
product_reads="$(
metric_from_test_log "${scoped_log}" phase172_probe_materialization_read_ops
)"
strace_reads="$(awk '$NF == "pread64" { print $4; exit }' "${strace_log}")"
if [[ -n "${product_reads}" && -n "${strace_reads}" &&
"$(equal_values "${product_reads}" "${strace_reads}")" == "true" ]]; then
scoped_match=true
fi
write_summary "strace_available=true"
write_summary "scoped_product_materialization_reads=${product_reads:-missing}"
write_summary "scoped_strace_pread64_calls=${strace_reads:-missing}"
else
write_summary "strace_available=true"
write_summary "scoped_strace_execution=failed"
fi
else
write_summary "strace_available=false"
fi
write_summary "scoped_strace_matches_product_counter=${scoped_match}"
d2_admitted=false
if [[ "${sequential_pass_count}" -ge 4 &&
"${scattered_pass_count}" -ge 4 &&
"${sequential_wrap_count}" -ge 4 &&
"${scoped_match}" == "true" ]]; then
d2_admitted=true
fi
write_summary "d2_single_read_candidate_admitted=${d2_admitted}"
if [[ "${d2_admitted}" == "true" ]]; then
write_summary "next_recommendation=implement_disabled_single_read_materialization"
else
write_summary "next_recommendation=stop_before_single_read_materialization"
fi
write_summary "phase172_wal_materialization_baseline_status=ok"