From 49b9fe67b7e3da312a5cc07052aa4f7b43a6a4c8 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 00:33:33 -0800 Subject: [PATCH 01/14] fix(storage): retain checkpoint proof across newer WAL appends --- .../checkpoint_append_progress_v3_test.go | 131 ++++++++++++++++++ .../core/storage/chunk_layer_map_v3.go | 3 +- .../walstore_map_checkpoint_v3_test.go | 8 +- seaweed-block/core/storage/walstore_v3.go | 15 +- 4 files changed, 142 insertions(+), 15 deletions(-) create mode 100644 seaweed-block/core/storage/checkpoint_append_progress_v3_test.go diff --git a/seaweed-block/core/storage/checkpoint_append_progress_v3_test.go b/seaweed-block/core/storage/checkpoint_append_progress_v3_test.go new file mode 100644 index 0000000000..e16a466364 --- /dev/null +++ b/seaweed-block/core/storage/checkpoint_append_progress_v3_test.go @@ -0,0 +1,131 @@ +package storage + +import ( + "bytes" + "errors" + "testing" +) + +func TestChunkLayerV3_CheckpointProgressUnderContinuousAppends(t *testing.T) { + s, _ := newMappedCheckpointStoreV3(t) + remote := newFakeChunkRemote() + mustAttach(t, s, remote, ctConfig(1)) + if _, err := s.Write(0, blk(1)); err != nil { + t.Fatal(err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + realSync := s.v3.ownedMap.syncFile + t.Cleanup(func() { s.v3.ownedMap.syncFile = realSync }) + refusals := 0 + for round := uint32(0); round < 8; round++ { + injected := false + s.v3.ownedMap.syncFile = func() error { + if !injected { + injected = true + if _, err := s.Write(round+1, blk(byte(round+2))); err != nil { + return err + } + } + return realSync() + } + err := s.flusher.flushOnce() + s.v3.ownedMap.syncFile = realSync + if err != nil && !errors.Is(err, ErrMapCoverageStale) { + t.Fatal(err) + } + if errors.Is(err, ErrMapCoverageStale) { + refusals++ + } + if !injected { + t.Fatal("cycle did not overlap a write") + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + } + cp := s.CheckpointLSN() + t.Logf("continuous writes: cycles8 refusals%d cp%d wack%d dirty%d", refusals, cp, s.v3.wack.Load(), s.dm.len()) + if cp == 0 { + t.Fatal("checkpoint made no progress across eight completed extent/map persistence cycles while newer appends continued") + } +} + +func TestCheckpointV3_NewerBatchReplaysAfterPreparedPrefix(t *testing.T) { + s, path := newMappedCheckpointStoreV3(t) + remote := newFakeChunkRemote() + layer := mustAttach(t, s, remote, ctConfig(1)) + if _, err := s.Write(1, blk(0x11)); err != nil { + t.Fatal(err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + s.v3.testMapPrepared = func() { + if _, err := s.WriteBatch(1, [][]byte{blk(0xB2), blk(0xC3)}); err != nil { + t.Fatal(err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + } + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + s.v3.testMapPrepared = nil + d := s.v3.pub.current() + if d.CheckpointLSN != 1 || d.MapCoveredCheckpoint != 1 || s.dm.len() != 2 { + t.Fatalf("prefix cp=%d C=%d dirty=%d", d.CheckpointLSN, d.MapCoveredCheckpoint, s.dm.len()) + } + if err := layer.Close(); err != nil { + t.Fatal(err) + } + crashRecoveryHardeningStore(t, s) + s.mu.Lock() + s.closed = true + s.mu.Unlock() + r, err := openWALStoreV3ForTest(path) + if err != nil { + t.Fatal(err) + } + r.DisableAutoFlushForRecoveryTest() + t.Cleanup(func() { _ = r.Close() }) + if _, err = r.Recover(); err != nil { + t.Fatal(err) + } + for lba, want := range map[uint32][]byte{1: blk(0xB2), 2: blk(0xC3)} { + if !bytes.Equal(readV3(t, r, lba), want) { + t.Fatalf("replayed LBA%d lost", lba) + } + } + restored := mustAttach(t, r, remote, ctConfig(1)) + cut, err := restored.Cut(ctTimeout(t)) + if err != nil { + t.Fatal(err) + } + image := remote.imageOf(t, cut.Head) + if !bytes.Equal(image[4096:8192], blk(0xB2)) || !bytes.Equal(image[8192:12288], blk(0xC3)) { + t.Fatal("capture omitted newer replayed batch") + } +} + +func TestCheckpointV3_EffectiveBaseWriteStillInvalidatesProof(t *testing.T) { + s, _ := newMappedCheckpointStoreV3(t) + h := beginV3(t, s, 0, idA) + cp := s.CheckpointLSN() + prepared, err := s.prepareOwnedMapCheckpointV3(cp) + if err != nil { + t.Fatal(err) + } + before := s.v3.pub.current() + if err = h.WriteBase(1, blk(0xA7)); err != nil { + t.Fatal(err) + } + if _, err = s.v3.pub.publishMapV3(&s.mu, nil, prepared, nil); !errors.Is(err, ErrMapCoverageStale) { + t.Fatalf("effective BASE mutation proof accepted: %v", err) + } + if s.v3.pub.current() != before { + t.Fatal("stale BASE candidate changed slots") + } +} diff --git a/seaweed-block/core/storage/chunk_layer_map_v3.go b/seaweed-block/core/storage/chunk_layer_map_v3.go index 295c436f5e..28b62756b0 100644 --- a/seaweed-block/core/storage/chunk_layer_map_v3.go +++ b/seaweed-block/core/storage/chunk_layer_map_v3.go @@ -9,7 +9,8 @@ func (l *chunkLayerImpl) usesOwnedMapV3() bool { return l.s.v3 != nil && l.s.v3. // (or an authority-checked no-op), outside bmMu/stMu and the capture barrier. // The capture's mutation versions were sampled under the quiesced barrier. // Store.mu prevents a WAL append from slipping between the version check and -// the UNKNOWN update. A later write updates max LSN and invalidates proofs. +// the UNKNOWN update. A later WAL append updates max LSN and stays retained; +// an effective UNKNOWN change or lifecycle transition invalidates proofs. // A failed map publication leaves the old disk UNKNOWN conservative; a map // persistence failure also latches the store, while the remote HEAD remains // the successfully captured image. No remote durability claim is undone. diff --git a/seaweed-block/core/storage/walstore_map_checkpoint_v3_test.go b/seaweed-block/core/storage/walstore_map_checkpoint_v3_test.go index b479497f55..27bba23235 100644 --- a/seaweed-block/core/storage/walstore_map_checkpoint_v3_test.go +++ b/seaweed-block/core/storage/walstore_map_checkpoint_v3_test.go @@ -144,8 +144,10 @@ func TestWALStoreV3_PreparedCheckpointRefusesChangedProof(t *testing.T) { release() select { case err := <-done: - if !errors.Is(err, ErrMapCoverageStale) { + if event == "recover" && !errors.Is(err, ErrMapCoverageStale) { t.Errorf("stale prepared checkpoint=%v", err) + } else if event == "write" && err != nil { + t.Errorf("newer retained append invalidated prefix coverage: %v", err) } case <-time.After(5 * time.Second): t.Fatal("flusher did not settle") @@ -156,8 +158,10 @@ func TestWALStoreV3_PreparedCheckpointRefusesChangedProof(t *testing.T) { t.Fatal("flusher result without join") } s.v3.testMapPrepared = nil - if s.v3.pub.current() != before { + if event == "recover" && s.v3.pub.current() != before { t.Error("stale proof published a checkpoint") + } else if event == "write" && s.CheckpointLSN() != 1 { + t.Error("newer retained append blocked the older checkpoint") } if s.stickyIOFault() != nil { t.Error("proof refusal incorrectly latched a persistence fault") diff --git a/seaweed-block/core/storage/walstore_v3.go b/seaweed-block/core/storage/walstore_v3.go index ea7f8d68fd..d894405060 100644 --- a/seaweed-block/core/storage/walstore_v3.go +++ b/seaweed-block/core/storage/walstore_v3.go @@ -654,13 +654,9 @@ func (s *WALStore) appendWriteV3(lba uint32, data []byte, lsn uint64) (uint64, e if s.v3.w == nil { return 0, errWALBindingV3 // a half-published reset before its Recover } - // Reserve proof invalidation before the WAL can change. This is under - // the existing store lock; a refused append only causes conservative retry. - if s.v3.mapProof != nil { - if err := s.v3.mapProof.mutatedV3(); err != nil { - return 0, err - } - } + // A strictly newer append stays in the retained WAL suffix. It cannot + // invalidate coverage of an older checkpoint prefix; effective BASE and + // lifecycle mutations still invalidate the map proof at their own seams. if err := s.rolloverCheckpointV3Locked(); err != nil { return 0, err } @@ -710,11 +706,6 @@ func (s *WALStore) writeBatchV3Locked(startLBA uint32, blocks [][]byte, firstLSN s.instr.recordWALCopy(len(payload), time.Since(copyStart)) n := uint64(len(blocks)) lastLSN := firstLSN + n - 1 - if s.v3.mapProof != nil { - if err := s.v3.mapProof.mutatedV3(); err != nil { - return nil, err - } - } e := walEntryV3{LSN: firstLSN, BatchCount: n, Type: walEntryWriteBatch, LBA: uint64(startLBA), Length: uint32(len(payload)), Data: payload} if err := s.rolloverCheckpointV3Locked(); err != nil { return nil, err From 7887101d269758c865fc967a2b5964a9bbc9ebd9 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 00:35:46 -0800 Subject: [PATCH 02/14] docs: record prefix proof regression coverage --- seaweed-block/docs/design/invariants.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 43a8867335..653ffda191 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -335,7 +335,7 @@ The "Machine / transition" column refers to Part A. Notes under a table record w | `INV-WAL-V3-OWNER-001` | v3 read/write open, offline readonly open and migrate-v3 acquire the same exclusive nonblocking OS file lock before reading slots or changing bytes. Contention refuses with volume locked; descriptor close releases it, allowing retry. | M1 open admission / offline migration precondition | `core/storage/volume_lock*.go`; `walstore_v3.go`; `walstore_readonly_v3.go`; `cmd/sw-block/migrate.go` | `TestMigrateV3RefusesAnOpenV3Volume`, `TestMigrateV3ExcludesOpenUntilCommitFinishes` (tag `swblock_format_v3_test`), `TestWALStoreV3CreatorKeepsOwnershipThroughPublication`, `TestWALStoreV3OwnerExcludesOpenAndReadOnly` | OS mutual exclusion is a caller obligation, outside the abstract crash model; existing open states unchanged | STUB | | `INV-WAL-V3-CATCHUP-001` | A dark v3 catch-up source refuses while installing, including an empty at-head request. Requests covered by an installed BASE require rebuild (typed WALRecycled); damage in retained WAL remains an integrity failure. Before emitting any entries the scan revalidates recovery generation, nonce, BASE state/ID and install epoch, so begin/complete/retire ABA cannot publish a superseded prefix. | M1 BASE lifecycle / M3 CatchingUp (dark callers) | `core/storage/walstore_recovery.go` `ScanLBAs`, `scanLBAsV3`, `v3CatchUpEntries` | `TestCatchUpV3InstallingAtHeadRefuses`, `TestCatchUpV3CompletedBASEUsesRebuild`, `TestCatchUpV3InstallRetireABARefusesOldScan`, `TestCatchUpV3CorruptFirstRecordFails`, `TestCatchUpV3CorruptMiddleRecordFails`, `TestCatchUpV3CompletedBASESuffix` (tag `swblock_format_v3_test`, actual catch-up sender) | Existing BASE and catch-up transitions unchanged; this physical scan/source-lifetime obligation is covered by deterministic caller tests | STUB | | `INV-WAL-V3-BINDING-001` | The dark v3 writer stamps the selected nonce and absolute cursor, fits each append/padding inside the dual-slot reuse floor, and refuses later I/O after a pwrite failure. A dark scanner checks nonce and exact expected cursor before using Length/count, checks the full record again, skips only geometric end slack, and stops at the first untrusted record without payload resynchronization. It returns a typed scan result, never ACK or serving permission. | M1 Recovering (dark muscles only) | `core/storage/wal_io_v3.go` `append`, `scanWALV3`, `walSnapshotV3` | `TestWALIOV3_RealWriterReopenScan`, `TestWALIOV3_WrapPaddingAndSlack`, `TestWALIOV3_StopsAtBindingBeforeEmbeddedRecord`, `TestWALIOV3_EmbeddedRecordInPayloadIsNotScanned`, `TestWALIOV3_InstalledScanBeginsAtMaxTail`, `TestWALIOV3_FloorAndPwriteFailureRefuse` | Record/lap admission is abstracted in composed WALFormatR5; physical framing/wrap boundaries remain code-test obligations | STUB | -| `INV-WAL-V3-MAP-PUBLISH-001` | After a dark publisher binds a validated map, every publication carries a matching immutable tuple with merged checkpoint <= C <= merged W. A prepared replacement needs a higher generation, non-regressing coverage and the same sidecar/open proof domain with unchanged epoch/mutation token. Stale candidates write no slot; W-only rollover carries the current root; unknown slot outcomes pin dependencies. | M1 (dark map publication only; checkpoint/capture caller wiring pending) | `core/storage/chunk_map_publication_v3.go`; `core/storage/descriptor_v3.go` `publishLockedWithMapV3` | `TestWALStoreV3_SeedNeverUsesLegacyDescriptorWriter`, `TestDurableProviderV3_InvalidHEADFrontierRefusesBeforeClaim`, `TestDurableProviderV3_HEADRestorePreservesRemoteImageAndNextLSN`, `TestDurableProviderV3_HEADRestoreAfterLostClaimResponse`, `TestDurableProviderV3_MappedCheckpointCaptureAndReopen`, `TestDurableProviderV3_MissingMapRefusesBeforeBackend`, `TestDurableProviderV3_DefaultSelectorCreatesV3` (tag `swblock_format_v3_test`), `TestChunkLayerV3_MapOnlyCaptureNeedsNoLegacyBitmap`, `TestChunkLayerV3_IgnoresProvidedLegacyBitmap`, `TestChunkLayerV3_MapOnlyFreshZeroHEADPreservesLocalWrites`, `TestChunkLayerV3_MapOnlyRefusesLegacyBASEHeaderMutation`, `TestChunkLayerV3_MapStatusConcurrentClose`, `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, `TestChunkLayerV3_MaxLSNSelectsAfterReopenWithCleanLegacyBitmap`, `TestChunkLayerV3_ChangedCaptureTokenKeepsUNKNOWN`, `TestChunkLayerV3_UnsettledCaptureNeverClearsUNKNOWN`, `TestChunkLayerV3_RefusesMapGeometryBeforeRemote`, `TestWALStoreV3_AutomaticMapCheckpoint`, `TestWALStoreV3_PreparedCheckpointRefusesChangedProof`, `TestWALStoreV3_AutomaticMapPersistenceFailureLatchesStore`, `TestWALStoreV3_UncertainMapCheckpointPinsDependencies`, `TestWALStoreV3_AutomaticCheckpointMetadataOrderAndRetry`, `TestWALStoreV3_AutomaticMapRecoverRebuildsCoverage`, `TestWALStoreV3_OpenRequiresBothMapGenerations`, `TestWALStoreV3_MappedCreateOpenOwnsMap`, `TestMapPublicationV3_BindValidatesBothSlotDependencies`, `TestMapPublicationV3_HeldPublicationsBothOrders`, `TestMapPublicationV3_IsolatedMergedCoverageAndWPositive`, `TestMapPublicationV3_ProofEpochAndMutationRefusal`, `TestMapPublicationV3_UncertainFinalResponsePinsCandidate`, `TestMapPublicationV3_CoverageWAndNoUnpreparedRoot`, `TestMapPublicationV3_ProofChangedDuringPersistenceRefuses`; `TestWALStoreV3_RealRecoverInvalidatesMapProofAtStartAndEnd`, `TestWALStoreV3_FailedRecoverInvalidatesMapProofAtBothBoundaries` | WALFormatR5 map coverage / volatile proof epoch; physical caller wiring remains a code obligation | STUB | +| `INV-WAL-V3-MAP-PUBLISH-001` | After a dark publisher binds a validated map, every publication carries a matching immutable tuple with merged checkpoint <= C <= merged W. A prepared replacement needs a higher generation, non-regressing coverage and the same sidecar/open proof domain with unchanged epoch/mutation token. Stale candidates write no slot; W-only rollover carries the current root; unknown slot outcomes pin dependencies. | M1 (dark map publication only; checkpoint/capture caller wiring pending) | `core/storage/chunk_map_publication_v3.go`; `core/storage/descriptor_v3.go` `publishLockedWithMapV3` | `TestWALStoreV3_SeedNeverUsesLegacyDescriptorWriter`, `TestDurableProviderV3_InvalidHEADFrontierRefusesBeforeClaim`, `TestDurableProviderV3_HEADRestorePreservesRemoteImageAndNextLSN`, `TestDurableProviderV3_HEADRestoreAfterLostClaimResponse`, `TestDurableProviderV3_MappedCheckpointCaptureAndReopen`, `TestDurableProviderV3_MissingMapRefusesBeforeBackend`, `TestDurableProviderV3_DefaultSelectorCreatesV3` (tag `swblock_format_v3_test`), `TestChunkLayerV3_MapOnlyCaptureNeedsNoLegacyBitmap`, `TestChunkLayerV3_IgnoresProvidedLegacyBitmap`, `TestChunkLayerV3_MapOnlyFreshZeroHEADPreservesLocalWrites`, `TestChunkLayerV3_MapOnlyRefusesLegacyBASEHeaderMutation`, `TestChunkLayerV3_MapStatusConcurrentClose`, `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, `TestChunkLayerV3_MaxLSNSelectsAfterReopenWithCleanLegacyBitmap`, `TestChunkLayerV3_ChangedCaptureTokenKeepsUNKNOWN`, `TestChunkLayerV3_UnsettledCaptureNeverClearsUNKNOWN`, `TestChunkLayerV3_RefusesMapGeometryBeforeRemote`, `TestWALStoreV3_AutomaticMapCheckpoint`, `TestWALStoreV3_PreparedCheckpointRefusesChangedProof`, `TestChunkLayerV3_CheckpointProgressUnderContinuousAppends`, `TestCheckpointV3_NewerBatchReplaysAfterPreparedPrefix`, `TestCheckpointV3_EffectiveBaseWriteStillInvalidatesProof`, `TestWALStoreV3_AutomaticMapPersistenceFailureLatchesStore`, `TestWALStoreV3_UncertainMapCheckpointPinsDependencies`, `TestWALStoreV3_AutomaticCheckpointMetadataOrderAndRetry`, `TestWALStoreV3_AutomaticMapRecoverRebuildsCoverage`, `TestWALStoreV3_OpenRequiresBothMapGenerations`, `TestWALStoreV3_MappedCreateOpenOwnsMap`, `TestMapPublicationV3_BindValidatesBothSlotDependencies`, `TestMapPublicationV3_HeldPublicationsBothOrders`, `TestMapPublicationV3_IsolatedMergedCoverageAndWPositive`, `TestMapPublicationV3_ProofEpochAndMutationRefusal`, `TestMapPublicationV3_UncertainFinalResponsePinsCandidate`, `TestMapPublicationV3_CoverageWAndNoUnpreparedRoot`, `TestMapPublicationV3_ProofChangedDuringPersistenceRefuses`; `TestWALStoreV3_RealRecoverInvalidatesMapProofAtStartAndEnd`, `TestWALStoreV3_FailedRecoverInvalidatesMapProofAtBothBoundaries` | WALFormatR5 map coverage / volatile proof epoch; physical caller wiring remains a code obligation | STUB | | `INV-WAL-V3-FLUSH-LIFETIME-001` | A dark v3 flusher binds its dirty snapshot and extent materialization to the original even Recover generation. A cycle spanning Recover/reset publishes no checkpoint/map and retires no reused dirty entry. | M1 Recovering / checkpoint publication | `core/storage/flusher.go`; `walstore_map_checkpoint_v3.go`; `walstore_v3.go` `flushLifetimeValidV3` | `TestWALStoreV3_FlushMaterializationBoundToRecoveryLifetime` | Existing recovery/map proof lifetime; implementation correspondence | STUB | | `INV-WAL-V3-MAP-BYTES-001` | A dark v3 map candidate names immutable, owned, identity- and geometry-checked pages and root. Domain-separated body digests, reserved/unused bytes, exact page counts, file bounds and non-aliasing intervals all validate before entries escape. Persistence orders pages/fsync, root/fsync, directory fsync; a persistence-transaction error yields no candidate and latches subsequent I/O; preflight and Stat errors do not latch. Extents are reused only when no live root references them (both slot roots, in-flight candidates, an uncertain candidate until reopen); the free tail is truncated above the highest live page. | M1 (dark map preparation only) | `core/storage/chunk_lsn_map_v3.go` `Prepare`, `readChunkLSNMapV3`; `core/storage/chunk_map_extents_v3.go` (live set, allocation, release, truncation); `core/storage/chunk_map_publication_v3.go` `publishMapV3`; `core/storage/descriptor_v3.go` (slot report, uncertain candidate) | `TestChunkMapV3FileStaysBoundedUnderSteadyCheckpoints` (`core/storage/chunkmap_bounded_v3_test.go`); `TestChunkMapExtentsV3FallbackRootIsNeverReused`, `TestChunkMapExtentsV3NewerInFlightCandidateIsNotReused`, `TestChunkMapExtentsV3CrashBeforePublicationOfAReusedExtent`, `TestChunkMapExtentsV3TruncationKeepsAFallbackAtTheTail`, `TestChunkMapExtentsV3RejectedPublicationsStayBounded`, `TestChunkMapExtentsV3ReopenRegistersTheFallbackRoot`, `TestChunkMapExtentsV3TruncationFaultKeepsTheSlotRoots`, `TestChunkMapExtentsV3UncertainCandidateStaysPinned`, `TestChunkMapExtentsV3StatsAfterReopen`, `TestChunkMapExtentsV3ProofStalePreparesStayBounded`, `TestChunkMapExtentsV3DurableButRefusedPublicationStaysPinned` (`core/storage/chunk_map_extents_v3_test.go`); `TestChunkLSNMapV3_CanonicalVectors`, `TestChunkLSNMapV3_PersistReloadAndReuse`, `TestChunkLSNMapV3_CorruptionAndBounds`, `TestChunkLSNMapV3_FailureDoesNotPublishOrReuse`, `TestChunkLSNMapV3_OrderOwnedOpenAndClippedPage`, `TestChunkLSNMapV3_RejectsRehashedMalformedRecords`, `TestChunkLSNMapV3_EntryBoundBeforeRootIO`, `TestChunkLSNMapV3_WholePageHashIsNotBodyDigest`, `TestChunkLSNMapV3_PreflightErrorDoesNotLatch` | WALFormatR5 abstract map dependency; physical encoding/digest/order are code obligations | STUB | | `INV-WAL-V3-PUBLISH-001` | Every v3 descriptor change goes through one publisher. It writes the fallback slot with slotGen+1 under `descMu`. It takes `WALStore.mu` only to snapshot and releases it before slot I/O, and fsync is the leaf. It rebases onto the authoritative descriptor: W and the checkpoint are max-merged, and identity, geometry and nonce changes are refused, as are tail regression, a map root change without a higher generation and any BASE edge outside DESIGN 8.5 (installed -> 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 | @@ -355,7 +355,7 @@ 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-FLUSH-LIFETIME-001`: Capture recoverGen under store.mu with the dirty snapshot, before WAL materialization/extent I/O. Recheck the original generation under syncMu before either mapped or historical dark checkpoint publication. Under store.mu, recheck again before local tail progress and LSN-only compare/delete; Recover uses the same store lock at both boundaries. This adds no new lock or I/O under a publication lock. The pre-proof held control materializes unacknowledged A2, damages only that WAL suffix, Recover keeps W1, then reuses the same LBA/offset/LSN for acknowledged B2. Old publication must refuse, retain B, and a fresh retry must put B in the physical extent before crash-style reopen verifies exact bytes. -- `INV-WAL-V3-MAP-PUBLISH-001`: The open/quiesced bind validates the selected and every valid fallback map root/page dependency before installing a proof domain, with a slot snapshot recheck after I/O. A corrupt fallback refuses binding even if the selected map is intact; validation writes no slots and preserves the prior domain on failure. This is a binding seam control, not automatic create/open or capture wiring. 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. The dark map-requiring actual-store opener now loads its owned sidecar and validates both slots before workers start, binds a fresh proof domain, and Close releases the map. The explicit mapped creator persists an all-UNKNOWN initial map before publishing its first slot. Earlier unmapped row5 fixtures have a separately named test-only opt-out, not a production selector. Owned-map stores now prepare a typed snapshot/proof outside publication locks and publish real checkpoint coverage through publishMapV3 under syncMu. The existing map mutex reserves candidate generations; transaction failures latch the whole store before returning. Writes invalidate proofs before append and update per-chunk max LSN under store.mu, while Recover rebuilds that volatile cache from the selected root and retained WAL prefix. Metadata/chunk callbacks precede map and descriptor durability. The dark actual chunk capture now also selects owned-map UNKNOWN/max-LSN candidates after checkpoint, samples chunk mutation tokens under its barrier, and clears UNKNOWN only after definite HEAD publication with unchanged tokens. Its resulting map snapshot is published through the same proof/coverage checks; failed or unresolved cuts clear nothing, and failed local map publication keeps disk UNKNOWN conservative. Replaying an already checkpoint-covered record does not invent a fresh logical map mutation. A mismatched chunk geometry is refused before remote contact. Eviction uses the same owned-map/WAL dirt predicate, so checkpointed data awaiting capture cannot be replaced by a fill from an older HEAD. Normal impl3 capture attachment/checkpoint/status no longer loads, saves, resets or requires the legacy bitmap; v2 retains it. A provided legacy object is ignored. The immutable per-open proof discriminator permits status alongside Close without reading its mutable cleanup pointer. Legacy BASE header mutations remain refused; the descriptor install protocol now uses the dark chunk transition drain and permits completed BASE attachment (INV-WAL-V3-CHUNK-BASE-001). A private test-only provider factory now drives the actual DurableProvider/StorageBackend create, recover, write, Sync, flusher, capture and local reopen paths on mapped v3 without a legacy bitmap. The cross-package constructor wrappers exist only under swblock_format_v3_test; the normal provider selector remains legacy, and a missing owned map refuses without caching a backend. SeedChunkFrontier now dispatches to the shared v3 checkpoint publisher (row9c), without waiting on the committer under store.mu. The real provider invalid-frontier control proves preparation failure claims no HEAD and leaves the backend nonoperational. Row12a now removes the provider refusal and exercises the actual mapped FreshFromHead restore through the row9 single-publisher seed: seed/rebase precedes takeover CAS, a committed claim with a lost response is resolved by exact reread, inherited LSNs are not reused, immutable chunks fill lazily, and later capture/local reopen preserve exact bytes. An invalid inherited frontier refuses without claiming HEAD. Production selection remains v2; the dark BASE caller and readonly/status controls have dedicated rows below; production activation remains separate. WAL tail reclamation is not yet wired. Existing dark lifecycle tests drive invalidation primitives; only the two explicitly named real-store controls exercise actual Recover, ; automatic checkpoint and tagged provider controls above separately cover those real callers. 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`: The open/quiesced bind validates the selected and every valid fallback map root/page dependency before installing a proof domain, with a slot snapshot recheck after I/O. A corrupt fallback refuses binding even if the selected map is intact; validation writes no slots and preserves the prior domain on failure. This is a binding seam control, not automatic create/open or capture wiring. 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. The dark map-requiring actual-store opener now loads its owned sidecar and validates both slots before workers start, binds a fresh proof domain, and Close releases the map. The explicit mapped creator persists an all-UNKNOWN initial map before publishing its first slot. Earlier unmapped row5 fixtures have a separately named test-only opt-out, not a production selector. Owned-map stores now prepare a typed snapshot/proof outside publication locks and publish real checkpoint coverage through publishMapV3 under syncMu. The existing map mutex reserves candidate generations; transaction failures latch the whole store before returning. Strictly newer ordered WAL appends update per-chunk max LSN without invalidating an older checkpoint-prefix proof: their retained suffix is replayed before recovery serves. Effective BASE/UNKNOWN changes and lifecycle boundaries still invalidate proofs. Recover rebuilds the volatile cache from the selected root and retained WAL prefix. Metadata/chunk callbacks precede map and descriptor durability. The dark actual chunk capture now also selects owned-map UNKNOWN/max-LSN candidates after checkpoint, samples chunk mutation tokens under its barrier, and clears UNKNOWN only after definite HEAD publication with unchanged tokens. Its resulting map snapshot is published through the same proof/coverage checks; failed or unresolved cuts clear nothing, and failed local map publication keeps disk UNKNOWN conservative. Replaying an already checkpoint-covered record does not invent a fresh logical map mutation. A mismatched chunk geometry is refused before remote contact. Eviction uses the same owned-map/WAL dirt predicate, so checkpointed data awaiting capture cannot be replaced by a fill from an older HEAD. Normal impl3 capture attachment/checkpoint/status no longer loads, saves, resets or requires the legacy bitmap; v2 retains it. A provided legacy object is ignored. The immutable per-open proof discriminator permits status alongside Close without reading its mutable cleanup pointer. Legacy BASE header mutations remain refused; the descriptor install protocol now uses the dark chunk transition drain and permits completed BASE attachment (INV-WAL-V3-CHUNK-BASE-001). A private test-only provider factory now drives the actual DurableProvider/StorageBackend create, recover, write, Sync, flusher, capture and local reopen paths on mapped v3 without a legacy bitmap. The cross-package constructor wrappers exist only under swblock_format_v3_test; the normal provider selector remains legacy, and a missing owned map refuses without caching a backend. SeedChunkFrontier now dispatches to the shared v3 checkpoint publisher (row9c), without waiting on the committer under store.mu. The real provider invalid-frontier control proves preparation failure claims no HEAD and leaves the backend nonoperational. Row12a now removes the provider refusal and exercises the actual mapped FreshFromHead restore through the row9 single-publisher seed: seed/rebase precedes takeover CAS, a committed claim with a lost response is resolved by exact reread, inherited LSNs are not reused, immutable chunks fill lazily, and later capture/local reopen preserve exact bytes. An invalid inherited frontier refuses without claiming HEAD. Production selection remains v2; the dark BASE caller and readonly/status controls have dedicated rows below; production activation remains separate. WAL tail reclamation is not yet wired. Existing dark lifecycle tests drive invalidation primitives; only the two explicitly named real-store controls exercise actual Recover, ; automatic checkpoint and tagged provider controls above separately cover those real callers. 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. Sidecar extents are reused only after neither slot nor a pending or uncertain candidate references them; see `chunk_map_extents_v3.go` and its tests. From 186c7a0897a080788e232878a1ddc0161a5138c6 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 00:40:19 -0800 Subject: [PATCH 03/14] fix(storage): preserve exhausted proof-counter refusal on append --- .../checkpoint_append_progress_v3_test.go | 18 ++++++++++++++++++ seaweed-block/core/storage/walstore_v3.go | 6 ++++++ seaweed-block/docs/design/invariants.md | 2 +- 3 files changed, 25 insertions(+), 1 deletion(-) diff --git a/seaweed-block/core/storage/checkpoint_append_progress_v3_test.go b/seaweed-block/core/storage/checkpoint_append_progress_v3_test.go index e16a466364..b964b0ced5 100644 --- a/seaweed-block/core/storage/checkpoint_append_progress_v3_test.go +++ b/seaweed-block/core/storage/checkpoint_append_progress_v3_test.go @@ -129,3 +129,21 @@ func TestCheckpointV3_EffectiveBaseWriteStillInvalidatesProof(t *testing.T) { t.Fatal("stale BASE candidate changed slots") } } + +// Removing append-driven increments must not bypass terminal exhaustion. +func TestCheckpointV3_ExhaustedMutationCounterStillRefusesAppend(t *testing.T) { + for _, batch := range []bool{false, true} { + s, _ := newMappedCheckpointStoreV3(t) + before := s.NextLSN() + s.v3.mapProof.mutation.Store(counterMaxV3) + var err error + if batch { + _, err = s.WriteBatch(1, [][]byte{blk(1), blk(2)}) + } else { + _, err = s.Write(1, blk(1)) + } + if !errors.Is(err, ErrCounterExhausted) || s.NextLSN() != before || s.dm.len() != 0 { + t.Fatalf("exhaustion bypassed: batch=%t err=%v next=%d dirty=%d", batch, err, s.NextLSN(), s.dm.len()) + } + } +} diff --git a/seaweed-block/core/storage/walstore_v3.go b/seaweed-block/core/storage/walstore_v3.go index d894405060..8691653109 100644 --- a/seaweed-block/core/storage/walstore_v3.go +++ b/seaweed-block/core/storage/walstore_v3.go @@ -657,6 +657,9 @@ func (s *WALStore) appendWriteV3(lba uint32, data []byte, lsn uint64) (uint64, e // A strictly newer append stays in the retained WAL suffix. It cannot // invalidate coverage of an older checkpoint prefix; effective BASE and // lifecycle mutations still invalidate the map proof at their own seams. + if p := s.v3.mapProof; p != nil && p.mutation.Load() >= counterMaxV3 { + return 0, ErrCounterExhausted + } if err := s.rolloverCheckpointV3Locked(); err != nil { return 0, err } @@ -706,6 +709,9 @@ func (s *WALStore) writeBatchV3Locked(startLBA uint32, blocks [][]byte, firstLSN s.instr.recordWALCopy(len(payload), time.Since(copyStart)) n := uint64(len(blocks)) lastLSN := firstLSN + n - 1 + if p := s.v3.mapProof; p != nil && p.mutation.Load() >= counterMaxV3 { + return nil, ErrCounterExhausted + } e := walEntryV3{LSN: firstLSN, BatchCount: n, Type: walEntryWriteBatch, LBA: uint64(startLBA), Length: uint32(len(payload)), Data: payload} if err := s.rolloverCheckpointV3Locked(); err != nil { return nil, err diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 653ffda191..624b409247 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -335,7 +335,7 @@ The "Machine / transition" column refers to Part A. Notes under a table record w | `INV-WAL-V3-OWNER-001` | v3 read/write open, offline readonly open and migrate-v3 acquire the same exclusive nonblocking OS file lock before reading slots or changing bytes. Contention refuses with volume locked; descriptor close releases it, allowing retry. | M1 open admission / offline migration precondition | `core/storage/volume_lock*.go`; `walstore_v3.go`; `walstore_readonly_v3.go`; `cmd/sw-block/migrate.go` | `TestMigrateV3RefusesAnOpenV3Volume`, `TestMigrateV3ExcludesOpenUntilCommitFinishes` (tag `swblock_format_v3_test`), `TestWALStoreV3CreatorKeepsOwnershipThroughPublication`, `TestWALStoreV3OwnerExcludesOpenAndReadOnly` | OS mutual exclusion is a caller obligation, outside the abstract crash model; existing open states unchanged | STUB | | `INV-WAL-V3-CATCHUP-001` | A dark v3 catch-up source refuses while installing, including an empty at-head request. Requests covered by an installed BASE require rebuild (typed WALRecycled); damage in retained WAL remains an integrity failure. Before emitting any entries the scan revalidates recovery generation, nonce, BASE state/ID and install epoch, so begin/complete/retire ABA cannot publish a superseded prefix. | M1 BASE lifecycle / M3 CatchingUp (dark callers) | `core/storage/walstore_recovery.go` `ScanLBAs`, `scanLBAsV3`, `v3CatchUpEntries` | `TestCatchUpV3InstallingAtHeadRefuses`, `TestCatchUpV3CompletedBASEUsesRebuild`, `TestCatchUpV3InstallRetireABARefusesOldScan`, `TestCatchUpV3CorruptFirstRecordFails`, `TestCatchUpV3CorruptMiddleRecordFails`, `TestCatchUpV3CompletedBASESuffix` (tag `swblock_format_v3_test`, actual catch-up sender) | Existing BASE and catch-up transitions unchanged; this physical scan/source-lifetime obligation is covered by deterministic caller tests | STUB | | `INV-WAL-V3-BINDING-001` | The dark v3 writer stamps the selected nonce and absolute cursor, fits each append/padding inside the dual-slot reuse floor, and refuses later I/O after a pwrite failure. A dark scanner checks nonce and exact expected cursor before using Length/count, checks the full record again, skips only geometric end slack, and stops at the first untrusted record without payload resynchronization. It returns a typed scan result, never ACK or serving permission. | M1 Recovering (dark muscles only) | `core/storage/wal_io_v3.go` `append`, `scanWALV3`, `walSnapshotV3` | `TestWALIOV3_RealWriterReopenScan`, `TestWALIOV3_WrapPaddingAndSlack`, `TestWALIOV3_StopsAtBindingBeforeEmbeddedRecord`, `TestWALIOV3_EmbeddedRecordInPayloadIsNotScanned`, `TestWALIOV3_InstalledScanBeginsAtMaxTail`, `TestWALIOV3_FloorAndPwriteFailureRefuse` | Record/lap admission is abstracted in composed WALFormatR5; physical framing/wrap boundaries remain code-test obligations | STUB | -| `INV-WAL-V3-MAP-PUBLISH-001` | After a dark publisher binds a validated map, every publication carries a matching immutable tuple with merged checkpoint <= C <= merged W. A prepared replacement needs a higher generation, non-regressing coverage and the same sidecar/open proof domain with unchanged epoch/mutation token. Stale candidates write no slot; W-only rollover carries the current root; unknown slot outcomes pin dependencies. | M1 (dark map publication only; checkpoint/capture caller wiring pending) | `core/storage/chunk_map_publication_v3.go`; `core/storage/descriptor_v3.go` `publishLockedWithMapV3` | `TestWALStoreV3_SeedNeverUsesLegacyDescriptorWriter`, `TestDurableProviderV3_InvalidHEADFrontierRefusesBeforeClaim`, `TestDurableProviderV3_HEADRestorePreservesRemoteImageAndNextLSN`, `TestDurableProviderV3_HEADRestoreAfterLostClaimResponse`, `TestDurableProviderV3_MappedCheckpointCaptureAndReopen`, `TestDurableProviderV3_MissingMapRefusesBeforeBackend`, `TestDurableProviderV3_DefaultSelectorCreatesV3` (tag `swblock_format_v3_test`), `TestChunkLayerV3_MapOnlyCaptureNeedsNoLegacyBitmap`, `TestChunkLayerV3_IgnoresProvidedLegacyBitmap`, `TestChunkLayerV3_MapOnlyFreshZeroHEADPreservesLocalWrites`, `TestChunkLayerV3_MapOnlyRefusesLegacyBASEHeaderMutation`, `TestChunkLayerV3_MapStatusConcurrentClose`, `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, `TestChunkLayerV3_MaxLSNSelectsAfterReopenWithCleanLegacyBitmap`, `TestChunkLayerV3_ChangedCaptureTokenKeepsUNKNOWN`, `TestChunkLayerV3_UnsettledCaptureNeverClearsUNKNOWN`, `TestChunkLayerV3_RefusesMapGeometryBeforeRemote`, `TestWALStoreV3_AutomaticMapCheckpoint`, `TestWALStoreV3_PreparedCheckpointRefusesChangedProof`, `TestChunkLayerV3_CheckpointProgressUnderContinuousAppends`, `TestCheckpointV3_NewerBatchReplaysAfterPreparedPrefix`, `TestCheckpointV3_EffectiveBaseWriteStillInvalidatesProof`, `TestWALStoreV3_AutomaticMapPersistenceFailureLatchesStore`, `TestWALStoreV3_UncertainMapCheckpointPinsDependencies`, `TestWALStoreV3_AutomaticCheckpointMetadataOrderAndRetry`, `TestWALStoreV3_AutomaticMapRecoverRebuildsCoverage`, `TestWALStoreV3_OpenRequiresBothMapGenerations`, `TestWALStoreV3_MappedCreateOpenOwnsMap`, `TestMapPublicationV3_BindValidatesBothSlotDependencies`, `TestMapPublicationV3_HeldPublicationsBothOrders`, `TestMapPublicationV3_IsolatedMergedCoverageAndWPositive`, `TestMapPublicationV3_ProofEpochAndMutationRefusal`, `TestMapPublicationV3_UncertainFinalResponsePinsCandidate`, `TestMapPublicationV3_CoverageWAndNoUnpreparedRoot`, `TestMapPublicationV3_ProofChangedDuringPersistenceRefuses`; `TestWALStoreV3_RealRecoverInvalidatesMapProofAtStartAndEnd`, `TestWALStoreV3_FailedRecoverInvalidatesMapProofAtBothBoundaries` | WALFormatR5 map coverage / volatile proof epoch; physical caller wiring remains a code obligation | STUB | +| `INV-WAL-V3-MAP-PUBLISH-001` | After a dark publisher binds a validated map, every publication carries a matching immutable tuple with merged checkpoint <= C <= merged W. A prepared replacement needs a higher generation, non-regressing coverage and the same sidecar/open proof domain with unchanged epoch/mutation token. Stale candidates write no slot; W-only rollover carries the current root; unknown slot outcomes pin dependencies. | M1 (dark map publication only; checkpoint/capture caller wiring pending) | `core/storage/chunk_map_publication_v3.go`; `core/storage/descriptor_v3.go` `publishLockedWithMapV3` | `TestWALStoreV3_SeedNeverUsesLegacyDescriptorWriter`, `TestDurableProviderV3_InvalidHEADFrontierRefusesBeforeClaim`, `TestDurableProviderV3_HEADRestorePreservesRemoteImageAndNextLSN`, `TestDurableProviderV3_HEADRestoreAfterLostClaimResponse`, `TestDurableProviderV3_MappedCheckpointCaptureAndReopen`, `TestDurableProviderV3_MissingMapRefusesBeforeBackend`, `TestDurableProviderV3_DefaultSelectorCreatesV3` (tag `swblock_format_v3_test`), `TestChunkLayerV3_MapOnlyCaptureNeedsNoLegacyBitmap`, `TestChunkLayerV3_IgnoresProvidedLegacyBitmap`, `TestChunkLayerV3_MapOnlyFreshZeroHEADPreservesLocalWrites`, `TestChunkLayerV3_MapOnlyRefusesLegacyBASEHeaderMutation`, `TestChunkLayerV3_MapStatusConcurrentClose`, `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, `TestChunkLayerV3_MaxLSNSelectsAfterReopenWithCleanLegacyBitmap`, `TestChunkLayerV3_ChangedCaptureTokenKeepsUNKNOWN`, `TestChunkLayerV3_UnsettledCaptureNeverClearsUNKNOWN`, `TestChunkLayerV3_RefusesMapGeometryBeforeRemote`, `TestWALStoreV3_AutomaticMapCheckpoint`, `TestWALStoreV3_PreparedCheckpointRefusesChangedProof`, `TestChunkLayerV3_CheckpointProgressUnderContinuousAppends`, `TestCheckpointV3_NewerBatchReplaysAfterPreparedPrefix`, `TestCheckpointV3_EffectiveBaseWriteStillInvalidatesProof`, `TestCheckpointV3_ExhaustedMutationCounterStillRefusesAppend`, `TestWALStoreV3_AutomaticMapPersistenceFailureLatchesStore`, `TestWALStoreV3_UncertainMapCheckpointPinsDependencies`, `TestWALStoreV3_AutomaticCheckpointMetadataOrderAndRetry`, `TestWALStoreV3_AutomaticMapRecoverRebuildsCoverage`, `TestWALStoreV3_OpenRequiresBothMapGenerations`, `TestWALStoreV3_MappedCreateOpenOwnsMap`, `TestMapPublicationV3_BindValidatesBothSlotDependencies`, `TestMapPublicationV3_HeldPublicationsBothOrders`, `TestMapPublicationV3_IsolatedMergedCoverageAndWPositive`, `TestMapPublicationV3_ProofEpochAndMutationRefusal`, `TestMapPublicationV3_UncertainFinalResponsePinsCandidate`, `TestMapPublicationV3_CoverageWAndNoUnpreparedRoot`, `TestMapPublicationV3_ProofChangedDuringPersistenceRefuses`; `TestWALStoreV3_RealRecoverInvalidatesMapProofAtStartAndEnd`, `TestWALStoreV3_FailedRecoverInvalidatesMapProofAtBothBoundaries` | WALFormatR5 map coverage / volatile proof epoch; physical caller wiring remains a code obligation | STUB | | `INV-WAL-V3-FLUSH-LIFETIME-001` | A dark v3 flusher binds its dirty snapshot and extent materialization to the original even Recover generation. A cycle spanning Recover/reset publishes no checkpoint/map and retires no reused dirty entry. | M1 Recovering / checkpoint publication | `core/storage/flusher.go`; `walstore_map_checkpoint_v3.go`; `walstore_v3.go` `flushLifetimeValidV3` | `TestWALStoreV3_FlushMaterializationBoundToRecoveryLifetime` | Existing recovery/map proof lifetime; implementation correspondence | STUB | | `INV-WAL-V3-MAP-BYTES-001` | A dark v3 map candidate names immutable, owned, identity- and geometry-checked pages and root. Domain-separated body digests, reserved/unused bytes, exact page counts, file bounds and non-aliasing intervals all validate before entries escape. Persistence orders pages/fsync, root/fsync, directory fsync; a persistence-transaction error yields no candidate and latches subsequent I/O; preflight and Stat errors do not latch. Extents are reused only when no live root references them (both slot roots, in-flight candidates, an uncertain candidate until reopen); the free tail is truncated above the highest live page. | M1 (dark map preparation only) | `core/storage/chunk_lsn_map_v3.go` `Prepare`, `readChunkLSNMapV3`; `core/storage/chunk_map_extents_v3.go` (live set, allocation, release, truncation); `core/storage/chunk_map_publication_v3.go` `publishMapV3`; `core/storage/descriptor_v3.go` (slot report, uncertain candidate) | `TestChunkMapV3FileStaysBoundedUnderSteadyCheckpoints` (`core/storage/chunkmap_bounded_v3_test.go`); `TestChunkMapExtentsV3FallbackRootIsNeverReused`, `TestChunkMapExtentsV3NewerInFlightCandidateIsNotReused`, `TestChunkMapExtentsV3CrashBeforePublicationOfAReusedExtent`, `TestChunkMapExtentsV3TruncationKeepsAFallbackAtTheTail`, `TestChunkMapExtentsV3RejectedPublicationsStayBounded`, `TestChunkMapExtentsV3ReopenRegistersTheFallbackRoot`, `TestChunkMapExtentsV3TruncationFaultKeepsTheSlotRoots`, `TestChunkMapExtentsV3UncertainCandidateStaysPinned`, `TestChunkMapExtentsV3StatsAfterReopen`, `TestChunkMapExtentsV3ProofStalePreparesStayBounded`, `TestChunkMapExtentsV3DurableButRefusedPublicationStaysPinned` (`core/storage/chunk_map_extents_v3_test.go`); `TestChunkLSNMapV3_CanonicalVectors`, `TestChunkLSNMapV3_PersistReloadAndReuse`, `TestChunkLSNMapV3_CorruptionAndBounds`, `TestChunkLSNMapV3_FailureDoesNotPublishOrReuse`, `TestChunkLSNMapV3_OrderOwnedOpenAndClippedPage`, `TestChunkLSNMapV3_RejectsRehashedMalformedRecords`, `TestChunkLSNMapV3_EntryBoundBeforeRootIO`, `TestChunkLSNMapV3_WholePageHashIsNotBodyDigest`, `TestChunkLSNMapV3_PreflightErrorDoesNotLatch` | WALFormatR5 abstract map dependency; physical encoding/digest/order are code obligations | STUB | | `INV-WAL-V3-PUBLISH-001` | Every v3 descriptor change goes through one publisher. It writes the fallback slot with slotGen+1 under `descMu`. It takes `WALStore.mu` only to snapshot and releases it before slot I/O, and fsync is the leaf. It rebases onto the authoritative descriptor: W and the checkpoint are max-merged, and identity, geometry and nonce changes are refused, as are tail regression, a map root change without a higher generation and any BASE edge outside DESIGN 8.5 (installed -> 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 | From c728fb4191f3043bc4881bc5dd5102c6d8cee8bd Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 02:41:36 -0800 Subject: [PATCH 04/14] test(storage): cover prefix proofs across rollover and hydration --- .../checkpoint_append_progress_v3_test.go | 179 ++++++++++++++++++ .../storage/walstore_map_checkpoint_v3.go | 2 + seaweed-block/docs/design/invariants.md | 2 +- 3 files changed, 182 insertions(+), 1 deletion(-) diff --git a/seaweed-block/core/storage/checkpoint_append_progress_v3_test.go b/seaweed-block/core/storage/checkpoint_append_progress_v3_test.go index b964b0ced5..910d5408b3 100644 --- a/seaweed-block/core/storage/checkpoint_append_progress_v3_test.go +++ b/seaweed-block/core/storage/checkpoint_append_progress_v3_test.go @@ -3,6 +3,7 @@ package storage import ( "bytes" "errors" + "path/filepath" "testing" ) @@ -19,6 +20,7 @@ func TestChunkLayerV3_CheckpointProgressUnderContinuousAppends(t *testing.T) { realSync := s.v3.ownedMap.syncFile t.Cleanup(func() { s.v3.ownedMap.syncFile = realSync }) refusals := 0 + previousCP := uint64(0) for round := uint32(0); round < 8; round++ { injected := false s.v3.ownedMap.syncFile = func() error { @@ -41,6 +43,11 @@ func TestChunkLayerV3_CheckpointProgressUnderContinuousAppends(t *testing.T) { if !injected { t.Fatal("cycle did not overlap a write") } + if cp := s.CheckpointLSN(); cp <= previousCP { + t.Fatalf("cycle %d: checkpoint %d did not advance beyond %d", round, cp, previousCP) + } else { + previousCP = cp + } if _, err := s.Sync(); err != nil { t.Fatal(err) } @@ -147,3 +154,175 @@ func TestCheckpointV3_ExhaustedMutationCounterStillRefusesAppend(t *testing.T) { } } } + +// A write's real fallback rollover can run after a map candidate was prepared. +// It preserves the older prefix and the later append remains available to replay. +func TestCheckpointV3_AppendRolloverAfterPrepareKeepsRetainedSuffix(t *testing.T) { + s, path := newMappedCheckpointStoreV3(t) + s.SetRecoveryRetentionLSNs(1) + writeSynced(t, s, 1, 2) + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + prepared, err := s.prepareOwnedMapCheckpointV3(2) + if err != nil { + t.Fatal(err) + } + tail := s.v3.w.reclaimThroughV3(2) + before := s.v3.pub.current() + if tail <= before.RetainedTail { + t.Fatal("setup: no releasable retained record") + } + // One real slot publication advances the current tail only. The next Write + // must bring the fallback forward before it can reuse that released range. + if _, err := s.v3.pub.publish(nil, nil, func(d *descriptorV3) error { + d.RetainedTail = tail + d.RetainedHead = max(d.RetainedHead, tail) + return nil + }); err != nil { + t.Fatal(err) + } + current, floor, ok := s.v3.pub.walSnapshotV3() + if !ok || floor >= tail { + t.Fatal("setup: fallback did not pin rollover") + } + if lsn, err := s.Write(3, blk(0xD3)); err != nil || lsn != 3 { + t.Fatalf("write: lsn %d err %v", lsn, err) + } + after := s.v3.pub.current() + if after.SlotGen != current.SlotGen+1 { + t.Fatal("Write did not execute the fallback rollover") + } + if _, err := s.v3.pub.publishMapV3(&s.mu, nil, prepared, nil); err != nil { + t.Fatalf("prefix publication after rollover: %v", err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + d, floor, ok := s.v3.pub.walSnapshotV3() + if !ok || d.CheckpointLSN != 2 || d.MapCoveredCheckpoint != 2 || d.W < 3 || floor != tail || d.RetainedTail != tail { + t.Fatalf("prefix/suffix boundary: cp%d C%d W%d floor%d tail%d want%d", d.CheckpointLSN, d.MapCoveredCheckpoint, d.W, floor, d.RetainedTail, tail) + } + s.SetRecoveryRetentionLSNs(1) + var scanned []RecoveryEntry + if err := s.ScanLBAs(3, func(e RecoveryEntry) error { scanned = append(scanned, e); return nil }); err != nil || len(scanned) != 1 || scanned[0].LSN != 3 || !bytes.Equal(scanned[0].Data, blk(0xD3)) { + t.Fatalf("retained suffix: %+v err %v", scanned, err) + } + crashRecoveryHardeningStore(t, s) + s.mu.Lock() + s.closed = true + s.mu.Unlock() + r, err := openWALStoreV3ForTest(path) + if err != nil { + t.Fatal(err) + } + r.DisableAutoFlushForRecoveryTest() + t.Cleanup(func() { _ = r.Close() }) + if _, err := r.Recover(); err != nil { + t.Fatal(err) + } + if !bytes.Equal(readV3(t, r, 3), blk(0xD3)) { + t.Fatal("retained suffix lost after reopen") + } +} + +func TestCheckpointV3_LazyFillDoesNotInvalidatePreparedPrefix(t *testing.T) { + path := filepath.Join(t.TempDir(), "hydrating") + s, err := createMappedWALStoreV3ForTest(path, ctNumBlocks, ctBlockSize, v3TestWAL, WModeStrict, ctChunkBlocks) + if err != nil { + t.Fatal(err) + } + s.DisableAutoFlushForRecoveryTest() + t.Cleanup(func() { _ = s.Close() }) + image := make([]byte, ctNumBlocks*ctBlockSize) + copy(image[9*ctBlockSize:], blk(0xA9)) + remote := newFakeChunkRemote() + remote.seedHead(t, image, 10, 1) + if err := s.SeedChunkFrontier(10); err != nil { + t.Fatal(err) + } + cfg := ctConfig(2) + cfg.FreshFromHead = true + layer := mustAttach(t, s, remote, cfg).(*chunkLayerImpl) + prepared, err := s.prepareOwnedMapCheckpointV3(10) + if err != nil { + t.Fatal(err) + } + layer.stMu.Lock() + absent := layer.absent[2] + layer.stMu.Unlock() + if !absent { + t.Fatal("setup: chunk is not absent") + } + if got, err := s.Read(9); err != nil || !bytes.Equal(got, blk(0xA9)) { + t.Fatalf("lazy read: %v", err) + } + layer.stMu.Lock() + absent = layer.absent[2] + layer.stMu.Unlock() + if absent { + t.Fatal("read did not hydrate chunk") + } + if !prepared.proof.validV3(s.v3.mapProof) { + t.Fatal("lazy fill invalidated the checkpoint prefix") + } + if _, err := s.v3.pub.publishMapV3(&s.mu, nil, prepared, nil); err != nil { + t.Fatalf("publish after lazy fill: %v", err) + } +} + +// At every cycle the ring reaches the real admission soft-pressure range. +// An append overlaps map persistence, yet each completed cycle must reclaim; +// none may require a cut or new remote HEAD to escape repeated proof refusal. +func TestChunkLayerV3_CheckpointProgressAtWALPressure(t *testing.T) { + for _, mode := range []WMode{WModeStrict, WModeLagged} { + t.Run(map[WMode]string{WModeStrict: "A", WModeLagged: "C"}[mode], func(t *testing.T) { + path := filepath.Join(t.TempDir(), "pressure") + s, err := createMappedWALStoreV3ForTest(path, 64, 4096, 64*1024, mode, 4) + if err != nil { + t.Fatal(err) + } + s.DisableAutoFlushForRecoveryTest() + t.Cleanup(func() { _ = s.Close() }) + mustAttach(t, s, newFakeChunkRemote(), ctConfig(1)) + realSync := s.v3.ownedMap.syncFile + t.Cleanup(func() { s.v3.ownedMap.syncFile = realSync }) + previousCP := uint64(0) + for cycle := 0; cycle < 8; cycle++ { + for s.walUsedFraction() < 0.72 { + if _, err := s.Write(uint32(s.NextLSN()%64), blk(byte(s.NextLSN()))); err != nil { + t.Fatal(err) + } + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + injected := false + s.v3.ownedMap.syncFile = func() error { + if !injected { + injected = true + if _, err := s.Write(uint32(s.NextLSN()%64), blk(byte(s.NextLSN()))); err != nil { + return err + } + } + return realSync() + } + err := s.flusher.flushOnce() + s.v3.ownedMap.syncFile = realSync + if err != nil { + t.Fatalf("pressure cycle%d: %v", cycle, err) + } + cp := s.CheckpointLSN() + if !injected || cp <= previousCP { + t.Fatalf("no progress cycle%d cp%d previous%d", cycle, cp, previousCP) + } + previousCP = cp + } + floor, ok := s.v3.pub.reuseFloor() + if !ok || floor < 5*64*1024 { + t.Fatalf("no sustained ring reuse: floor%d", floor) + } + t.Logf("cycles8 checkpoint%d floor%d busy0", previousCP, floor) + }) + } +} diff --git a/seaweed-block/core/storage/walstore_map_checkpoint_v3.go b/seaweed-block/core/storage/walstore_map_checkpoint_v3.go index 029d0ba210..3b9fe9aca1 100644 --- a/seaweed-block/core/storage/walstore_map_checkpoint_v3.go +++ b/seaweed-block/core/storage/walstore_map_checkpoint_v3.go @@ -36,6 +36,8 @@ func (s *WALStore) prepareOwnedMapCheckpointV3(cp uint64) (*preparedMapPublicati return nil, ErrMapCoverageStale } proof := domain.snapshotV3() + // Entries may already contain LSNs above cp from earlier appends: max-LSN + // entries are monotone and idempotent under retained-suffix replay. entries := append([]chunkLSNEntryV3(nil), v.mapEntries...) v.pub.descMu.Unlock() s.mu.RUnlock() diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 624b409247..aef36d1bbf 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -355,7 +355,7 @@ 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-FLUSH-LIFETIME-001`: Capture recoverGen under store.mu with the dirty snapshot, before WAL materialization/extent I/O. Recheck the original generation under syncMu before either mapped or historical dark checkpoint publication. Under store.mu, recheck again before local tail progress and LSN-only compare/delete; Recover uses the same store lock at both boundaries. This adds no new lock or I/O under a publication lock. The pre-proof held control materializes unacknowledged A2, damages only that WAL suffix, Recover keeps W1, then reuses the same LBA/offset/LSN for acknowledged B2. Old publication must refuse, retain B, and a fresh retry must put B in the physical extent before crash-style reopen verifies exact bytes. -- `INV-WAL-V3-MAP-PUBLISH-001`: The open/quiesced bind validates the selected and every valid fallback map root/page dependency before installing a proof domain, with a slot snapshot recheck after I/O. A corrupt fallback refuses binding even if the selected map is intact; validation writes no slots and preserves the prior domain on failure. This is a binding seam control, not automatic create/open or capture wiring. 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. The dark map-requiring actual-store opener now loads its owned sidecar and validates both slots before workers start, binds a fresh proof domain, and Close releases the map. The explicit mapped creator persists an all-UNKNOWN initial map before publishing its first slot. Earlier unmapped row5 fixtures have a separately named test-only opt-out, not a production selector. Owned-map stores now prepare a typed snapshot/proof outside publication locks and publish real checkpoint coverage through publishMapV3 under syncMu. The existing map mutex reserves candidate generations; transaction failures latch the whole store before returning. Strictly newer ordered WAL appends update per-chunk max LSN without invalidating an older checkpoint-prefix proof: their retained suffix is replayed before recovery serves. Effective BASE/UNKNOWN changes and lifecycle boundaries still invalidate proofs. Recover rebuilds the volatile cache from the selected root and retained WAL prefix. Metadata/chunk callbacks precede map and descriptor durability. The dark actual chunk capture now also selects owned-map UNKNOWN/max-LSN candidates after checkpoint, samples chunk mutation tokens under its barrier, and clears UNKNOWN only after definite HEAD publication with unchanged tokens. Its resulting map snapshot is published through the same proof/coverage checks; failed or unresolved cuts clear nothing, and failed local map publication keeps disk UNKNOWN conservative. Replaying an already checkpoint-covered record does not invent a fresh logical map mutation. A mismatched chunk geometry is refused before remote contact. Eviction uses the same owned-map/WAL dirt predicate, so checkpointed data awaiting capture cannot be replaced by a fill from an older HEAD. Normal impl3 capture attachment/checkpoint/status no longer loads, saves, resets or requires the legacy bitmap; v2 retains it. A provided legacy object is ignored. The immutable per-open proof discriminator permits status alongside Close without reading its mutable cleanup pointer. Legacy BASE header mutations remain refused; the descriptor install protocol now uses the dark chunk transition drain and permits completed BASE attachment (INV-WAL-V3-CHUNK-BASE-001). A private test-only provider factory now drives the actual DurableProvider/StorageBackend create, recover, write, Sync, flusher, capture and local reopen paths on mapped v3 without a legacy bitmap. The cross-package constructor wrappers exist only under swblock_format_v3_test; the normal provider selector remains legacy, and a missing owned map refuses without caching a backend. SeedChunkFrontier now dispatches to the shared v3 checkpoint publisher (row9c), without waiting on the committer under store.mu. The real provider invalid-frontier control proves preparation failure claims no HEAD and leaves the backend nonoperational. Row12a now removes the provider refusal and exercises the actual mapped FreshFromHead restore through the row9 single-publisher seed: seed/rebase precedes takeover CAS, a committed claim with a lost response is resolved by exact reread, inherited LSNs are not reused, immutable chunks fill lazily, and later capture/local reopen preserve exact bytes. An invalid inherited frontier refuses without claiming HEAD. Production selection remains v2; the dark BASE caller and readonly/status controls have dedicated rows below; production activation remains separate. WAL tail reclamation is not yet wired. Existing dark lifecycle tests drive invalidation primitives; only the two explicitly named real-store controls exercise actual Recover, ; automatic checkpoint and tagged provider controls above separately cover those real callers. 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`: The open/quiesced bind validates the selected and every valid fallback map root/page dependency before installing a proof domain, with a slot snapshot recheck after I/O. A corrupt fallback refuses binding even if the selected map is intact; validation writes no slots and preserves the prior domain on failure. This is a binding seam control, not automatic create/open or capture wiring. 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. The dark map-requiring actual-store opener now loads its owned sidecar and validates both slots before workers start, binds a fresh proof domain, and Close releases the map. The explicit mapped creator persists an all-UNKNOWN initial map before publishing its first slot. Earlier unmapped row5 fixtures have a separately named test-only opt-out, not a production selector. Owned-map stores now prepare a typed snapshot/proof outside publication locks and publish real checkpoint coverage through publishMapV3 under syncMu. The existing map mutex reserves candidate generations; transaction failures latch the whole store before returning. The entry snapshot may already contain LSNs above cp from pre-snapshot appends; max-LSN entries remain monotone and idempotent under replay. Strictly newer ordered WAL appends update per-chunk max LSN without invalidating an older checkpoint-prefix proof: their retained suffix is replayed before recovery serves. Effective BASE/UNKNOWN changes and lifecycle boundaries still invalidate proofs. Recover rebuilds the volatile cache from the selected root and retained WAL prefix. Metadata/chunk callbacks precede map and descriptor durability. The dark actual chunk capture now also selects owned-map UNKNOWN/max-LSN candidates after checkpoint, samples chunk mutation tokens under its barrier, and clears UNKNOWN only after definite HEAD publication with unchanged tokens. Its resulting map snapshot is published through the same proof/coverage checks; failed or unresolved cuts clear nothing, and failed local map publication keeps disk UNKNOWN conservative. Replaying an already checkpoint-covered record does not invent a fresh logical map mutation. A mismatched chunk geometry is refused before remote contact. Eviction uses the same owned-map/WAL dirt predicate, so checkpointed data awaiting capture cannot be replaced by a fill from an older HEAD. Normal impl3 capture attachment/checkpoint/status no longer loads, saves, resets or requires the legacy bitmap; v2 retains it. A provided legacy object is ignored. The immutable per-open proof discriminator permits status alongside Close without reading its mutable cleanup pointer. Legacy BASE header mutations remain refused; the descriptor install protocol now uses the dark chunk transition drain and permits completed BASE attachment (INV-WAL-V3-CHUNK-BASE-001). A private test-only provider factory now drives the actual DurableProvider/StorageBackend create, recover, write, Sync, flusher, capture and local reopen paths on mapped v3 without a legacy bitmap. The cross-package constructor wrappers exist only under swblock_format_v3_test; the normal provider selector remains legacy, and a missing owned map refuses without caching a backend. SeedChunkFrontier now dispatches to the shared v3 checkpoint publisher (row9c), without waiting on the committer under store.mu. The real provider invalid-frontier control proves preparation failure claims no HEAD and leaves the backend nonoperational. Row12a now removes the provider refusal and exercises the actual mapped FreshFromHead restore through the row9 single-publisher seed: seed/rebase precedes takeover CAS, a committed claim with a lost response is resolved by exact reread, inherited LSNs are not reused, immutable chunks fill lazily, and later capture/local reopen preserve exact bytes. An invalid inherited frontier refuses without claiming HEAD. Production selection remains v2; the dark BASE caller and readonly/status controls have dedicated rows below; production activation remains separate. WAL tail reclamation is not yet wired. Existing dark lifecycle tests drive invalidation primitives; only the two explicitly named real-store controls exercise actual Recover, ; automatic checkpoint and tagged provider controls above separately cover those real callers. 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. Sidecar extents are reused only after neither slot nor a pending or uncertain candidate references them; see `chunk_map_extents_v3.go` and its tests. From 3aa38eadd8eaaa6e465213f730c0f6b36d1c4b68 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 00:50:33 -0800 Subject: [PATCH 05/14] test: expose checkpoint persistence refusals and successes --- .../durable/checkpoint_status_test.go | 62 +++++++++++++++++++ .../storage/checkpoint_diagnostics_test.go | 51 +++++++++++++++ 2 files changed, 113 insertions(+) create mode 100644 seaweed-block/core/frontend/durable/checkpoint_status_test.go create mode 100644 seaweed-block/core/storage/checkpoint_diagnostics_test.go diff --git a/seaweed-block/core/frontend/durable/checkpoint_status_test.go b/seaweed-block/core/frontend/durable/checkpoint_status_test.go new file mode 100644 index 0000000000..7b46ce5f64 --- /dev/null +++ b/seaweed-block/core/frontend/durable/checkpoint_status_test.go @@ -0,0 +1,62 @@ +package durable_test + +import ( + "context" + "encoding/json" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +func TestDurableProvider_CheckpointPersistenceStatus(t *testing.T) { + remote := storage.NewMemChunkRemote() + p, err := durable.NewDurableProvider(durable.ProviderConfig{ + Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, + NumBlocks: 64, ChunkBlocks: 4, ChunkCaptureInterval: 0, + ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }, + }, v1View()) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { p.Close() }) + if _, err := p.RecoverVolume(context.Background(), "v1"); err != nil { + t.Fatal(err) + } + be, err := p.Open(context.Background(), "v1") + if err != nil { + t.Fatal(err) + } + if _, err := be.Write(context.Background(), 0, make([]byte, 4096)); err != nil { + t.Fatal(err) + } + if err := be.Sync(context.Background()); err != nil { + t.Fatal(err) + } + deadline := time.Now().Add(5 * time.Second) + for { + statuses := p.DurableStatuses() + raw, err := json.Marshal(statuses) + if err != nil { + t.Fatal(err) + } + var wire []struct { + CheckpointPersistence *struct { + Successes uint64 + Refusals uint64 + Failures uint64 + } + } + if err := json.Unmarshal(raw, &wire); err != nil { + t.Fatal(err) + } + if len(wire) == 1 && wire[0].CheckpointPersistence != nil && wire[0].CheckpointPersistence.Successes > 0 { + return + } + if time.Now().After(deadline) { + t.Fatalf("no checkpoint persist status in durable response: %s", raw) + } + time.Sleep(10 * time.Millisecond) + } +} diff --git a/seaweed-block/core/storage/checkpoint_diagnostics_test.go b/seaweed-block/core/storage/checkpoint_diagnostics_test.go new file mode 100644 index 0000000000..d811d47dde --- /dev/null +++ b/seaweed-block/core/storage/checkpoint_diagnostics_test.go @@ -0,0 +1,51 @@ +package storage + +import ( + "encoding/json" + "errors" + "strings" + "testing" +) + +func TestCheckpointDiagnostics_RefusalThenSuccess(t *testing.T) { + s, _ := newMappedCheckpointStoreV3(t) + writeSynced(t, s, 1, 1) + s.v3.testMapPrepared = func() { + if _, err := s.Write(2, blk(2)); err != nil { + t.Fatal(err) + } + } + before := s.v3.pub.current() + err := s.flusher.flushOnce() + if !errors.Is(err, ErrMapCoverageStale) { + t.Fatalf("refusal: %v", err) + } + if !strings.Contains(err.Error(), "proof_changed") { + t.Errorf("missing refusal reason: %v", err) + } + if s.v3.pub.current() != before || s.dm.len() != 2 || s.stickyIOFault() != nil { + t.Fatal("refusal changed publication/retry/fault state") + } + raw, _ := json.Marshal(s.FlusherInstrumentation()) + var counts map[string]uint64 + if err := json.Unmarshal(raw, &counts); err != nil { + t.Fatal(err) + } + if counts["CheckpointRefusals"] != 1 || counts["CheckpointSuccesses"] != 0 { + t.Fatalf("refusal counters: %s", raw) + } + s.v3.testMapPrepared = nil + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + raw, _ = json.Marshal(s.FlusherInstrumentation()) + if err := json.Unmarshal(raw, &counts); err != nil { + t.Fatal(err) + } + if counts["CheckpointRefusals"] != 1 || counts["CheckpointSuccesses"] != 1 || s.CheckpointLSN() != 2 || s.dm.len() != 0 { + t.Fatalf("retry counters/state: %s cp=%d", raw, s.CheckpointLSN()) + } +} From 0df88965e97aebcf15e53c01864507ac7da3361c Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 00:52:26 -0800 Subject: [PATCH 06/14] storage: report checkpoint retry reasons and cumulative outcomes --- .../durable/checkpoint_status_test.go | 3 + .../core/frontend/durable/provider.go | 31 ++++----- .../core/frontend/durable/storage_adapter.go | 42 +++++++----- .../core/storage/checkpoint_diagnostics.go | 64 ++++++++++++++++++ .../storage/checkpoint_diagnostics_test.go | 67 +++++++++++++++++++ .../core/storage/chunk_map_publication_v3.go | 20 +++--- seaweed-block/core/storage/flusher.go | 9 +-- .../core/storage/flusher_instrumentation.go | 9 +++ .../storage/walstore_map_checkpoint_v3.go | 10 +-- 9 files changed, 204 insertions(+), 51 deletions(-) create mode 100644 seaweed-block/core/storage/checkpoint_diagnostics.go diff --git a/seaweed-block/core/frontend/durable/checkpoint_status_test.go b/seaweed-block/core/frontend/durable/checkpoint_status_test.go index 7b46ce5f64..b3ad4cb9ce 100644 --- a/seaweed-block/core/frontend/durable/checkpoint_status_test.go +++ b/seaweed-block/core/frontend/durable/checkpoint_status_test.go @@ -21,6 +21,9 @@ func TestDurableProvider_CheckpointPersistenceStatus(t *testing.T) { t.Fatal(err) } t.Cleanup(func() { p.Close() }) + if _, err := p.EnsureStorage("v1"); err != nil { + t.Fatal(err) + } if _, err := p.RecoverVolume(context.Background(), "v1"); err != nil { t.Fatal(err) } diff --git a/seaweed-block/core/frontend/durable/provider.go b/seaweed-block/core/frontend/durable/provider.go index f305998a2e..eef6e4d0dc 100644 --- a/seaweed-block/core/frontend/durable/provider.go +++ b/seaweed-block/core/frontend/durable/provider.go @@ -251,21 +251,22 @@ type volHandle struct { // handle. It intentionally exposes lineage and readiness facts without giving // callers a control surface. type VolumeStatus struct { - VolumeID string - Path string - Impl string - ReplicaID string - Epoch uint64 - EndpointVersion uint64 - Latched bool - Operational bool - FrontierKnown bool - DurableLSN uint64 - RetainedLSN uint64 - HeadLSN uint64 - Evidence string - Closed bool - WriteProfile WriteProfileStatus + VolumeID string + Path string + Impl string + ReplicaID string + Epoch uint64 + EndpointVersion uint64 + Latched bool + Operational bool + FrontierKnown bool + DurableLSN uint64 + RetainedLSN uint64 + HeadLSN uint64 + Evidence string + Closed bool + WriteProfile WriteProfileStatus + CheckpointPersistence *storage.CheckpointPersistenceStatus `json:",omitempty"` // Chunk is the chunk layer's state and cut counters; walstore-chunk // volumes only. Chunk *ChunkStatus diff --git a/seaweed-block/core/frontend/durable/storage_adapter.go b/seaweed-block/core/frontend/durable/storage_adapter.go index 2aab01a159..440d1b3e47 100644 --- a/seaweed-block/core/frontend/durable/storage_adapter.go +++ b/seaweed-block/core/frontend/durable/storage_adapter.go @@ -288,6 +288,13 @@ func (b *StorageBackend) durableStatus(volumeID, path, impl string) VolumeStatus if c, ok := b.storage.(interface{ HolesSuspected() uint64 }); ok { holes = c.HolesSuspected() } + var checkpoint *storage.CheckpointPersistenceStatus + if reporter, ok := b.storage.(interface { + CheckpointPersistence() storage.CheckpointPersistenceStatus + }); ok { + snapshot := reporter.CheckpointPersistence() + checkpoint = &snapshot + } writeProfile := b.WriteProfile() if instrumented, ok := b.storage.(storage.WriteInstrumented); ok { storageProfile := instrumented.WriteInstrumentation() @@ -316,23 +323,24 @@ func (b *StorageBackend) durableStatus(volumeID, path, impl string) VolumeStatus writeProfile.DirtyMapUpdateDurationNanos = storageProfile.DirtyMapUpdateDurationNanos } return VolumeStatus{ - Warnings: warnings, - HolesSuspected: holes, - VolumeID: volumeID, - Path: path, - Impl: impl, - ReplicaID: id.ReplicaID, - Epoch: id.Epoch, - EndpointVersion: id.EndpointVersion, - Latched: id.Epoch > 0 && id.EndpointVersion > 0, - Operational: b.operational.Load(), - FrontierKnown: true, - DurableLSN: durableLSN, - RetainedLSN: retainedLSN, - HeadLSN: headLSN, - Evidence: evidence, - Closed: closed, - WriteProfile: writeProfile, + Warnings: warnings, + HolesSuspected: holes, + VolumeID: volumeID, + Path: path, + Impl: impl, + ReplicaID: id.ReplicaID, + Epoch: id.Epoch, + EndpointVersion: id.EndpointVersion, + Latched: id.Epoch > 0 && id.EndpointVersion > 0, + Operational: b.operational.Load(), + FrontierKnown: true, + DurableLSN: durableLSN, + RetainedLSN: retainedLSN, + HeadLSN: headLSN, + Evidence: evidence, + Closed: closed, + WriteProfile: writeProfile, + CheckpointPersistence: checkpoint, } } diff --git a/seaweed-block/core/storage/checkpoint_diagnostics.go b/seaweed-block/core/storage/checkpoint_diagnostics.go new file mode 100644 index 0000000000..2fc3fd3af5 --- /dev/null +++ b/seaweed-block/core/storage/checkpoint_diagnostics.go @@ -0,0 +1,64 @@ +package storage + +import ( + "errors" + "log" + "time" +) + +// CheckpointPersistenceStatus counts flusher checkpoint calls in this open. +// Success includes a safely clamped/unchanged checkpoint; it is not a slot-write +// count. Fields are cumulative atomic observations, not a coherent frontier. +type CheckpointPersistenceStatus struct { + Successes uint64 + Refusals uint64 + Failures uint64 +} + +func (s *WALStore) CheckpointPersistence() CheckpointPersistenceStatus { + if s.flusher == nil { + return CheckpointPersistenceStatus{} + } + i := &s.flusher.instr + return CheckpointPersistenceStatus{i.checkpointSuccesses.Load(), i.checkpointRefusals.Load(), i.checkpointFailures.Load()} +} + +func (i *flusherInstrumentation) recordCheckpoint(err error) { + switch { + case err == nil: + i.checkpointSuccesses.Add(1) + case errors.Is(err, ErrMapCoverageStale): + i.checkpointRefusals.Add(1) + default: + i.checkpointFailures.Add(1) + } +} + +type mapCoverageRefusal string + +func (r mapCoverageRefusal) Error() string { return ErrMapCoverageStale.Error() + ": " + string(r) } +func (r mapCoverageRefusal) Unwrap() error { return ErrMapCoverageStale } + +// Owned exclusively by the flusher run loop; no storage lock or I/O ordering +// changes. Terminal errors are never rate limited. +type checkpointLogLimiter struct { + last time.Time + suppressed uint64 +} + +func (l *checkpointLogLimiter) report(err error, now time.Time) { + if !errors.Is(err, ErrMapCoverageStale) { + log.Printf("storage: flusher: %v", err) + return + } + if !l.last.IsZero() && now.Sub(l.last) < 30*time.Second { + l.suppressed++ + return + } + var reason mapCoverageRefusal + if !errors.As(err, &reason) { + reason = "unspecified" + } + log.Printf("storage: flusher: checkpoint deferred reason=%s suppressed=%d: %v", reason, l.suppressed, err) + l.last, l.suppressed = now, 0 +} diff --git a/seaweed-block/core/storage/checkpoint_diagnostics_test.go b/seaweed-block/core/storage/checkpoint_diagnostics_test.go index d811d47dde..2670beb977 100644 --- a/seaweed-block/core/storage/checkpoint_diagnostics_test.go +++ b/seaweed-block/core/storage/checkpoint_diagnostics_test.go @@ -1,14 +1,19 @@ package storage import ( + "bytes" "encoding/json" "errors" + "fmt" + "log" "strings" "testing" + "time" ) func TestCheckpointDiagnostics_RefusalThenSuccess(t *testing.T) { s, _ := newMappedCheckpointStoreV3(t) + mustAttach(t, s, newFakeChunkRemote(), ctConfig(1)) writeSynced(t, s, 1, 1) s.v3.testMapPrepared = func() { if _, err := s.Write(2, blk(2)); err != nil { @@ -49,3 +54,65 @@ func TestCheckpointDiagnostics_RefusalThenSuccess(t *testing.T) { t.Fatalf("retry counters/state: %s cp=%d", raw, s.CheckpointLSN()) } } + +func TestCheckpointDiagnostics_PrepareRefusalAndIOFailure(t *testing.T) { + for _, fault := range []bool{false, true} { + t.Run(fmt.Sprint(fault), func(t *testing.T) { + s, _ := newMappedCheckpointStoreV3(t) + mustAttach(t, s, newFakeChunkRemote(), ctConfig(1)) + writeSynced(t, s, 1, 1) + realSync := s.v3.ownedMap.syncFile + injected := errors.New("checkpoint map fsync fault") + once := false + s.v3.ownedMap.syncFile = func() error { + if fault { + return injected + } + if !once { + once = true + if _, err := s.Write(2, blk(2)); err != nil { + t.Fatal(err) + } + } + return realSync() + } + err := s.flusher.flushOnce() + got := s.CheckpointPersistence() + if fault { + if !errors.Is(err, injected) || got.Failures != 1 || got.Refusals != 0 || s.stickyIOFault() == nil { + t.Fatalf("fault %v counts=%+v", err, got) + } + } else { + if !errors.Is(err, ErrMapCoverageStale) || !strings.Contains(err.Error(), "proof_changed_during_prepare") || got.Refusals != 1 || got.Failures != 0 || s.stickyIOFault() != nil { + t.Fatalf("refusal %v counts=%+v", err, got) + } + } + if got.Successes != 0 || s.CheckpointLSN() != 0 || s.dm.len() == 0 { + t.Fatal("failed checkpoint advanced or lost retry ownership") + } + }) + } +} + +func TestCheckpointDiagnostics_LogRateLimit(t *testing.T) { + var out bytes.Buffer + old := log.Writer() + log.SetOutput(&out) + t.Cleanup(func() { log.SetOutput(old) }) + var limiter checkpointLogLimiter + now := time.Unix(100, 0) + stale := fmt.Errorf("persist checkpoint: %w", mapCoverageRefusal("proof_changed")) + limiter.report(stale, now) + for i := 0; i < 5; i++ { + limiter.report(stale, now.Add(time.Second)) + } + // A terminal failure must remain visible while refusals are suppressed. + terminal := errors.New("real fsync fault") + limiter.report(terminal, now.Add(2*time.Second)) + limiter.report(terminal, now.Add(3*time.Second)) + limiter.report(stale, now.Add(30*time.Second)) + got := out.String() + if strings.Count(got, "checkpoint deferred") != 2 || strings.Count(got, "real fsync fault") != 2 || !strings.Contains(got, "reason=proof_changed suppressed=5") { + t.Fatalf("logs: %s", got) + } +} diff --git a/seaweed-block/core/storage/chunk_map_publication_v3.go b/seaweed-block/core/storage/chunk_map_publication_v3.go index 8869949475..2ef10237b2 100644 --- a/seaweed-block/core/storage/chunk_map_publication_v3.go +++ b/seaweed-block/core/storage/chunk_map_publication_v3.go @@ -57,7 +57,7 @@ type preparedMapPublicationV3 struct { // Preparation takes the sidecar mutex and I/O only, before store/desc locks. func prepareMapPublicationV3(m *chunkLSNMapV3, d *mapProofEpochV3, g, C uint64, entries []chunkLSNEntryV3, prior *chunkMapCandidateV3) (*preparedMapPublicationV3, error) { if m == nil || d == nil { - return nil, ErrMapCoverageStale + return nil, mapCoverageRefusal("map_binding_missing") } proof := d.snapshotV3() c, e := m.Prepare(g, C, entries, prior) @@ -66,7 +66,7 @@ func prepareMapPublicationV3(m *chunkLSNMapV3, d *mapProofEpochV3, g, C uint64, } if !proof.validV3(d) { m.abandonCandidateV3(c) // prepared but never publishable - return nil, ErrMapCoverageStale + return nil, mapCoverageRefusal("proof_changed_during_prepare") } return &preparedMapPublicationV3{candidate: c, proof: proof}, nil } @@ -84,13 +84,13 @@ func sameMapTupleV3(d descriptorV3, c *chunkMapCandidateV3) bool { // even when none of its pages belong to the selected generation. func (p *descriptorPublisherV3) bindMapV3(c *chunkMapCandidateV3, d *mapProofEpochV3) error { if c == nil || c.owner == nil || d == nil { - return ErrMapCoverageStale + return mapCoverageRefusal("map_binding_missing") } p.descMu.Lock() current, other, otherValid := p.cur, p.other, p.otherValid p.descMu.Unlock() if !sameMapTupleV3(current, c) { - return ErrMapCoverageStale + return mapCoverageRefusal("map_tuple_changed") } if _, _, e := readChunkLSNMapV3(c.owner.fd, current, c.owner.chunkBlocks); e != nil { return e @@ -106,7 +106,7 @@ func (p *descriptorPublisherV3) bindMapV3(c *chunkMapCandidateV3, d *mapProofEpo p.descMu.Lock() defer p.descMu.Unlock() if p.cur != current || p.otherValid != otherValid || (otherValid && p.other != other) { - return ErrMapCoverageStale + return mapCoverageRefusal("descriptor_changed_during_bind") } p.mapCurrent = c p.mapDomain = d @@ -115,7 +115,7 @@ func (p *descriptorPublisherV3) bindMapV3(c *chunkMapCandidateV3, d *mapProofEpo func (p *descriptorPublisherV3) validateMapPublicationV3(next descriptorV3, prepared *preparedMapPublicationV3) error { if p.mapCurrent == nil { if prepared != nil { - return ErrMapCoverageStale + return mapCoverageRefusal("map_not_bound") } return nil } // dark core not bound yet @@ -123,20 +123,20 @@ func (p *descriptorPublisherV3) validateMapPublicationV3(next descriptorV3, prep if prepared != nil { c = prepared.candidate if c == nil || c.owner != p.mapCurrent.owner || !prepared.proof.validV3(p.mapDomain) { - return ErrMapCoverageStale + return mapCoverageRefusal("proof_changed") } if c.generation <= p.mapCurrent.generation || c.covered < p.mapCurrent.covered { - return ErrMapCoverageStale + return mapCoverageRefusal("candidate_superseded") } } if !sameMapTupleV3(next, c) || c.covered < next.CheckpointLSN || c.covered > next.W { - return ErrMapCoverageStale + return mapCoverageRefusal("map_coverage_mismatch") } return nil } func (p *descriptorPublisherV3) publishMapV3(storeMu sync.Locker, snap func(), prepared *preparedMapPublicationV3, mutate func(*descriptorV3) error) (descriptorV3, error) { if prepared == nil || prepared.candidate == nil { - return descriptorV3{}, ErrMapCoverageStale + return descriptorV3{}, mapCoverageRefusal("candidate_missing") } d, err := p.publishWithMapV3(storeMu, snap, func(d *descriptorV3) error { if mutate != nil { diff --git a/seaweed-block/core/storage/flusher.go b/seaweed-block/core/storage/flusher.go index 6d52d7bf24..930e057a89 100644 --- a/seaweed-block/core/storage/flusher.go +++ b/seaweed-block/core/storage/flusher.go @@ -3,7 +3,6 @@ package storage import ( "encoding/binary" "fmt" - "log" "sort" "sync" "sync/atomic" @@ -111,6 +110,7 @@ func (f *flusher) runWithStartSignal(started chan<- struct{}) { if started != nil { close(started) } + var diagnostics checkpointLogLimiter for { select { case <-f.stopCh: @@ -120,11 +120,11 @@ func (f *flusher) runWithStartSignal(started chan<- struct{}) { return case <-ticker.C: if err := f.flushOnce(); err != nil { - log.Printf("storage: flusher: %v", err) + diagnostics.report(err, time.Now()) } case <-f.notifyCh: if err := f.flushOnce(); err != nil { - log.Printf("storage: flusher (notify): %v", err) + diagnostics.report(err, time.Now()) } } } @@ -283,6 +283,7 @@ func (f *flusher) flushOnceInternal(allowClosed bool) (err error) { } else { publishErr = store.persistCheckpointAndRelease(maxLSN, maxLSNPhys, maxLSNEntrySize) } + f.instr.recordCheckpoint(publishErr) if err := publishErr; err != nil { return fmt.Errorf("flusher: persist checkpoint %d: %w", maxLSN, err) } @@ -313,7 +314,7 @@ func (f *flusher) flushOnceInternal(allowClosed bool) (err error) { store.mu.Lock() if !store.v3.flushLifetimeValidV3(recoveryGen) { store.mu.Unlock() - return ErrMapCoverageStale + return mapCoverageRefusal("recovery_lifetime_changed") } checkpoint = store.checkpointLSN if checkpoint >= maxLSN && maxLSN+1 > store.walTail { diff --git a/seaweed-block/core/storage/flusher_instrumentation.go b/seaweed-block/core/storage/flusher_instrumentation.go index 3d7cf587fb..ec3fcf1827 100644 --- a/seaweed-block/core/storage/flusher_instrumentation.go +++ b/seaweed-block/core/storage/flusher_instrumentation.go @@ -12,6 +12,9 @@ const maxCheckpointWriteBytes = 1 << 20 // checkpoint work. Operation counters include failed attempts; byte counters // include only successful writes. type FlusherInstrumentationStatus struct { + CheckpointSuccesses uint64 + CheckpointRefusals uint64 + CheckpointFailures uint64 CyclesStarted uint64 CyclesSucceeded uint64 CyclesFailed uint64 @@ -63,6 +66,9 @@ type FlusherInstrumentationStatus struct { } type flusherInstrumentation struct { + checkpointSuccesses atomic.Uint64 + checkpointRefusals atomic.Uint64 + checkpointFailures atomic.Uint64 cyclesStarted atomic.Uint64 cyclesSucceeded atomic.Uint64 cyclesFailed atomic.Uint64 @@ -284,6 +290,9 @@ func updateAtomicMax(target *atomic.Uint64, value uint64) { func (i *flusherInstrumentation) snapshot() FlusherInstrumentationStatus { return FlusherInstrumentationStatus{ + CheckpointSuccesses: i.checkpointSuccesses.Load(), + CheckpointRefusals: i.checkpointRefusals.Load(), + CheckpointFailures: i.checkpointFailures.Load(), CyclesStarted: i.cyclesStarted.Load(), CyclesSucceeded: i.cyclesSucceeded.Load(), CyclesFailed: i.cyclesFailed.Load(), diff --git a/seaweed-block/core/storage/walstore_map_checkpoint_v3.go b/seaweed-block/core/storage/walstore_map_checkpoint_v3.go index 3b9fe9aca1..a21d4f86a0 100644 --- a/seaweed-block/core/storage/walstore_map_checkpoint_v3.go +++ b/seaweed-block/core/storage/walstore_map_checkpoint_v3.go @@ -33,7 +33,7 @@ func (s *WALStore) prepareOwnedMapCheckpointV3(cp uint64) (*preparedMapPublicati if prior == nil || prior.owner != v.ownedMap || domain != v.mapProof { v.pub.descMu.Unlock() s.mu.RUnlock() - return nil, ErrMapCoverageStale + return nil, mapCoverageRefusal("map_binding_changed") } proof := domain.snapshotV3() // Entries may already contain LSNs above cp from earlier appends: max-LSN @@ -47,7 +47,7 @@ func (s *WALStore) prepareOwnedMapCheckpointV3(cp uint64) (*preparedMapPublicati } if !proof.validV3(domain) { v.ownedMap.abandonCandidateV3(c) // prepared but never publishable - return nil, ErrMapCoverageStale + return nil, mapCoverageRefusal("proof_changed_during_prepare") } return &preparedMapPublicationV3{candidate: c, proof: proof}, nil } @@ -72,7 +72,7 @@ func (s *WALStore) persistOwnedMapCheckpointV3(highestLSN, recoveryGen uint64) e s.mu.Lock() defer s.mu.Unlock() if !v.flushLifetimeValidV3(recoveryGen) { - return ErrMapCoverageStale + return mapCoverageRefusal("recovery_lifetime_changed") } return s.rolloverCheckpointV3Locked() } @@ -120,7 +120,7 @@ func (s *WALStore) publishCheckpointV3(cp uint64, seed bool, recoveryGen uint64) // I/O and could belong to a newer Recover lifetime than those bytes. if !v.flushLifetimeValidV3(recoveryGen) { prepared.abandonV3() - return descriptorV3{}, ErrMapCoverageStale + return descriptorV3{}, mapCoverageRefusal("recovery_lifetime_changed") } wack := v.wack.Load() if seed { @@ -128,7 +128,7 @@ func (s *WALStore) publishCheckpointV3(cp uint64, seed bool, recoveryGen uint64) } if wack < cp { prepared.abandonV3() - return descriptorV3{}, ErrMapCoverageStale + return descriptorV3{}, mapCoverageRefusal("checkpoint_above_wack") } s.mu.RLock() retention := s.recoveryRetentionLSNs From b97352083ae9dc508d30975d30fb22cd36e5d6c4 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 00:53:32 -0800 Subject: [PATCH 07/14] storage: print the stable checkpoint refusal reason --- seaweed-block/core/storage/checkpoint_diagnostics.go | 2 +- seaweed-block/docs/design/invariants.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/seaweed-block/core/storage/checkpoint_diagnostics.go b/seaweed-block/core/storage/checkpoint_diagnostics.go index 2fc3fd3af5..46aa71e185 100644 --- a/seaweed-block/core/storage/checkpoint_diagnostics.go +++ b/seaweed-block/core/storage/checkpoint_diagnostics.go @@ -59,6 +59,6 @@ func (l *checkpointLogLimiter) report(err error, now time.Time) { if !errors.As(err, &reason) { reason = "unspecified" } - log.Printf("storage: flusher: checkpoint deferred reason=%s suppressed=%d: %v", reason, l.suppressed, err) + log.Printf("storage: flusher: checkpoint deferred reason=%s suppressed=%d: %v", string(reason), l.suppressed, err) l.last, l.suppressed = now, 0 } diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index aef36d1bbf..4592eb7d82 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -63,7 +63,7 @@ stateDiagram-v2 | FaultLatched | FaultLatched | every later `Sync`, write, checkpoint and `Recover` on the same open store is refused | `core/storage/walstore.go` `stickyIOFault` | `INV-WAL-FSYNC-STICKY-001` | | any | Closed | `Close`; a store with a latched fault does not write the final superblock | `core/storage/walstore.go` `WALStore.Close` | — | -Production C11 file persistence was removed in row 14b: the durable provider no longer constructs a bitmap sidecar, and the historical file codec exists only in `legacy_c11_file_fixture_test.go`. `INV-CUT-BITMAP-001` retains its explicit legacy engine tests until row 14a; it does not certify the v3 disk format. Native checkpoint/capture coverage is `TestWALStoreV3_AutomaticMapCheckpoint`, `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, and `TestChunkLayer_OwnedMapIncrementalAfterRestart` (checkpointed and WAL-only changes survive reopen without a C11 sidecar). The production map publication/coverage rules remain `INV-WAL-V3-MAP-PUBLISH-001`; no descriptor transition, format or durability boundary changes here. The receiver session bitmap (`INV-RECV-BITMAP-CORE`) is separate and unchanged. +Production C11 file persistence was removed in row 14b: the durable provider no longer constructs a bitmap sidecar, and the historical file codec exists only in `legacy_c11_file_fixture_test.go`. `INV-CUT-BITMAP-001` retains its explicit legacy engine tests until row 14a; it does not certify the v3 disk format. Native checkpoint/capture coverage is `TestCheckpointDiagnostics_RefusalThenSuccess`, `TestCheckpointDiagnostics_PrepareRefusalAndIOFailure`, `TestWALStoreV3_AutomaticMapCheckpoint`, `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, and `TestChunkLayer_OwnedMapIncrementalAfterRestart` (checkpointed and WAL-only changes survive reopen without a C11 sidecar). The production map publication/coverage rules remain `INV-WAL-V3-MAP-PUBLISH-001`; no descriptor transition, format or durability boundary changes here. The receiver session bitmap (`INV-RECV-BITMAP-CORE`) is separate and unchanged. Public walstore Create now selects mapped format v3/impl3 (mode C by default, mode A by create option). Open and offline readonly use A/B slot and owned-map validation; valid legacy formats are refused with `ErrUnsupportedLegacyFormat`, rather than silently retrofitted. The temporary old-engine/raw-codec test scope and every named native replacement are recorded in [the legacy inventory](format-v3-legacy-test-inventory.md). Native recovery validates nonce/cursor binding and a contiguous physical LSN prefix before applying the mode-specific W rule; an acknowledged-range integrity failure blocks startup. The provider's create geometry, auto probe, capture, HEAD restore and readonly/status controls exercise the public selector (`INV-WAL-V3-ACTIVATION-001`). Before reading v3 slots, both read/write and offline read-only open acquire an exclusive nonblocking file lock; the offline migration CLI acquires the same lock before any descriptor read or mutation (`INV-WAL-V3-OWNER-001`). Contention refuses open/migration without changing bytes; descriptor close or process exit releases ownership. This implements the existing offline-migration precondition, not a new serving state. The mapped v3 checkpoint also carries a complete-record physical tail through the covered LSN minus the configured retention window; partial batches remain retained. The existing sole publisher then performs metadata-only rollover when the fallback still pins that prefix. Reuse still requires both valid same-nonce slot tails and retirement of checkpointed dirty references under writer exclusion; idle, unchanged-checkpoint and admission paths also settle a pinned fallback. An unlocked catch-up scan revalidates the coherent checkpoint and tail before emitting anything. A failed rollover latches and grants no reuse (`INV-WAL-V3-RECLAIM-001`). From d6023969a06ab7930a32ff6e316bee897446a79c Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 00:54:29 -0800 Subject: [PATCH 08/14] storage: distinguish recovery and map generation refusals --- .../core/host/volume/status_server_test.go | 24 ++++++++++++------- seaweed-block/core/storage/descriptor_v3.go | 2 +- seaweed-block/core/storage/walstore_v3.go | 4 ++-- 3 files changed, 18 insertions(+), 12 deletions(-) diff --git a/seaweed-block/core/host/volume/status_server_test.go b/seaweed-block/core/host/volume/status_server_test.go index 50fffb65d1..cbdf18d3eb 100644 --- a/seaweed-block/core/host/volume/status_server_test.go +++ b/seaweed-block/core/host/volume/status_server_test.go @@ -7,6 +7,7 @@ import ( "bytes" "context" "encoding/json" + "github.com/seaweedfs/seaweed-block/core/storage" "net/http" "net/http/httptest" "strings" @@ -981,15 +982,16 @@ func TestStatusServer_DurableStatusEndpoint_EnabledAfterStart_ReturnsLineage(t * } defer func() { _ = s.Close(context.Background()) }() s.SetDurableStatusSource(stubDurableStatusSource{vols: []durable.VolumeStatus{{ - VolumeID: "v1", - Path: "/tmp/v1.bin", - Impl: "smartwal", - ReplicaID: "r1", - Epoch: 1, - EndpointVersion: 1, - Latched: true, - Operational: true, - Evidence: "recovered LSN=0", + VolumeID: "v1", + Path: "/tmp/v1.bin", + Impl: "smartwal", + ReplicaID: "r1", + Epoch: 1, + EndpointVersion: 1, + Latched: true, + Operational: true, + Evidence: "recovered LSN=0", + CheckpointPersistence: &storage.CheckpointPersistenceStatus{Successes: 3, Refusals: 2, Failures: 1}, }}}) resp, err := http.Get("http://" + addr + "/status/durable?volume=v1") @@ -1015,6 +1017,10 @@ func TestStatusServer_DurableStatusEndpoint_EnabledAfterStart_ReturnsLineage(t * if len(body.Volumes) != 1 || !body.Volumes[0].Latched || !body.Volumes[0].Operational || body.Volumes[0].Epoch != 1 { t.Fatalf("unexpected durable volume body: %+v", body.Volumes) } + checkpoint := body.Volumes[0].CheckpointPersistence + if checkpoint == nil || checkpoint.Successes != 3 || checkpoint.Refusals != 2 || checkpoint.Failures != 1 { + t.Fatalf("checkpoint counters missing from HTTP response: %+v", checkpoint) + } } func TestG9B_StatusProjection_ReturnedReplicaCanBeDurableReadyButFrontendNotReady(t *testing.T) { diff --git a/seaweed-block/core/storage/descriptor_v3.go b/seaweed-block/core/storage/descriptor_v3.go index 1300ef199a..62310d03a4 100644 --- a/seaweed-block/core/storage/descriptor_v3.go +++ b/seaweed-block/core/storage/descriptor_v3.go @@ -332,7 +332,7 @@ func mergeDescriptorV3Mode(cur, next *descriptorV3, reset bool) error { next.MapLineage != cur.MapLineage || next.MapFormatID != cur.MapFormatID { if next.MapGeneration <= cur.MapGeneration { return fmt.Errorf("%w: %w: map root change without a higher generation (%d -> %d)", - ErrMapCoverageStale, errDescriptorTransition, cur.MapGeneration, next.MapGeneration) + mapCoverageRefusal("map_generation_not_increasing"), errDescriptorTransition, cur.MapGeneration, next.MapGeneration) } if next.MapLineage != cur.MapLineage { return fmt.Errorf("%w: map lineage change outside an install or reset", errDescriptorTransition) diff --git a/seaweed-block/core/storage/walstore_v3.go b/seaweed-block/core/storage/walstore_v3.go index 8691653109..cf6f2cdbc7 100644 --- a/seaweed-block/core/storage/walstore_v3.go +++ b/seaweed-block/core/storage/walstore_v3.go @@ -1091,7 +1091,7 @@ func (f *flusher) readDirtyRecordV3Cached(e snapshotEntry, cache *flushRecordCac store := f.store d := store.v3.pub.current() if cache != nil && !store.v3.flushLifetimeValidV3(cache.recoveryGen) { - return nil, 0, ErrMapCoverageStale + return nil, 0, mapCoverageRefusal("recovery_lifetime_changed") } var entry walEntryV3 var size uint64 @@ -1160,7 +1160,7 @@ func (s *WALStore) persistCheckpointV3(highestLSN, recoveryGen uint64) error { v.syncMu.Lock() defer v.syncMu.Unlock() if !v.flushLifetimeValidV3(recoveryGen) { - return ErrMapCoverageStale + return mapCoverageRefusal("recovery_lifetime_changed") } wack := v.wack.Load() if wack < checkpoint { From 4129cc3668a7bf828040c49b998bf676bf75ac65 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 02:45:22 -0800 Subject: [PATCH 09/14] test(storage): compose checkpoint diagnostics with prefix and extent guards --- seaweed-block/core/storage/checkpoint_diagnostics_test.go | 7 +++++++ seaweed-block/core/storage/chunk_map_extents_v3_test.go | 5 +++-- seaweed-block/docs/design/invariants.md | 2 +- 3 files changed, 11 insertions(+), 3 deletions(-) diff --git a/seaweed-block/core/storage/checkpoint_diagnostics_test.go b/seaweed-block/core/storage/checkpoint_diagnostics_test.go index 2670beb977..9bdba0daf2 100644 --- a/seaweed-block/core/storage/checkpoint_diagnostics_test.go +++ b/seaweed-block/core/storage/checkpoint_diagnostics_test.go @@ -19,6 +19,10 @@ func TestCheckpointDiagnostics_RefusalThenSuccess(t *testing.T) { if _, err := s.Write(2, blk(2)); err != nil { t.Fatal(err) } + // Simulate the effective-mutation class; newer WAL appends alone are safe. + if err := s.v3.mapProof.mutatedV3(); err != nil { + t.Fatal(err) + } } before := s.v3.pub.current() err := s.flusher.flushOnce() @@ -73,6 +77,9 @@ func TestCheckpointDiagnostics_PrepareRefusalAndIOFailure(t *testing.T) { if _, err := s.Write(2, blk(2)); err != nil { t.Fatal(err) } + if err := s.v3.mapProof.mutatedV3(); err != nil { + t.Fatal(err) + } } return realSync() } diff --git a/seaweed-block/core/storage/chunk_map_extents_v3_test.go b/seaweed-block/core/storage/chunk_map_extents_v3_test.go index 72cf43e1af..e920af07a0 100644 --- a/seaweed-block/core/storage/chunk_map_extents_v3_test.go +++ b/seaweed-block/core/storage/chunk_map_extents_v3_test.go @@ -1,6 +1,7 @@ package storage import ( + "errors" "os" "path/filepath" "testing" @@ -430,7 +431,7 @@ func TestChunkMapExtentsV3ProofStalePreparesStayBounded(t *testing.T) { } cp := s.v3.pub.current().CheckpointLSN for i := 0; i < 150; i++ { - if _, err := s.prepareOwnedMapCheckpointV3(cp); err != ErrMapCoverageStale { + if _, err := s.prepareOwnedMapCheckpointV3(cp); !errors.Is(err, ErrMapCoverageStale) { t.Fatalf("checkpoint prepare %d: err = %v, want ErrMapCoverageStale", i, err) } } @@ -438,7 +439,7 @@ func TestChunkMapExtentsV3ProofStalePreparesStayBounded(t *testing.T) { for i := 0; i < 150; i++ { g += 1000 entries := append([]chunkLSNEntryV3(nil), s.v3.mapEntries...) - if _, err := prepareMapPublicationV3(m, s.v3.mapProof, g, cp, entries, nil); err != ErrMapCoverageStale { + if _, err := prepareMapPublicationV3(m, s.v3.mapProof, g, cp, entries, nil); !errors.Is(err, ErrMapCoverageStale) { t.Fatalf("publication prepare %d: err = %v, want ErrMapCoverageStale", i, err) } } diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 4592eb7d82..3f27e03cc6 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -335,7 +335,7 @@ The "Machine / transition" column refers to Part A. Notes under a table record w | `INV-WAL-V3-OWNER-001` | v3 read/write open, offline readonly open and migrate-v3 acquire the same exclusive nonblocking OS file lock before reading slots or changing bytes. Contention refuses with volume locked; descriptor close releases it, allowing retry. | M1 open admission / offline migration precondition | `core/storage/volume_lock*.go`; `walstore_v3.go`; `walstore_readonly_v3.go`; `cmd/sw-block/migrate.go` | `TestMigrateV3RefusesAnOpenV3Volume`, `TestMigrateV3ExcludesOpenUntilCommitFinishes` (tag `swblock_format_v3_test`), `TestWALStoreV3CreatorKeepsOwnershipThroughPublication`, `TestWALStoreV3OwnerExcludesOpenAndReadOnly` | OS mutual exclusion is a caller obligation, outside the abstract crash model; existing open states unchanged | STUB | | `INV-WAL-V3-CATCHUP-001` | A dark v3 catch-up source refuses while installing, including an empty at-head request. Requests covered by an installed BASE require rebuild (typed WALRecycled); damage in retained WAL remains an integrity failure. Before emitting any entries the scan revalidates recovery generation, nonce, BASE state/ID and install epoch, so begin/complete/retire ABA cannot publish a superseded prefix. | M1 BASE lifecycle / M3 CatchingUp (dark callers) | `core/storage/walstore_recovery.go` `ScanLBAs`, `scanLBAsV3`, `v3CatchUpEntries` | `TestCatchUpV3InstallingAtHeadRefuses`, `TestCatchUpV3CompletedBASEUsesRebuild`, `TestCatchUpV3InstallRetireABARefusesOldScan`, `TestCatchUpV3CorruptFirstRecordFails`, `TestCatchUpV3CorruptMiddleRecordFails`, `TestCatchUpV3CompletedBASESuffix` (tag `swblock_format_v3_test`, actual catch-up sender) | Existing BASE and catch-up transitions unchanged; this physical scan/source-lifetime obligation is covered by deterministic caller tests | STUB | | `INV-WAL-V3-BINDING-001` | The dark v3 writer stamps the selected nonce and absolute cursor, fits each append/padding inside the dual-slot reuse floor, and refuses later I/O after a pwrite failure. A dark scanner checks nonce and exact expected cursor before using Length/count, checks the full record again, skips only geometric end slack, and stops at the first untrusted record without payload resynchronization. It returns a typed scan result, never ACK or serving permission. | M1 Recovering (dark muscles only) | `core/storage/wal_io_v3.go` `append`, `scanWALV3`, `walSnapshotV3` | `TestWALIOV3_RealWriterReopenScan`, `TestWALIOV3_WrapPaddingAndSlack`, `TestWALIOV3_StopsAtBindingBeforeEmbeddedRecord`, `TestWALIOV3_EmbeddedRecordInPayloadIsNotScanned`, `TestWALIOV3_InstalledScanBeginsAtMaxTail`, `TestWALIOV3_FloorAndPwriteFailureRefuse` | Record/lap admission is abstracted in composed WALFormatR5; physical framing/wrap boundaries remain code-test obligations | STUB | -| `INV-WAL-V3-MAP-PUBLISH-001` | After a dark publisher binds a validated map, every publication carries a matching immutable tuple with merged checkpoint <= C <= merged W. A prepared replacement needs a higher generation, non-regressing coverage and the same sidecar/open proof domain with unchanged epoch/mutation token. Stale candidates write no slot; W-only rollover carries the current root; unknown slot outcomes pin dependencies. | M1 (dark map publication only; checkpoint/capture caller wiring pending) | `core/storage/chunk_map_publication_v3.go`; `core/storage/descriptor_v3.go` `publishLockedWithMapV3` | `TestWALStoreV3_SeedNeverUsesLegacyDescriptorWriter`, `TestDurableProviderV3_InvalidHEADFrontierRefusesBeforeClaim`, `TestDurableProviderV3_HEADRestorePreservesRemoteImageAndNextLSN`, `TestDurableProviderV3_HEADRestoreAfterLostClaimResponse`, `TestDurableProviderV3_MappedCheckpointCaptureAndReopen`, `TestDurableProviderV3_MissingMapRefusesBeforeBackend`, `TestDurableProviderV3_DefaultSelectorCreatesV3` (tag `swblock_format_v3_test`), `TestChunkLayerV3_MapOnlyCaptureNeedsNoLegacyBitmap`, `TestChunkLayerV3_IgnoresProvidedLegacyBitmap`, `TestChunkLayerV3_MapOnlyFreshZeroHEADPreservesLocalWrites`, `TestChunkLayerV3_MapOnlyRefusesLegacyBASEHeaderMutation`, `TestChunkLayerV3_MapStatusConcurrentClose`, `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, `TestChunkLayerV3_MaxLSNSelectsAfterReopenWithCleanLegacyBitmap`, `TestChunkLayerV3_ChangedCaptureTokenKeepsUNKNOWN`, `TestChunkLayerV3_UnsettledCaptureNeverClearsUNKNOWN`, `TestChunkLayerV3_RefusesMapGeometryBeforeRemote`, `TestWALStoreV3_AutomaticMapCheckpoint`, `TestWALStoreV3_PreparedCheckpointRefusesChangedProof`, `TestChunkLayerV3_CheckpointProgressUnderContinuousAppends`, `TestCheckpointV3_NewerBatchReplaysAfterPreparedPrefix`, `TestCheckpointV3_EffectiveBaseWriteStillInvalidatesProof`, `TestCheckpointV3_ExhaustedMutationCounterStillRefusesAppend`, `TestWALStoreV3_AutomaticMapPersistenceFailureLatchesStore`, `TestWALStoreV3_UncertainMapCheckpointPinsDependencies`, `TestWALStoreV3_AutomaticCheckpointMetadataOrderAndRetry`, `TestWALStoreV3_AutomaticMapRecoverRebuildsCoverage`, `TestWALStoreV3_OpenRequiresBothMapGenerations`, `TestWALStoreV3_MappedCreateOpenOwnsMap`, `TestMapPublicationV3_BindValidatesBothSlotDependencies`, `TestMapPublicationV3_HeldPublicationsBothOrders`, `TestMapPublicationV3_IsolatedMergedCoverageAndWPositive`, `TestMapPublicationV3_ProofEpochAndMutationRefusal`, `TestMapPublicationV3_UncertainFinalResponsePinsCandidate`, `TestMapPublicationV3_CoverageWAndNoUnpreparedRoot`, `TestMapPublicationV3_ProofChangedDuringPersistenceRefuses`; `TestWALStoreV3_RealRecoverInvalidatesMapProofAtStartAndEnd`, `TestWALStoreV3_FailedRecoverInvalidatesMapProofAtBothBoundaries` | WALFormatR5 map coverage / volatile proof epoch; physical caller wiring remains a code obligation | STUB | +| `INV-WAL-V3-MAP-PUBLISH-001` | After a dark publisher binds a validated map, every publication carries a matching immutable tuple with merged checkpoint <= C <= merged W. A prepared replacement needs a higher generation, non-regressing coverage and the same sidecar/open proof domain with unchanged epoch/mutation token. Stale candidates write no slot; W-only rollover carries the current root; unknown slot outcomes pin dependencies. | M1 (dark map publication only; checkpoint/capture caller wiring pending) | `core/storage/chunk_map_publication_v3.go`; `core/storage/descriptor_v3.go` `publishLockedWithMapV3` | `TestWALStoreV3_SeedNeverUsesLegacyDescriptorWriter`, `TestDurableProviderV3_InvalidHEADFrontierRefusesBeforeClaim`, `TestDurableProviderV3_HEADRestorePreservesRemoteImageAndNextLSN`, `TestDurableProviderV3_HEADRestoreAfterLostClaimResponse`, `TestDurableProviderV3_MappedCheckpointCaptureAndReopen`, `TestDurableProviderV3_MissingMapRefusesBeforeBackend`, `TestDurableProviderV3_DefaultSelectorCreatesV3` (tag `swblock_format_v3_test`), `TestChunkLayerV3_MapOnlyCaptureNeedsNoLegacyBitmap`, `TestChunkLayerV3_IgnoresProvidedLegacyBitmap`, `TestChunkLayerV3_MapOnlyFreshZeroHEADPreservesLocalWrites`, `TestChunkLayerV3_MapOnlyRefusesLegacyBASEHeaderMutation`, `TestChunkLayerV3_MapStatusConcurrentClose`, `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, `TestChunkLayerV3_MaxLSNSelectsAfterReopenWithCleanLegacyBitmap`, `TestChunkLayerV3_ChangedCaptureTokenKeepsUNKNOWN`, `TestChunkLayerV3_UnsettledCaptureNeverClearsUNKNOWN`, `TestChunkLayerV3_RefusesMapGeometryBeforeRemote`, `TestWALStoreV3_AutomaticMapCheckpoint`, `TestWALStoreV3_PreparedCheckpointRefusesChangedProof`, `TestChunkLayerV3_CheckpointProgressUnderContinuousAppends`, `TestCheckpointV3_NewerBatchReplaysAfterPreparedPrefix`, `TestCheckpointV3_EffectiveBaseWriteStillInvalidatesProof`, `TestCheckpointV3_ExhaustedMutationCounterStillRefusesAppend`, `TestCheckpointV3_AppendRolloverAfterPrepareKeepsRetainedSuffix`, `TestCheckpointV3_LazyFillDoesNotInvalidatePreparedPrefix`, `TestChunkLayerV3_CheckpointProgressAtWALPressure`, `TestWALStoreV3_AutomaticMapPersistenceFailureLatchesStore`, `TestWALStoreV3_UncertainMapCheckpointPinsDependencies`, `TestWALStoreV3_AutomaticCheckpointMetadataOrderAndRetry`, `TestWALStoreV3_AutomaticMapRecoverRebuildsCoverage`, `TestWALStoreV3_OpenRequiresBothMapGenerations`, `TestWALStoreV3_MappedCreateOpenOwnsMap`, `TestMapPublicationV3_BindValidatesBothSlotDependencies`, `TestMapPublicationV3_HeldPublicationsBothOrders`, `TestMapPublicationV3_IsolatedMergedCoverageAndWPositive`, `TestMapPublicationV3_ProofEpochAndMutationRefusal`, `TestMapPublicationV3_UncertainFinalResponsePinsCandidate`, `TestMapPublicationV3_CoverageWAndNoUnpreparedRoot`, `TestMapPublicationV3_ProofChangedDuringPersistenceRefuses`; `TestWALStoreV3_RealRecoverInvalidatesMapProofAtStartAndEnd`, `TestWALStoreV3_FailedRecoverInvalidatesMapProofAtBothBoundaries` | WALFormatR5 map coverage / volatile proof epoch; physical caller wiring remains a code obligation | STUB | | `INV-WAL-V3-FLUSH-LIFETIME-001` | A dark v3 flusher binds its dirty snapshot and extent materialization to the original even Recover generation. A cycle spanning Recover/reset publishes no checkpoint/map and retires no reused dirty entry. | M1 Recovering / checkpoint publication | `core/storage/flusher.go`; `walstore_map_checkpoint_v3.go`; `walstore_v3.go` `flushLifetimeValidV3` | `TestWALStoreV3_FlushMaterializationBoundToRecoveryLifetime` | Existing recovery/map proof lifetime; implementation correspondence | STUB | | `INV-WAL-V3-MAP-BYTES-001` | A dark v3 map candidate names immutable, owned, identity- and geometry-checked pages and root. Domain-separated body digests, reserved/unused bytes, exact page counts, file bounds and non-aliasing intervals all validate before entries escape. Persistence orders pages/fsync, root/fsync, directory fsync; a persistence-transaction error yields no candidate and latches subsequent I/O; preflight and Stat errors do not latch. Extents are reused only when no live root references them (both slot roots, in-flight candidates, an uncertain candidate until reopen); the free tail is truncated above the highest live page. | M1 (dark map preparation only) | `core/storage/chunk_lsn_map_v3.go` `Prepare`, `readChunkLSNMapV3`; `core/storage/chunk_map_extents_v3.go` (live set, allocation, release, truncation); `core/storage/chunk_map_publication_v3.go` `publishMapV3`; `core/storage/descriptor_v3.go` (slot report, uncertain candidate) | `TestChunkMapV3FileStaysBoundedUnderSteadyCheckpoints` (`core/storage/chunkmap_bounded_v3_test.go`); `TestChunkMapExtentsV3FallbackRootIsNeverReused`, `TestChunkMapExtentsV3NewerInFlightCandidateIsNotReused`, `TestChunkMapExtentsV3CrashBeforePublicationOfAReusedExtent`, `TestChunkMapExtentsV3TruncationKeepsAFallbackAtTheTail`, `TestChunkMapExtentsV3RejectedPublicationsStayBounded`, `TestChunkMapExtentsV3ReopenRegistersTheFallbackRoot`, `TestChunkMapExtentsV3TruncationFaultKeepsTheSlotRoots`, `TestChunkMapExtentsV3UncertainCandidateStaysPinned`, `TestChunkMapExtentsV3StatsAfterReopen`, `TestChunkMapExtentsV3ProofStalePreparesStayBounded`, `TestChunkMapExtentsV3DurableButRefusedPublicationStaysPinned` (`core/storage/chunk_map_extents_v3_test.go`); `TestChunkLSNMapV3_CanonicalVectors`, `TestChunkLSNMapV3_PersistReloadAndReuse`, `TestChunkLSNMapV3_CorruptionAndBounds`, `TestChunkLSNMapV3_FailureDoesNotPublishOrReuse`, `TestChunkLSNMapV3_OrderOwnedOpenAndClippedPage`, `TestChunkLSNMapV3_RejectsRehashedMalformedRecords`, `TestChunkLSNMapV3_EntryBoundBeforeRootIO`, `TestChunkLSNMapV3_WholePageHashIsNotBodyDigest`, `TestChunkLSNMapV3_PreflightErrorDoesNotLatch` | WALFormatR5 abstract map dependency; physical encoding/digest/order are code obligations | STUB | | `INV-WAL-V3-PUBLISH-001` | Every v3 descriptor change goes through one publisher. It writes the fallback slot with slotGen+1 under `descMu`. It takes `WALStore.mu` only to snapshot and releases it before slot I/O, and fsync is the leaf. It rebases onto the authoritative descriptor: W and the checkpoint are max-merged, and identity, geometry and nonce changes are refused, as are tail regression, a map root change without a higher generation and any BASE edge outside DESIGN 8.5 (installed -> 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 | From 194f1552e2da9bd1427e000eadf868a7685be873 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 03:05:35 -0800 Subject: [PATCH 10/14] test(storage): cover no-sync pressure and speculative prefix boundaries --- .../checkpoint_append_progress_v3_test.go | 343 +++++++++++++++++- .../storage/walstore_map_checkpoint_v3.go | 4 +- seaweed-block/core/storage/walstore_v3.go | 2 +- seaweed-block/docs/design/invariants.md | 4 +- 4 files changed, 343 insertions(+), 10 deletions(-) diff --git a/seaweed-block/core/storage/checkpoint_append_progress_v3_test.go b/seaweed-block/core/storage/checkpoint_append_progress_v3_test.go index 910d5408b3..602d819a9b 100644 --- a/seaweed-block/core/storage/checkpoint_append_progress_v3_test.go +++ b/seaweed-block/core/storage/checkpoint_append_progress_v3_test.go @@ -2,9 +2,11 @@ package storage import ( "bytes" + "encoding/binary" "errors" "path/filepath" "testing" + "time" ) func TestChunkLayerV3_CheckpointProgressUnderContinuousAppends(t *testing.T) { @@ -288,20 +290,28 @@ func TestChunkLayerV3_CheckpointProgressAtWALPressure(t *testing.T) { realSync := s.v3.ownedMap.syncFile t.Cleanup(func() { s.v3.ownedMap.syncFile = realSync }) previousCP := uint64(0) + expected := make(map[uint32][]byte) + write := func() error { + lsn := s.NextLSN() + lba := uint32(lsn % 64) + data := checkpointProgressBlock(lsn) + if _, err := s.Write(lba, data); err != nil { + return err + } + expected[lba] = data + return nil + } for cycle := 0; cycle < 8; cycle++ { for s.walUsedFraction() < 0.72 { - if _, err := s.Write(uint32(s.NextLSN()%64), blk(byte(s.NextLSN()))); err != nil { + if err := write(); err != nil { t.Fatal(err) } } - if _, err := s.Sync(); err != nil { - t.Fatal(err) - } injected := false s.v3.ownedMap.syncFile = func() error { if !injected { injected = true - if _, err := s.Write(uint32(s.NextLSN()%64), blk(byte(s.NextLSN()))); err != nil { + if err := write(); err != nil { return err } } @@ -322,7 +332,328 @@ func TestChunkLayerV3_CheckpointProgressAtWALPressure(t *testing.T) { if !ok || floor < 5*64*1024 { t.Fatalf("no sustained ring reuse: floor%d", floor) } - t.Logf("cycles8 checkpoint%d floor%d busy0", previousCP, floor) + for lba, want := range expected { + if got, err := s.Read(lba); err != nil || !bytes.Equal(got, want) { + t.Fatalf("no-Flush readback LBA%d: %v", lba, err) + } + } + t.Logf("no client Sync: cycles8 checkpoint%d floor%d busy0", previousCP, floor) + }) + } +} + +func checkpointProgressBlock(lsn uint64) []byte { + data := make([]byte, 4096) + for i := 0; i < len(data); i += 8 { + binary.LittleEndian.PutUint64(data[i:i+8], lsn*4096+uint64(i)) + } + return data +} + +// An active history pin gives one bounded, typed refusal; local flusher work +// after releasing it restores progress without a client Sync or new remote cut. +func TestCheckpointV3_NoFlushPressureWithRealPin(t *testing.T) { + path := filepath.Join(t.TempDir(), "pinned") + s, err := createMappedWALStoreV3ForTest(path, 64, 4096, 64*1024, WModeStrict, 4) + if err != nil { + t.Fatal(err) + } + s.DisableAutoFlushForRecoveryTest() + t.Cleanup(func() { _ = s.Close() }) + mustAttach(t, s, newFakeChunkRemote(), ctConfig(1)) + s.SetRecycleFloorSource(&fakeRecycleFloorSource{floor: 0, anyActive: true}) + expected := make(map[uint32][]byte) + for s.walUsedFraction() < 0.90 { + lsn := s.NextLSN() + lba := uint32(lsn) + data := checkpointProgressBlock(lsn) + if _, err := s.Write(lba, data); err != nil { + t.Fatal(err) + } + expected[lba] = data + } + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + if s.CheckpointLSN() != 0 || s.v3.wack.Load() == 0 { + t.Fatal("real retention pin did not constrain an internally synced checkpoint") + } + next := s.NextLSN() + start := time.Now() + _, err = s.Write(uint32(next), checkpointProgressBlock(next)) + elapsed := time.Since(start) + if !errors.Is(err, ErrWALPressureTimeout) || elapsed >= 5*time.Second || s.NextLSN() != next { + t.Fatalf("pinned busy: err%v elapsed%v next%d want%d", err, elapsed, s.NextLSN(), next) + } + count := 0 + if err := s.ScanLBAs(1, func(e RecoveryEntry) error { + count++ + if e.LSN != uint64(count) || !bytes.Equal(e.Data, expected[e.LBA]) { + return errors.New("pinned retained prefix differs from submitted bytes") + } + return nil + }); err != nil || count != len(expected) { + t.Fatalf("pinned exact prefix count%d want%d: %v", count, len(expected), err) + } + s.SetRecycleFloorSource(nil) + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } // no Write/Sync wakes it + if s.CheckpointLSN() != next-1 { + t.Fatal("released pin did not permit passive local checkpoint progress") + } + if lsn, err := s.Write(uint32(next), checkpointProgressBlock(next)); err != nil || lsn != next { + t.Fatalf("retry: %d %v", lsn, err) + } + expected[uint32(next)] = checkpointProgressBlock(next) + for lba, want := range expected { + if got, err := s.Read(lba); err != nil || !bytes.Equal(got, want) { + t.Fatalf("pinned readback LBA%d: %v", lba, err) + } + } + t.Logf("busy1 elapsed%v retained%d checkpoint%d", elapsed, count, s.CheckpointLSN()) +} + +func TestCheckpointV3_AppendRolloverFaultRefusesHeldCandidate(t *testing.T) { + s, _ := newMappedCheckpointStoreV3(t) + s.SetRecoveryRetentionLSNs(1) + writeSynced(t, s, 1, 2) + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + prepared, err := s.prepareOwnedMapCheckpointV3(2) + if err != nil { + t.Fatal(err) + } + tail := s.v3.w.reclaimThroughV3(2) + if _, err := s.v3.pub.publish(nil, nil, func(d *descriptorV3) error { + d.RetainedTail = tail + d.RetainedHead = max(d.RetainedHead, tail) + return nil + }); err != nil { + t.Fatal(err) + } + before := s.v3.pub.current() + _, floor, ok := s.v3.pub.walSnapshotV3() + if !ok || floor >= tail { + t.Fatal("setup: no pinned fallback") + } + injected := errors.New("append rollover slot fault") + s.v3.testBeforeSlotWrite = func() error { return injected } + _, err = s.Write(3, blk(0xD3)) + s.v3.testBeforeSlotWrite = nil + if !errors.Is(err, injected) || s.stickyIOFault() == nil || s.NextLSN() != 3 || s.dm.len() != 0 { + t.Fatalf("rollover fault: %v next%d dirty%d", err, s.NextLSN(), s.dm.len()) + } + if _, err := s.v3.pub.publishMapV3(&s.mu, nil, prepared, nil); err == nil { + t.Fatal("held candidate published through sticky rollover failure") + } + if s.v3.pub.current() != before { + t.Fatal("rollover fault changed authoritative tuple") + } + if nextFloor, _ := s.v3.pub.reuseFloor(); nextFloor != floor { + t.Fatal("failed rollover released fallback floor") + } +} + +// Max-LSN map entries may include unsynced writes above both cp and W. A +// reused LSN can then set UNKNOWN without changing the prefix proof token. +func TestCheckpointV3_SpeculativeMaximumAfterDroppedSuffix(t *testing.T) { + s, path := newMappedCheckpointStoreV3(t) + remote := newFakeChunkRemote() + layer := mustAttach(t, s, remote, ctConfig(1)) + if _, err := s.Write(1, blk(0xA1)); err != nil { + t.Fatal(err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + if _, err := layer.Cut(ctTimeout(t)); err != nil { + t.Fatal(err) + } + if s.v3.mapEntries[0].Unknown { + t.Fatal("setup: initial definite cut did not clear UNKNOWN") + } + if _, err := s.Write(1, blk(0xA2)); err != nil { + t.Fatal(err) + } + if _, err := s.Write(1, blk(0xA3)); err != nil { + t.Fatal(err) + } + prepared, err := s.prepareOwnedMapCheckpointV3(1) + if err != nil { + t.Fatal(err) + } + d := s.v3.pub.current() + e := prepared.candidate.entries[0] + if e.LSN != 3 || e.Unknown || d.CheckpointLSN != 1 || d.W != 1 { + t.Fatalf("speculative maximum: entry%+v cp%d W%d", e, d.CheckpointLSN, d.W) + } + if _, err := s.v3.pub.publishMapV3(&s.mu, nil, prepared, nil); err != nil { + t.Fatal(err) + } + if err := layer.Close(); err != nil { + t.Fatal(err) + } + crashRecoveryHardeningStore(t, s) + s.mu.Lock() + s.closed = true + s.mu.Unlock() + damageRecord(t, path, 2) // unacknowledged record2 tears; the following3 is dropped + r, err := openWALStoreV3ForTest(path) + if err != nil { + t.Fatal(err) + } + r.DisableAutoFlushForRecoveryTest() + t.Cleanup(func() { _ = r.Close() }) + if _, err := r.Recover(); err != nil { + t.Fatal(err) + } + if r.NextLSN() != 2 || r.v3.mapEntries[0].LSN != 3 { + t.Fatal("dropped suffix did not leave the conservative persisted maximum") + } + held, err := r.prepareOwnedMapCheckpointV3(1) + if err != nil { + t.Fatal(err) + } + if held.candidate.entries[0].Unknown { + t.Fatal("setup: held candidate already UNKNOWN") + } + if lsn, err := r.Write(1, blk(0xB2)); err != nil || lsn != 2 { + t.Fatalf("reused LSN: %d %v", lsn, err) + } + if !r.v3.mapEntries[0].Unknown || r.v3.mapEntries[0].LSN != 3 { + t.Fatal("reused LSN did not conservatively set UNKNOWN beneath the high maximum") + } + if !held.proof.validV3(r.v3.mapProof) { + t.Fatal("reused ordered append invalidated the older prefix") + } + if _, err := r.v3.pub.publishMapV3(&r.mu, nil, held, nil); err != nil { + t.Fatal(err) + } + if _, err := r.Sync(); err != nil { + t.Fatal(err) + } + crashRecoveryHardeningStore(t, r) + r.mu.Lock() + r.closed = true + r.mu.Unlock() + r2, err := openWALStoreV3ForTest(path) + if err != nil { + t.Fatal(err) + } + r2.DisableAutoFlushForRecoveryTest() + t.Cleanup(func() { _ = r2.Close() }) + if _, err := r2.Recover(); err != nil { + t.Fatal(err) + } + if !r2.v3.mapEntries[0].Unknown || !bytes.Equal(readV3(t, r2, 1), blk(0xB2)) { + t.Fatal("replay did not restore UNKNOWN and exact reused-LSN bytes") + } + restored := mustAttach(t, r2, remote, ctConfig(2)) + cut, err := restored.Cut(ctTimeout(t)) + if err != nil { + t.Fatal(err) + } + image := remote.imageOf(t, cut.Head) + if !bytes.Equal(image[4096:8192], blk(0xB2)) { + t.Fatal("capture treated the speculative maximum as remotely clean") + } +} + +func TestCheckpointV3_HeldHydrationWithLocalWriteAndFlush(t *testing.T) { + for _, flush := range []bool{false, true} { + t.Run(map[bool]string{false: "wal", true: "extent"}[flush], func(t *testing.T) { + path := filepath.Join(t.TempDir(), "hydrating") + s, err := createMappedWALStoreV3ForTest(path, ctNumBlocks, ctBlockSize, v3TestWAL, WModeStrict, ctChunkBlocks) + if err != nil { + t.Fatal(err) + } + s.DisableAutoFlushForRecoveryTest() + t.Cleanup(func() { _ = s.Close() }) + image := make([]byte, ctNumBlocks*ctBlockSize) + copy(image[8*ctBlockSize:], blk(0xA8)) + copy(image[9*ctBlockSize:], blk(0xA9)) + remote := newFakeChunkRemote() + remote.seedHead(t, image, 10, 1) + if err := s.SeedChunkFrontier(10); err != nil { + t.Fatal(err) + } + cfg := ctConfig(2) + cfg.FreshFromHead = true + layer := mustAttach(t, s, remote, cfg) + held, err := s.prepareOwnedMapCheckpointV3(10) + if err != nil { + t.Fatal(err) + } + entered, release := holdNextGet(t, remote) + done := make(chan error, 1) + go func() { + got, err := s.Read(9) + if err == nil && !bytes.Equal(got, blk(0xB9)) { + err = errors.New("held read did not return newer local bytes") + } + done <- err + }() + waitKey(t, entered, "cold fill before a competing local write") + if _, err := s.Write(9, blk(0xB9)); err != nil { + t.Fatal(err) + } + if flush { + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + } + dirty := s.dm.len() + release() + if err := waitErr(t, done, "fill and post-miss WAL recheck"); err != nil { + t.Fatal(err) + } + if s.dm.len() != dirty || !held.proof.validV3(s.v3.mapProof) { + t.Fatal("hydration manufactured logical dirt or invalidated the prefix proof") + } + before := s.v3.pub.current() + _, err = s.v3.pub.publishMapV3(&s.mu, nil, held, nil) + if flush { + if !errors.Is(err, ErrMapCoverageStale) || s.v3.pub.current() != before { + t.Fatalf("superseded candidate after flush: %v", err) + } + } else { + if err != nil { + t.Fatal(err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + } + if !bytes.Equal(readV3(t, s, 8), blk(0xA8)) || !bytes.Equal(readV3(t, s, 9), blk(0xB9)) { + t.Fatal("HEAD fill or local write was overwritten") + } + if err := layer.Close(); err != nil { + t.Fatal(err) + } + crashRecoveryHardeningStore(t, s) + s.mu.Lock() + s.closed = true + s.mu.Unlock() + r, err := openWALStoreV3ForTest(path) + if err != nil { + t.Fatal(err) + } + r.DisableAutoFlushForRecoveryTest() + t.Cleanup(func() { _ = r.Close() }) + if _, err := r.Recover(); err != nil { + t.Fatal(err) + } + if !bytes.Equal(readV3(t, r, 8), blk(0xA8)) || !bytes.Equal(readV3(t, r, 9), blk(0xB9)) { + t.Fatal("reopen lost exact hydrated/local bytes") + } }) } } diff --git a/seaweed-block/core/storage/walstore_map_checkpoint_v3.go b/seaweed-block/core/storage/walstore_map_checkpoint_v3.go index a21d4f86a0..ee902f622d 100644 --- a/seaweed-block/core/storage/walstore_map_checkpoint_v3.go +++ b/seaweed-block/core/storage/walstore_map_checkpoint_v3.go @@ -7,6 +7,8 @@ package storage // Caller holds WALStore.mu. Higher-LSN writes update the max; a reused or // lower/equal effective LSN is conservative UNKNOWN, independent of the max. +// A reused ordered LSN below a speculative max can set UNKNOWN here without +// invalidating a prefix proof; the max and retained suffix stay conservative. // Capture is the only future owner allowed to clear UNKNOWN after a version // check. Keeping it set here cannot manufacture a remotely clean chunk. func (s *WALStore) recordMapWriteV3(lba, lsn uint64) { @@ -36,7 +38,7 @@ func (s *WALStore) prepareOwnedMapCheckpointV3(cp uint64) (*preparedMapPublicati return nil, mapCoverageRefusal("map_binding_changed") } proof := domain.snapshotV3() - // Entries may already contain LSNs above cp from earlier appends: max-LSN + // Entries may already contain LSNs above cp or W from earlier appends: max-LSN // entries are monotone and idempotent under retained-suffix replay. entries := append([]chunkLSNEntryV3(nil), v.mapEntries...) v.pub.descMu.Unlock() diff --git a/seaweed-block/core/storage/walstore_v3.go b/seaweed-block/core/storage/walstore_v3.go index cf6f2cdbc7..76d28a7d93 100644 --- a/seaweed-block/core/storage/walstore_v3.go +++ b/seaweed-block/core/storage/walstore_v3.go @@ -655,7 +655,7 @@ func (s *WALStore) appendWriteV3(lba uint32, data []byte, lsn uint64) (uint64, e return 0, errWALBindingV3 // a half-published reset before its Recover } // A strictly newer append stays in the retained WAL suffix. It cannot - // invalidate coverage of an older checkpoint prefix; effective BASE and + // invalidate coverage of an older checkpoint prefix; BASE writes, capture UNKNOWN clearing and // lifecycle mutations still invalidate the map proof at their own seams. if p := s.v3.mapProof; p != nil && p.mutation.Load() >= counterMaxV3 { return 0, ErrCounterExhausted diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 3f27e03cc6..40c144fa06 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -335,7 +335,7 @@ The "Machine / transition" column refers to Part A. Notes under a table record w | `INV-WAL-V3-OWNER-001` | v3 read/write open, offline readonly open and migrate-v3 acquire the same exclusive nonblocking OS file lock before reading slots or changing bytes. Contention refuses with volume locked; descriptor close releases it, allowing retry. | M1 open admission / offline migration precondition | `core/storage/volume_lock*.go`; `walstore_v3.go`; `walstore_readonly_v3.go`; `cmd/sw-block/migrate.go` | `TestMigrateV3RefusesAnOpenV3Volume`, `TestMigrateV3ExcludesOpenUntilCommitFinishes` (tag `swblock_format_v3_test`), `TestWALStoreV3CreatorKeepsOwnershipThroughPublication`, `TestWALStoreV3OwnerExcludesOpenAndReadOnly` | OS mutual exclusion is a caller obligation, outside the abstract crash model; existing open states unchanged | STUB | | `INV-WAL-V3-CATCHUP-001` | A dark v3 catch-up source refuses while installing, including an empty at-head request. Requests covered by an installed BASE require rebuild (typed WALRecycled); damage in retained WAL remains an integrity failure. Before emitting any entries the scan revalidates recovery generation, nonce, BASE state/ID and install epoch, so begin/complete/retire ABA cannot publish a superseded prefix. | M1 BASE lifecycle / M3 CatchingUp (dark callers) | `core/storage/walstore_recovery.go` `ScanLBAs`, `scanLBAsV3`, `v3CatchUpEntries` | `TestCatchUpV3InstallingAtHeadRefuses`, `TestCatchUpV3CompletedBASEUsesRebuild`, `TestCatchUpV3InstallRetireABARefusesOldScan`, `TestCatchUpV3CorruptFirstRecordFails`, `TestCatchUpV3CorruptMiddleRecordFails`, `TestCatchUpV3CompletedBASESuffix` (tag `swblock_format_v3_test`, actual catch-up sender) | Existing BASE and catch-up transitions unchanged; this physical scan/source-lifetime obligation is covered by deterministic caller tests | STUB | | `INV-WAL-V3-BINDING-001` | The dark v3 writer stamps the selected nonce and absolute cursor, fits each append/padding inside the dual-slot reuse floor, and refuses later I/O after a pwrite failure. A dark scanner checks nonce and exact expected cursor before using Length/count, checks the full record again, skips only geometric end slack, and stops at the first untrusted record without payload resynchronization. It returns a typed scan result, never ACK or serving permission. | M1 Recovering (dark muscles only) | `core/storage/wal_io_v3.go` `append`, `scanWALV3`, `walSnapshotV3` | `TestWALIOV3_RealWriterReopenScan`, `TestWALIOV3_WrapPaddingAndSlack`, `TestWALIOV3_StopsAtBindingBeforeEmbeddedRecord`, `TestWALIOV3_EmbeddedRecordInPayloadIsNotScanned`, `TestWALIOV3_InstalledScanBeginsAtMaxTail`, `TestWALIOV3_FloorAndPwriteFailureRefuse` | Record/lap admission is abstracted in composed WALFormatR5; physical framing/wrap boundaries remain code-test obligations | STUB | -| `INV-WAL-V3-MAP-PUBLISH-001` | After a dark publisher binds a validated map, every publication carries a matching immutable tuple with merged checkpoint <= C <= merged W. A prepared replacement needs a higher generation, non-regressing coverage and the same sidecar/open proof domain with unchanged epoch/mutation token. Stale candidates write no slot; W-only rollover carries the current root; unknown slot outcomes pin dependencies. | M1 (dark map publication only; checkpoint/capture caller wiring pending) | `core/storage/chunk_map_publication_v3.go`; `core/storage/descriptor_v3.go` `publishLockedWithMapV3` | `TestWALStoreV3_SeedNeverUsesLegacyDescriptorWriter`, `TestDurableProviderV3_InvalidHEADFrontierRefusesBeforeClaim`, `TestDurableProviderV3_HEADRestorePreservesRemoteImageAndNextLSN`, `TestDurableProviderV3_HEADRestoreAfterLostClaimResponse`, `TestDurableProviderV3_MappedCheckpointCaptureAndReopen`, `TestDurableProviderV3_MissingMapRefusesBeforeBackend`, `TestDurableProviderV3_DefaultSelectorCreatesV3` (tag `swblock_format_v3_test`), `TestChunkLayerV3_MapOnlyCaptureNeedsNoLegacyBitmap`, `TestChunkLayerV3_IgnoresProvidedLegacyBitmap`, `TestChunkLayerV3_MapOnlyFreshZeroHEADPreservesLocalWrites`, `TestChunkLayerV3_MapOnlyRefusesLegacyBASEHeaderMutation`, `TestChunkLayerV3_MapStatusConcurrentClose`, `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, `TestChunkLayerV3_MaxLSNSelectsAfterReopenWithCleanLegacyBitmap`, `TestChunkLayerV3_ChangedCaptureTokenKeepsUNKNOWN`, `TestChunkLayerV3_UnsettledCaptureNeverClearsUNKNOWN`, `TestChunkLayerV3_RefusesMapGeometryBeforeRemote`, `TestWALStoreV3_AutomaticMapCheckpoint`, `TestWALStoreV3_PreparedCheckpointRefusesChangedProof`, `TestChunkLayerV3_CheckpointProgressUnderContinuousAppends`, `TestCheckpointV3_NewerBatchReplaysAfterPreparedPrefix`, `TestCheckpointV3_EffectiveBaseWriteStillInvalidatesProof`, `TestCheckpointV3_ExhaustedMutationCounterStillRefusesAppend`, `TestCheckpointV3_AppendRolloverAfterPrepareKeepsRetainedSuffix`, `TestCheckpointV3_LazyFillDoesNotInvalidatePreparedPrefix`, `TestChunkLayerV3_CheckpointProgressAtWALPressure`, `TestWALStoreV3_AutomaticMapPersistenceFailureLatchesStore`, `TestWALStoreV3_UncertainMapCheckpointPinsDependencies`, `TestWALStoreV3_AutomaticCheckpointMetadataOrderAndRetry`, `TestWALStoreV3_AutomaticMapRecoverRebuildsCoverage`, `TestWALStoreV3_OpenRequiresBothMapGenerations`, `TestWALStoreV3_MappedCreateOpenOwnsMap`, `TestMapPublicationV3_BindValidatesBothSlotDependencies`, `TestMapPublicationV3_HeldPublicationsBothOrders`, `TestMapPublicationV3_IsolatedMergedCoverageAndWPositive`, `TestMapPublicationV3_ProofEpochAndMutationRefusal`, `TestMapPublicationV3_UncertainFinalResponsePinsCandidate`, `TestMapPublicationV3_CoverageWAndNoUnpreparedRoot`, `TestMapPublicationV3_ProofChangedDuringPersistenceRefuses`; `TestWALStoreV3_RealRecoverInvalidatesMapProofAtStartAndEnd`, `TestWALStoreV3_FailedRecoverInvalidatesMapProofAtBothBoundaries` | WALFormatR5 map coverage / volatile proof epoch; physical caller wiring remains a code obligation | STUB | +| `INV-WAL-V3-MAP-PUBLISH-001` | After a dark publisher binds a validated map, every publication carries a matching immutable tuple with merged checkpoint <= C <= merged W. A prepared replacement needs a higher generation, non-regressing coverage and the same sidecar/open proof domain with unchanged epoch/mutation token. Stale candidates write no slot; W-only rollover carries the current root; unknown slot outcomes pin dependencies. | M1 (dark map publication only; checkpoint/capture caller wiring pending) | `core/storage/chunk_map_publication_v3.go`; `core/storage/descriptor_v3.go` `publishLockedWithMapV3` | `TestWALStoreV3_SeedNeverUsesLegacyDescriptorWriter`, `TestDurableProviderV3_InvalidHEADFrontierRefusesBeforeClaim`, `TestDurableProviderV3_HEADRestorePreservesRemoteImageAndNextLSN`, `TestDurableProviderV3_HEADRestoreAfterLostClaimResponse`, `TestDurableProviderV3_MappedCheckpointCaptureAndReopen`, `TestDurableProviderV3_MissingMapRefusesBeforeBackend`, `TestDurableProviderV3_DefaultSelectorCreatesV3` (tag `swblock_format_v3_test`), `TestChunkLayerV3_MapOnlyCaptureNeedsNoLegacyBitmap`, `TestChunkLayerV3_IgnoresProvidedLegacyBitmap`, `TestChunkLayerV3_MapOnlyFreshZeroHEADPreservesLocalWrites`, `TestChunkLayerV3_MapOnlyRefusesLegacyBASEHeaderMutation`, `TestChunkLayerV3_MapStatusConcurrentClose`, `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, `TestChunkLayerV3_MaxLSNSelectsAfterReopenWithCleanLegacyBitmap`, `TestChunkLayerV3_ChangedCaptureTokenKeepsUNKNOWN`, `TestChunkLayerV3_UnsettledCaptureNeverClearsUNKNOWN`, `TestChunkLayerV3_RefusesMapGeometryBeforeRemote`, `TestWALStoreV3_AutomaticMapCheckpoint`, `TestWALStoreV3_PreparedCheckpointRefusesChangedProof`, `TestChunkLayerV3_CheckpointProgressUnderContinuousAppends`, `TestCheckpointV3_NewerBatchReplaysAfterPreparedPrefix`, `TestCheckpointV3_EffectiveBaseWriteStillInvalidatesProof`, `TestCheckpointV3_ExhaustedMutationCounterStillRefusesAppend`, `TestCheckpointV3_AppendRolloverAfterPrepareKeepsRetainedSuffix`, `TestCheckpointV3_LazyFillDoesNotInvalidatePreparedPrefix`, `TestChunkLayerV3_CheckpointProgressAtWALPressure`, `TestCheckpointV3_NoFlushPressureWithRealPin`, `TestCheckpointV3_AppendRolloverFaultRefusesHeldCandidate`, `TestCheckpointV3_SpeculativeMaximumAfterDroppedSuffix`, `TestCheckpointV3_HeldHydrationWithLocalWriteAndFlush`, `TestWALStoreV3_AutomaticMapPersistenceFailureLatchesStore`, `TestWALStoreV3_UncertainMapCheckpointPinsDependencies`, `TestWALStoreV3_AutomaticCheckpointMetadataOrderAndRetry`, `TestWALStoreV3_AutomaticMapRecoverRebuildsCoverage`, `TestWALStoreV3_OpenRequiresBothMapGenerations`, `TestWALStoreV3_MappedCreateOpenOwnsMap`, `TestMapPublicationV3_BindValidatesBothSlotDependencies`, `TestMapPublicationV3_HeldPublicationsBothOrders`, `TestMapPublicationV3_IsolatedMergedCoverageAndWPositive`, `TestMapPublicationV3_ProofEpochAndMutationRefusal`, `TestMapPublicationV3_UncertainFinalResponsePinsCandidate`, `TestMapPublicationV3_CoverageWAndNoUnpreparedRoot`, `TestMapPublicationV3_ProofChangedDuringPersistenceRefuses`; `TestWALStoreV3_RealRecoverInvalidatesMapProofAtStartAndEnd`, `TestWALStoreV3_FailedRecoverInvalidatesMapProofAtBothBoundaries` | WALFormatR5 map coverage / volatile proof epoch; physical caller wiring remains a code obligation | STUB | | `INV-WAL-V3-FLUSH-LIFETIME-001` | A dark v3 flusher binds its dirty snapshot and extent materialization to the original even Recover generation. A cycle spanning Recover/reset publishes no checkpoint/map and retires no reused dirty entry. | M1 Recovering / checkpoint publication | `core/storage/flusher.go`; `walstore_map_checkpoint_v3.go`; `walstore_v3.go` `flushLifetimeValidV3` | `TestWALStoreV3_FlushMaterializationBoundToRecoveryLifetime` | Existing recovery/map proof lifetime; implementation correspondence | STUB | | `INV-WAL-V3-MAP-BYTES-001` | A dark v3 map candidate names immutable, owned, identity- and geometry-checked pages and root. Domain-separated body digests, reserved/unused bytes, exact page counts, file bounds and non-aliasing intervals all validate before entries escape. Persistence orders pages/fsync, root/fsync, directory fsync; a persistence-transaction error yields no candidate and latches subsequent I/O; preflight and Stat errors do not latch. Extents are reused only when no live root references them (both slot roots, in-flight candidates, an uncertain candidate until reopen); the free tail is truncated above the highest live page. | M1 (dark map preparation only) | `core/storage/chunk_lsn_map_v3.go` `Prepare`, `readChunkLSNMapV3`; `core/storage/chunk_map_extents_v3.go` (live set, allocation, release, truncation); `core/storage/chunk_map_publication_v3.go` `publishMapV3`; `core/storage/descriptor_v3.go` (slot report, uncertain candidate) | `TestChunkMapV3FileStaysBoundedUnderSteadyCheckpoints` (`core/storage/chunkmap_bounded_v3_test.go`); `TestChunkMapExtentsV3FallbackRootIsNeverReused`, `TestChunkMapExtentsV3NewerInFlightCandidateIsNotReused`, `TestChunkMapExtentsV3CrashBeforePublicationOfAReusedExtent`, `TestChunkMapExtentsV3TruncationKeepsAFallbackAtTheTail`, `TestChunkMapExtentsV3RejectedPublicationsStayBounded`, `TestChunkMapExtentsV3ReopenRegistersTheFallbackRoot`, `TestChunkMapExtentsV3TruncationFaultKeepsTheSlotRoots`, `TestChunkMapExtentsV3UncertainCandidateStaysPinned`, `TestChunkMapExtentsV3StatsAfterReopen`, `TestChunkMapExtentsV3ProofStalePreparesStayBounded`, `TestChunkMapExtentsV3DurableButRefusedPublicationStaysPinned` (`core/storage/chunk_map_extents_v3_test.go`); `TestChunkLSNMapV3_CanonicalVectors`, `TestChunkLSNMapV3_PersistReloadAndReuse`, `TestChunkLSNMapV3_CorruptionAndBounds`, `TestChunkLSNMapV3_FailureDoesNotPublishOrReuse`, `TestChunkLSNMapV3_OrderOwnedOpenAndClippedPage`, `TestChunkLSNMapV3_RejectsRehashedMalformedRecords`, `TestChunkLSNMapV3_EntryBoundBeforeRootIO`, `TestChunkLSNMapV3_WholePageHashIsNotBodyDigest`, `TestChunkLSNMapV3_PreflightErrorDoesNotLatch` | WALFormatR5 abstract map dependency; physical encoding/digest/order are code obligations | STUB | | `INV-WAL-V3-PUBLISH-001` | Every v3 descriptor change goes through one publisher. It writes the fallback slot with slotGen+1 under `descMu`. It takes `WALStore.mu` only to snapshot and releases it before slot I/O, and fsync is the leaf. It rebases onto the authoritative descriptor: W and the checkpoint are max-merged, and identity, geometry and nonce changes are refused, as are tail regression, a map root change without a higher generation and any BASE edge outside DESIGN 8.5 (installed -> 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 | @@ -355,7 +355,7 @@ 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-FLUSH-LIFETIME-001`: Capture recoverGen under store.mu with the dirty snapshot, before WAL materialization/extent I/O. Recheck the original generation under syncMu before either mapped or historical dark checkpoint publication. Under store.mu, recheck again before local tail progress and LSN-only compare/delete; Recover uses the same store lock at both boundaries. This adds no new lock or I/O under a publication lock. The pre-proof held control materializes unacknowledged A2, damages only that WAL suffix, Recover keeps W1, then reuses the same LBA/offset/LSN for acknowledged B2. Old publication must refuse, retain B, and a fresh retry must put B in the physical extent before crash-style reopen verifies exact bytes. -- `INV-WAL-V3-MAP-PUBLISH-001`: The open/quiesced bind validates the selected and every valid fallback map root/page dependency before installing a proof domain, with a slot snapshot recheck after I/O. A corrupt fallback refuses binding even if the selected map is intact; validation writes no slots and preserves the prior domain on failure. This is a binding seam control, not automatic create/open or capture wiring. 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. The dark map-requiring actual-store opener now loads its owned sidecar and validates both slots before workers start, binds a fresh proof domain, and Close releases the map. The explicit mapped creator persists an all-UNKNOWN initial map before publishing its first slot. Earlier unmapped row5 fixtures have a separately named test-only opt-out, not a production selector. Owned-map stores now prepare a typed snapshot/proof outside publication locks and publish real checkpoint coverage through publishMapV3 under syncMu. The existing map mutex reserves candidate generations; transaction failures latch the whole store before returning. The entry snapshot may already contain LSNs above cp from pre-snapshot appends; max-LSN entries remain monotone and idempotent under replay. Strictly newer ordered WAL appends update per-chunk max LSN without invalidating an older checkpoint-prefix proof: their retained suffix is replayed before recovery serves. Effective BASE/UNKNOWN changes and lifecycle boundaries still invalidate proofs. Recover rebuilds the volatile cache from the selected root and retained WAL prefix. Metadata/chunk callbacks precede map and descriptor durability. The dark actual chunk capture now also selects owned-map UNKNOWN/max-LSN candidates after checkpoint, samples chunk mutation tokens under its barrier, and clears UNKNOWN only after definite HEAD publication with unchanged tokens. Its resulting map snapshot is published through the same proof/coverage checks; failed or unresolved cuts clear nothing, and failed local map publication keeps disk UNKNOWN conservative. Replaying an already checkpoint-covered record does not invent a fresh logical map mutation. A mismatched chunk geometry is refused before remote contact. Eviction uses the same owned-map/WAL dirt predicate, so checkpointed data awaiting capture cannot be replaced by a fill from an older HEAD. Normal impl3 capture attachment/checkpoint/status no longer loads, saves, resets or requires the legacy bitmap; v2 retains it. A provided legacy object is ignored. The immutable per-open proof discriminator permits status alongside Close without reading its mutable cleanup pointer. Legacy BASE header mutations remain refused; the descriptor install protocol now uses the dark chunk transition drain and permits completed BASE attachment (INV-WAL-V3-CHUNK-BASE-001). A private test-only provider factory now drives the actual DurableProvider/StorageBackend create, recover, write, Sync, flusher, capture and local reopen paths on mapped v3 without a legacy bitmap. The cross-package constructor wrappers exist only under swblock_format_v3_test; the normal provider selector remains legacy, and a missing owned map refuses without caching a backend. SeedChunkFrontier now dispatches to the shared v3 checkpoint publisher (row9c), without waiting on the committer under store.mu. The real provider invalid-frontier control proves preparation failure claims no HEAD and leaves the backend nonoperational. Row12a now removes the provider refusal and exercises the actual mapped FreshFromHead restore through the row9 single-publisher seed: seed/rebase precedes takeover CAS, a committed claim with a lost response is resolved by exact reread, inherited LSNs are not reused, immutable chunks fill lazily, and later capture/local reopen preserve exact bytes. An invalid inherited frontier refuses without claiming HEAD. Production selection remains v2; the dark BASE caller and readonly/status controls have dedicated rows below; production activation remains separate. WAL tail reclamation is not yet wired. Existing dark lifecycle tests drive invalidation primitives; only the two explicitly named real-store controls exercise actual Recover, ; automatic checkpoint and tagged provider controls above separately cover those real callers. 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`: The open/quiesced bind validates the selected and every valid fallback map root/page dependency before installing a proof domain, with a slot snapshot recheck after I/O. A corrupt fallback refuses binding even if the selected map is intact; validation writes no slots and preserves the prior domain on failure. This is a binding seam control, not automatic create/open or capture wiring. 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. The dark map-requiring actual-store opener now loads its owned sidecar and validates both slots before workers start, binds a fresh proof domain, and Close releases the map. The explicit mapped creator persists an all-UNKNOWN initial map before publishing its first slot. Earlier unmapped row5 fixtures have a separately named test-only opt-out, not a production selector. Owned-map stores now prepare a typed snapshot/proof outside publication locks and publish real checkpoint coverage through publishMapV3 under syncMu. The existing map mutex reserves candidate generations; transaction failures latch the whole store before returning. The entry snapshot may already contain LSNs above cp or W from pre-snapshot appends; max-LSN entries remain monotone and idempotent under replay. Strictly newer ordered WAL appends update per-chunk max LSN without invalidating an older checkpoint-prefix proof: their retained suffix is replayed before recovery serves. BASE writes, capture UNKNOWN clearing and lifecycle boundaries still invalidate proofs. A reused ordered LSN below a speculative retained map maximum can set UNKNOWN without invalidating the prefix; the high max and replayed retained suffix remain conservative. Recover rebuilds the volatile cache from the selected root and retained WAL prefix. Metadata/chunk callbacks precede map and descriptor durability. The dark actual chunk capture now also selects owned-map UNKNOWN/max-LSN candidates after checkpoint, samples chunk mutation tokens under its barrier, and clears UNKNOWN only after definite HEAD publication with unchanged tokens. Its resulting map snapshot is published through the same proof/coverage checks; failed or unresolved cuts clear nothing, and failed local map publication keeps disk UNKNOWN conservative. Replaying an already checkpoint-covered record does not invent a fresh logical map mutation. A mismatched chunk geometry is refused before remote contact. Eviction uses the same owned-map/WAL dirt predicate, so checkpointed data awaiting capture cannot be replaced by a fill from an older HEAD. Normal impl3 capture attachment/checkpoint/status no longer loads, saves, resets or requires the legacy bitmap; v2 retains it. A provided legacy object is ignored. The immutable per-open proof discriminator permits status alongside Close without reading its mutable cleanup pointer. Legacy BASE header mutations remain refused; the descriptor install protocol now uses the dark chunk transition drain and permits completed BASE attachment (INV-WAL-V3-CHUNK-BASE-001). A private test-only provider factory now drives the actual DurableProvider/StorageBackend create, recover, write, Sync, flusher, capture and local reopen paths on mapped v3 without a legacy bitmap. The cross-package constructor wrappers exist only under swblock_format_v3_test; the normal provider selector remains legacy, and a missing owned map refuses without caching a backend. SeedChunkFrontier now dispatches to the shared v3 checkpoint publisher (row9c), without waiting on the committer under store.mu. The real provider invalid-frontier control proves preparation failure claims no HEAD and leaves the backend nonoperational. Row12a now removes the provider refusal and exercises the actual mapped FreshFromHead restore through the row9 single-publisher seed: seed/rebase precedes takeover CAS, a committed claim with a lost response is resolved by exact reread, inherited LSNs are not reused, immutable chunks fill lazily, and later capture/local reopen preserve exact bytes. An invalid inherited frontier refuses without claiming HEAD. Production selection remains v2; the dark BASE caller and readonly/status controls have dedicated rows below; production activation remains separate. WAL tail reclamation is not yet wired. Existing dark lifecycle tests drive invalidation primitives; only the two explicitly named real-store controls exercise actual Recover, ; automatic checkpoint and tagged provider controls above separately cover those real callers. 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. Sidecar extents are reused only after neither slot nor a pending or uncertain candidate references them; see `chunk_map_extents_v3.go` and its tests. From 33a6adf6ca9781399403ccdf54af7dd9e7b49534 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 03:09:17 -0800 Subject: [PATCH 11/14] test(storage): require reuse refusal after uncertain rollover --- .../core/storage/checkpoint_append_progress_v3_test.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/seaweed-block/core/storage/checkpoint_append_progress_v3_test.go b/seaweed-block/core/storage/checkpoint_append_progress_v3_test.go index 602d819a9b..b6dc94bb2a 100644 --- a/seaweed-block/core/storage/checkpoint_append_progress_v3_test.go +++ b/seaweed-block/core/storage/checkpoint_append_progress_v3_test.go @@ -451,8 +451,8 @@ func TestCheckpointV3_AppendRolloverFaultRefusesHeldCandidate(t *testing.T) { if s.v3.pub.current() != before { t.Fatal("rollover fault changed authoritative tuple") } - if nextFloor, _ := s.v3.pub.reuseFloor(); nextFloor != floor { - t.Fatal("failed rollover released fallback floor") + if nextFloor, valid := s.v3.pub.reuseFloor(); valid || nextFloor != 0 { + t.Fatal("uncertain rollover must disable reuse until reopen") } } From 9acab6eebaeb7fc0c33a203dbdbf70d57c1cb3d0 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 03:10:31 -0800 Subject: [PATCH 12/14] test(storage): sync hydrated extents before reopen assertions --- .../storage/checkpoint_append_progress_v3_test.go | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/seaweed-block/core/storage/checkpoint_append_progress_v3_test.go b/seaweed-block/core/storage/checkpoint_append_progress_v3_test.go index b6dc94bb2a..e693f76698 100644 --- a/seaweed-block/core/storage/checkpoint_append_progress_v3_test.go +++ b/seaweed-block/core/storage/checkpoint_append_progress_v3_test.go @@ -624,13 +624,12 @@ func TestCheckpointV3_HeldHydrationWithLocalWriteAndFlush(t *testing.T) { if !errors.Is(err, ErrMapCoverageStale) || s.v3.pub.current() != before { t.Fatalf("superseded candidate after flush: %v", err) } - } else { - if err != nil { - t.Fatal(err) - } - if _, err := s.Sync(); err != nil { - t.Fatal(err) - } + } else if err != nil { + t.Fatal(err) + } + // Cover the hydrated extent bytes too before the reopen oracle. + if _, err := s.Sync(); err != nil { + t.Fatal(err) } if !bytes.Equal(readV3(t, s, 8), blk(0xA8)) || !bytes.Equal(readV3(t, s, 9), blk(0xB9)) { t.Fatal("HEAD fill or local write was overwritten") From 370be25e9489d77b3d7d33b647c3a309585f7a08 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 03:13:45 -0800 Subject: [PATCH 13/14] test(storage): isolate cut proof invalidation from map generation --- .../checkpoint_append_progress_v3_test.go | 34 +++++++++++++++++++ seaweed-block/core/storage/walstore_v3.go | 4 +-- seaweed-block/docs/design/invariants.md | 2 +- 3 files changed, 37 insertions(+), 3 deletions(-) diff --git a/seaweed-block/core/storage/checkpoint_append_progress_v3_test.go b/seaweed-block/core/storage/checkpoint_append_progress_v3_test.go index e693f76698..b12f704f6c 100644 --- a/seaweed-block/core/storage/checkpoint_append_progress_v3_test.go +++ b/seaweed-block/core/storage/checkpoint_append_progress_v3_test.go @@ -656,3 +656,37 @@ func TestCheckpointV3_HeldHydrationWithLocalWriteAndFlush(t *testing.T) { }) } } + +func TestCheckpointV3_DefiniteCutClearInvalidatesHeldProof(t *testing.T) { + s, _ := newMappedCheckpointStoreV3(t) + layer := mustAttach(t, s, newFakeChunkRemote(), ctConfig(1)) + writeSynced(t, s, 1, 1) + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + held, err := s.prepareOwnedMapCheckpointV3(1) + if err != nil { + t.Fatal(err) + } + if !s.v3.mapEntries[0].Unknown { + t.Fatal("setup: no UNKNOWN to clear") + } + if _, err := layer.Cut(ctTimeout(t)); err != nil { + t.Fatal(err) + } + if s.v3.mapEntries[0].Unknown { + t.Fatal("definite cut did not clear UNKNOWN") + } + // Inspect the proof itself so the newer map generation cannot mask a missing + // clear-invalidation guard in the publication refusal below. + if held.proof.validV3(s.v3.mapProof) { + t.Fatal("capture UNKNOWN clearing left the old proof valid") + } + before := s.v3.pub.current() + if _, err := s.v3.pub.publishMapV3(&s.mu, nil, held, nil); !errors.Is(err, ErrMapCoverageStale) { + t.Fatalf("old capture proof: %v", err) + } + if s.v3.pub.current() != before { + t.Fatal("capture-stale candidate changed a slot") + } +} diff --git a/seaweed-block/core/storage/walstore_v3.go b/seaweed-block/core/storage/walstore_v3.go index 76d28a7d93..9d48c7374a 100644 --- a/seaweed-block/core/storage/walstore_v3.go +++ b/seaweed-block/core/storage/walstore_v3.go @@ -655,8 +655,8 @@ func (s *WALStore) appendWriteV3(lba uint32, data []byte, lsn uint64) (uint64, e return 0, errWALBindingV3 // a half-published reset before its Recover } // A strictly newer append stays in the retained WAL suffix. It cannot - // invalidate coverage of an older checkpoint prefix; BASE writes, capture UNKNOWN clearing and - // lifecycle mutations still invalidate the map proof at their own seams. + // invalidate coverage of an older checkpoint prefix. BASE writes, capture + // UNKNOWN clearing and lifecycle mutations still invalidate at their seams. if p := s.v3.mapProof; p != nil && p.mutation.Load() >= counterMaxV3 { return 0, ErrCounterExhausted } diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 40c144fa06..9177bc28cf 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -335,7 +335,7 @@ The "Machine / transition" column refers to Part A. Notes under a table record w | `INV-WAL-V3-OWNER-001` | v3 read/write open, offline readonly open and migrate-v3 acquire the same exclusive nonblocking OS file lock before reading slots or changing bytes. Contention refuses with volume locked; descriptor close releases it, allowing retry. | M1 open admission / offline migration precondition | `core/storage/volume_lock*.go`; `walstore_v3.go`; `walstore_readonly_v3.go`; `cmd/sw-block/migrate.go` | `TestMigrateV3RefusesAnOpenV3Volume`, `TestMigrateV3ExcludesOpenUntilCommitFinishes` (tag `swblock_format_v3_test`), `TestWALStoreV3CreatorKeepsOwnershipThroughPublication`, `TestWALStoreV3OwnerExcludesOpenAndReadOnly` | OS mutual exclusion is a caller obligation, outside the abstract crash model; existing open states unchanged | STUB | | `INV-WAL-V3-CATCHUP-001` | A dark v3 catch-up source refuses while installing, including an empty at-head request. Requests covered by an installed BASE require rebuild (typed WALRecycled); damage in retained WAL remains an integrity failure. Before emitting any entries the scan revalidates recovery generation, nonce, BASE state/ID and install epoch, so begin/complete/retire ABA cannot publish a superseded prefix. | M1 BASE lifecycle / M3 CatchingUp (dark callers) | `core/storage/walstore_recovery.go` `ScanLBAs`, `scanLBAsV3`, `v3CatchUpEntries` | `TestCatchUpV3InstallingAtHeadRefuses`, `TestCatchUpV3CompletedBASEUsesRebuild`, `TestCatchUpV3InstallRetireABARefusesOldScan`, `TestCatchUpV3CorruptFirstRecordFails`, `TestCatchUpV3CorruptMiddleRecordFails`, `TestCatchUpV3CompletedBASESuffix` (tag `swblock_format_v3_test`, actual catch-up sender) | Existing BASE and catch-up transitions unchanged; this physical scan/source-lifetime obligation is covered by deterministic caller tests | STUB | | `INV-WAL-V3-BINDING-001` | The dark v3 writer stamps the selected nonce and absolute cursor, fits each append/padding inside the dual-slot reuse floor, and refuses later I/O after a pwrite failure. A dark scanner checks nonce and exact expected cursor before using Length/count, checks the full record again, skips only geometric end slack, and stops at the first untrusted record without payload resynchronization. It returns a typed scan result, never ACK or serving permission. | M1 Recovering (dark muscles only) | `core/storage/wal_io_v3.go` `append`, `scanWALV3`, `walSnapshotV3` | `TestWALIOV3_RealWriterReopenScan`, `TestWALIOV3_WrapPaddingAndSlack`, `TestWALIOV3_StopsAtBindingBeforeEmbeddedRecord`, `TestWALIOV3_EmbeddedRecordInPayloadIsNotScanned`, `TestWALIOV3_InstalledScanBeginsAtMaxTail`, `TestWALIOV3_FloorAndPwriteFailureRefuse` | Record/lap admission is abstracted in composed WALFormatR5; physical framing/wrap boundaries remain code-test obligations | STUB | -| `INV-WAL-V3-MAP-PUBLISH-001` | After a dark publisher binds a validated map, every publication carries a matching immutable tuple with merged checkpoint <= C <= merged W. A prepared replacement needs a higher generation, non-regressing coverage and the same sidecar/open proof domain with unchanged epoch/mutation token. Stale candidates write no slot; W-only rollover carries the current root; unknown slot outcomes pin dependencies. | M1 (dark map publication only; checkpoint/capture caller wiring pending) | `core/storage/chunk_map_publication_v3.go`; `core/storage/descriptor_v3.go` `publishLockedWithMapV3` | `TestWALStoreV3_SeedNeverUsesLegacyDescriptorWriter`, `TestDurableProviderV3_InvalidHEADFrontierRefusesBeforeClaim`, `TestDurableProviderV3_HEADRestorePreservesRemoteImageAndNextLSN`, `TestDurableProviderV3_HEADRestoreAfterLostClaimResponse`, `TestDurableProviderV3_MappedCheckpointCaptureAndReopen`, `TestDurableProviderV3_MissingMapRefusesBeforeBackend`, `TestDurableProviderV3_DefaultSelectorCreatesV3` (tag `swblock_format_v3_test`), `TestChunkLayerV3_MapOnlyCaptureNeedsNoLegacyBitmap`, `TestChunkLayerV3_IgnoresProvidedLegacyBitmap`, `TestChunkLayerV3_MapOnlyFreshZeroHEADPreservesLocalWrites`, `TestChunkLayerV3_MapOnlyRefusesLegacyBASEHeaderMutation`, `TestChunkLayerV3_MapStatusConcurrentClose`, `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, `TestChunkLayerV3_MaxLSNSelectsAfterReopenWithCleanLegacyBitmap`, `TestChunkLayerV3_ChangedCaptureTokenKeepsUNKNOWN`, `TestChunkLayerV3_UnsettledCaptureNeverClearsUNKNOWN`, `TestChunkLayerV3_RefusesMapGeometryBeforeRemote`, `TestWALStoreV3_AutomaticMapCheckpoint`, `TestWALStoreV3_PreparedCheckpointRefusesChangedProof`, `TestChunkLayerV3_CheckpointProgressUnderContinuousAppends`, `TestCheckpointV3_NewerBatchReplaysAfterPreparedPrefix`, `TestCheckpointV3_EffectiveBaseWriteStillInvalidatesProof`, `TestCheckpointV3_ExhaustedMutationCounterStillRefusesAppend`, `TestCheckpointV3_AppendRolloverAfterPrepareKeepsRetainedSuffix`, `TestCheckpointV3_LazyFillDoesNotInvalidatePreparedPrefix`, `TestChunkLayerV3_CheckpointProgressAtWALPressure`, `TestCheckpointV3_NoFlushPressureWithRealPin`, `TestCheckpointV3_AppendRolloverFaultRefusesHeldCandidate`, `TestCheckpointV3_SpeculativeMaximumAfterDroppedSuffix`, `TestCheckpointV3_HeldHydrationWithLocalWriteAndFlush`, `TestWALStoreV3_AutomaticMapPersistenceFailureLatchesStore`, `TestWALStoreV3_UncertainMapCheckpointPinsDependencies`, `TestWALStoreV3_AutomaticCheckpointMetadataOrderAndRetry`, `TestWALStoreV3_AutomaticMapRecoverRebuildsCoverage`, `TestWALStoreV3_OpenRequiresBothMapGenerations`, `TestWALStoreV3_MappedCreateOpenOwnsMap`, `TestMapPublicationV3_BindValidatesBothSlotDependencies`, `TestMapPublicationV3_HeldPublicationsBothOrders`, `TestMapPublicationV3_IsolatedMergedCoverageAndWPositive`, `TestMapPublicationV3_ProofEpochAndMutationRefusal`, `TestMapPublicationV3_UncertainFinalResponsePinsCandidate`, `TestMapPublicationV3_CoverageWAndNoUnpreparedRoot`, `TestMapPublicationV3_ProofChangedDuringPersistenceRefuses`; `TestWALStoreV3_RealRecoverInvalidatesMapProofAtStartAndEnd`, `TestWALStoreV3_FailedRecoverInvalidatesMapProofAtBothBoundaries` | WALFormatR5 map coverage / volatile proof epoch; physical caller wiring remains a code obligation | STUB | +| `INV-WAL-V3-MAP-PUBLISH-001` | After a dark publisher binds a validated map, every publication carries a matching immutable tuple with merged checkpoint <= C <= merged W. A prepared replacement needs a higher generation, non-regressing coverage and the same sidecar/open proof domain with unchanged epoch/mutation token. Stale candidates write no slot; W-only rollover carries the current root; unknown slot outcomes pin dependencies. | M1 (dark map publication only; checkpoint/capture caller wiring pending) | `core/storage/chunk_map_publication_v3.go`; `core/storage/descriptor_v3.go` `publishLockedWithMapV3` | `TestWALStoreV3_SeedNeverUsesLegacyDescriptorWriter`, `TestDurableProviderV3_InvalidHEADFrontierRefusesBeforeClaim`, `TestDurableProviderV3_HEADRestorePreservesRemoteImageAndNextLSN`, `TestDurableProviderV3_HEADRestoreAfterLostClaimResponse`, `TestDurableProviderV3_MappedCheckpointCaptureAndReopen`, `TestDurableProviderV3_MissingMapRefusesBeforeBackend`, `TestDurableProviderV3_DefaultSelectorCreatesV3` (tag `swblock_format_v3_test`), `TestChunkLayerV3_MapOnlyCaptureNeedsNoLegacyBitmap`, `TestChunkLayerV3_IgnoresProvidedLegacyBitmap`, `TestChunkLayerV3_MapOnlyFreshZeroHEADPreservesLocalWrites`, `TestChunkLayerV3_MapOnlyRefusesLegacyBASEHeaderMutation`, `TestChunkLayerV3_MapStatusConcurrentClose`, `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, `TestChunkLayerV3_MaxLSNSelectsAfterReopenWithCleanLegacyBitmap`, `TestChunkLayerV3_ChangedCaptureTokenKeepsUNKNOWN`, `TestChunkLayerV3_UnsettledCaptureNeverClearsUNKNOWN`, `TestChunkLayerV3_RefusesMapGeometryBeforeRemote`, `TestWALStoreV3_AutomaticMapCheckpoint`, `TestWALStoreV3_PreparedCheckpointRefusesChangedProof`, `TestChunkLayerV3_CheckpointProgressUnderContinuousAppends`, `TestCheckpointV3_NewerBatchReplaysAfterPreparedPrefix`, `TestCheckpointV3_EffectiveBaseWriteStillInvalidatesProof`, `TestCheckpointV3_ExhaustedMutationCounterStillRefusesAppend`, `TestCheckpointV3_AppendRolloverAfterPrepareKeepsRetainedSuffix`, `TestCheckpointV3_LazyFillDoesNotInvalidatePreparedPrefix`, `TestChunkLayerV3_CheckpointProgressAtWALPressure`, `TestCheckpointV3_NoFlushPressureWithRealPin`, `TestCheckpointV3_AppendRolloverFaultRefusesHeldCandidate`, `TestCheckpointV3_SpeculativeMaximumAfterDroppedSuffix`, `TestCheckpointV3_HeldHydrationWithLocalWriteAndFlush`, `TestCheckpointV3_DefiniteCutClearInvalidatesHeldProof`, `TestWALStoreV3_AutomaticMapPersistenceFailureLatchesStore`, `TestWALStoreV3_UncertainMapCheckpointPinsDependencies`, `TestWALStoreV3_AutomaticCheckpointMetadataOrderAndRetry`, `TestWALStoreV3_AutomaticMapRecoverRebuildsCoverage`, `TestWALStoreV3_OpenRequiresBothMapGenerations`, `TestWALStoreV3_MappedCreateOpenOwnsMap`, `TestMapPublicationV3_BindValidatesBothSlotDependencies`, `TestMapPublicationV3_HeldPublicationsBothOrders`, `TestMapPublicationV3_IsolatedMergedCoverageAndWPositive`, `TestMapPublicationV3_ProofEpochAndMutationRefusal`, `TestMapPublicationV3_UncertainFinalResponsePinsCandidate`, `TestMapPublicationV3_CoverageWAndNoUnpreparedRoot`, `TestMapPublicationV3_ProofChangedDuringPersistenceRefuses`; `TestWALStoreV3_RealRecoverInvalidatesMapProofAtStartAndEnd`, `TestWALStoreV3_FailedRecoverInvalidatesMapProofAtBothBoundaries` | WALFormatR5 map coverage / volatile proof epoch; physical caller wiring remains a code obligation | STUB | | `INV-WAL-V3-FLUSH-LIFETIME-001` | A dark v3 flusher binds its dirty snapshot and extent materialization to the original even Recover generation. A cycle spanning Recover/reset publishes no checkpoint/map and retires no reused dirty entry. | M1 Recovering / checkpoint publication | `core/storage/flusher.go`; `walstore_map_checkpoint_v3.go`; `walstore_v3.go` `flushLifetimeValidV3` | `TestWALStoreV3_FlushMaterializationBoundToRecoveryLifetime` | Existing recovery/map proof lifetime; implementation correspondence | STUB | | `INV-WAL-V3-MAP-BYTES-001` | A dark v3 map candidate names immutable, owned, identity- and geometry-checked pages and root. Domain-separated body digests, reserved/unused bytes, exact page counts, file bounds and non-aliasing intervals all validate before entries escape. Persistence orders pages/fsync, root/fsync, directory fsync; a persistence-transaction error yields no candidate and latches subsequent I/O; preflight and Stat errors do not latch. Extents are reused only when no live root references them (both slot roots, in-flight candidates, an uncertain candidate until reopen); the free tail is truncated above the highest live page. | M1 (dark map preparation only) | `core/storage/chunk_lsn_map_v3.go` `Prepare`, `readChunkLSNMapV3`; `core/storage/chunk_map_extents_v3.go` (live set, allocation, release, truncation); `core/storage/chunk_map_publication_v3.go` `publishMapV3`; `core/storage/descriptor_v3.go` (slot report, uncertain candidate) | `TestChunkMapV3FileStaysBoundedUnderSteadyCheckpoints` (`core/storage/chunkmap_bounded_v3_test.go`); `TestChunkMapExtentsV3FallbackRootIsNeverReused`, `TestChunkMapExtentsV3NewerInFlightCandidateIsNotReused`, `TestChunkMapExtentsV3CrashBeforePublicationOfAReusedExtent`, `TestChunkMapExtentsV3TruncationKeepsAFallbackAtTheTail`, `TestChunkMapExtentsV3RejectedPublicationsStayBounded`, `TestChunkMapExtentsV3ReopenRegistersTheFallbackRoot`, `TestChunkMapExtentsV3TruncationFaultKeepsTheSlotRoots`, `TestChunkMapExtentsV3UncertainCandidateStaysPinned`, `TestChunkMapExtentsV3StatsAfterReopen`, `TestChunkMapExtentsV3ProofStalePreparesStayBounded`, `TestChunkMapExtentsV3DurableButRefusedPublicationStaysPinned` (`core/storage/chunk_map_extents_v3_test.go`); `TestChunkLSNMapV3_CanonicalVectors`, `TestChunkLSNMapV3_PersistReloadAndReuse`, `TestChunkLSNMapV3_CorruptionAndBounds`, `TestChunkLSNMapV3_FailureDoesNotPublishOrReuse`, `TestChunkLSNMapV3_OrderOwnedOpenAndClippedPage`, `TestChunkLSNMapV3_RejectsRehashedMalformedRecords`, `TestChunkLSNMapV3_EntryBoundBeforeRootIO`, `TestChunkLSNMapV3_WholePageHashIsNotBodyDigest`, `TestChunkLSNMapV3_PreflightErrorDoesNotLatch` | WALFormatR5 abstract map dependency; physical encoding/digest/order are code obligations | STUB | | `INV-WAL-V3-PUBLISH-001` | Every v3 descriptor change goes through one publisher. It writes the fallback slot with slotGen+1 under `descMu`. It takes `WALStore.mu` only to snapshot and releases it before slot I/O, and fsync is the leaf. It rebases onto the authoritative descriptor: W and the checkpoint are max-merged, and identity, geometry and nonce changes are refused, as are tail regression, a map root change without a higher generation and any BASE edge outside DESIGN 8.5 (installed -> 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 | From 3abdc01336f9906cedef156a6e9a83ec0514ded2 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 04:19:30 -0800 Subject: [PATCH 14/14] test(storage): settle held hydration workers before cleanup --- .../checkpoint_append_progress_v3_test.go | 31 +++++++++++++------ 1 file changed, 22 insertions(+), 9 deletions(-) diff --git a/seaweed-block/core/storage/checkpoint_append_progress_v3_test.go b/seaweed-block/core/storage/checkpoint_append_progress_v3_test.go index b12f704f6c..4ddf562718 100644 --- a/seaweed-block/core/storage/checkpoint_append_progress_v3_test.go +++ b/seaweed-block/core/storage/checkpoint_append_progress_v3_test.go @@ -591,7 +591,19 @@ func TestCheckpointV3_HeldHydrationWithLocalWriteAndFlush(t *testing.T) { } entered, release := holdNextGet(t, remote) done := make(chan error, 1) + joined := make(chan struct{}) + // Release the fetch before joining, including failures before release(). + // Register before launch so store/layer cleanup never precedes the join. + t.Cleanup(func() { + release() + select { + case <-joined: + case <-time.After(ctLocalBound): + t.Errorf("held hydration reader did not settle within %v after release", ctLocalBound) + } + }) go func() { + defer close(joined) got, err := s.Read(9) if err == nil && !bytes.Equal(got, blk(0xB9)) { err = errors.New("held read did not return newer local bytes") @@ -599,17 +611,18 @@ func TestCheckpointV3_HeldHydrationWithLocalWriteAndFlush(t *testing.T) { done <- err }() waitKey(t, entered, "cold fill before a competing local write") - if _, err := s.Write(9, blk(0xB9)); err != nil { - t.Fatal(err) - } - if flush { - if _, err := s.Sync(); err != nil { - t.Fatal(err) + within(t, "local write and optional flush while hydration is held", func() error { + if _, err := s.Write(9, blk(0xB9)); err != nil { + return err } - if err := s.flusher.flushOnce(); err != nil { - t.Fatal(err) + if flush { + if _, err := s.Sync(); err != nil { + return err + } + return s.flusher.flushOnce() } - } + return nil + }) dirty := s.dm.len() release() if err := waitErr(t, done, "fill and post-miss WAL recheck"); err != nil {