From 53a5cab66e6ea96e1e75f22e2baf957f96091071 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 6 Jul 2026 16:01:13 -0700 Subject: [PATCH] phase148: prototype multiblock wal records locally --- seaweed-block/core/storage/dirty_map.go | 44 +-- seaweed-block/core/storage/flusher.go | 53 ++-- seaweed-block/core/storage/recovery.go | 26 +- seaweed-block/core/storage/wal_entry.go | 21 +- seaweed-block/core/storage/walstore.go | 82 +++++- .../core/storage/walstore_multiblock_test.go | 271 ++++++++++++++++++ .../core/storage/walstore_readonly.go | 17 +- .../core/storage/walstore_recovery.go | 29 +- .../docs/releases/nvme-tcp-supported-lab.md | 22 ++ seaweed-block/docs/roadmap.md | 2 + seaweed-block/internal/docs/current-plan.md | 85 +++--- ...n_wal_multiblock_record_local_prototype.md | 46 +++ .../internal/docs/product-roadmap.md | 5 + ...block-record-local-prototype-qa-signoff.md | 70 +++++ ...-multiblock-record-local-prototype-gate.sh | 62 ++++ 15 files changed, 733 insertions(+), 102 deletions(-) create mode 100644 seaweed-block/core/storage/walstore_multiblock_test.go create mode 100644 seaweed-block/internal/docs/finished-plans/phase148_finishedplan_wal_multiblock_record_local_prototype.md create mode 100644 seaweed-block/internal/docs/qa-assignments/phase148-wal-multiblock-record-local-prototype-qa-signoff.md create mode 100644 seaweed-block/scripts/run-phase148-wal-multiblock-record-local-prototype-gate.sh diff --git a/seaweed-block/core/storage/dirty_map.go b/seaweed-block/core/storage/dirty_map.go index 0f99a96ed3..ab0025cf31 100644 --- a/seaweed-block/core/storage/dirty_map.go +++ b/seaweed-block/core/storage/dirty_map.go @@ -6,9 +6,10 @@ import "sync" // the WAL — used by readers to fetch unflushed data and by the // flusher to apply WAL records to the extent region. type dirtyEntry struct { - walOffset uint64 - lsn uint64 - length uint32 + walOffset uint64 + dataOffset uint32 + lsn uint64 + length uint32 } // dirtyShard is one independently-locked partition of the dirtyMap. @@ -44,21 +45,25 @@ 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) putAt(lba, walOffset uint64, dataOffset uint32, lsn uint64, length uint32) { s := d.shard(lba) s.mu.Lock() - s.m[lba] = dirtyEntry{walOffset: walOffset, lsn: lsn, length: length} + s.m[lba] = dirtyEntry{walOffset: walOffset, dataOffset: dataOffset, lsn: lsn, length: length} s.mu.Unlock() } -func (d *dirtyMap) get(lba uint64) (walOffset, lsn uint64, length uint32, ok bool) { +func (d *dirtyMap) get(lba uint64) (walOffset uint64, dataOffset uint32, lsn uint64, length uint32, ok bool) { s := d.shard(lba) s.mu.RLock() e, found := s.m[lba] s.mu.RUnlock() if !found { - return 0, 0, 0, false + return 0, 0, 0, 0, false } - return e.walOffset, e.lsn, e.length, true + return e.walOffset, e.dataOffset, e.lsn, e.length, true } func (d *dirtyMap) delete(lba uint64) { @@ -73,13 +78,13 @@ func (d *dirtyMap) delete(lba uint64) { // // Used by the flusher cleanup path to avoid the race where: // -// 1. Flusher snapshots {LBA, oldLSN}. -// 2. Concurrent Write() updates the entry to {LBA, newLSN}. -// 3. Flusher writes oldLSN's data to extent. -// 4. Flusher tries to clean up — without this guard, an -// unconditional delete by LBA would also drop the newer entry, -// leaving the new write unflushed AND invisible to subsequent -// reads (which would fall back to stale extent bytes). +// 1. Flusher snapshots {LBA, oldLSN}. +// 2. Concurrent Write() updates the entry to {LBA, newLSN}. +// 3. Flusher writes oldLSN's data to extent. +// 4. Flusher tries to clean up — without this guard, an +// unconditional delete by LBA would also drop the newer entry, +// leaving the new write unflushed AND invisible to subsequent +// reads (which would fall back to stale extent bytes). // // V2's flusher uses this same compare-then-delete pattern. func (d *dirtyMap) compareAndDelete(lba, expectedLSN uint64) bool { @@ -95,10 +100,11 @@ func (d *dirtyMap) compareAndDelete(lba, expectedLSN uint64) bool { // snapshotEntry is one entry returned by snapshot(). type snapshotEntry struct { - LBA uint64 - WALOffset uint64 - LSN uint64 - Length uint32 + LBA uint64 + WALOffset uint64 + DataOffset uint32 + LSN uint64 + Length uint32 } // snapshot copies all current entries lock-free for the caller. Each @@ -112,7 +118,7 @@ func (d *dirtyMap) snapshot() []snapshotEntry { s.mu.RLock() for lba, e := range s.m { out = append(out, snapshotEntry{ - LBA: lba, WALOffset: e.walOffset, LSN: e.lsn, Length: e.length, + LBA: lba, WALOffset: e.walOffset, DataOffset: e.dataOffset, LSN: e.lsn, Length: e.length, }) } s.mu.RUnlock() diff --git a/seaweed-block/core/storage/flusher.go b/seaweed-block/core/storage/flusher.go index 8eec903590..59c2f2f921 100644 --- a/seaweed-block/core/storage/flusher.go +++ b/seaweed-block/core/storage/flusher.go @@ -18,19 +18,19 @@ import ( // replica-aware retention floor — those are V2 features outside // V3 Phase 08 scope). The core algorithm is unchanged: // -// 1. Snapshot the dirty map. -// 2. For each entry, read the WAL record header at the recorded -// offset and compare the on-disk LSN to the snapshot LSN. A -// mismatch means the WAL slot was recycled — skip the entry. -// 3. Read the data section, write it to the extent at the LBA's -// natural offset. -// 4. fsync the file once for the whole batch. -// 5. Advance the on-disk checkpoint LSN to the highest LSN that -// was actually verified-and-flushed. -// 6. Remove flushed entries from the dirty map using -// compare-and-delete: only drop an entry whose LSN still -// matches what we flushed. A concurrent Write() that bumped -// the entry's LSN must NOT have its newer data lost. +// 1. Snapshot the dirty map. +// 2. For each entry, read the WAL record header at the recorded +// offset and compare the on-disk LSN to the snapshot LSN. A +// mismatch means the WAL slot was recycled — skip the entry. +// 3. Read the data section, write it to the extent at the LBA's +// natural offset. +// 4. fsync the file once for the whole batch. +// 5. Advance the on-disk checkpoint LSN to the highest LSN that +// was actually verified-and-flushed. +// 6. Remove flushed entries from the dirty map using +// compare-and-delete: only drop an entry whose LSN still +// matches what we flushed. A concurrent Write() that bumped +// the entry's LSN must NOT have its newer data lost. // // Note: V2 has no batch-size cutoff. The flusher processes the // whole snapshot in one cycle. This was a deliberate V2 choice @@ -166,17 +166,30 @@ func (f *flusher) flushOnce() error { return fmt.Errorf("flusher: read WAL header at %d: %w", e.WALOffset, err) } entryLSN := binary.LittleEndian.Uint64(hdrBuf[0:8]) + entryBlockCount := binary.LittleEndian.Uint64(hdrBuf[8:16]) if entryLSN != e.LSN { - // Stale slot — WAL has been recycled at this offset. - // Drop the dirty map entry only if it still matches the - // stale snapshot we just observed (compare-and-delete). - store.dm.compareAndDelete(e.LBA, e.LSN) - continue + entryType := hdrBuf[16] + if entryType != walEntryWriteBatch { + // Stale slot — WAL has been recycled at this offset. + // Drop the dirty map entry only if it still matches the + // stale snapshot we just observed (compare-and-delete). + store.dm.compareAndDelete(e.LBA, e.LSN) + continue + } + if entryBlockCount == 0 || e.DataOffset%store.sb.BlockSize != 0 { + store.dm.compareAndDelete(e.LBA, e.LSN) + continue + } + blockIndex := uint64(e.DataOffset / store.sb.BlockSize) + if blockIndex >= entryBlockCount || entryLSN+blockIndex != e.LSN { + store.dm.compareAndDelete(e.LBA, e.LSN) + continue + } } entryType := hdrBuf[16] entrySize := uint64(walEntryHeaderSize) switch entryType { - case walEntryWrite: + case walEntryWrite, walEntryWriteBatch: dataLen := parseLengthFromHeader(hdrBuf) if dataLen == 0 { continue @@ -202,7 +215,7 @@ func (f *flusher) flushOnce() error { e := entries[p.idx] var data []byte if p.isWrite { - d, err := store.readFromWAL(e.WALOffset) + d, err := store.readFromWAL(e.WALOffset, e.DataOffset) if err != nil { return fmt.Errorf("flusher: read WAL data for LBA %d: %w", e.LBA, err) } diff --git a/seaweed-block/core/storage/recovery.go b/seaweed-block/core/storage/recovery.go index 04a6a0d422..81fbe13dc2 100644 --- a/seaweed-block/core/storage/recovery.go +++ b/seaweed-block/core/storage/recovery.go @@ -93,7 +93,7 @@ func recoverWAL(fd *os.File, sb *superblock, dm *dirtyMap) (recoveryResult, erro continue } var payloadLen uint64 - if entryType == walEntryWrite { + if entryType == walEntryWrite || entryType == walEntryWriteBatch { payloadLen = uint64(lengthField) } entrySize := uint64(walEntryHeaderSize) + payloadLen @@ -119,7 +119,21 @@ 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.put(entry.LBA+uint64(i), pos, entry.LSN, sb.BlockSize) + dm.putAt(entry.LBA+uint64(i), pos, i*sb.BlockSize, entry.LSN, sb.BlockSize) + } + result.EntriesReplayed++ + case walEntryWriteBatch: + blocks := uint32(entry.Reserved) + if blocks == 0 || entry.Length != blocks*sb.BlockSize { + result.TornEntries++ + break + } + for i := uint32(0); i < blocks; i++ { + lsn := entry.LSN + uint64(i) + if lsn <= checkpointLSN { + continue + } + dm.putAt(entry.LBA+uint64(i), pos, i*sb.BlockSize, lsn, sb.BlockSize) } result.EntriesReplayed++ case walEntryTrim: @@ -134,8 +148,12 @@ func recoverWAL(fd *os.File, sb *superblock, dm *dirtyMap) (recoveryResult, erro case walEntryBarrier: // no data; skip } - if entry.LSN > result.HighestLSN { - result.HighestLSN = entry.LSN + highestEntryLSN := entry.LSN + if entry.Type == walEntryWriteBatch && entry.Reserved > 0 { + highestEntryLSN = entry.LSN + entry.Reserved - 1 + } + if highestEntryLSN > result.HighestLSN { + result.HighestLSN = highestEntryLSN } pos += entrySize } diff --git a/seaweed-block/core/storage/wal_entry.go b/seaweed-block/core/storage/wal_entry.go index bee2e77c68..cfd8d0f58f 100644 --- a/seaweed-block/core/storage/wal_entry.go +++ b/seaweed-block/core/storage/wal_entry.go @@ -10,10 +10,11 @@ import ( // WAL entry kinds. const ( - walEntryWrite = 0x01 - walEntryTrim = 0x02 - walEntryBarrier = 0x03 - walEntryPadding = 0xFF + walEntryWrite = 0x01 + walEntryTrim = 0x02 + walEntryBarrier = 0x03 + walEntryWriteBatch = 0x04 + walEntryPadding = 0xFF // walEntryHeaderSize is the TOTAL fixed overhead per record. Layout: // prefix (30 bytes): @@ -113,6 +114,16 @@ func (e *walEntry) encodedSize() (int, error) { if uint32(len(e.Data)) != e.Length { return 0, fmt.Errorf("%w: data len %d != Length %d", errInvalidEntry, len(e.Data), e.Length) } + case walEntryWriteBatch: + if e.Reserved == 0 { + return 0, fmt.Errorf("%w: batch write entry with zero block count", errInvalidEntry) + } + if len(e.Data) == 0 { + return 0, fmt.Errorf("%w: batch write entry with no data", errInvalidEntry) + } + if uint32(len(e.Data)) != e.Length { + return 0, fmt.Errorf("%w: batch data len %d != Length %d", errInvalidEntry, len(e.Data), e.Length) + } case walEntryTrim: if len(e.Data) != 0 { return 0, fmt.Errorf("%w: trim entry must have no data payload", errInvalidEntry) @@ -197,7 +208,7 @@ func decodeWALEntry(buf []byte) (walEntry, error) { off += 4 var dataLen int - if e.Type == walEntryWrite || e.Type == walEntryPadding { + if e.Type == walEntryWrite || e.Type == walEntryWriteBatch || e.Type == walEntryPadding { dataLen = int(e.Length) } dataEnd := off + dataLen diff --git a/seaweed-block/core/storage/walstore.go b/seaweed-block/core/storage/walstore.go index f8215ca2c9..1cfd56feb1 100644 --- a/seaweed-block/core/storage/walstore.go +++ b/seaweed-block/core/storage/walstore.go @@ -103,6 +103,11 @@ type WALStore struct { syncs atomic.Uint64 // total fsync operations performed (test/diagnostic) instr writeInstrumentation + + // multiBlockRecords is a disabled-by-default Phase 148 local prototype. + // It must not be wired into production paths before version/compatibility + // gates and mounted NVMe/TCP profiling pass. + multiBlockRecords bool } // CreateWALStore initializes a new store file at path. Fails if path @@ -447,8 +452,13 @@ func (s *WALStore) WriteBatch(startLBA uint32, blocks [][]byte) ([]uint64, error } firstLSN := s.nextLSN s.nextLSN += uint64(len(blocks)) + useMultiBlock := s.multiBlockRecords && len(blocks) > 1 s.mu.Unlock() + if useMultiBlock { + return s.writeBatchMultiBlock(startLBA, blocks, firstLSN) + } + entries := make([]walEntry, len(blocks)) lsns := make([]uint64, len(blocks)) for i, data := range blocks { @@ -484,6 +494,55 @@ func (s *WALStore) WriteBatch(startLBA uint32, blocks [][]byte) ([]uint64, error return lsns, nil } +func (s *WALStore) writeBatchMultiBlock(startLBA uint32, blocks [][]byte, firstLSN uint64) ([]uint64, error) { + totalLen := 0 + for _, data := range blocks { + totalLen += len(data) + } + payload := make([]byte, 0, totalLen) + for _, data := range blocks { + payload = append(payload, data...) + } + entry := &walEntry{ + LSN: firstLSN, + Reserved: uint64(len(blocks)), + Type: walEntryWriteBatch, + LBA: uint64(startLBA), + Length: uint32(len(payload)), + Data: payload, + } + walRelOff, err := s.wal.append(entry) + if err != nil { + return nil, fmt.Errorf("storage: WAL multiblock append: %w", err) + } + + lsns := make([]uint64, len(blocks)) + dirtyStart := time.Now() + for i, data := range blocks { + lsn := firstLSN + uint64(i) + lsns[i] = lsn + s.dm.putAt( + uint64(startLBA+uint32(i)), + walRelOff, + uint32(i*int(s.sb.BlockSize)), + lsn, + uint32(len(data)), + ) + } + s.instr.recordDirtyMapUpdate(len(blocks), time.Since(dirtyStart)) + + s.mu.Lock() + lastLSN := lsns[len(lsns)-1] + if lastLSN > s.walHead { + s.walHead = lastLSN + } + if s.walTail == 0 { + s.walTail = firstLSN + } + s.mu.Unlock() + return lsns, nil +} + func (s *WALStore) WriteInstrumentation() WriteInstrumentationStatus { return s.instr.snapshot() } @@ -502,8 +561,8 @@ func (s *WALStore) Read(lba uint32) ([]byte, error) { } s.mu.RUnlock() - if walRelOff, _, _, ok := s.dm.get(uint64(lba)); ok { - return s.readFromWAL(walRelOff) + if walRelOff, dataOffset, _, _, ok := s.dm.get(uint64(lba)); ok { + return s.readFromWAL(walRelOff, dataOffset) } return s.readFromExtent(lba) } @@ -511,7 +570,7 @@ func (s *WALStore) Read(lba uint32) ([]byte, error) { // readFromWAL pulls a single block out of a WAL Write/Trim entry // previously deposited by Append. The walRelOff points at the start // of the entry; data starts at walEntryHeaderSize bytes into it. -func (s *WALStore) readFromWAL(walRelOff uint64) ([]byte, error) { +func (s *WALStore) readFromWAL(walRelOff uint64, dataOffset uint32) ([]byte, error) { headerBuf := make([]byte, walEntryHeaderSize) absOff := int64(s.sb.WALOffset + walRelOff) if _, err := s.fd.ReadAt(headerBuf, absOff); err != nil { @@ -522,8 +581,15 @@ func (s *WALStore) readFromWAL(walRelOff uint64) ([]byte, error) { // Trim entry — return zeros, same as a never-written LBA. return make([]byte, s.sb.BlockSize), nil } - data := make([]byte, length) - if _, err := s.fd.ReadAt(data, absOff+int64(walEntryPrefixSize)); err != nil { + if dataOffset >= length { + return nil, fmt.Errorf("storage: WAL read data offset %d >= length %d", dataOffset, length) + } + readLen := s.sb.BlockSize + if remaining := length - dataOffset; remaining < readLen { + readLen = remaining + } + data := make([]byte, readLen) + if _, err := s.fd.ReadAt(data, absOff+int64(walEntryPrefixSize)+int64(dataOffset)); err != nil { return nil, fmt.Errorf("storage: WAL read data: %w", err) } // In the simple "one block per WAL write" case, length == blockSize. @@ -533,6 +599,12 @@ func (s *WALStore) readFromWAL(walRelOff uint64) ([]byte, error) { return data, nil } +func (s *WALStore) enableMultiBlockRecordsForTest(enabled bool) { + s.mu.Lock() + defer s.mu.Unlock() + s.multiBlockRecords = enabled +} + func (s *WALStore) readFromExtent(lba uint32) ([]byte, error) { data := make([]byte, s.sb.BlockSize) off := int64(s.extentBase + uint64(lba)*uint64(s.sb.BlockSize)) diff --git a/seaweed-block/core/storage/walstore_multiblock_test.go b/seaweed-block/core/storage/walstore_multiblock_test.go new file mode 100644 index 0000000000..51d31a0799 --- /dev/null +++ b/seaweed-block/core/storage/walstore_multiblock_test.go @@ -0,0 +1,271 @@ +package storage + +import ( + "bytes" + "encoding/binary" + "path/filepath" + "testing" + "time" +) + +func TestWALMultiBlock_EncodeDecode(t *testing.T) { + block0 := makeBlock(4096, 0xA0) + block1 := makeBlock(4096, 0xB0) + data := append(append([]byte{}, block0...), block1...) + + entry := walEntry{ + LSN: 10, + Reserved: 2, + Type: walEntryWriteBatch, + LBA: 7, + Length: uint32(len(data)), + Data: data, + } + encoded, err := entry.encode() + if err != nil { + t.Fatalf("encode: %v", err) + } + decoded, err := decodeWALEntry(encoded) + if err != nil { + t.Fatalf("decode: %v", err) + } + if decoded.Type != walEntryWriteBatch { + t.Fatalf("type=%d want %d", decoded.Type, walEntryWriteBatch) + } + if decoded.LSN != 10 || decoded.Reserved != 2 || decoded.LBA != 7 { + t.Fatalf("identity mismatch: %+v", decoded) + } + if !bytes.Equal(decoded.Data[:4096], block0) || !bytes.Equal(decoded.Data[4096:], block1) { + t.Fatal("decoded batch payload mismatch") + } +} + +func TestWALStore_MultiBlockFeatureDisabledByDefault(t *testing.T) { + path := filepath.Join(t.TempDir(), "store.bin") + s, err := CreateWALStore(path, 16, 4096) + if err != nil { + t.Fatal(err) + } + defer s.Close() + s.flusher.Stop() + + if _, err := s.WriteBatch(2, [][]byte{ + makeBlock(4096, 0xA1), + makeBlock(4096, 0xA2), + makeBlock(4096, 0xA3), + }); err != nil { + t.Fatalf("WriteBatch: %v", err) + } + entries := s.dm.snapshot() + if len(entries) != 3 { + t.Fatalf("dirty entries=%d want 3", len(entries)) + } + seenOffsets := map[uint64]bool{} + header := make([]byte, walEntryHeaderSize) + for _, e := range entries { + seenOffsets[e.WALOffset] = true + if e.DataOffset != 0 { + t.Fatalf("default dirty data offset=%d want 0", e.DataOffset) + } + if _, err := s.fd.ReadAt(header, int64(s.sb.WALOffset+e.WALOffset)); err != nil { + t.Fatalf("read header: %v", err) + } + if typ := header[16]; typ != walEntryWrite { + t.Fatalf("default entry type=%d want walEntryWrite", typ) + } + } + if len(seenOffsets) != 3 { + t.Fatalf("default WriteBatch offsets=%d want 3 independent records", len(seenOffsets)) + } +} + +func TestWALStore_MultiBlockDirtyRead(t *testing.T) { + path := filepath.Join(t.TempDir(), "store.bin") + s, err := CreateWALStore(path, 16, 4096) + if err != nil { + t.Fatal(err) + } + defer s.Close() + s.flusher.Stop() + s.enableMultiBlockRecordsForTest(true) + + blocks := [][]byte{ + makeBlock(4096, 0xB1), + makeBlock(4096, 0xB2), + makeBlock(4096, 0xB3), + } + lsns, err := s.WriteBatch(4, blocks) + if err != nil { + t.Fatalf("WriteBatch: %v", err) + } + for i, lsn := range lsns { + if want := uint64(i + 1); lsn != want { + t.Fatalf("lsn[%d]=%d want %d", i, lsn, want) + } + } + entries := s.dm.snapshot() + if len(entries) != 3 { + t.Fatalf("dirty entries=%d want 3", len(entries)) + } + offset := entries[0].WALOffset + for _, e := range entries { + if e.WALOffset != offset { + t.Fatalf("batch dirty offset changed: %d vs %d", e.WALOffset, offset) + } + } + for i, want := range blocks { + got, err := s.Read(uint32(4 + i)) + if err != nil { + t.Fatalf("Read %d: %v", i, err) + } + if !bytes.Equal(got, want) { + t.Fatalf("Read %d returned wrong block", i) + } + } +} + +func TestWALStore_MultiBlockRecoverSplitsPerBlock(t *testing.T) { + path := filepath.Join(t.TempDir(), "store.bin") + func() { + s, err := CreateWALStore(path, 16, 4096) + if err != nil { + t.Fatal(err) + } + s.flusher.Stop() + s.enableMultiBlockRecordsForTest(true) + if _, err := s.WriteBatch(1, [][]byte{ + makeBlock(4096, 0xC1), + makeBlock(4096, 0xC2), + makeBlock(4096, 0xC3), + }); err != nil { + t.Fatalf("WriteBatch: %v", err) + } + if stable, err := s.Sync(); err != nil || stable != 3 { + t.Fatalf("Sync stable=%d err=%v, want stable=3", stable, err) + } + s.committer.Stop() + _ = s.fd.Close() + }() + + s, err := OpenWALStore(path) + if err != nil { + t.Fatal(err) + } + defer s.Close() + if recovered, err := s.Recover(); err != nil || recovered != 3 { + t.Fatalf("Recover=%d err=%v, want 3", recovered, err) + } + for i, marker := range []byte{0xC1, 0xC2, 0xC3} { + got, err := s.Read(uint32(1 + i)) + if err != nil { + t.Fatalf("Read %d: %v", i, err) + } + if got[0] != marker { + t.Fatalf("Read %d marker=%02x want %02x", i, got[0], marker) + } + } +} + +func TestWALStore_MultiBlockFlusherSplitsPerBlock(t *testing.T) { + path := filepath.Join(t.TempDir(), "store.bin") + s, err := CreateWALStore(path, 16, 4096) + if err != nil { + t.Fatal(err) + } + defer s.Close() + s.enableMultiBlockRecordsForTest(true) + + blocks := [][]byte{ + makeBlock(4096, 0xD1), + makeBlock(4096, 0xD2), + makeBlock(4096, 0xD3), + } + if _, err := s.WriteBatch(6, blocks); err != nil { + t.Fatalf("WriteBatch: %v", err) + } + if stable, err := s.Sync(); err != nil || stable != 3 { + t.Fatalf("Sync stable=%d err=%v, want stable=3", stable, err) + } + deadline := time.Now().Add(2 * time.Second) + for time.Now().Before(deadline) { + if s.CheckpointLSN() >= 3 && s.dm.len() == 0 { + break + } + time.Sleep(20 * time.Millisecond) + } + if s.CheckpointLSN() < 3 { + t.Fatalf("checkpoint=%d want >=3", s.CheckpointLSN()) + } + if got := s.dm.len(); got != 0 { + t.Fatalf("dirty map len=%d want 0 after flush", got) + } + for i, want := range blocks { + got, err := s.readFromExtent(uint32(6 + i)) + if err != nil { + t.Fatalf("read extent %d: %v", i, err) + } + if !bytes.Equal(got, want) { + t.Fatalf("extent block %d mismatch", i) + } + } +} + +func TestWALStore_MultiBlockScanLBAsSplitsPerLSN(t *testing.T) { + path := filepath.Join(t.TempDir(), "store.bin") + s, err := CreateWALStore(path, 16, 4096) + if err != nil { + t.Fatal(err) + } + defer s.Close() + s.flusher.Stop() + s.enableMultiBlockRecordsForTest(true) + + if _, err := s.WriteBatch(8, [][]byte{ + makeBlock(4096, 0xE1), + makeBlock(4096, 0xE2), + makeBlock(4096, 0xE3), + }); err != nil { + t.Fatalf("WriteBatch: %v", err) + } + if _, err := s.Sync(); err != nil { + t.Fatalf("Sync: %v", err) + } + var got []RecoveryEntry + if err := s.ScanLBAs(1, func(e RecoveryEntry) error { + dup := append([]byte(nil), e.Data...) + e.Data = dup + got = append(got, e) + return nil + }); err != nil { + t.Fatalf("ScanLBAs: %v", err) + } + if len(got) != 3 { + t.Fatalf("entries=%d want 3", len(got)) + } + for i, e := range got { + if wantLSN := uint64(i + 1); e.LSN != wantLSN { + t.Fatalf("entry %d LSN=%d want %d", i, e.LSN, wantLSN) + } + if wantLBA := uint32(8 + i); e.LBA != wantLBA { + t.Fatalf("entry %d LBA=%d want %d", i, e.LBA, wantLBA) + } + if wantMarker := byte(0xE1 + i); e.Data[0] != wantMarker { + t.Fatalf("entry %d marker=%02x want %02x", i, e.Data[0], wantMarker) + } + } + + header := make([]byte, walEntryHeaderSize) + entries := s.dm.snapshot() + if len(entries) == 0 { + t.Fatal("dirty map empty") + } + if _, err := s.fd.ReadAt(header, int64(s.sb.WALOffset+entries[0].WALOffset)); err != nil { + t.Fatalf("read header: %v", err) + } + if gotType := header[16]; gotType != walEntryWriteBatch { + t.Fatalf("entry type=%d want walEntryWriteBatch", gotType) + } + if count := binary.LittleEndian.Uint64(header[8:16]); count != 3 { + t.Fatalf("batch count=%d want 3", count) + } +} diff --git a/seaweed-block/core/storage/walstore_readonly.go b/seaweed-block/core/storage/walstore_readonly.go index 3c2e1d9eb6..421de58bd4 100644 --- a/seaweed-block/core/storage/walstore_readonly.go +++ b/seaweed-block/core/storage/walstore_readonly.go @@ -101,13 +101,13 @@ func (r *WALStoreReader) Read(lba uint32) ([]byte, error) { } // WAL-recent first. Inline the same logic as WALStore.readFromWAL // + readFromExtent, but operating against the read-only fd. - if walRelOff, _, _, ok := r.dm.get(uint64(lba)); ok { - return r.readFromWAL(walRelOff) + if walRelOff, dataOffset, _, _, ok := r.dm.get(uint64(lba)); ok { + return r.readFromWAL(walRelOff, dataOffset) } return r.readFromExtent(lba) } -func (r *WALStoreReader) readFromWAL(walRelOff uint64) ([]byte, error) { +func (r *WALStoreReader) readFromWAL(walRelOff uint64, dataOffset uint32) ([]byte, error) { headerBuf := make([]byte, walEntryHeaderSize) absOff := int64(r.sb.WALOffset + walRelOff) if _, err := r.fd.ReadAt(headerBuf, absOff); err != nil { @@ -117,8 +117,15 @@ func (r *WALStoreReader) readFromWAL(walRelOff uint64) ([]byte, error) { if length == 0 { return make([]byte, r.sb.BlockSize), nil } - data := make([]byte, length) - if _, err := r.fd.ReadAt(data, absOff+int64(walEntryPrefixSize)); err != nil { + if dataOffset >= length { + return nil, fmt.Errorf("storage: OpenReadOnly WAL data offset %d >= length %d", dataOffset, length) + } + readLen := r.sb.BlockSize + if remaining := length - dataOffset; remaining < readLen { + readLen = remaining + } + data := make([]byte, readLen) + if _, err := r.fd.ReadAt(data, absOff+int64(walEntryPrefixSize)+int64(dataOffset)); err != nil { return nil, fmt.Errorf("storage: OpenReadOnly WAL data: %w", err) } return data, nil diff --git a/seaweed-block/core/storage/walstore_recovery.go b/seaweed-block/core/storage/walstore_recovery.go index 9180997ae5..8b836496ca 100644 --- a/seaweed-block/core/storage/walstore_recovery.go +++ b/seaweed-block/core/storage/walstore_recovery.go @@ -128,7 +128,7 @@ func (s *WALStore) ScanLBAs(fromLSN uint64, fn func(RecoveryEntry) error) error continue } var payloadLen uint64 - if entryType == walEntryWrite { + if entryType == walEntryWrite || entryType == walEntryWriteBatch { payloadLen = uint64(lengthField) } entrySize := uint64(walEntryHeaderSize) + payloadLen @@ -153,7 +153,11 @@ func (s *WALStore) ScanLBAs(fromLSN uint64, fn func(RecoveryEntry) error) error // monotonic only WITHIN A RANGE — we may need to keep // scanning past entries below fromLSN in the wraparound // case. Filter inline rather than break. - if entry.LSN < fromLSN { + highestEntryLSN := entry.LSN + if entry.Type == walEntryWriteBatch && entry.Reserved > 0 { + highestEntryLSN = entry.LSN + entry.Reserved - 1 + } + if highestEntryLSN < fromLSN { continue } if entry.LSN >= headLSN { @@ -185,6 +189,27 @@ func (s *WALStore) ScanLBAs(fromLSN uint64, fn func(RecoveryEntry) error) error return err } } + case walEntryWriteBatch: + blocks := uint32(entry.Reserved) + if blocks == 0 || entry.Length != blocks*blockSize { + return fmt.Errorf("storage: walstore ScanLBAs invalid batch record at %d", pos-entrySize) + } + for i := uint32(0); i < blocks; i++ { + lsn := entry.LSN + uint64(i) + if lsn < fromLSN || lsn >= headLSN { + continue + } + blockData := entry.Data[i*blockSize : (i+1)*blockSize] + emit := RecoveryEntry{ + LSN: lsn, + LBA: uint32(entry.LBA) + i, + Flags: walEntryWrite, + Data: blockData, + } + if err := fn(emit); err != nil { + return err + } + } case walEntryTrim: blocks := entry.Length / blockSize if blocks == 0 { diff --git a/seaweed-block/docs/releases/nvme-tcp-supported-lab.md b/seaweed-block/docs/releases/nvme-tcp-supported-lab.md index fc5ebebfea..ce9502f3f6 100644 --- a/seaweed-block/docs/releases/nvme-tcp-supported-lab.md +++ b/seaweed-block/docs/releases/nvme-tcp-supported-lab.md @@ -89,6 +89,7 @@ The supported-lab claim is intentionally narrow: | 145 | WAL record materialization allocation reduction | PASS | | 146 | WAL materialization effectiveness profile | PASS | | 147 | WAL multi-block record design gate | PASS | +| 148 | WAL multi-block record local prototype | PASS | Key QA sign-offs: @@ -120,6 +121,7 @@ Key QA sign-offs: - `internal/docs/qa-assignments/phase145-wal-record-materialization-reduction-qa-signoff.md` - `internal/docs/qa-assignments/phase146-wal-record-materialization-effectiveness-qa-signoff.md` - `internal/docs/qa-assignments/phase147-wal-multiblock-record-design-qa-signoff.md` +- `internal/docs/qa-assignments/phase148-wal-multiblock-record-local-prototype-qa-signoff.md` ## Performance Baseline @@ -540,6 +542,26 @@ The design gate keeps the current WAL format unchanged and documents the required format-version, CRC, dirty-map, recovery, flusher, checkpoint, and dirty-read invariants before any prototype writes a new record shape. +Phase 148 implemented that prototype locally behind a disabled-by-default test +gate: + +```text +phase148_wal_multiblock_record_local_prototype_status=ok +default_wal_format_unchanged=true +feature_gate_default=false +multiblock_encode_decode=pass +multiblock_dirty_read=pass +multiblock_recovery_split=pass +multiblock_flusher_split=pass +single_block_compatibility=pass +current_recovery_compatibility=pass +phase148_decision=profile_next +next_recommendation=phase149_wal_multiblock_record_profile_gate +cleanup_status=ok +``` + +This is not wired to Kubernetes and not enabled by default. + Phase 127 closes the source/component side of the ANA Change Notice gap: ```text diff --git a/seaweed-block/docs/roadmap.md b/seaweed-block/docs/roadmap.md index 9912fef0cb..75228090d5 100644 --- a/seaweed-block/docs/roadmap.md +++ b/seaweed-block/docs/roadmap.md @@ -116,6 +116,8 @@ Seaweed Block can already demonstrate a narrow Kubernetes block-storage loop: backend step selected by Phase 147 is a disabled-by-default multi-block WAL record prototype. The current WAL format remains unchanged until local encode/decode, dirty-read, recovery-split, and flusher-split tests pass. + Phase 148 closes that local correctness gate; the next step is profiling + record-count reduction before any runtime or Kubernetes opt-in. - Kubernetes NVMe/TCP mounted reconnect is source-gated through changed desired path-set evidence: CSI-node can connect a newly published desired NVMe path, prune the stale old host path for the same NQN, preserve pod diff --git a/seaweed-block/internal/docs/current-plan.md b/seaweed-block/internal/docs/current-plan.md index 8506cffaa4..944e0f3ed0 100644 --- a/seaweed-block/internal/docs/current-plan.md +++ b/seaweed-block/internal/docs/current-plan.md @@ -1,37 +1,11 @@ -# Current Plan: Phase 148 WAL Multi-Block Record Local Prototype +# Current Plan: Phase 149 WAL Multi-Block Record Profile Gate Status: planning. -Phase 147 closed the WAL multi-block record design gate: - -```text -phase147_wal_multiblock_record_design_status=ok -current_wal_format_unchanged=true -current_recovery_compatibility=pass -candidate_design=multi_block_record -candidate_reduces_record_count=true -candidate_reduces_write_calls=false -durability_invariant_documented=true -recovery_invariant_documented=true -phase147_decision=prototype_next -next_recommendation=phase148_wal_multiblock_record_local_prototype -cleanup_status=ok -``` - -## Goal - -Prototype a multi-block WAL record locally behind an explicit feature gate. The -prototype must prove encode/decode, dirty read, recovery split, and flusher split -semantics without changing the default WAL format or Kubernetes behavior. - -## Required Evidence +Phase 148 closed the local multi-block WAL record prototype: ```text phase148_wal_multiblock_record_local_prototype_status=ok -frontend_transport=tcp -roce_claim_allowed=false -nvme_rdma_claim_allowed=false -performance_slo_claim_allowed=false default_wal_format_unchanged=true feature_gate_default=false multiblock_encode_decode=pass @@ -40,30 +14,57 @@ multiblock_recovery_split=pass multiblock_flusher_split=pass single_block_compatibility=pass current_recovery_compatibility=pass -phase148_decision= +phase148_decision=profile_next +next_recommendation=phase149_wal_multiblock_record_profile_gate +cleanup_status=ok +``` + +## Goal + +Profile the multi-block WAL prototype under a controlled opt-in and decide +whether it is worth wiring into a mounted NVMe/TCP lab gate. The default path +must remain single-block WAL records. + +## Required Evidence + +```text +phase149_wal_multiblock_record_profile_status=ok +frontend_transport=tcp +roce_claim_allowed=false +nvme_rdma_claim_allowed=false +performance_slo_claim_allowed=false +default_wal_format_unchanged=true +feature_gate_default=false +single_block_compatibility=pass +current_recovery_compatibility=pass +profile_scope= +single_block_wal_encode_ops= +multiblock_wal_encode_ops= +record_count_reduction_visible= +dirty_read_verified=true +recovery_verified=true +phase149_decision= next_recommendation= cleanup_status=ok ``` ## Boundaries -- Do not enable the new record shape by default. -- Do not use the new record shape from Kubernetes/blockvolume in this phase. +- Do not enable multi-block records by default. +- Do not claim throughput/SLO from this phase. - Do not raise the default H2C size. -- Do not claim throughput/SLO from this design gate. -- Keep old single-block WAL recovery compatibility green. +- If this phase stays local-storage only, do not imply mounted NVMe/TCP + improvement. ## Candidate Work -1. Add a disabled-by-default local option for multi-block WAL records. -2. Encode/decode one batch record as `firstLSN + blockIndex` and - `firstLBA + blockIndex`. -3. Extend only the local test path enough to prove dirty reads, recovery split, - and flusher split. -4. Keep current single-block format as default and compatibility path. +1. Add a local storage profile comparing single-block and multi-block record + counts for the same contiguous WriteBatch workload. +2. Keep correctness checks in the same gate: dirty read and recovery must pass. +3. If the record-count reduction is clear, recommend a runtime opt-in wiring + phase. If not, defer the prototype. ## Exit Criteria -Phase 148 can close when the prototype proves correctness locally or is -explicitly deferred with a concrete blocker. A later phase must run the mounted -NVMe/TCP profile before any user-facing performance statement. +Phase 149 can close when it either justifies wiring a runtime opt-in for mounted +NVMe/TCP profiling, or defers multi-block records with concrete evidence. diff --git a/seaweed-block/internal/docs/finished-plans/phase148_finishedplan_wal_multiblock_record_local_prototype.md b/seaweed-block/internal/docs/finished-plans/phase148_finishedplan_wal_multiblock_record_local_prototype.md new file mode 100644 index 0000000000..b095c3e08b --- /dev/null +++ b/seaweed-block/internal/docs/finished-plans/phase148_finishedplan_wal_multiblock_record_local_prototype.md @@ -0,0 +1,46 @@ +# Phase 148 Finished Plan: WAL Multi-Block Record Local Prototype + +Status: **closed 2026-07-06, local gate PASS**. + +## Problem + +Phase 147 selected multi-block WAL records as the next deeper WAL optimization +candidate. The risk was correctness: a batch record changes dirty reads, +recovery, flusher, and `ScanLBAs` semantics. Phase 148 needed to prove those +semantics locally before any runtime or Kubernetes exposure. + +## Work + +Phase 148 added: + +- `walEntryWriteBatch = 0x04`; +- dirty-map `dataOffset`; +- disabled-by-default `multiBlockRecords` test gate; +- multi-block `WriteBatch` prototype; +- batch-aware dirty reads, read-only verifier reads, recovery, flusher, and + `ScanLBAs`; +- `scripts/run-phase148-wal-multiblock-record-local-prototype-gate.sh`; +- `core/storage/walstore_multiblock_test.go`. + +## Evidence + +```text +phase148_wal_multiblock_record_local_prototype_status=ok +default_wal_format_unchanged=true +feature_gate_default=false +multiblock_encode_decode=pass +multiblock_dirty_read=pass +multiblock_recovery_split=pass +multiblock_flusher_split=pass +single_block_compatibility=pass +current_recovery_compatibility=pass +phase148_decision=profile_next +next_recommendation=phase149_wal_multiblock_record_profile_gate +cleanup_status=ok +``` + +## Conclusion + +The local prototype is correct enough to profile behind an explicit opt-in. It +is still not enabled by default, not wired to Kubernetes, and not a performance +claim. diff --git a/seaweed-block/internal/docs/product-roadmap.md b/seaweed-block/internal/docs/product-roadmap.md index 9008a4eb12..18e33ffc5e 100644 --- a/seaweed-block/internal/docs/product-roadmap.md +++ b/seaweed-block/internal/docs/product-roadmap.md @@ -483,6 +483,11 @@ rebuild, delete safety, or cleanup must start as a separate gated phase. encoded records into fewer `WriteAt` calls, while record count remains the structural encode/recovery cost. The current WAL format stays unchanged; the next phase may prototype a disabled-by-default multi-block record locally. +- Phase 148 is closed for the local prototype. Multi-block WAL records now have + a disabled-by-default test gate with encode/decode, dirty-read, recovery-split, + flusher-split, and `ScanLBAs` coverage. It is not wired into Kubernetes or the + default blockvolume path; Phase 149 must profile record-count reduction before + runtime opt-in wiring. - Later protocol candidates: complete a real NVMe/RDMA target, characterize NVMe/TCP performance, or bridge to object/NIXL acceleration where the product surface is object/storage rather than block PVC. Keep these separate so diff --git a/seaweed-block/internal/docs/qa-assignments/phase148-wal-multiblock-record-local-prototype-qa-signoff.md b/seaweed-block/internal/docs/qa-assignments/phase148-wal-multiblock-record-local-prototype-qa-signoff.md new file mode 100644 index 0000000000..55344f212a --- /dev/null +++ b/seaweed-block/internal/docs/qa-assignments/phase148-wal-multiblock-record-local-prototype-qa-signoff.md @@ -0,0 +1,70 @@ +# Phase 148 QA Sign-off: WAL Multi-Block Record Local Prototype + +Status: **PASS**. + +Branch: `phase148-wal-multiblock-record-local-prototype`. + +## Scope + +Phase 148 implements a disabled-by-default local prototype for multi-block WAL +records. It does not change Kubernetes/blockvolume defaults, H2C defaults, or +public NVMe/TCP claims. + +The prototype is enabled only by an internal test gate: + +```text +enableMultiBlockRecordsForTest(true) +``` + +## Checks + +```text +bash -n scripts/run-phase148-wal-multiblock-record-local-prototype-gate.sh +bash scripts/run-phase148-wal-multiblock-record-local-prototype-gate.sh +go test ./core/storage -run MultiBlock -count=1 +go test ./core/storage ./core/frontend/durable -count=1 +``` + +Result: + +```text +ok github.com/seaweedfs/seaweed-block/core/storage +ok github.com/seaweedfs/seaweed-block/core/frontend/durable +``` + +## Summary + +```text +phase148_wal_multiblock_record_local_prototype_status=ok +frontend_transport=tcp +roce_claim_allowed=false +nvme_rdma_claim_allowed=false +performance_slo_claim_allowed=false +default_wal_format_unchanged=true +feature_gate_default=false +multiblock_encode_decode=pass +multiblock_dirty_read=pass +multiblock_recovery_split=pass +multiblock_flusher_split=pass +single_block_compatibility=pass +current_recovery_compatibility=pass +phase148_decision=profile_next +next_recommendation=phase149_wal_multiblock_record_profile_gate +cleanup_status=ok +``` + +## What Changed + +- Added `walEntryWriteBatch = 0x04`. +- Added dirty-map data offsets so multiple LBAs can point into one WAL record. +- Added disabled-by-default `multiBlockRecords` test gate. +- Added multi-block `WriteBatch` path that returns per-block LSNs while writing + one batch WAL record. +- Extended dirty reads, read-only verifier reads, recovery, flusher, and + `ScanLBAs` to split batch records by per-block LSN/LBA. + +## Verdict + +Phase 148 passes as a local prototype. The next gate should profile the +prototype under a controlled opt-in before any mounted NVMe/TCP or release +claim. The current default path remains single-block WAL records. diff --git a/seaweed-block/scripts/run-phase148-wal-multiblock-record-local-prototype-gate.sh b/seaweed-block/scripts/run-phase148-wal-multiblock-record-local-prototype-gate.sh new file mode 100644 index 0000000000..cecece0ab3 --- /dev/null +++ b/seaweed-block/scripts/run-phase148-wal-multiblock-record-local-prototype-gate.sh @@ -0,0 +1,62 @@ +#!/usr/bin/env bash +set -euo pipefail + +ROOT="${1:-$(pwd)}" +ARTIFACT_DIR="${SW_BLOCK_ARTIFACT_DIR:-${ROOT}/results/phase148-wal-multiblock-record-local-prototype-gate}" +SUMMARY="${ARTIFACT_DIR}/phase148-wal-multiblock-record-local-prototype-summary.txt" +if [[ -n "${SW_BLOCK_GO_BIN:-}" ]]; then + GO_BIN="${SW_BLOCK_GO_BIN}" +elif command -v go.exe >/dev/null 2>&1; then + GO_BIN="go.exe" +else + GO_BIN="go" +fi + +mkdir -p "${ARTIFACT_DIR}" +: >"${SUMMARY}" + +write_summary() { + echo "$*" | tee -a "${SUMMARY}" >/dev/null +} + +require_text() { + local path="$1" + local pattern="$2" + local label="$3" + if ! grep -Fq "$pattern" "$path"; then + echo "missing ${label}: ${pattern}" >&2 + exit 1 + fi +} + +write_summary "phase148_wal_multiblock_record_local_prototype_status=running" +write_summary "frontend_transport=tcp" +write_summary "roce_claim_allowed=false" +write_summary "nvme_rdma_claim_allowed=false" +write_summary "performance_slo_claim_allowed=false" + +require_text "${ROOT}/core/storage/wal_entry.go" "walEntryWriteBatch = 0x04" "batch entry type" +require_text "${ROOT}/core/storage/walstore.go" "multiBlockRecords bool" "disabled feature field" +require_text "${ROOT}/core/storage/walstore.go" "enableMultiBlockRecordsForTest" "test-only enable gate" +write_summary "default_wal_format_unchanged=true" +write_summary "feature_gate_default=false" + +cd "${ROOT}" +"${GO_BIN}" test ./core/storage -run MultiBlock -count=1 \ + >"${ARTIFACT_DIR}/go-test-multiblock.log" \ + 2>&1 +write_summary "multiblock_encode_decode=pass" +write_summary "multiblock_dirty_read=pass" +write_summary "multiblock_recovery_split=pass" +write_summary "multiblock_flusher_split=pass" + +"${GO_BIN}" test ./core/storage ./core/frontend/durable -count=1 \ + >"${ARTIFACT_DIR}/go-test-compatibility.log" \ + 2>&1 +write_summary "single_block_compatibility=pass" +write_summary "current_recovery_compatibility=pass" + +write_summary "phase148_decision=profile_next" +write_summary "next_recommendation=phase149_wal_multiblock_record_profile_gate" +write_summary "cleanup_status=ok" +write_summary "phase148_wal_multiblock_record_local_prototype_status=ok"