From ca21ed83d34a486eda26d54ccd86bc3d5eb3852c Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 28 Apr 2026 02:02:44 -0700 Subject: [PATCH] G6 #2-5: --wal-retention-lsns flag + walstore retention gate + tests MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Per G6 §1.A α binding (architect 2026-04-29) + §1.H audit PROCEED-with-minor-patch verdict at seaweed_block@5b09768. §1.A α implementation (operator-tunable WAL retention window): - core/storage/walstore.go (+27 LOC): new field recoveryRetentionLSNs uint64 + SetRecoveryRetentionLSNs/ RecoveryRetentionLSNs accessors. Zero (default) preserves pre-G6 strict checkpoint-driven recycle. - core/storage/walstore_recovery.go (+15 LOC, 8 LOC reshape): recovery scan gate relaxed from if fromLSN <= checkpointLSN to floor = checkpointLSN - retentionLSNs (saturating to 0) if fromLSN <= floor Boundary semantic preserved: == floor is rejected, > floor accepted. Diagnostic detail string extended with retentionLSNs + floor for forensics. - core/frontend/durable/provider.go (+22 LOC): new ProviderConfig field WALRetentionLSNs; plumbed into both openExisting (line 346) and createFresh (line 374) walstore paths via ws.SetRecoveryRetentionLSNs. ImplSmartWAL ignores the flag (ring capacity bounds retention; documented in godoc). - cmd/blockvolume/main.go (+12 LOC, 1 reshape): --wal-retention-lsns flag (uint64, default 0). Help text documents substrate-specific semantics (walstore honors; smartwal sizes via --durable-blocks). Plumbed into durable.ProviderConfig.WALRetentionLSNs. §2 #3 engine table-driven dispatch test: - core/engine/g6_walrecycle_dispatch_test.go (NEW, ~190 LOC): TestG6_SessionFailed_DispatchByFailureKind_TableDriven (3 subcases): WALRecycled → Decision=Rebuild + RebuildPinned=true + StartRebuild emit; Transport / SubstrateIO → no rebuild pin, retry catch-up. TestG6_RebuildPinned_StaysSticky_AcrossProbe: post-WAL-recycled pin survives a fresh probe that would classify as catch-up; Decision stays Rebuild; no StartCatchUp emit. TestG6_WALRecycled_PublishDegradedSurfaceFires: PublishDegraded AND StartRebuild emit on the same Apply (operator-visible signal alongside recovery dispatch). §2 substrate retention-gate tests: - core/storage/walstore_retention_test.go (NEW, ~150 LOC): 4 tests covering Default/Zero=strict-recycle (pre-G6 baseline), NonZero=widens window with floor=checkpoint-retention, LargerThanCheckpoint=clamps to 0 (saturating subtraction), TypedFailureKind=*RecoveryFailure envelope preserved (load- bearing for transport's classifyRecoveryFailure path). Test results: - core/storage/ TestWALStore_RecoveryRetention_*: 4/4 PASS - core/engine/ TestG6_*: 3 tests + 3 subcases = 6/6 PASS - Full ./... regression: in progress (will report after). Pinned by: - INV-G6-RETENTION-POLICY-OPERATOR-VISIBLE (§2 #2 + #4 hardware retention-OK case) - INV-G6-CATCHUP-CONVERGES-WITHIN-RETENTION (§2 #4 hardware) - INV-G6-WALRECYCLE-DISPATCHES-REBUILD (§2 #3 engine + #5 hardware) - INV-G6-ENGINE-NO-REBUILD-PINNED-ON-OTHER-FAILURES (§2 #3 negative control: Transport / SubstrateIO do NOT pin rebuild) Halt-condition NOT triggered. Full audit plumbing was already in place (T4d-1 typed envelopes + T4d-1 transport mapping + apply.go WALRecycled branch); G6 #2-#5 add only the operator knob, the substrate gate relaxation, and the test pins. Next: QA harness extension (wait_until_rebuild_dispatched) unblocked by commit #1's rebuild-START log marker; D-scenario extended for §2 #4 + #5 single-run per §2 #6. --- seaweed-block/cmd/blockvolume/main.go | 28 ++- .../engine/g6_walrecycle_dispatch_test.go | 180 +++++++++++++++++ .../core/frontend/durable/provider.go | 27 +++ seaweed-block/core/storage/walstore.go | 36 ++++ .../core/storage/walstore_recovery.go | 32 ++- .../core/storage/walstore_retention_test.go | 183 ++++++++++++++++++ 6 files changed, 475 insertions(+), 11 deletions(-) create mode 100644 seaweed-block/core/engine/g6_walrecycle_dispatch_test.go create mode 100644 seaweed-block/core/storage/walstore_retention_test.go diff --git a/seaweed-block/cmd/blockvolume/main.go b/seaweed-block/cmd/blockvolume/main.go index 9a9f8bd120..2146ee58fe 100644 --- a/seaweed-block/cmd/blockvolume/main.go +++ b/seaweed-block/cmd/blockvolume/main.go @@ -79,6 +79,15 @@ type flags struct { durableBlocks uint durableBlockSize uint + // G6 §1.A α: WAL retention window past checkpoint LSN. Zero = + // pre-G6 strict checkpoint-driven recycle (existing behavior). + // Non-zero = walstore relaxes recovery-scan recycle gate to + // fromLSN > checkpointLSN - walRetentionLSNs, giving a slow + // replica room to catch up while it lags within the window. + // Substrate semantics differ: see ProviderConfig.WALRetentionLSNs + // godoc. Pinned by INV-G6-RETENTION-POLICY-OPERATOR-VISIBLE. + walRetentionLSNs uint64 + // G5-5C degraded-peer probe loop (primary-side runtime recovery // trigger). Off by default; --degraded-probe-interval=0 keeps the // loop disabled so existing G5-4 deployments behave unchanged. @@ -115,6 +124,16 @@ func parseFlags(args []string) (flags, error) { fs.StringVar(&f.durableImpl, "durable-impl", "smartwal", "LogicalStorage impl: smartwal (default) or walstore; ignored unless --durable-root is set") fs.UintVar(&f.durableBlocks, "durable-blocks", 2048, "number of blocks per volume on first create (ignored when opening existing)") fs.UintVar(&f.durableBlockSize, "durable-blocksize", 4096, "block size in bytes on first create") + fs.Uint64Var(&f.walRetentionLSNs, "wal-retention-lsns", 0, + "G6 §1.A α: WAL retention window past checkpoint LSN (walstore only). "+ + "Zero (default) preserves pre-G6 strict checkpoint-driven recycle. "+ + "Non-zero relaxes the recovery-scan recycle gate so a replica lagging "+ + "within the configured envelope still has a catch-up scan path; once a "+ + "replica falls past this window the engine escalates to rebuild. "+ + "Substrate semantics: walstore (append-only) honors this directly; "+ + "smartwal (fixed-size ring) bounds retention via --durable-blocks instead "+ + "and ignores this flag. Recommended starting value for sustained-write "+ + "workloads on walstore: 10000 LSNs (sized to expected replica lag).") fs.DurationVar(&f.degradedProbeInterval, "degraded-probe-interval", 0, "G5-5C primary-side degraded-peer probe loop interval; 0 = OFF (default; existing G5-4 behavior preserved). "+ "Recommended production value: 5s. Distinct from --degraded-probe-cooldown-base: this is how often "+ @@ -341,10 +360,11 @@ func run(f flags) int { var durableProv *durable.DurableProvider if f.durableRoot != "" { cfg := durable.ProviderConfig{ - Impl: durable.ImplName(f.durableImpl), - StorageRoot: f.durableRoot, - BlockSize: int(f.durableBlockSize), - NumBlocks: uint32(f.durableBlocks), + Impl: durable.ImplName(f.durableImpl), + StorageRoot: f.durableRoot, + BlockSize: int(f.durableBlockSize), + NumBlocks: uint32(f.durableBlocks), + WALRetentionLSNs: f.walRetentionLSNs, // G6 §1.A α } dp, err := durable.NewDurableProvider(cfg, h.ProjectionView()) if err != nil { diff --git a/seaweed-block/core/engine/g6_walrecycle_dispatch_test.go b/seaweed-block/core/engine/g6_walrecycle_dispatch_test.go new file mode 100644 index 0000000000..d3654ac0ae --- /dev/null +++ b/seaweed-block/core/engine/g6_walrecycle_dispatch_test.go @@ -0,0 +1,180 @@ +package engine + +import ( + "testing" +) + +// G6 §1.A α + §2 #3 engine table-driven dispatch test: +// +// When a recovery session fails with a typed FailureKind, the engine +// branches: +// - WALRecycled → Decision=Rebuild + RebuildPinned=true + emit StartRebuild +// - Transport → Attempts++ + retry catch-up (if budget remains) +// - SubstrateIO → Attempts++ + retry catch-up (if budget remains) +// - StartTimeout → no retry (executor never started; bypass budget) +// +// G5-5C Batch 4's TestG5_5C_Dispatch_CatchUpVsRebuild_TableDriven +// already pinned the (R, S, H) → Decision shape on a fresh probe. +// This test pins the orthogonal axis: how a session-CLOSE event with +// a typed FailureKind affects dispatch. The two together cover both +// entry points to Decision=Rebuild. +// +// Pinned by: +// - INV-G6-WALRECYCLE-DISPATCHES-REBUILD (positive: WAL-recycled +// close emits StartRebuild and pins rebuild against future probes) +// - INV-G6-ENGINE-NO-REBUILD-PINNED-ON-OTHER-FAILURES (negative: +// only WALRecycled pins; Transport / SubstrateIO stay on catch-up +// retry path) + +// helperPrepareRunningSession primes a state machine to "in-flight +// catch-up session" so applySessionClosedFailed has something to +// terminate. Returns the SessionID. +func helperPrepareRunningSession(t *testing.T, st *ReplicaState, kind SessionKind) uint64 { + t.Helper() + const sessionID uint64 = 42 + Apply(st, AssignmentObserved{ + VolumeID: "vol1", ReplicaID: "r1", + Epoch: 1, EndpointVersion: 1, + DataAddr: "a", CtrlAddr: "b", + }) + Apply(st, ProbeSucceeded{ReplicaID: "r1", EndpointVersion: 1, TransportEpoch: 1}) + Apply(st, RecoveryFactsObserved{ReplicaID: "r1", R: 50, S: 10, H: 100}) + Apply(st, SessionPrepared{ + ReplicaID: "r1", SessionID: sessionID, + Kind: kind, + TargetLSN: 100, + }) + Apply(st, SessionStarted{ReplicaID: "r1", SessionID: sessionID}) + if st.Session.Phase != PhaseRunning { + t.Fatalf("setup: Phase = %s, want PhaseRunning", st.Session.Phase) + } + return sessionID +} + +// TestG6_SessionFailed_DispatchByFailureKind_TableDriven pins how +// each FailureKind shapes the engine response. +func TestG6_SessionFailed_DispatchByFailureKind_TableDriven(t *testing.T) { + cases := []struct { + name string + failureKind RecoveryFailureKind + wantDecision RecoveryDecision + wantRebuildPinned bool + wantCmd string // expected command emit on this Apply: "StartRebuild" / "StartCatchUp" / "" + }{ + { + name: "wal_recycled_pins_rebuild_and_emits_start_rebuild", + failureKind: RecoveryFailureWALRecycled, + wantDecision: DecisionRebuild, + wantRebuildPinned: true, + wantCmd: "StartRebuild", + }, + { + name: "transport_failure_does_not_pin_rebuild", + failureKind: RecoveryFailureTransport, + wantDecision: DecisionCatchUp, // unchanged from setup; retry budget engages + wantRebuildPinned: false, + wantCmd: "StartCatchUp", // engine retries within budget + }, + { + name: "substrate_io_does_not_pin_rebuild", + failureKind: RecoveryFailureSubstrateIO, + wantDecision: DecisionCatchUp, // unchanged; retry budget engages + wantRebuildPinned: false, + wantCmd: "StartCatchUp", + }, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + st := &ReplicaState{} + sessionID := helperPrepareRunningSession(t, st, SessionCatchUp) + + r := Apply(st, SessionClosedFailed{ + ReplicaID: "r1", + SessionID: sessionID, + FailureKind: c.failureKind, + Reason: "test-induced " + c.name, + }) + + if got := st.Recovery.Decision; got != c.wantDecision { + t.Errorf("Recovery.Decision = %s, want %s", got, c.wantDecision) + } + if got := st.Recovery.RebuildPinned; got != c.wantRebuildPinned { + t.Errorf("Recovery.RebuildPinned = %v, want %v", got, c.wantRebuildPinned) + } + + if c.wantCmd == "" { + assertNoCommand(t, r, "StartRebuild") + assertNoCommand(t, r, "StartCatchUp") + } else { + assertHasCommand(t, r, c.wantCmd) + // Strict mutual exclusion: only one recovery cmd. + other := "StartCatchUp" + if c.wantCmd == "StartCatchUp" { + other = "StartRebuild" + } + assertNoCommand(t, r, other) + } + }) + } +} + +// TestG6_RebuildPinned_StaysSticky_AcrossProbe verifies the +// load-bearing piece of INV-G6-WALRECYCLE-DISPATCHES-REBUILD: once +// the engine pins Rebuild via WAL-recycled close, a subsequent +// probe-derived (R, S, H) classification cannot downgrade Decision +// back to CatchUp. Without this, a transient probe arriving +// mid-rebuild could re-classify the gap as catch-up-eligible and +// leave the replica permanently stuck. +func TestG6_RebuildPinned_StaysSticky_AcrossProbe(t *testing.T) { + st := &ReplicaState{} + sessionID := helperPrepareRunningSession(t, st, SessionCatchUp) + + // Force a WAL-recycled close → pins rebuild. + Apply(st, SessionClosedFailed{ + ReplicaID: "r1", + SessionID: sessionID, + FailureKind: RecoveryFailureWALRecycled, + Reason: "wal recycled at the boundary", + }) + if !st.Recovery.RebuildPinned { + t.Fatal("setup: RebuildPinned should be true after WAL-recycled close") + } + if st.Recovery.Decision != DecisionRebuild { + t.Fatalf("setup: Decision = %s, want Rebuild", st.Recovery.Decision) + } + + // New probe arrives reporting R=50 / S=10 / H=100 — would + // classify as DecisionCatchUp under the strict (R, S, H) decide + // rule. RebuildPinned must override. + r := Apply(st, RecoveryFactsObserved{ReplicaID: "r1", R: 50, S: 10, H: 100}) + if st.Recovery.Decision != DecisionRebuild { + t.Errorf("post-probe Decision = %s, want Rebuild (RebuildPinned should override)", + st.Recovery.Decision) + } + // And no catch-up emit — pin must filter the dispatch too. + assertNoCommand(t, r, "StartCatchUp") +} + +// TestG6_WALRecycled_PublishDegradedSurfaceFires verifies the +// diagnostic surface: when WAL-recycled triggers, engine emits +// PublishDegraded so the runtime layer can call peer.Invalidate / +// log the reason. This is the operator-visible signal that's load- +// bearing for QA's wait_until_rebuild_dispatched harness (which +// scrapes for both rebuild-start AND degraded-published markers). +func TestG6_WALRecycled_PublishDegradedSurfaceFires(t *testing.T) { + st := &ReplicaState{} + sessionID := helperPrepareRunningSession(t, st, SessionCatchUp) + + r := Apply(st, SessionClosedFailed{ + ReplicaID: "r1", + SessionID: sessionID, + FailureKind: RecoveryFailureWALRecycled, + Reason: "wal recycled at the boundary", + }) + + // Both PublishDegraded AND StartRebuild should emit on the same + // Apply — the diagnostic surface fires alongside the recovery + // dispatch. + assertHasCommand(t, r, "PublishDegraded") + assertHasCommand(t, r, "StartRebuild") +} diff --git a/seaweed-block/core/frontend/durable/provider.go b/seaweed-block/core/frontend/durable/provider.go index 6057e222b2..7aae550d54 100644 --- a/seaweed-block/core/frontend/durable/provider.go +++ b/seaweed-block/core/frontend/durable/provider.go @@ -78,6 +78,23 @@ type ProviderConfig struct { // OpenTimeout caps how long Open waits for the projection to // report healthy for the requested volumeID. Zero → default 5s. OpenTimeout time.Duration + + // WALRetentionLSNs is the operator-tunable retention window past + // the substrate's checkpoint LSN (G6 §1.A α). Zero = pre-G6 + // strict checkpoint-driven recycle. Non-zero relaxes the recycle + // gate so a slow replica still has a recovery scan path while + // it lags within the configured envelope. + // + // Substrate semantics: + // - ImplWALStore (append-only): WAL retention is purely the + // scan-time gate; non-zero value relaxes the gate to + // fromLSN > checkpointLSN - WALRetentionLSNs. + // - ImplSmartWAL (fixed-size ring): retention is implicit from + // ring capacity (--durable-blocks). This flag is informational + // for ImplSmartWAL; operators size retention via NumBlocks. + // + // Pinned by: INV-G6-RETENTION-POLICY-OPERATOR-VISIBLE. + WALRetentionLSNs uint64 } // DurableProvider is the production frontend.Provider implementation. @@ -347,6 +364,12 @@ func (p *DurableProvider) openExisting(volumeID, path string) (*volHandle, error if err != nil { return nil, fmt.Errorf("durable: OpenWALStore %s: %w", path, err) } + // G6 §1.A α: plumb operator-tunable retention into walstore. + // Zero (pre-G6 default) preserves strict checkpoint-driven + // recycle. + if p.cfg.WALRetentionLSNs > 0 { + ws.SetRecoveryRetentionLSNs(p.cfg.WALRetentionLSNs) + } s = ws case ImplSmartWAL: sw, err := smartwal.OpenStore(path) @@ -375,6 +398,10 @@ func (p *DurableProvider) createFresh(volumeID, path string) (*volHandle, error) if err != nil { return nil, fmt.Errorf("durable: CreateWALStore %s: %w", path, err) } + // G6 §1.A α (see openExisting comment for semantics). + if p.cfg.WALRetentionLSNs > 0 { + ws.SetRecoveryRetentionLSNs(p.cfg.WALRetentionLSNs) + } s = ws case ImplSmartWAL: sw, err := smartwal.CreateStore(path, p.cfg.NumBlocks, p.cfg.BlockSize) diff --git a/seaweed-block/core/storage/walstore.go b/seaweed-block/core/storage/walstore.go index bb91cccbbc..c02165a6c9 100644 --- a/seaweed-block/core/storage/walstore.go +++ b/seaweed-block/core/storage/walstore.go @@ -74,6 +74,17 @@ type WALStore struct { // only by the flusher. checkpointLSN uint64 + // recoveryRetentionLSNs is the operator-tunable retention window + // past checkpointLSN: the recovery scan accepts fromLSN as long as + // fromLSN > checkpointLSN - recoveryRetentionLSNs (G6 §1.A α). + // Zero means strict checkpoint-driven recycle (pre-G6 behavior). + // Operator sets via blockvolume's --wal-retention-lsns flag at + // store construction. Stored in-memory only — NOT persisted to + // the superblock; on restart the daemon re-applies the flag. + // + // Pinned by: INV-G6-RETENTION-POLICY-OPERATOR-VISIBLE. + recoveryRetentionLSNs uint64 + syncs atomic.Uint64 // total fsync operations performed (test/diagnostic) } @@ -485,6 +496,31 @@ func (s *WALStore) NumBlocks() uint32 { // BlockSize returns the IO unit size in bytes. func (s *WALStore) BlockSize() int { return int(s.sb.BlockSize) } +// SetRecoveryRetentionLSNs configures the WAL retention window past +// checkpointLSN. After this is set, the recovery scan accepts +// fromLSN > checkpointLSN - retentionLSNs (G6 §1.A α). Zero (the +// default) preserves pre-G6 strict checkpoint-driven recycle. +// +// Operator-tunable via blockvolume's --wal-retention-lsns flag. +// In-memory only; not persisted (re-applied on restart from CLI). +// +// Called by: DurableProvider construction path after walstore is +// opened, with the operator-supplied value from cmd/blockvolume. +// Owns: recoveryRetentionLSNs field under s.mu. +func (s *WALStore) SetRecoveryRetentionLSNs(n uint64) { + s.mu.Lock() + defer s.mu.Unlock() + s.recoveryRetentionLSNs = n +} + +// RecoveryRetentionLSNs returns the currently-configured retention +// window past checkpointLSN. Test/diagnostic accessor. +func (s *WALStore) RecoveryRetentionLSNs() uint64 { + s.mu.RLock() + defer s.mu.RUnlock() + return s.recoveryRetentionLSNs +} + // AdvanceFrontier bumps the recorded frontier without writing data. // Used by the rebuild server to declare the replica's frontier // matches the primary's head once base blocks are installed. diff --git a/seaweed-block/core/storage/walstore_recovery.go b/seaweed-block/core/storage/walstore_recovery.go index 4621a1d54a..9b8df807e3 100644 --- a/seaweed-block/core/storage/walstore_recovery.go +++ b/seaweed-block/core/storage/walstore_recovery.go @@ -57,21 +57,39 @@ func (s *WALStore) ScanLBAs(fromLSN uint64, fn func(RecoveryEntry) error) error } checkpointLSN := s.checkpointLSN headLSN := s.nextLSN + retentionLSNs := s.recoveryRetentionLSNs s.mu.RUnlock() - // ErrWALRecycled: fromLSN must be > checkpointLSN. The flusher - // only advances checkpointLSN AFTER writing the corresponding - // extent blocks; entries with LSN <= checkpointLSN are no longer - // available in the WAL (their physical WAL space may have been - // reused by newer appends). - if fromLSN <= checkpointLSN && checkpointLSN > 0 { + // G6 §1.A α retention gate: the strict pre-G6 recycle threshold + // is checkpointLSN; G6 introduces an operator-tunable retention + // window so a slow replica still has a recovery scan path while + // it lags within the configured envelope. + // + // Effective recycle floor: + // floor = checkpointLSN - retentionLSNs (saturating to 0) + // + // fromLSN is recycled when fromLSN <= floor (strict <= preserved + // from pre-G6 to keep the boundary semantic identical: an LSN + // equal to the floor IS recycled). retentionLSNs == 0 reduces to + // the pre-G6 'fromLSN <= checkpointLSN' gate exactly. + // + // Pinned by: INV-G6-CATCHUP-CONVERGES-WITHIN-RETENTION (positive) + // + INV-G6-RETENTION-POLICY-OPERATOR-VISIBLE (the knob itself). + floor := checkpointLSN + if retentionLSNs >= floor { + floor = 0 + } else { + floor = checkpointLSN - retentionLSNs + } + if fromLSN <= floor && checkpointLSN > 0 { // T4d-1: wrap in typed RecoveryFailure so transport can // extract the kind via errors.As. errors.Is(err, // ErrWALRecycled) still works via Unwrap, preserving // pre-T4d-1 callers during the migration window. return NewWALRecycledFailure( ErrWALRecycled, - fmt.Sprintf("fromLSN=%d checkpointLSN=%d headLSN=%d", fromLSN, checkpointLSN, headLSN), + fmt.Sprintf("fromLSN=%d checkpointLSN=%d headLSN=%d retentionLSNs=%d floor=%d", + fromLSN, checkpointLSN, headLSN, retentionLSNs, floor), ) } if fromLSN >= headLSN { diff --git a/seaweed-block/core/storage/walstore_retention_test.go b/seaweed-block/core/storage/walstore_retention_test.go new file mode 100644 index 0000000000..3e496b0e34 --- /dev/null +++ b/seaweed-block/core/storage/walstore_retention_test.go @@ -0,0 +1,183 @@ +package storage + +import ( + "errors" + "path/filepath" + "testing" +) + +// G6 §1.A α + §2 substrate retention-gate tests: +// +// Pre-G6: walstore's recovery scan rejects fromLSN <= checkpointLSN +// (strict gate; G5-5C scenario D evidence). +// +// G6: WALRetentionLSNs widens the window so fromLSN > (checkpointLSN +// - retention) is still scannable. This buys a slow replica room to +// catch up before the engine has to escalate to rebuild. +// +// Pinned by: +// - INV-G6-CATCHUP-CONVERGES-WITHIN-RETENTION (positive: within window +// scan succeeds) +// - INV-G6-RETENTION-POLICY-OPERATOR-VISIBLE (the knob is a real +// operator-tunable plumbed from --wal-retention-lsns) + +// freshWALStore creates a walstore in a temp dir and returns it. +// Uses small block geometry — the tests exercise scan-gate semantics, +// not block-IO performance. +func freshWALStore(t *testing.T) *WALStore { + t.Helper() + dir := t.TempDir() + path := filepath.Join(dir, "v.bin") + ws, err := CreateWALStore(path, 64, 4096) + if err != nil { + t.Fatalf("CreateWALStore: %v", err) + } + t.Cleanup(func() { _ = ws.Close() }) + return ws +} + +// advanceCheckpointForTest writes data to grow nextLSN, then forces +// the in-memory checkpointLSN to a chosen value so the test can +// exercise the retention gate at a known boundary. Test-only path — +// production advances checkpointLSN via the flusher. +func advanceCheckpointForTest(t *testing.T, ws *WALStore, lsn uint64) { + t.Helper() + ws.mu.Lock() + defer ws.mu.Unlock() + if lsn >= ws.nextLSN { + ws.nextLSN = lsn + 1 + } + ws.checkpointLSN = lsn +} + +// fakeRecoveryEntry is a tiny consumer for ScanLBAs whose only +// purpose is to count callbacks. The retention-gate tests don't +// care about the entries themselves — only whether the scan +// returns or rejects. +type recoveryEntryCounter struct { + count int +} + +func (c *recoveryEntryCounter) onEntry(RecoveryEntry) error { + c.count++ + return nil +} + +// TestWALStore_RecoveryRetention_Default_StrictRecycle pins pre-G6 +// behavior under the new code: when WALRetentionLSNs is 0 (default), +// the gate behaves exactly as before — fromLSN <= checkpointLSN is +// rejected with WALRecycled. +func TestWALStore_RecoveryRetention_Default_StrictRecycle(t *testing.T) { + ws := freshWALStore(t) + advanceCheckpointForTest(t, ws, 100) + + if got := ws.RecoveryRetentionLSNs(); got != 0 { + t.Fatalf("default retention = %d, want 0", got) + } + + // fromLSN = 50 (well under checkpoint=100) must be recycled. + c := &recoveryEntryCounter{} + err := ws.ScanLBAs(50, c.onEntry) + if err == nil { + t.Fatal("fromLSN=50 with checkpoint=100 + retention=0 should be recycled") + } + if !errors.Is(err, ErrWALRecycled) { + t.Errorf("expected ErrWALRecycled (or unwrap chain match), got %v", err) + } + + // fromLSN = 100 is at-or-below checkpoint → still recycled + // (boundary preserved: <= is rejected, > is accepted). + err = ws.ScanLBAs(100, c.onEntry) + if !errors.Is(err, ErrWALRecycled) { + t.Errorf("fromLSN=100 (== checkpoint) with retention=0 should be recycled, got %v", err) + } +} + +// TestWALStore_RecoveryRetention_NonZero_WidensWindow verifies the +// G6 α path: setting retention=N accepts fromLSN as low as +// checkpointLSN - N (exclusive: at floor still rejected; above floor +// accepted). +func TestWALStore_RecoveryRetention_NonZero_WidensWindow(t *testing.T) { + ws := freshWALStore(t) + advanceCheckpointForTest(t, ws, 100) + ws.SetRecoveryRetentionLSNs(20) + if got := ws.RecoveryRetentionLSNs(); got != 20 { + t.Fatalf("retention after Set: got %d, want 20", got) + } + + // floor = 100 - 20 = 80; fromLSN > 80 is accepted, fromLSN <= 80 + // is rejected. + c := &recoveryEntryCounter{} + + // fromLSN = 90: above floor → accepted (no error). The scan + // itself may produce no entries because we haven't written + // anything in the window; that's fine — this test only pins the + // gate decision, not scan content. + if err := ws.ScanLBAs(90, c.onEntry); err != nil { + t.Errorf("fromLSN=90 with checkpoint=100 + retention=20 should be accepted, got %v", err) + } + + // fromLSN = 81: above floor (80) → accepted. + if err := ws.ScanLBAs(81, c.onEntry); err != nil { + t.Errorf("fromLSN=81 with checkpoint=100 + retention=20 should be accepted (floor=80), got %v", err) + } + + // fromLSN = 80: at floor → rejected (<= floor recycles). + err := ws.ScanLBAs(80, c.onEntry) + if !errors.Is(err, ErrWALRecycled) { + t.Errorf("fromLSN=80 (==floor) should be recycled, got %v", err) + } + + // fromLSN = 50: well below floor → rejected. + err = ws.ScanLBAs(50, c.onEntry) + if !errors.Is(err, ErrWALRecycled) { + t.Errorf("fromLSN=50 (= +// checkpoint, the floor saturates to 0 and any fromLSN > 0 is +// accepted. +func TestWALStore_RecoveryRetention_LargerThanCheckpoint_ClampsToZero(t *testing.T) { + ws := freshWALStore(t) + advanceCheckpointForTest(t, ws, 100) + ws.SetRecoveryRetentionLSNs(1_000_000) // way larger than checkpoint + + c := &recoveryEntryCounter{} + // fromLSN = 1: floor saturates to 0; 1 > 0 → accepted. + if err := ws.ScanLBAs(1, c.onEntry); err != nil { + t.Errorf("fromLSN=1 with retention >> checkpoint should be accepted (floor saturates to 0), got %v", err) + } +} + +// TestWALStore_RecoveryRetention_TypedFailureKind verifies that the +// recycle-rejection error is the typed RecoveryFailure envelope (so +// the transport layer can extract via errors.As). This pins the +// substrate side of INV-G6-WALRECYCLE-DISPATCHES-REBUILD: if the +// substrate returned a bare sentinel here, transport's +// classifyRecoveryFailure would fall through to RecoveryFailureTransport +// and the engine wouldn't escalate to rebuild. +func TestWALStore_RecoveryRetention_TypedFailureKind(t *testing.T) { + ws := freshWALStore(t) + advanceCheckpointForTest(t, ws, 100) + ws.SetRecoveryRetentionLSNs(20) + + c := &recoveryEntryCounter{} + err := ws.ScanLBAs(50, c.onEntry) // below floor 80 → rejected + if err == nil { + t.Fatal("expected recycle error") + } + + var rf *RecoveryFailure + if !errors.As(err, &rf) { + t.Fatalf("expected typed *RecoveryFailure (so transport can map kind via errors.As), got %T (%v)", err, err) + } + if rf.Kind != StorageRecoveryFailureWALRecycled { + t.Errorf("RecoveryFailure.Kind = %v, want StorageRecoveryFailureWALRecycled", rf.Kind) + } + // errors.Is chain still works for legacy callers. + if !errors.Is(err, ErrWALRecycled) { + t.Error("errors.Is(err, ErrWALRecycled) should still hold via Unwrap chain") + } +}