From 94f1e5d083126714effdfa60062f0001dc130cfd Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 30 Nov 2026 19:04:51 -0800 Subject: [PATCH 1/8] test: reproduce dropped speculative suffix with coverage format --- .../checkpoint_append_progress_v3_test.go | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) 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 4ddf562718..a6f7dc5323 100644 --- a/seaweed-block/core/storage/checkpoint_append_progress_v3_test.go +++ b/seaweed-block/core/storage/checkpoint_append_progress_v3_test.go @@ -2,6 +2,7 @@ package storage import ( "bytes" + "context" "encoding/binary" "errors" "path/filepath" @@ -459,7 +460,26 @@ func TestCheckpointV3_AppendRolloverFaultRefusesHeldCandidate(t *testing.T) { // 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) { + for _, coverage := range []bool{false, true} { + t.Run(map[bool]string{false: "format1", true: "coverage"}[coverage], func(t *testing.T) { + testSpeculativeMaximumAfterDroppedSuffix(t, coverage) + }) + } +} + +func testSpeculativeMaximumAfterDroppedSuffix(t *testing.T, coverage bool) { s, path := newMappedCheckpointStoreV3(t) + if coverage { + s.HoldExtentDrainUntilChunkLayer() + if _, err := s.Recover(); err != nil { + t.Fatal(err) + } + if err := s.InitializeChunkCoverage(context.Background(), 1, func(uint64, uint64) (ChunkCoverageSeed, error) { + return ChunkCoverageSeed{All: true}, nil + }, coverageNoPages); err != nil { + t.Fatal(err) + } + } remote := newFakeChunkRemote() layer := mustAttach(t, s, remote, ctConfig(1)) if _, err := s.Write(1, blk(0xA1)); err != nil { From 0783eee74b829eb5b651ec012c58a54991a42a8d Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 30 Nov 2026 19:07:09 -0800 Subject: [PATCH 2/8] test: pin coverage authority after a discarded first append --- .../storage/coverage_dropped_suffix_test.go | 56 +++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 seaweed-block/core/storage/coverage_dropped_suffix_test.go diff --git a/seaweed-block/core/storage/coverage_dropped_suffix_test.go b/seaweed-block/core/storage/coverage_dropped_suffix_test.go new file mode 100644 index 0000000000..72ff1c01cd --- /dev/null +++ b/seaweed-block/core/storage/coverage_dropped_suffix_test.go @@ -0,0 +1,56 @@ +package storage + +import ( + "context" + "testing" +) + +// A speculative append can introduce the first local bit of a chunk. If the +// unacknowledged record is dropped, recovery must neither refuse the store nor +// retain that bit as authority over an extent that never received the write. +func TestCoverageDroppedSuffixDoesNotCreateLocalAuthority(t *testing.T) { + s, path := newMappedCheckpointStoreV3(t) + s.HoldExtentDrainUntilChunkLayer() + if _, err := s.Recover(); err != nil { + t.Fatal(err) + } + if err := s.InitializeChunkCoverage(context.Background(), 1, func(uint64, uint64) (ChunkCoverageSeed, error) { + return ChunkCoverageSeed{}, nil + }, coverageNoPages); err != nil { + t.Fatal(err) + } + if _, err := s.Write(0, blk(0xA1)); err != nil { + t.Fatal(err) + } + prepared, err := s.prepareOwnedMapCheckpointV3(0) + if err != nil { + t.Fatal(err) + } + if _, err := s.v3.pub.publishMapV3(&s.mu, nil, prepared, nil); err != nil { + t.Fatal(err) + } + if s.v3.pub.current().W != 0 { + t.Fatal("setup acknowledged the speculative append") + } + crashRecoveryHardeningStore(t, s) + s.mu.Lock() + s.closed = true + s.mu.Unlock() + damageRecord(t, path, 1) + r, err := openWALStoreV3ForTest(path) + if err != nil { + t.Fatal(err) + } + r.DisableAutoFlushForRecoveryTest() + r.HoldExtentDrainUntilChunkLayer() + t.Cleanup(func() { _ = r.Close() }) + if _, err := r.Recover(); err != nil { + t.Fatalf("dropped unacknowledged suffix made coverage unopenable: %v", err) + } + if r.NextLSN() != 1 { + t.Fatalf("dropped first append left next LSN %d", r.NextLSN()) + } + if got, position, err := r.Coverage(0); err != nil || got != CoverageNone || position != 0 { + t.Fatalf("dropped WAL created local authority: coverage=%v position=%d err=%v", got, position, err) + } +} From 650b034b91685195f9789f56dc1726da1983c1c3 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 30 Nov 2026 19:14:50 -0800 Subject: [PATCH 3/8] fix: sync captured WAL prefix before coverage map pages --- .../checkpoint_append_progress_v3_test.go | 20 --- .../storage/coverage_dropped_suffix_test.go | 56 -------- .../storage/coverage_wal_before_page_test.go | 124 ++++++++++++++++++ .../storage/walstore_map_checkpoint_v3.go | 9 ++ seaweed-block/docs/design/invariants.md | 2 +- .../docs/design/model-code-trace-coverage.tsv | 1 + 6 files changed, 135 insertions(+), 77 deletions(-) delete mode 100644 seaweed-block/core/storage/coverage_dropped_suffix_test.go create mode 100644 seaweed-block/core/storage/coverage_wal_before_page_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 index a6f7dc5323..4ddf562718 100644 --- a/seaweed-block/core/storage/checkpoint_append_progress_v3_test.go +++ b/seaweed-block/core/storage/checkpoint_append_progress_v3_test.go @@ -2,7 +2,6 @@ package storage import ( "bytes" - "context" "encoding/binary" "errors" "path/filepath" @@ -460,26 +459,7 @@ func TestCheckpointV3_AppendRolloverFaultRefusesHeldCandidate(t *testing.T) { // 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) { - for _, coverage := range []bool{false, true} { - t.Run(map[bool]string{false: "format1", true: "coverage"}[coverage], func(t *testing.T) { - testSpeculativeMaximumAfterDroppedSuffix(t, coverage) - }) - } -} - -func testSpeculativeMaximumAfterDroppedSuffix(t *testing.T, coverage bool) { s, path := newMappedCheckpointStoreV3(t) - if coverage { - s.HoldExtentDrainUntilChunkLayer() - if _, err := s.Recover(); err != nil { - t.Fatal(err) - } - if err := s.InitializeChunkCoverage(context.Background(), 1, func(uint64, uint64) (ChunkCoverageSeed, error) { - return ChunkCoverageSeed{All: true}, nil - }, coverageNoPages); err != nil { - t.Fatal(err) - } - } remote := newFakeChunkRemote() layer := mustAttach(t, s, remote, ctConfig(1)) if _, err := s.Write(1, blk(0xA1)); err != nil { diff --git a/seaweed-block/core/storage/coverage_dropped_suffix_test.go b/seaweed-block/core/storage/coverage_dropped_suffix_test.go deleted file mode 100644 index 72ff1c01cd..0000000000 --- a/seaweed-block/core/storage/coverage_dropped_suffix_test.go +++ /dev/null @@ -1,56 +0,0 @@ -package storage - -import ( - "context" - "testing" -) - -// A speculative append can introduce the first local bit of a chunk. If the -// unacknowledged record is dropped, recovery must neither refuse the store nor -// retain that bit as authority over an extent that never received the write. -func TestCoverageDroppedSuffixDoesNotCreateLocalAuthority(t *testing.T) { - s, path := newMappedCheckpointStoreV3(t) - s.HoldExtentDrainUntilChunkLayer() - if _, err := s.Recover(); err != nil { - t.Fatal(err) - } - if err := s.InitializeChunkCoverage(context.Background(), 1, func(uint64, uint64) (ChunkCoverageSeed, error) { - return ChunkCoverageSeed{}, nil - }, coverageNoPages); err != nil { - t.Fatal(err) - } - if _, err := s.Write(0, blk(0xA1)); err != nil { - t.Fatal(err) - } - prepared, err := s.prepareOwnedMapCheckpointV3(0) - if err != nil { - t.Fatal(err) - } - if _, err := s.v3.pub.publishMapV3(&s.mu, nil, prepared, nil); err != nil { - t.Fatal(err) - } - if s.v3.pub.current().W != 0 { - t.Fatal("setup acknowledged the speculative append") - } - crashRecoveryHardeningStore(t, s) - s.mu.Lock() - s.closed = true - s.mu.Unlock() - damageRecord(t, path, 1) - r, err := openWALStoreV3ForTest(path) - if err != nil { - t.Fatal(err) - } - r.DisableAutoFlushForRecoveryTest() - r.HoldExtentDrainUntilChunkLayer() - t.Cleanup(func() { _ = r.Close() }) - if _, err := r.Recover(); err != nil { - t.Fatalf("dropped unacknowledged suffix made coverage unopenable: %v", err) - } - if r.NextLSN() != 1 { - t.Fatalf("dropped first append left next LSN %d", r.NextLSN()) - } - if got, position, err := r.Coverage(0); err != nil || got != CoverageNone || position != 0 { - t.Fatalf("dropped WAL created local authority: coverage=%v position=%d err=%v", got, position, err) - } -} diff --git a/seaweed-block/core/storage/coverage_wal_before_page_test.go b/seaweed-block/core/storage/coverage_wal_before_page_test.go new file mode 100644 index 0000000000..358833ec4b --- /dev/null +++ b/seaweed-block/core/storage/coverage_wal_before_page_test.go @@ -0,0 +1,124 @@ +package storage + +import ( + "bytes" + "context" + "errors" + "testing" +) + +func TestCoveragePublicationSyncsItsSpeculativeWALBeforeMap(t *testing.T) { + for _, initialAck := range []bool{false, true} { + t.Run(map[bool]string{false: "first_local_bit", true: "speculative_max"}[initialAck], func(t *testing.T) { + s, path := newMappedCheckpointStoreV3(t) + s.HoldExtentDrainUntilChunkLayer() + if _, err := s.Recover(); err != nil { + t.Fatal(err) + } + if err := s.InitializeChunkCoverage(context.Background(), 1, func(uint64, uint64) (ChunkCoverageSeed, error) { + return ChunkCoverageSeed{}, nil + }, coverageNoPages); err != nil { + t.Fatal(err) + } + if initialAck { + if _, err := s.Write(0, blk(0xA1)); err != nil { + t.Fatal(err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + } + maxLSN := uint64(1) + if initialAck { + maxLSN = 3 + } + for i := s.NextLSN(); i <= maxLSN; i++ { + if _, err := s.Write(0, blk(byte(0xA0+i))); err != nil { + t.Fatal(err) + } + } + walSynced := false + realWALSync := s.syncWALFile + s.syncWALFile = func() error { + err := realWALSync() + if err == nil { + walSynced = true + } + return err + } + s.v3.ownedMap.testBeforeLiveSnapshot = func() { + if !walSynced { + t.Fatal("coverage map preparation preceded its WAL-level sync") + } + } + prepared, err := s.prepareOwnedMapCheckpointV3(0) + s.v3.ownedMap.testBeforeLiveSnapshot = nil + s.syncWALFile = realWALSync + if err != nil { + t.Fatal(err) + } + if !walSynced || prepared.candidate.entries[0].LSN != maxLSN { + t.Fatal("snapshot did not preserve and sync its speculative maximum") + } + if _, err := s.v3.pub.publishMapV3(&s.mu, nil, prepared, nil); err != nil { + t.Fatal(err) + } + // A crash may lose only the suffix appended AFTER the covering sync. + // Tearing a covered record instead models disk damage, not power loss. + if _, err := s.Write(0, blk(0xEE)); err != nil { + t.Fatal(err) + } + crashRecoveryHardeningStore(t, s) + s.mu.Lock() + s.closed = true + s.mu.Unlock() + damageRecord(t, path, maxLSN+1) + r, err := openWALStoreV3ForTest(path) + if err != nil { + t.Fatal(err) + } + r.DisableAutoFlushForRecoveryTest() + r.HoldExtentDrainUntilChunkLayer() + t.Cleanup(func() { _ = r.Close() }) + if _, err := r.Recover(); err != nil { + t.Fatalf("lost post-publication suffix refused coverage recovery: %v", err) + } + if r.NextLSN() != maxLSN+1 { + t.Fatalf("next LSN %d, want %d", r.NextLSN(), maxLSN+1) + } + got, position, err := r.Coverage(0) + if err != nil || got != CoverageSome || position != maxLSN { + t.Fatalf("covered WAL lost bitmap: %v/%d %v", got, position, err) + } + if !bytes.Equal(readV3(t, r, 0), blk(byte(0xA0+maxLSN))) { + t.Fatal("covered WAL did not recover exact latest bytes") + } + }) + } +} + +func TestCoveragePublicationRefusesWALSyncFailureBeforeMap(t *testing.T) { + s, _ := newMappedCheckpointStoreV3(t) + s.HoldExtentDrainUntilChunkLayer() + if _, err := s.Recover(); err != nil { + t.Fatal(err) + } + if err := s.InitializeChunkCoverage(context.Background(), 1, func(uint64, uint64) (ChunkCoverageSeed, error) { + return ChunkCoverageSeed{}, nil + }, coverageNoPages); err != nil { + t.Fatal(err) + } + if _, err := s.Write(0, blk(0xA1)); err != nil { + t.Fatal(err) + } + before := s.v3.pub.current() + boom := errors.New("WAL-before-map sync failure") + s.syncWALFile = func() error { return boom } + s.v3.ownedMap.testBeforeLiveSnapshot = func() { t.Fatal("failed WAL sync reached map preparation") } + if _, err := s.prepareOwnedMapCheckpointV3(0); !errors.Is(err, boom) { + t.Fatalf("WAL sync failure not returned: %v", err) + } + if s.stickyIOFault() == nil || s.v3.pub.current() != before { + t.Fatal("failed WAL sync did not latch or changed the descriptor") + } +} diff --git a/seaweed-block/core/storage/walstore_map_checkpoint_v3.go b/seaweed-block/core/storage/walstore_map_checkpoint_v3.go index c738abf099..726e12e012 100644 --- a/seaweed-block/core/storage/walstore_map_checkpoint_v3.go +++ b/seaweed-block/core/storage/walstore_map_checkpoint_v3.go @@ -64,12 +64,21 @@ func (s *WALStore) prepareOwnedMapCheckpointV3(cp uint64) (*preparedMapPublicati // 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...) + walHead := s.walHead v.pub.descMu.Unlock() s.mu.RUnlock() // Capture bitmap entries before the data sync. A fill or append may have // arrived after the flusher's earlier sync; publishing that bit first could // make an unwritten extent authoritative after a crash. if prior.formatID() == mapFormatIDCoverage { + // Local bits can name speculative appends above W. Make the captured + // WAL prefix durable before any map page can name those bits. This is + // the WAL leaf, not Sync: preparation may run on the flusher itself. + if walHead > v.wack.Load() { + if err := s.syncFile(nil, s.syncWALFile); err != nil { + return nil, err + } + } if err := s.syncFile(nil, s.fd.Sync); err != nil { return nil, err } diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index a8aaaafba5..5fb433ba49 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -625,7 +625,7 @@ The "Machine / transition" column refers to Part A. Notes under a table record w | `INV-CHUNK-RECORD-SHADOW-001` | While serving, the chunk record follows the engine's events through the kernel; an event bound to a captured version is skipped, never refused, after a write; at each barrier every chunk the engine captures is a record candidate. The record decides nothing and writes no page. | M3 Serving (chunk record shadow) | `core/storage/chunk_record_shadow.go` `newChunkRecordShadow`, `chunkRecordShadow.check`; `core/storage/chunk_layer.go` `noteMutation`, `fillOnce`, `EvictChunk`, `recoveredLocked`, `BeforeCheckpointAdvance`, `shadowCommit`, `shadowCommitCaptured` (also from `resolvePending`, `SettleDetach`); `core/storage/chunk_cut_payload.go` `markEqualNow`; `core/storage/chunk_record_runtime.go` `ApplyIf` | `TestShadowWriteCoverageFollowsTheStoreBitmap`, `TestShadowFillRacedByAWriteEndsUnknown`, `TestShadowCutOfAPartialChunkKeepsItPartial`, `TestShadowAttachKeepsACheckpointedWriteACandidate`, `TestShadowWriteRacingHashAndCommitIsSkippedNotRefused`, `TestShadowEvictEdges`, `TestShadowRecordWritesNoPage`, `TestShadowCheckerIsExactAndCatchesAMissingWrite`, `TestShadowRecoverChangesOnlyTheRecoveredChunks`, `TestShadowBaseInstallCompletingChangesEveryChunk`, `TestShadowDelayedSettlementCommitsTheCapturedChunks`, `TestShadowProductionCheckDoesNotScanTheRecord`, `TestShadowScratchExemptionIsBoundToItsCapturedVersion` (`core/storage/chunk_record_shadow_test.go`); every test of the package runs with the shadow strict, misses and extra record candidates both (`TestMain`, `core/storage/chunk_record_shadow_main_test.go`) | chunk-kernel/2 (the per-chunk state models are not in this repository) | ACTIVE | | `INV-CHUNK-FOREIGN-ROOT-FENCE-001` | A HEAD that moved past the holder's base without superseding it and is not its own proposal must keep the chunk root; one that changed it fences the layer (`errChunkForeignRoot`), so no chunk is held clean against a root that no longer names it. | M5 Commit (head conflict, settlement) | `core/storage/chunk_layer.go` `adoptHeadLocked` (from `captureLocked`, `SettleDetach`, `resolvePending`) | `TestShadowForeignRootWithoutSupersedeFences` (`core/storage/chunk_record_shadow_test.go`) | HeadWriters (only metadata writers move HEAD without superseding; not in this repository) | ACTIVE | | `INV-CHUNK-RECORD-PAYLOAD-001` | Persisting and loading a chunk record preserves every entry's state and hash, including entries on either side of a segment boundary. | M1 chunk record codec (caller not wired) | `core/storage/chunk_record.go` `encodeChunkRecordPage`, `decodeChunkRecordPage` | `TestRecordEntryPayloadRoundTripsAcrossSegments` (`core/storage/chunk_record_test.go`; state-zero and one-entry hash-drop controls) | Encoding fidelity; no state transition change | STUB | -| `INV-CHUNK-COVERAGE-RETAINED-001` | A coverage-map baseline is installed by recovery only when every chunk position is at or below the retained WAL frontier; a discarded suffix cannot regain local bits through later LSN reuse. | M1 recovery (caller not wired) | `core/storage/walstore_v3.go` `WALStore.recoverV3` | `TestChunkCoverageBaselineCannotOutliveItsRetainedWAL` | SlotFence2 position-check premise; storage component guard | STUB | +| `INV-CHUNK-COVERAGE-RETAINED-001` | A coverage-map baseline is installed by recovery only when every chunk position is at or below the retained WAL frontier; a discarded suffix cannot regain local bits through later LSN reuse. | M1 recovery (caller not wired) | `core/storage/walstore_v3.go` `WALStore.recoverV3`; `core/storage/walstore_map_checkpoint_v3.go` `prepareOwnedMapCheckpointV3` | `TestChunkCoverageBaselineCannotOutliveItsRetainedWAL`, `TestCoveragePublicationSyncsItsSpeculativeWALBeforeMap`, `TestCoveragePublicationRefusesWALSyncFailureBeforeMap` | SlotFence2 position-check premise; WAL before bitmap pages | STUB | | `INV-CHUNK-LOCAL-COVERAGE-001` | Coverage returns local none/some/all and the chunk position from one observation; it is unavailable until successful recovery and bitmap initialization. | M1 chunk bitmap (caller not wired) | `core/storage/chunk_coverage.go` `WALStore.Coverage`, `WALStore.InitializeChunkCoverage` | `TestChunkCoverageBaselineCannotOutliveItsRetainedWAL`, `TestChunkCoverageAdmissionPrecedesSeed`, `TestChunkCoverageInitializesEmptyWithoutFabricatingLocalBlocks`, `TestChunkCoverageAcknowledgedWriteSurvivesReplay`, `TestChunkCoverageCheckpointKeepsAllAcrossAPageBoundary`, `TestChunkCoverageRequiresSuccessfulRecovery` (`core/storage/chunk_coverage_test.go`) | MoveWide2 durable per-block map premise; SlotFence publication | STUB | | `INV-CHUNK-LOCAL-MUTATION-001` | A successful local clear or mark has synced its map publication; marking all-local syncs extent bytes first. A failed publication grants no permission to drop bytes or persist an all-local record. | M1 chunk bitmap mutation (caller not wired) | `core/storage/chunk_local_mutation.go` `ClearChunkLocal`, `MarkChunksLocal`, `publishChunksLocal` | `TestCrashAfterAbsentPageBeforeClearKeepsBytesAndLaterWrite`, `TestMarkChunksLocalPublishesOncePerRestoreBatch`, `TestClearChunkLocalIsDurableBeforeReturn`, `TestMarkChunkLocalSyncsBytesBeforePublishingCoverage`, `TestMarkChunkLocalRefusesFailedExtentSyncBeforeMapIO`, `TestChunkLocalMutationRefusesUnavailableBoundsAndMapFailure` | MoveWide2.Fill/Evict/Drop; caller admission and page-before-drop remain caller obligations | STUB | | `INV-CHUNK-LOCAL-EPOCH-001` | After a format marker, initialization never reads legacy presence: the same epoch rebuilds pages from the bitmap; another epoch is refused without changing storage. | M1 bitmap initialization (caller not wired) | `core/storage/chunk_coverage.go` `WALStore.InitializeChunkCoverage` | `TestChunkCoverageLegacyFenceCannotRelabelAnInitializedEpoch`, `TestChunkCoverageMarkedEpochNeverReseedsPresence`, `TestChunkCoverageMarkerWithoutBitmapCannotReadPresence` (`core/storage/chunk_coverage_test.go`) | SlotFence marker authority; UpgradeWide3 | STUB | diff --git a/seaweed-block/docs/design/model-code-trace-coverage.tsv b/seaweed-block/docs/design/model-code-trace-coverage.tsv index e8aa1a910c..19745df806 100644 --- a/seaweed-block/docs/design/model-code-trace-coverage.tsv +++ b/seaweed-block/docs/design/model-code-trace-coverage.tsv @@ -11,3 +11,4 @@ SlotFence2 intact unmarked half-fence fallback only, typed event and process cou MoveWide2 Fill: durable bytes before local bitmap core/storage/chunk_local_mutation.go:WALStore.MarkChunksLocal core/storage/chunk_local_mutation_test.go:TestMarkChunksLocalPublishesOncePerRestoreBatch; core/storage/chunk_local_mutation_test.go:TestMarkChunkLocalSyncsBytesBeforePublishingCoverage; core/storage/chunk_local_mutation_test.go:TestMarkChunkLocalRefusesFailedExtentSyncBeforeMapIO STUB MoveWide2 Evict/Drop: durable clear before caller drops bytes core/storage/chunk_local_mutation.go:WALStore.ClearChunkLocal core/storage/chunk_local_mutation_test.go:TestCrashAfterAbsentPageBeforeClearKeepsBytesAndLaterWrite; core/storage/chunk_local_mutation_test.go:TestClearChunkLocalIsDurableBeforeReturn; core/storage/chunk_local_mutation_test.go:TestChunkLocalMutationRefusesUnavailableBoundsAndMapFailure STUB +SlotFence2 WAL prefix durable before bitmap pages name speculative positions core/storage/walstore_map_checkpoint_v3.go:prepareOwnedMapCheckpointV3 core/storage/coverage_wal_before_page_test.go:TestCoveragePublicationSyncsItsSpeculativeWALBeforeMap; core/storage/coverage_wal_before_page_test.go:TestCoveragePublicationRefusesWALSyncFailureBeforeMap STUB From 0739925e681ba75a77a92d01ed2948fc3a028ecf Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 30 Nov 2026 19:18:02 -0800 Subject: [PATCH 4/8] docs: name current HEAD keys and tests; drop a removed perf command The HEAD entry's conditional keys are swb.layout.gen and swb.layout.volume, written by LayoutStore.UpdateHead; the integration tests named in the workspace design were replaced by the layout ones. The manifest perf test no longer exists, so its command is removed. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/docs/chunk-manifests.md | 11 ----------- seaweed-block/docs/design/agent-workspace-design.md | 6 +++--- 2 files changed, 3 insertions(+), 14 deletions(-) diff --git a/seaweed-block/docs/chunk-manifests.md b/seaweed-block/docs/chunk-manifests.md index 311768c7bc..87856be1ab 100644 --- a/seaweed-block/docs/chunk-manifests.md +++ b/seaweed-block/docs/chunk-manifests.md @@ -45,14 +45,3 @@ counters after joining workers. The worker queue mutex guards admission and first error only, with no I/O under it. Failure cancels new admission and joins all owned calls before clean-abort intent cleanup. A remote ignoring cancellation can delay that join; it is never reported settled early. - -## Reproducible proxy measurements - -`go test -tags=manifest_perf ./core/frontend/chunkstore -run '^TestManifestPerf_' -count=1 -timeout=600s -v` - -This materializes and fsyncs immutable files, including all 10 GiB of the large -volume. Metadata uses the deterministic filer model. It compares 64 dirty -4 MiB chunks at concurrency 1/8 in alternating order (three samples each), and -flat versus segmented snapshot/fork operations (three samples each). Reported -root bytes exclude segment bytes, which are reported separately. It excludes -network latency, the block frontend, guest fsync and power-loss behavior. diff --git a/seaweed-block/docs/design/agent-workspace-design.md b/seaweed-block/docs/design/agent-workspace-design.md index 02c55445e0..3601413535 100644 --- a/seaweed-block/docs/design/agent-workspace-design.md +++ b/seaweed-block/docs/design/agent-workspace-design.md @@ -86,7 +86,7 @@ Per volume, under the chunk base directory in the filer (`core/frontend/chunksto | Entry | Content | Written | |---|---|---| -| `HEAD` | the published state as JSON; `{gen, epoch, holder}` mirrored in extended attributes (`swb.gen`, `swb.epoch`, `swb.holder`) | conditional update on `{gen, epoch}`; the first HEAD is an exclusive create | +| `HEAD` | the published state as JSON; the entry's extended attributes carry its generation and volume identity (`swb.layout.gen`, `swb.layout.volume`) | conditional update on `{swb.layout.gen, swb.layout.volume}`; the first HEAD is an exclusive create | | `keys/` | one entry per chunk key, naming the needle (fid) that holds the bytes | exclusive create; never rebound | | `intents/` | the keys a holder is about to publish (GC roots); id `-<16 hex>` | created before the first upload, removed after the outcome is known | | `VOLUME` | identity, geometry (`NumBlocks`, `BlockSize`, `ChunkBlocks`), origin (create or fork) and parent | write-once | @@ -152,7 +152,7 @@ Listings carry each snapshot's root and dependents. Usage reports snapshot/depen 10. **CAS** HEAD on `{gen, epoch}` with `RemoteLSN = H`. On success, drop the intents and settle unchanged owned-map versions, keeping post-cut dirt. 11. **Unknown outcome:** re-read HEAD; never retry blindly. If unresolved, keep the proposal pending and keep the intents. -`ChunkRemote.CASHead` (`core/frontend/chunkstore/chunk_remote.go`) refuses a lower epoch, any move of a `deleting`, `purging` or `deleted` HEAD, a `{gen, epoch}` mismatch and a lower `RemoteLSN`, then issues the filer's conditional `UpdateEntry` with `expected_extended = {swb.gen, swb.epoch}`. Only a definite refusal is a precondition failure; any other error is an unknown outcome. +`LayoutRemote.CASHead` (`core/frontend/chunkstore/layout_remote.go`) commits through the layout kernel; the HEAD write itself is `LayoutStore.UpdateHead` (`core/frontend/chunkstore/layout_store.go`), the filer's conditional `UpdateEntry` with `expected_extended = {swb.layout.gen, swb.layout.volume}`. On a refusal it reads HEAD again: a changed claim (epoch, holder or claim id) or a detached HEAD fences the holder, and a `deleting` or `deleted` HEAD ends the commit. Only a definite refusal is a precondition failure; any other error is an unknown outcome. **Reads after a move.** A block absent locally is fetched from the chunk named in HEAD, by a bounded per-chunk shared worker. Frontend callers share their arrival deadline across attach and all missing chunks; contextless internal readers retain `ReadMissTimeout` (default 30 s). Fetched bytes are installed only if they do not overwrite a newer local extent version; the dirty map is consulted again after the fetch, so a newer WAL-only write still wins on reads, and HEAD's value may sit beneath it as the backing value, which is correct if a crash loses that unsynced write (`OnReadMiss`; walstore `readFromExtent`). @@ -437,7 +437,7 @@ Not done yet: ## 10. Tests - Contract tests C1–C11 for the chunk layer (`core/storage/chunk_layer_contract_test.go`, `chunk_layer_c11_test.go`), with a fake remote that can hold a CAS or create and complete it after the caller gave up. -- Real SeaweedFS (build tag `chunkstore_integration`, real master, volume and filer processes): `TestIntegration_ChunkRemoteContract` (`core/frontend/chunkstore/chunk_remote_integration_test.go`), `TestIntegration_DeleteVolumeThenGC` (`core/frontend/chunkstore/volume_delete_integration_test.go`), `TestIntegration_RetainAndUsage` (`core/frontend/chunkstore/retention_integration_test.go`), `TestIntegration_OpsChunkGC_RealMasterAndStore` (`cmd/sw-block/chunk_gc_integration_test.go`), and `TestIntegration_ConcurrentHEADCASRealFiler` (`core/frontend/chunkstore/concurrent_cas_integration_test.go`), which holds concurrent HEAD updates until every client has read, then lets the real filer's `expected_extended` check decide. +- Real SeaweedFS (build tag `chunkstore_integration`, real master, volume and filer processes): `TestIntegration_HeadConditionalWritesRefusedByAStockFiler` (`core/frontend/chunkstore/layout_head_cas_integration_test.go`), `TestIntegration_ObjectMarkAndConditionalDelete` and `TestIntegration_CatalogRestoreAndDelete` (`core/frontend/chunkstore/layout_objects_integration_test.go`), `TestCutoverWriteSnapshotKillRestartRestore` (`cmd/blockvolume/cutover_end_to_end_integration_test.go`), and `TestIntegration_ConcurrentConditionalWritesOneWinner` (`core/frontend/chunkstore/layout_concurrent_cas_integration_test.go`), which releases 16 writers with the same condition together and checks that the real filer's `expected_extended` check lets exactly one through. - Binary tests with real `blockvolume` and `blockmaster`, for example `TestBinaryWorkspaceLeaseOptInOwnsCLEANShutdown` (`cmd/blockvolume/workspace_lease_binary_test.go`). - Two-host lab lifecycle with Firecracker microVMs (§13). - Not covered: several filers sharing a store, a filer that predates `expected_extended`, and power loss on the local host (see [core §2.2](block-design.md#22-what-is-not-covered)). From a872fd6513193f80b382ea202815a516c1568b86 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 30 Nov 2026 19:20:56 -0800 Subject: [PATCH 5/8] test: cover WAL ordering at every bitmap publication entrypoint --- .../storage/coverage_wal_before_page_test.go | 120 ++++++++++++++++++ 1 file changed, 120 insertions(+) diff --git a/seaweed-block/core/storage/coverage_wal_before_page_test.go b/seaweed-block/core/storage/coverage_wal_before_page_test.go index 358833ec4b..e464acc1c9 100644 --- a/seaweed-block/core/storage/coverage_wal_before_page_test.go +++ b/seaweed-block/core/storage/coverage_wal_before_page_test.go @@ -122,3 +122,123 @@ func TestCoveragePublicationRefusesWALSyncFailureBeforeMap(t *testing.T) { t.Fatal("failed WAL sync did not latch or changed the descriptor") } } + +func TestCoverageMutationEntrypointsSyncTheWholeSnapshot(t *testing.T) { + for _, operation := range []string{"clear", "mark", "batch"} { + t.Run(operation, func(t *testing.T) { + s, path := newMappedCheckpointStoreV3(t) + s.HoldExtentDrainUntilChunkLayer() + if _, err := s.Recover(); err != nil { + t.Fatal(err) + } + if err := s.InitializeChunkCoverage(context.Background(), 1, func(uint64, uint64) (ChunkCoverageSeed, error) { + return ChunkCoverageSeed{All: operation == "clear"}, nil + }, coverageNoPages); err != nil { + t.Fatal(err) + } + // The target chunk is clean/zero and its extents already contain + // zero bytes. Another chunk has a WAL-only speculative append; + // even a mutation of the clean target publishes that entry too. + if _, err := s.Write(0, blk(0xD1)); err != nil { + t.Fatal(err) + } + synced := false + realSync := s.syncWALFile + s.syncWALFile = func() error { + if !s.mu.TryLock() { + t.Fatal("WAL leaf called under store lock") + } + s.mu.Unlock() + err := realSync() + synced = err == nil + return err + } + s.v3.ownedMap.testBeforeLiveSnapshot = func() { + if !synced { + t.Fatal("mutation reached map before WAL sync") + } + } + var err error + switch operation { + case "clear": + err = s.ClearChunkLocal(1) + case "mark": + err = s.MarkChunkLocal(1) + case "batch": + err = s.MarkChunksLocal([]uint64{1, 2}) + } + s.v3.ownedMap.testBeforeLiveSnapshot = nil + s.syncWALFile = realSync + if err != nil { + t.Fatal(err) + } + if !synced { + t.Fatal("mutation did not sync the speculative snapshot") + } + crashRecoveryHardeningStore(t, s) + s.mu.Lock() + s.closed = true + s.mu.Unlock() + r, err := openWALStoreV3ForTest(path) + if err != nil { + t.Fatal(err) + } + r.DisableAutoFlushForRecoveryTest() + r.HoldExtentDrainUntilChunkLayer() + t.Cleanup(func() { _ = r.Close() }) + if _, err := r.Recover(); err != nil { + t.Fatal(err) + } + if !bytes.Equal(readV3(t, r, 0), blk(0xD1)) { + t.Fatal("mutation lost another chunk's covered WAL") + } + want := CoverageAll + if operation == "clear" { + want = CoverageNone + } + if got, _, err := r.Coverage(1); err != nil || got != want { + t.Fatalf("target coverage %v, want %v: %v", got, want, err) + } + }) + } +} + +func TestCoverageInitializationRequiresAnAlreadyDurableSnapshot(t *testing.T) { + s, _ := newMappedCheckpointStoreV3(t) + s.HoldExtentDrainUntilChunkLayer() + if _, err := s.Recover(); err != nil { + t.Fatal(err) + } + if _, err := s.Write(0, blk(0xD1)); err != nil { + t.Fatal(err) + } + synced := false + realSync := s.syncWALFile + s.syncWALFile = func() error { + err := realSync() + synced = err == nil + return err + } + mapStarted := false + s.v3.ownedMap.testBeforeLiveSnapshot = func() { + mapStarted = true + if !synced { + t.Fatal("initialization prepared map without durable WAL") + } + } + seed := func(uint64, uint64) (ChunkCoverageSeed, error) { return ChunkCoverageSeed{}, nil } + if err := s.InitializeChunkCoverage(context.Background(), 1, seed, coverageNoPages); err == nil || mapStarted { + t.Fatalf("unsynced initialization: err=%v mapStarted=%v", err, mapStarted) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + if err := s.InitializeChunkCoverage(context.Background(), 1, seed, coverageNoPages); err != nil { + t.Fatal(err) + } + s.v3.ownedMap.testBeforeLiveSnapshot = nil + s.syncWALFile = realSync + if !mapStarted || !synced { + t.Fatal("initialization did not use a synced snapshot") + } +} From 81b88710ac0e7e36fa585974970434584b6912d4 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 30 Nov 2026 19:21:49 -0800 Subject: [PATCH 6/8] docs: the HEAD CAS step names the current conditional keys Co-Authored-By: Claude Opus 5.5 --- seaweed-block/docs/design/agent-workspace-design.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/seaweed-block/docs/design/agent-workspace-design.md b/seaweed-block/docs/design/agent-workspace-design.md index 3601413535..82687d170d 100644 --- a/seaweed-block/docs/design/agent-workspace-design.md +++ b/seaweed-block/docs/design/agent-workspace-design.md @@ -149,7 +149,7 @@ Listings carry each snapshot's root and dependents. Usage reports snapshot/depen 7. **Intent first:** write an intent naming every key, then upload in parallel (`UploadConcurrency`, `--chunk-upload-concurrency`, default 8, 1 to 64). 8. **Manifest:** build segments; new segments are also covered by an intent before upload (`PrepareManifest`). 9. **Re-admit** right before the CAS; fence if a superseding holder owns HEAD (`supersededBy`). -10. **CAS** HEAD on `{gen, epoch}` with `RemoteLSN = H`. On success, drop the intents and settle unchanged owned-map versions, keeping post-cut dirt. +10. **CAS** HEAD on `{swb.layout.gen, swb.layout.volume}` with `RemoteLSN = H`. On success, drop the intents and settle unchanged owned-map versions, keeping post-cut dirt. 11. **Unknown outcome:** re-read HEAD; never retry blindly. If unresolved, keep the proposal pending and keep the intents. `LayoutRemote.CASHead` (`core/frontend/chunkstore/layout_remote.go`) commits through the layout kernel; the HEAD write itself is `LayoutStore.UpdateHead` (`core/frontend/chunkstore/layout_store.go`), the filer's conditional `UpdateEntry` with `expected_extended = {swb.layout.gen, swb.layout.volume}`. On a refusal it reads HEAD again: a changed claim (epoch, holder or claim id) or a detached HEAD fences the holder, and a `deleting` or `deleted` HEAD ends the commit. Only a definite refusal is a precondition failure; any other error is an unknown outcome. From 01cd2806c5df18ce13452304091b8ed3d424418f Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 30 Nov 2026 19:23:44 -0800 Subject: [PATCH 7/8] test: cover crashes before the WAL-before-page sync --- .../storage/coverage_wal_before_page_test.go | 62 +++++++++++++++++++ 1 file changed, 62 insertions(+) diff --git a/seaweed-block/core/storage/coverage_wal_before_page_test.go b/seaweed-block/core/storage/coverage_wal_before_page_test.go index e464acc1c9..0eac965bbf 100644 --- a/seaweed-block/core/storage/coverage_wal_before_page_test.go +++ b/seaweed-block/core/storage/coverage_wal_before_page_test.go @@ -242,3 +242,65 @@ func TestCoverageInitializationRequiresAnAlreadyDurableSnapshot(t *testing.T) { t.Fatal("initialization did not use a synced snapshot") } } + +func TestCoverageCrashBetweenAppendAndSyncKeepsOnlyDurablePrefix(t *testing.T) { + for _, acknowledged := range []bool{false, true} { + t.Run(map[bool]string{false: "empty_prefix", true: "acknowledged_prefix"}[acknowledged], func(t *testing.T) { + s, path := newMappedCheckpointStoreV3(t) + s.HoldExtentDrainUntilChunkLayer() + if _, err := s.Recover(); err != nil { + t.Fatal(err) + } + if err := s.InitializeChunkCoverage(context.Background(), 1, func(uint64, uint64) (ChunkCoverageSeed, error) { + return ChunkCoverageSeed{}, nil + }, coverageNoPages); err != nil { + t.Fatal(err) + } + frontier := uint64(0) + if acknowledged { + if _, err := s.Write(0, blk(0xA1)); err != nil { + t.Fatal(err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + frontier = 1 + } + before := s.v3.pub.current() + if _, err := s.Write(1, blk(0xEE)); err != nil { + t.Fatal(err) + } + if s.v3.pub.current() != before { + t.Fatal("append published a bitmap before sync") + } + crashRecoveryHardeningStore(t, s) + s.mu.Lock() + s.closed = true + s.mu.Unlock() + damageRecord(t, path, frontier+1) + r, err := openWALStoreV3ForTest(path) + if err != nil { + t.Fatal(err) + } + r.DisableAutoFlushForRecoveryTest() + r.HoldExtentDrainUntilChunkLayer() + t.Cleanup(func() { _ = r.Close() }) + if _, err := r.Recover(); err != nil { + t.Fatal(err) + } + want := CoverageNone + if acknowledged { + want = CoverageSome + } + if got, position, err := r.Coverage(0); err != nil || got != want || position != frontier { + t.Fatalf("pre-sync crash retained wrong authority: %v/%d, want %v/%d: %v", got, position, want, frontier, err) + } + if r.NextLSN() != frontier+1 { + t.Fatalf("dropped append left next LSN %d", r.NextLSN()) + } + if acknowledged && !bytes.Equal(readV3(t, r, 0), blk(0xA1)) { + t.Fatal("lost acknowledged prefix bytes") + } + }) + } +} From 646b6c5a2b8204d622a65264a7c7d346efee620c Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 30 Nov 2026 19:25:50 -0800 Subject: [PATCH 8/8] fix: classify unsynced coverage initialization as stale --- seaweed-block/core/storage/chunk_coverage.go | 2 +- seaweed-block/core/storage/coverage_wal_before_page_test.go | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/seaweed-block/core/storage/chunk_coverage.go b/seaweed-block/core/storage/chunk_coverage.go index 6c85c5df17..c7c9ebe932 100644 --- a/seaweed-block/core/storage/chunk_coverage.go +++ b/seaweed-block/core/storage/chunk_coverage.go @@ -158,7 +158,7 @@ func (s *WALStore) InitializeChunkCoverage(ctx context.Context, epoch uint64, se position := v.wack.Load() if s.nextLSN-1 != position { s.mu.RUnlock() - return errors.New("storage: initialize coverage after recovery and Sync") + return fmt.Errorf("%w: initialize coverage after recovery and Sync", ErrMapCoverageStale) } if current.MapFormatID == mapFormatIDCoverage && current.LocalWorkEpoch == epoch { view := chunkCoverageSnapshot{entries: append([]chunkLSNEntryV3(nil), v.mapEntries...), position: position} diff --git a/seaweed-block/core/storage/coverage_wal_before_page_test.go b/seaweed-block/core/storage/coverage_wal_before_page_test.go index 0eac965bbf..e5ff77c89f 100644 --- a/seaweed-block/core/storage/coverage_wal_before_page_test.go +++ b/seaweed-block/core/storage/coverage_wal_before_page_test.go @@ -227,7 +227,7 @@ func TestCoverageInitializationRequiresAnAlreadyDurableSnapshot(t *testing.T) { } } seed := func(uint64, uint64) (ChunkCoverageSeed, error) { return ChunkCoverageSeed{}, nil } - if err := s.InitializeChunkCoverage(context.Background(), 1, seed, coverageNoPages); err == nil || mapStarted { + if err := s.InitializeChunkCoverage(context.Background(), 1, seed, coverageNoPages); !errors.Is(err, ErrMapCoverageStale) || mapStarted { t.Fatalf("unsynced initialization: err=%v mapStarted=%v", err, mapStarted) } if _, err := s.Sync(); err != nil {