From 055fd468a07b5cd26941c68013acd585802afb08 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 30 Apr 2026 13:46:45 -0700 Subject: [PATCH] =?UTF-8?q?storage+recovery:=20=C2=A76.10=20BASE=20bypass?= =?UTF-8?q?=20=E2=80=94=20WriteExtentDirect=20+=20RebuildSession=20switch?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Implements consensus §6.10 (INV-RECV-BITMAP-CORE / INV-RECV-WAL-NAIVE): BASE lane writes go directly to extent, bypassing the LSN-tracked WAL apply path entirely. The receiver's per-session bitmap is the sole arbiter of BASE-vs-WAL conflict at this LBA; substrate stale-skip is irrelevant for BASE because BASE never enters the WAL. Substrate contract delta (LogicalStorage): + WriteExtentDirect(lba uint32, data []byte) error Writes one block's bytes to the substrate's extent. No LSN. No frontier (R/S/H) advancement. Substrate stale-skip / WAL apply machinery NOT invoked. Receiver pairs with AdvanceFrontier in MarkBaseComplete to keep post-rebuild frontier reporting honest. Implementations: - BlockStore — write to in-memory blocks map; nextLSN/walHead untouched. - memorywal — append a record with LSN=0 sentinel; no retention/nextLSN advance. Receiver bitmap discipline keeps semantics correct (BASE only reaches substrate when WAL hasn't touched LBA). - WALStore — wraps existing private writeExtent; pwrites to extent file, no WAL append, no dirty-map entry. - smartwal.Store — pwrites directly to extent at lba's offset; ring NOT touched, no LSN/frontier advance. RebuildSession changes: - ApplyBaseBlock now calls store.WriteExtentDirect(lba, data) instead of store.ApplyEntry(lba, data, targetLSN). The targetLSN-as-base-LSN POC compromise (which silently rode substrate stale-skip) is gone. - MarkBaseComplete now calls store.AdvanceFrontier(targetLSN) — the explicit frontier-advance that ApplyEntry's side effect previously provided implicitly. Pre-§6.10, BASE applies bumped walHead per LBA; now we make the bump explicit at base-done. Contract test (TestContract_WriteExtentDirect): pins - WriteExtentDirect succeeds and Read returns the bytes - Frontier (H) and nextLSN MUST NOT advance (BASE has no LSN) - Subsequent ApplyEntry at LSN > 0 shadows the BASE bytes runs against BlockStore-mem / WALStore / MemoryWAL. Refs: v3-recovery-algorithm-consensus.md §6.10 (INV-RECV-BITMAP-CORE, INV-RECV-WAL-NAIVE); §6.3 cursor-monotonic sender invariant; mini-plan §12 design-candidate doc-track. Co-Authored-By: Claude Opus 4.7 (1M context) --- .../core/recovery/rebuild_session.go | 34 ++++++++-- seaweed-block/core/storage/contract_test.go | 65 +++++++++++++++++++ seaweed-block/core/storage/logical_storage.go | 29 +++++++++ seaweed-block/core/storage/memorywal/store.go | 33 ++++++++++ seaweed-block/core/storage/smartwal/store.go | 33 ++++++++++ seaweed-block/core/storage/store.go | 20 ++++++ seaweed-block/core/storage/walstore.go | 23 +++++++ 7 files changed, 231 insertions(+), 6 deletions(-) diff --git a/seaweed-block/core/recovery/rebuild_session.go b/seaweed-block/core/recovery/rebuild_session.go index 1b4a9ec5c2..96c4da41c2 100644 --- a/seaweed-block/core/recovery/rebuild_session.go +++ b/seaweed-block/core/recovery/rebuild_session.go @@ -65,10 +65,18 @@ func NewRebuildSession(store storage.LogicalStorage, targetLSN uint64) *RebuildS // (skipped=true, nil) when the WAL lane has already won this LBA; // (skipped=false, nil) when the substrate apply succeeded. // -// The base block is applied with `targetLSN` as its LSN. POC choice: -// base goes through the substrate's WAL just like WAL lane does. -// Production may want a direct-extent path to avoid WAL pressure; -// that is a layer-2/substrate question, not a layer-1 concern. +// Per v3-recovery-algorithm-consensus.md §6.10 (INV-RECV-BITMAP-CORE): +// BASE writes go through `WriteExtentDirect`, NOT the LSN-tracked +// `ApplyEntry` path. The bitmap is the sole arbiter of BASE-vs-WAL +// conflict at this LBA; the substrate's per-LBA stale-skip / WAL- +// record machinery does not interpret BASE bytes as a competing-LSN +// write (because BASE never enters the substrate's WAL). +// +// Frontier advancement is deferred to `MarkBaseComplete`, which calls +// `store.AdvanceFrontier(targetLSN)` once the BASE phase signals +// stream-complete. Pre-§6.10 code piggybacked on `ApplyEntry`'s +// implicit frontier-advance side effect; the new direct-extent path +// must opt in explicitly. // // INV-DUAL-LANE-WAL-WINS-BASE. func (s *RebuildSession) ApplyBaseBlock(lba uint32, data []byte) (skipped bool, err error) { @@ -80,8 +88,8 @@ func (s *RebuildSession) ApplyBaseBlock(lba uint32, data []byte) (skipped bool, if s.bitmap.IsApplied(lba) { return true, nil } - if err := s.store.ApplyEntry(lba, data, s.targetLSN); err != nil { - return false, fmt.Errorf("recovery: base apply lba=%d: %w", lba, err) + if err := s.store.WriteExtentDirect(lba, data); err != nil { + return false, fmt.Errorf("recovery: base extent-direct lba=%d: %w", lba, err) } return false, nil } @@ -142,10 +150,24 @@ func (s *RebuildSession) BaseBatchAcked(lbaUpper uint32) { // MarkBaseComplete signals that the base lane has shipped the last // block. Combined with walApplied ≥ targetLSN, this is the layer-1 // completion predicate. +// +// Per §6.10 frontier-pairing: BASE writes go through +// `WriteExtentDirect` which does NOT advance the substrate's +// nextLSN / walHead / syncedLSN. The recovery layer compensates by +// advancing the frontier to `targetLSN` here — once BASE is done, +// the replica's R/H boundaries reflect "the snapshot at fromLSN +// is installed" without needing a competing WAL apply at +// targetLSN. Subsequent WAL frames at LSN > targetLSN advance +// further via `ApplyEntry`'s normal side effects. func (s *RebuildSession) MarkBaseComplete() { s.mu.Lock() defer s.mu.Unlock() s.baseDone = true + // §6.10 frontier reconciliation: BASE bytes are now installed + // to extent; declare frontier at targetLSN so post-rebuild + // Sync()/Boundaries() report a non-degenerate value even on + // BASE-only sessions (no WAL frames in this session). + s.store.AdvanceFrontier(s.targetLSN) } // TryComplete reports whether the layer-1 completion predicate holds. diff --git a/seaweed-block/core/storage/contract_test.go b/seaweed-block/core/storage/contract_test.go index 594efb9cc0..c784923551 100644 --- a/seaweed-block/core/storage/contract_test.go +++ b/seaweed-block/core/storage/contract_test.go @@ -305,3 +305,68 @@ func TestContract_RecoverOnFreshStoreReturnsZero(t *testing.T) { } }) } + +// TestContract_WriteExtentDirect — INV-RECV-BITMAP-CORE (§6.10). +// WriteExtentDirect writes bytes to extent without advancing the +// substrate's LSN frontier (no nextLSN bump, no walHead bump). The +// recovery receiver pairs it with AdvanceFrontier; this test pins the +// "no automatic frontier advance" half of the contract on every +// substrate. +func TestContract_WriteExtentDirect(t *testing.T) { + runForEachImpl(t, func(t *testing.T, store LogicalStorage) { + bs := store.BlockSize() + baseBytes := makeBlock(bs, 0xAA) + + // Pre-condition: fresh substrate, frontier zero. + _, _, h0 := store.Boundaries() + if h0 != 0 { + t.Fatalf("fresh substrate H=%d want 0", h0) + } + + // WriteExtentDirect must succeed and become readable. + if err := store.WriteExtentDirect(3, baseBytes); err != nil { + t.Fatalf("WriteExtentDirect: %v", err) + } + got, err := store.Read(3) + if err != nil { + t.Fatalf("Read after WriteExtentDirect: %v", err) + } + if !bytes.Equal(got, baseBytes) { + t.Errorf("Read(3) returned %02x... want %02x...", got[:2], baseBytes[:2]) + } + + // Frontier MUST NOT have advanced — BASE has no LSN at this + // layer; recovery layer is responsible for explicit + // AdvanceFrontier when the BASE phase completes. + _, _, h1 := store.Boundaries() + if h1 != h0 { + t.Errorf("WriteExtentDirect advanced H from %d to %d (must NOT advance frontier)", h0, h1) + } + if next := store.NextLSN(); next != 1 { + t.Errorf("WriteExtentDirect advanced nextLSN to %d (must stay 1 on fresh substrate)", next) + } + + // A subsequent ApplyEntry at LSN > 0 must shadow the BASE + // bytes — this matches the recovery flow where WAL frames + // at higher LSNs naturally overwrite the BASE snapshot. + walBytes := makeBlock(bs, 0xBB) + if err := store.ApplyEntry(3, walBytes, 5); err != nil { + t.Fatalf("ApplyEntry after WriteExtentDirect: %v", err) + } + got2, err := store.Read(3) + if err != nil { + t.Fatalf("Read after ApplyEntry: %v", err) + } + if !bytes.Equal(got2, walBytes) { + t.Errorf("Read(3) after ApplyEntry returned %02x... want %02x...", got2[:2], walBytes[:2]) + } + + // Now ApplyEntry HAS advanced the frontier (its normal side + // effect), so H bumped — this is the receiver's existing + // side-effect contract for ApplyEntry, unrelated to BASE. + _, _, h2 := store.Boundaries() + if h2 < 5 { + t.Errorf("after ApplyEntry(lsn=5) H=%d want >= 5", h2) + } + }) +} diff --git a/seaweed-block/core/storage/logical_storage.go b/seaweed-block/core/storage/logical_storage.go index 77f996429f..3f9ef5d845 100644 --- a/seaweed-block/core/storage/logical_storage.go +++ b/seaweed-block/core/storage/logical_storage.go @@ -113,6 +113,35 @@ type LogicalStorage interface { // path so frontier tracking stays coherent with the source. ApplyEntry(lba uint32, data []byte, lsn uint64) error + // WriteExtentDirect installs one block's bytes directly into the + // substrate's extent, bypassing the WAL apply path entirely. Used + // by the recovery receiver's BASE lane (rebuild snapshot install) + // so the substrate's own per-LBA stale-skip / WAL-record machinery + // does NOT interpret BASE bytes as a competing-LSN write. + // + // Per v3-recovery-algorithm-consensus.md §6.10: + // - INV-RECV-BITMAP-CORE: the receiver's per-session bitmap is + // the SOLE arbiter of "BASE vs WAL won this LBA"; substrate + // stale-skip is irrelevant for BASE because BASE doesn't go + // through the WAL apply path. + // - BASE writes are LSN-less at this layer. Substrates that + // internally key records by LSN MUST synthesize a sensible + // non-conflicting LSN (e.g., 0 or below current retention) or + // write to a pure extent surface; the on-wire BASE frame + // carries no LSN. + // + // Frontier (R/S/H boundaries) is NOT advanced by this call — + // BASE-only sessions that need post-rebuild frontier reporting + // at >= fromLSN MUST pair this with an explicit AdvanceFrontier + // (the recovery layer does this in MarkBaseComplete). + // + // Returns an error if the substrate cannot honor the bypass + // semantics (e.g., a future read-only WAL substrate with no + // extent surface). Callers MUST surface the error rather than + // silently fall back to ApplyEntry — fallback re-introduces the + // stale-skip race the spec explicitly forbids. + WriteExtentDirect(lba uint32, data []byte) error + // AllBlocks snapshots every written LBA's current bytes. Used by // the rebuild server to enumerate what to ship. AllBlocks() map[uint32][]byte diff --git a/seaweed-block/core/storage/memorywal/store.go b/seaweed-block/core/storage/memorywal/store.go index ec25e979bf..e824787441 100644 --- a/seaweed-block/core/storage/memorywal/store.go +++ b/seaweed-block/core/storage/memorywal/store.go @@ -236,6 +236,39 @@ func (s *Store) ApplyEntry(lba uint32, data []byte, lsn uint64) error { return nil } +// WriteExtentDirect appends a record at LSN=0 (sentinel) so it is the +// most-recently-inserted entry for this LBA — Read's reverse-scan +// finds it first until a subsequent ApplyEntry at LSN>0 lands and +// shadows it. memorywal has no separate extent surface, so "extent +// direct" is realized through the same record list with no +// frontier / retention / nextLSN side effect. +// +// Per §6.10: BASE bypasses the LSN-tracked WAL apply path. The +// receiver's bitmap is the sole arbiter at this layer — memorywal +// does not consult LSN for BASE-vs-WAL arbitration; the receiver +// will only call this when its bitmap says no WAL has touched the +// LBA in this session. +func (s *Store) WriteExtentDirect(lba uint32, data []byte) error { + if lba >= s.numBlocks { + return fmt.Errorf("memorywal: WriteExtentDirect LBA %d out of range", lba) + } + if len(data) != s.blockSize { + return fmt.Errorf("memorywal: WriteExtentDirect data size %d != block size %d", len(data), s.blockSize) + } + s.mu.Lock() + defer s.mu.Unlock() + if s.closed { + return errors.New("memorywal: WriteExtentDirect after Close") + } + cp := make([]byte, s.blockSize) + copy(cp, data) + // LSN=0 sentinel — distinguishes BASE-direct from WAL-applied + // records in any future diagnostic scan; intentionally NOT a + // retention / nextLSN advance signal. + s.records = append(s.records, walRecord{LSN: 0, LBA: lba, Flags: storage.RecoveryEntryWrite, Data: cp}) + return nil +} + // AllBlocks returns last-writer-wins per LBA across retained records, // filtering out all-zero blocks (matches the LogicalStorage contract). func (s *Store) AllBlocks() map[uint32][]byte { diff --git a/seaweed-block/core/storage/smartwal/store.go b/seaweed-block/core/storage/smartwal/store.go index 55db221b59..a860c527f6 100644 --- a/seaweed-block/core/storage/smartwal/store.go +++ b/seaweed-block/core/storage/smartwal/store.go @@ -339,6 +339,39 @@ func (s *Store) AdvanceWALTail(newTail uint64) { } } +// WriteExtentDirect installs a base block directly into the extent +// without going through the WAL ring append path — INV-RECV-BITMAP- +// CORE (§6.10). The receiver's per-session bitmap is the sole arbiter +// of BASE-vs-WAL conflict at this LBA; substrate-level WAL replay / +// stale-skip is intentionally bypassed. +// +// No LSN is recorded; the ring is NOT touched. nextLSN / walHead are +// NOT advanced. The recovery layer pairs this with AdvanceFrontier +// (targetLSN) at MarkBaseComplete to keep post-rebuild frontier +// reporting honest. +// +// Durability follows the same rule as Write: bytes become durable +// only on the next successful Sync. +func (s *Store) WriteExtentDirect(lba uint32, data []byte) error { + if lba >= s.hdr.NumBlocks { + return fmt.Errorf("smartwal: WriteExtentDirect LBA %d out of range", lba) + } + if len(data) != int(s.hdr.BlockSize) { + return fmt.Errorf("smartwal: WriteExtentDirect data size %d != block size %d", len(data), s.hdr.BlockSize) + } + s.mu.RLock() + if s.closed { + s.mu.RUnlock() + return errors.New("smartwal: WriteExtentDirect after Close") + } + s.mu.RUnlock() + offset := s.extentBase + int64(lba)*int64(s.hdr.BlockSize) + if _, err := s.fd.WriteAt(data, offset); err != nil { + return fmt.Errorf("smartwal: WriteExtentDirect extent LBA %d: %w", lba, err) + } + return nil +} + // ApplyEntry writes a replicated block with the source's LSN. func (s *Store) ApplyEntry(lba uint32, data []byte, lsn uint64) error { if lba >= s.hdr.NumBlocks { diff --git a/seaweed-block/core/storage/store.go b/seaweed-block/core/storage/store.go index 7e486dc5cb..aba2b02013 100644 --- a/seaweed-block/core/storage/store.go +++ b/seaweed-block/core/storage/store.go @@ -295,6 +295,26 @@ func (s *BlockStore) ApplyEntry(lba uint32, data []byte, lsn uint64) error { return nil } +// WriteExtentDirect installs bytes into the in-memory block map without +// advancing nextLSN or walHead — INV-RECV-BITMAP-CORE (§6.10): BASE +// lane bypasses the LSN-tracked WAL apply path. The recovery receiver +// pairs this with AdvanceFrontier(targetLSN) in MarkBaseComplete to +// keep post-rebuild frontier reporting honest. +func (s *BlockStore) WriteExtentDirect(lba uint32, data []byte) error { + if lba >= s.numBlocks { + return fmt.Errorf("storage: WriteExtentDirect LBA %d out of range", lba) + } + if len(data) != s.blockSize { + return fmt.Errorf("storage: WriteExtentDirect data size %d != block size %d", len(data), s.blockSize) + } + s.mu.Lock() + defer s.mu.Unlock() + cp := make([]byte, s.blockSize) + copy(cp, data) + s.blocks[lba] = cp + return nil +} + // AllBlocks returns all written LBAs and their data (for rebuild serving). func (s *BlockStore) AllBlocks() map[uint32][]byte { s.mu.RLock() diff --git a/seaweed-block/core/storage/walstore.go b/seaweed-block/core/storage/walstore.go index 357a624c4a..84055b0d9a 100644 --- a/seaweed-block/core/storage/walstore.go +++ b/seaweed-block/core/storage/walstore.go @@ -584,6 +584,29 @@ func (s *WALStore) AdvanceWALTail(newTail uint64) { } } +// WriteExtentDirect installs a base block directly into the extent +// without going through the WAL append path — INV-RECV-BITMAP-CORE +// (§6.10). The receiver's per-session bitmap is the sole arbiter of +// BASE-vs-WAL conflict at this LBA; substrate-level WAL replay / +// stale-skip is intentionally bypassed. +// +// No LSN is recorded. nextLSN / walHead / dirtyMap are NOT advanced. +// The recovery layer pairs this with AdvanceFrontier(targetLSN) at +// MarkBaseComplete to keep post-rebuild frontier reporting honest. +// +// Durability follows the same rule as Write: bytes become durable +// only on the next successful Sync (the extent fsync covers them). +func (s *WALStore) WriteExtentDirect(lba uint32, data []byte) error { + maxLBA := uint32(s.sb.VolumeSize / uint64(s.sb.BlockSize)) + if lba >= maxLBA { + return fmt.Errorf("storage: WriteExtentDirect LBA %d out of range", lba) + } + if len(data) != int(s.sb.BlockSize) { + return fmt.Errorf("storage: WriteExtentDirect data size %d != block size %d", len(data), s.sb.BlockSize) + } + return s.writeExtent(lba, data) +} + // ApplyEntry writes a replicated block with the source's LSN rather // than allocating a fresh one. Same durability semantics as Write // (becomes durable on next Sync).