From f3a2b35c948ea7e7df5ab610209646972f8b5eb5 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 17 Nov 2026 03:17:19 -0800 Subject: [PATCH] storage: invalidate bound map proofs at actual Recover start and end --- .../core/storage/chunk_map_publication_v3.go | 13 ++ seaweed-block/core/storage/walstore.go | 15 +- .../storage/walstore_map_recover_v3_test.go | 155 ++++++++++++++++++ seaweed-block/docs/design/invariants.md | 4 +- 4 files changed, 184 insertions(+), 3 deletions(-) create mode 100644 seaweed-block/core/storage/walstore_map_recover_v3_test.go diff --git a/seaweed-block/core/storage/chunk_map_publication_v3.go b/seaweed-block/core/storage/chunk_map_publication_v3.go index 943b0390ab..bc9d4f2a8a 100644 --- a/seaweed-block/core/storage/chunk_map_publication_v3.go +++ b/seaweed-block/core/storage/chunk_map_publication_v3.go @@ -129,3 +129,16 @@ func (p *descriptorPublisherV3) publishMapV3(storeMu sync.Locker, snap func(), p return nil }, prepared) } + +// invalidateMapProofV3 is called under WALStore.mu at a lifecycle boundary. +// Taking the existing descMu orders the epoch change after any publication +// already inside descriptor I/O. It performs no callback, allocation or I/O. +// A not-yet-bound dark store has no candidate domain to invalidate. +func (p *descriptorPublisherV3) invalidateMapProofV3() error { + p.descMu.Lock() + defer p.descMu.Unlock() + if p.mapDomain == nil { + return nil + } + return p.mapDomain.invalidateV3() +} diff --git a/seaweed-block/core/storage/walstore.go b/seaweed-block/core/storage/walstore.go index 6f084e834d..107845be96 100644 --- a/seaweed-block/core/storage/walstore.go +++ b/seaweed-block/core/storage/walstore.go @@ -568,7 +568,7 @@ func (s *WALStore) HolesSuspected() uint64 { // // Idempotent: calling Recover twice on the same on-disk state yields // identical results. -func (s *WALStore) Recover() (uint64, error) { +func (s *WALStore) Recover() (frontier uint64, err error) { // Recover republishes the dirty map like a write: it holds the capture // barrier shared, so it can never publish bytes between a quiesced // cut's Sync (which fixes H) and that cut's copy. @@ -579,6 +579,19 @@ func (s *WALStore) Recover() (uint64, error) { defer s.lifecycleMu.RUnlock() s.mu.Lock() defer s.mu.Unlock() + if s.v3 != nil { + // The store lock orders both epoch boundaries with real map publishers. + // START invalidates old candidates; END also invalidates candidates + // prepared while this Recover was in flight, including on failure. + defer func() { + if endErr := s.v3.pub.invalidateMapProofV3(); endErr != nil { + frontier, err = 0, errors.Join(err, endErr) + } + }() + if err := s.v3.pub.invalidateMapProofV3(); err != nil { + return 0, err + } + } if s.closed { return 0, errors.New("storage: Recover after Close") } diff --git a/seaweed-block/core/storage/walstore_map_recover_v3_test.go b/seaweed-block/core/storage/walstore_map_recover_v3_test.go new file mode 100644 index 0000000000..138bf6f503 --- /dev/null +++ b/seaweed-block/core/storage/walstore_map_recover_v3_test.go @@ -0,0 +1,155 @@ +package storage + +import ( + "errors" + "path/filepath" + "sync" + "testing" + "time" +) + +// Row7 lifecycle slice: bind a durable map to the actual store publisher. +// This fixture does not claim automatic provider/chunk-layer map attachment. +func bindRecoveryMapV3(t *testing.T, s *WALStore) (*chunkLSNMapV3, *mapProofEpochV3, []chunkLSNEntryV3, *chunkMapCandidateV3) { + t.Helper() + d := s.v3.pub.current() + m, err := createChunkLSNMapV3(filepath.Join(t.TempDir(), "map"), d, 4) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + if err := m.Close(); err != nil { + t.Error(err) + } + }) + shape, err := mapShapeForV3(d, 4) + if err != nil { + t.Fatal(err) + } + es := make([]chunkLSNEntryV3, int(shape.chunks)) + for i := range es { + es[i].Unknown = true + } + c, err := m.Prepare(d.MapGeneration+1, d.CheckpointLSN, es, nil) + if err != nil { + t.Fatal(err) + } + if _, err = s.v3.pub.publish(&s.mu, nil, func(n *descriptorV3) error { *n = c.descriptor(*n); return nil }); err != nil { + t.Fatal(err) + } + proof := newMapProofEpochV3() + if err = s.v3.pub.bindMapV3(c, proof); err != nil { + t.Fatal(err) + } + return m, proof, es, c +} + +func TestWALStoreV3_RealRecoverInvalidatesMapProofAtStartAndEnd(t *testing.T) { + s, _ := newStoreV3(t, WModeLagged) + t.Cleanup(func() { + if err := s.Close(); err != nil { + t.Error(err) + } + }) + m, proof, es, current := bindRecoveryMapV3(t, s) + before, err := prepareMapPublicationV3(m, proof, current.generation+1, 0, es, current) + if err != nil { + t.Fatal(err) + } + startEpoch := proof.epoch.Load() + entered, resume, joined := make(chan struct{}), make(chan struct{}), make(chan struct{}) + var once sync.Once + release := func() { once.Do(func() { close(resume) }) } + done := make(chan error, 1) + // The existing slot-write hook parks the real Recover after START and before END. + s.v3.testBeforeSlotWrite = func() error { close(entered); <-resume; return nil } + t.Cleanup(func() { + release() + select { + case <-joined: + case <-time.After(5 * time.Second): + t.Error("Recover did not join") + } + }) + go func() { defer close(joined); _, e := s.Recover(); done <- e }() + select { + case <-entered: + case <-time.After(5 * time.Second): + t.Fatal("Recover did not reach its slot publication") + } + if before.proof.validV3(proof) || proof.epoch.Load() != startEpoch+1 { + t.Error("actual Recover START did not invalidate the previous map proof") + } + during, err := prepareMapPublicationV3(m, proof, current.generation+2, 0, es, current) + if err != nil { + t.Fatal(err) + } + release() + select { + case err = <-done: + case <-time.After(5 * time.Second): + t.Fatal("Recover did not finish") + } + select { + case <-joined: + case <-time.After(5 * time.Second): + t.Fatal("Recover result arrived but worker did not join") + } + s.v3.testBeforeSlotWrite = nil + if err != nil { + t.Fatal(err) + } + if proof.epoch.Load() != startEpoch+2 { + t.Error("actual Recover END did not advance the map proof epoch") + } + for label, prepared := range map[string]*preparedMapPublicationV3{"before": before, "during": during} { + if _, err = s.v3.pub.publishMapV3(&s.mu, nil, prepared, nil); !errors.Is(err, ErrMapCoverageStale) { + t.Errorf("%s real Recover candidate was not refused as stale: %v", label, err) + } + } + fresh, err := prepareMapPublicationV3(m, proof, current.generation+3, 0, es, current) + if err != nil { + t.Fatal(err) + } + if _, err = s.v3.pub.publishMapV3(&s.mu, nil, fresh, nil); err != nil { + t.Fatalf("fresh post-Recover candidate refused: %v", err) + } +} + +func TestWALStoreV3_FailedRecoverInvalidatesMapProofAtBothBoundaries(t *testing.T) { + s, _ := newStoreV3(t, WModeStrict) + t.Cleanup(func() { + if err := s.Close(); err != nil { + t.Error(err) + } + }) + if _, err := s.Write(0, blk(0x51)); err != nil { + t.Fatal(err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + m, proof, es, current := bindRecoveryMapV3(t, s) + before, err := prepareMapPublicationV3(m, proof, current.generation+1, 0, es, current) + if err != nil { + t.Fatal(err) + } + epoch := proof.epoch.Load() + off, _, _, _, ok := s.dm.get(0) + if !ok { + t.Fatal("synced write missing from WAL dirty map") + } + // Corrupt an acknowledged WAL payload: R installing is refused). A failed slot write (full or partial) or fsync publishes nothing. It latches the store fault inside the fsync leaf, before `fileSyncMu` is released, so a queued store Sync cannot acknowledge through it, keeps the uncertain candidate pinned and refuses every later publication, rollover and reuse until a reopen reads the slots back. A fault latched mid-flight is refused at the success boundary. A counter above 2^64-2 is refused with `ErrCounterExhausted` before any write. When the fallback slot pins reuse, a metadata-only rollover advances the floor, and no floor is ever computed across nonces. | M1 Serving (v3 descriptor publication) | `core/storage/descriptor_v3.go` `publish`, `mergeDescriptorV3`, `baseTransitionAllowedV3`, `rolloverIfPinned`, `reuseFloor` | `TestDescriptorV3PublishAlternatesSlotsAndReopenSelectsNewest`, `TestDescriptorV3MergeIsMonotonicAndRefusesForbiddenChanges`, `TestDescriptorV3ConcurrentPublishersNeverRegress`, `TestDescriptorV3LockOrderRecorder`, `TestDescriptorV3FsyncFailureIsStickyAndPublishesNothing`, `TestDescriptorV3FaultLatchedDuringPublicationRefusesAtSuccessBoundary`, `TestDescriptorV3FullRingRolloverAdvancesTheFloorWithoutAnyChange`, `TestDescriptorV3RolloverFsyncFailureKeepsTheFloorPinned`, `TestDescriptorV3MixedNoncesNeverYieldAReuseFloor`, `TestDescriptorV3BaseTransitionTable`, `TestDescriptorV3SlotWriteErrorLatchesAndPinsTheCandidate`, `TestDescriptorV3PublicationCounterExhaustion`, `TestDescriptorV3QueuedStoreSyncCannotAckAfterSlotWriteError` (`core/storage/descriptor_v3_test.go`) | — | STUB | | `INV-WAL-V3-W-001` | v3 Sync acknowledges only after an fsync covers the batch. In mode C (the default) the slot carries the previous batch's acknowledged W and the batch's single fsync covers WAL and slot; in mode A the WAL fsync precedes a slot publication with W = H. Recovery refuses (`wal_corrupt`) when the contiguous prefix R above max(CheckpointLSN, BaseLSN) is below W* = max(slot W, max trusted DurableLSN). Mode C's only unprotected acknowledged data is the newest batch, against media corruption before the next Sync or the idle refresh; `SetWMode` and the refresh close that window. | M1 Recovering → Serving \| RecoveryFailed; M1 write lifecycle: Appended → Synced (v3) | `core/storage/walstore_v3.go` `WALStore.syncWALBatchV3`, `refreshW`, `SetWMode`, `recoverV3`, `appendWriteV3`; `core/storage/recovery_v3.go` `decideRecoveryV3`, `contiguousPrefixV3` | `TestWALStoreV3RecoversEveryAcknowledgedWriteInBothModes`, `TestWALStoreV3ModeCWindowIsExactlyTheNewestBatch`, `TestWALStoreV3RefreshAndSetWModeCloseTheWindow`, `TestWALStoreV3TornUnsyncedTailIsNeverAFalseCorrupt`, `TestWALStoreV3AppendWriteErrorLatchesTheStore`, `TestWALStoreV3FlusherWritesTheExtentButHoldsTheCheckpointUntilTheMap`, `TestWALStoreV3SyncRechecksTheFaultAtTheAckBoundary`, `TestWALStoreV3SetWModeWaitsForAHeldBatch`, `TestWALStoreV3NoBatchAcksUnderAStaleModeAfterSetWMode`, `TestWALStoreV3SetWModeCrashCases`, `TestWALStoreV3SameOpenRecoverResetsTheAcknowledgedFrontier`, `TestWALStoreV3InstallingScanErrorIsTypedNotReady`, `TestWALStoreV3FlusherCycleRunsTheIdleRefresh` (`core/storage/walstore_v3_test.go`); `TestRecoveryV3Decision`, `TestRecoveryV3ContiguousPrefix` (`core/storage/recovery_v3_test.go`) | `WALFormat` composed model (claude05, r14 run) | STUB | @@ -294,7 +294,7 @@ The "Machine / transition" column refers to Part A. Notes under a table record w Notes: - `INV-WAL-V3-LSN-ORDER-001`: the writer gate prevents an out-of-order physical chain whose dropped unacked middle record could later resurrect. Raw scanner/recovery integrity verdicts and the v3 ApplyEntry superseded-no-op/refusal policy are separate caller obligations. Legacy ApplyEntry and production v2 behavior are unchanged. -- `INV-WAL-V3-MAP-PUBLISH-001`: dark-core controls only. Recover START and END invalidation (success/failure), reset/install transition hooks and real checkpoint/capture/provider wiring still require row 5b/7 integration. The lifecycle tests explicitly drive invalidation primitives; they do not claim to exercise a real Recover or flusher. The owner serializes lifecycle transitions with publication using its existing lifecycle admission. No new lock or callback is taken under descMu; validation uses immutable candidate fields and atomic proof loads. +- `INV-WAL-V3-MAP-PUBLISH-001`: Real Recover START and END invalidation is wired and controlled on success and WAL-integrity failure, with a durable map manually bound to the actual store publisher. Automatic map attach, reset/install transitions and checkpoint/capture/provider wiring still require integration. Existing dark lifecycle tests drive invalidation primitives; only the two explicitly named real-store controls exercise actual Recover, and none claims flusher or provider coverage. The owner serializes lifecycle transitions with publication using its existing lifecycle admission. No new lock or callback is taken under descMu; validation uses immutable candidate fields and atomic proof loads. - `INV-WAL-V3-MAP-BYTES-001`: row 6 prepares durable pinned tuples only. Root/merged-descriptor coverage, mutation proofs and real chunk/provider replacement are row 7; no serving or checkpoint advance is authorized by the codec/store. No sidecar page reclamation is implemented, so fallback or uncertain generations remain pinned conservatively.