diff --git a/seaweed-block/core/storage/chunk_coverage.go b/seaweed-block/core/storage/chunk_coverage.go index c7c9ebe932..98c3d725cd 100644 --- a/seaweed-block/core/storage/chunk_coverage.go +++ b/seaweed-block/core/storage/chunk_coverage.go @@ -173,6 +173,9 @@ func (s *WALStore) InitializeChunkCoverage(ctx context.Context, epoch uint64, se defer v.syncMu.Unlock() s.mu.Lock() defer s.mu.Unlock() + if s.nextLSN-1 != position { + return mapCoverageRefusal("coverage_initialization_append_changed") + } return s.finishCoverageFenceLocked(epoch) } entries := append([]chunkLSNEntryV3(nil), v.mapEntries...) @@ -238,7 +241,7 @@ func (s *WALStore) InitializeChunkCoverage(ctx context.Context, epoch uint64, se defer v.syncMu.Unlock() s.mu.Lock() defer s.mu.Unlock() - if v.pub.current() != current { + if v.pub.current() != current || s.nextLSN-1 != position { prepared.abandonV3() return mapCoverageRefusal("coverage_initialization_changed") } diff --git a/seaweed-block/core/storage/chunk_coverage_initialization_append_test.go b/seaweed-block/core/storage/chunk_coverage_initialization_append_test.go new file mode 100644 index 0000000000..d6b5167be2 --- /dev/null +++ b/seaweed-block/core/storage/chunk_coverage_initialization_append_test.go @@ -0,0 +1,107 @@ +package storage + +import ( + "bytes" + "context" + "errors" + "testing" + "time" +) + +func TestChunkCoverageInitializationCaptureBarrierExcludesPublicWrites(t *testing.T) { + s, _ := newMappedCheckpointStoreV3(t) + s.HoldExtentDrainUntilChunkLayer() + if _, err := s.Recover(); err != nil { + t.Fatal(err) + } + err := s.InitializeChunkCoverage(context.Background(), 7, + func(uint64, uint64) (ChunkCoverageSeed, error) { return ChunkCoverageSeed{}, nil }, + func(ChunkCoverageReader) error { + ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond) + defer cancel() + if _, err := s.WriteContext(ctx, 1, make([]byte, 4096)); !errors.Is(err, ErrWALPressureTimeout) { + t.Fatalf("public write crossed initialization capture barrier: %v", err) + } + return nil + }) + if err != nil { + t.Fatal(err) + } + if s.NextLSN() != 1 { + t.Fatal("refused public write advanced the log") + } +} + +// This fault control deliberately drops the outer capture barrier for one append. +// Public writes are excluded by that barrier; the final position check is defense in depth. +func TestChunkCoverageInitializationRefusesAnAppendDuringPagePreparation(t *testing.T) { + for _, marked := range []bool{false, true} { + name := "first upgrade" + if marked { + name = "same epoch retry" + } + t.Run(name, func(t *testing.T) { + s, path := newMappedCheckpointStoreV3(t) + s.HoldExtentDrainUntilChunkLayer() + if _, err := s.Recover(); err != nil { + t.Fatal(err) + } + empty := func(uint64, uint64) (ChunkCoverageSeed, error) { return ChunkCoverageSeed{}, nil } + if marked { + if err := s.InitializeChunkCoverage(context.Background(), 7, empty, coverageNoPages); err != nil { + t.Fatal(err) + } + } + before := s.v3.pub.current() + payload := bytes.Repeat([]byte{0xa7}, 4096) + called := false + err := s.InitializeChunkCoverage(context.Background(), 7, empty, func(ChunkCoverageReader) error { + called = true + s.captureMu.Unlock() + defer s.captureMu.Lock() + _, err := s.Write(1, payload) + return err + }) + if !called || !errors.Is(err, ErrMapCoverageStale) { + t.Fatalf("append during page preparation: called=%v err=%v; want stale refusal", called, err) + } + if s.v3.pub.current() != before { + t.Fatal("stale initialization published a descriptor") + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + if marked { + if c, pos, err := s.Coverage(0); err != nil || c != CoverageSome || pos != 1 { + t.Fatalf("append coverage was lost: %v/%d %v", c, pos, err) + } + } + seed := func(chunk, _ uint64) (ChunkCoverageSeed, error) { + if chunk == 0 { + return ChunkCoverageSeed{Blocks: []uint64{1}}, nil + } + return ChunkCoverageSeed{}, nil + } + if err := s.InitializeChunkCoverage(context.Background(), 7, seed, coverageNoPages); err != nil { + t.Fatal(err) + } + crashStore(t, s) + next, err := openWALStoreV3MapInternalForTest(path, true) + if err != nil { + t.Fatal(err) + } + next.HoldExtentDrainUntilChunkLayer() + next.DisableAutoFlushForRecoveryTest() + t.Cleanup(func() { next.Close() }) + if _, err := next.Recover(); err != nil { + t.Fatal(err) + } + if c, pos, err := next.Coverage(0); err != nil || c != CoverageSome || pos != 1 { + t.Fatalf("replayed coverage: %v/%d %v", c, pos, err) + } + if got, err := next.Read(1); err != nil || !bytes.Equal(got, payload) { + t.Fatalf("replayed bytes differ: %v", err) + } + }) + } +} diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 3438a69c8c..3abee426f0 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -627,6 +627,7 @@ The "Machine / transition" column refers to Part A. Notes under a table record w | `INV-CHUNK-RECORD-V11-001` | On the draft v1.1 format a layer upgrades its store once at attach and opens from its record; a fill's page claims no local block before one durable mark (partial fills and later writes too); an evict clears the store's bits only after its absent page is durable, retries too. | M1 Opened, M3 Serving (draft v1.1 format) | `core/storage/chunk_record_open.go` `openChunkRecordV11`, `loadChunkRecordV11`, `markFills`; `core/storage/chunk_record_upgrade.go` `upgradeChunkRecordWith`; `core/storage/chunk_record_runtime.go` `holdFills`, `PersistSegmentOf`; `core/storage/chunk_record_shadow.go` `evict`; `core/storage/chunk_layer.go` `EvictChunk`, `Close` | `TestV11AttachUpgradesTheStoreOnce`, `TestV11ReopenJudgesAWriteAfterThePageAsChanged`, `TestV11CleanStopWritesOnlyTheDirtyPages`, `TestV11UpgradeRecoversFromACrashAtEachStep`, `TestV11DamagedPageIsRebuiltFromTheStoreBits`, `TestV11FillsAreMarkedInOneBatchBeforeTheirPagesClaimThem`, `TestV11EvictSurvivesARestart` (`core/storage/chunk_record_v11_test.go`); `TestV11CloseDuringTheUpgradeRefusesTheAttach`, `TestV11EvictWithoutItsAbsentPageClearsNothing`, `TestV11ParkedFillBatchCannotOverwriteAnEvict`, `TestV11MalformedLeftoverPresenceDoesNotRefuseTheAttach`, `TestV11FinalPageFailureIsTheCloseResult` (`core/storage/chunk_record_v11_review_test.go`); `TestV11PartialFillWaitsForTheDurableMark`, `TestV11WriteAfterAHeldFillKeepsTheHold`, `TestV11EvictRetryStillWritesItsAbsentPage` (`core/storage/chunk_record_v11_hold_test.go`); `TestV11AbsentChunkSurvivesALostHeader`, `TestV11LogOnlyWriteSurvivesTheUpgrade` (`core/storage/chunk_record_v11_upgrade_test.go`) | chunk-kernel/2; CoverageDurable row 199 (the WAL is durable through a published position) (not in this repository) | DORMANT | | `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-INIT-POSITION-001` | Coverage initialization rechecks the captured append position under the final store lock before publishing a fence or replacing live entries; a changed position refuses the candidate. | M1 coverage initialization | `core/storage/chunk_coverage.go` `InitializeChunkCoverage` | `TestChunkCoverageInitializationRefusesAnAppendDuringPagePreparation`, `TestChunkCoverageInitializationCaptureBarrierExcludesPublicWrites` (`core/storage/chunk_coverage_initialization_append_test.go`) | SlotFence.Publish; capture barrier remains the public-write exclusion | ACTIVE | | `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 | diff --git a/seaweed-block/docs/design/model-code-trace-coverage.tsv b/seaweed-block/docs/design/model-code-trace-coverage.tsv index 19745df806..5c80350081 100644 --- a/seaweed-block/docs/design/model-code-trace-coverage.tsv +++ b/seaweed-block/docs/design/model-code-trace-coverage.tsv @@ -1,5 +1,5 @@ model item go_function tests status -SlotFence prepare pages before publishing the field core/storage/chunk_coverage.go:WALStore.InitializeChunkCoverage core/storage/chunk_coverage_test.go:TestChunkCoveragePreparedViewPrecedesTheFence; core/storage/chunk_coverage_test.go:TestChunkCoveragePreparedReaderRemainsImmutableAfterWrites STUB +SlotFence prepare pages before publishing the field core/storage/chunk_coverage.go:WALStore.InitializeChunkCoverage core/storage/chunk_coverage_test.go:TestChunkCoveragePreparedViewPrecedesTheFence; core/storage/chunk_coverage_test.go:TestChunkCoveragePreparedReaderRemainsImmutableAfterWrites; core/storage/chunk_coverage_initialization_append_test.go:TestChunkCoverageInitializationRefusesAnAppendDuringPagePreparation; core/storage/chunk_coverage_initialization_append_test.go:TestChunkCoverageInitializationCaptureBarrierExcludesPublicWrites STUB MoveWide2 durable per-block map premise core/storage/chunk_coverage_map.go:readCoverageMapPagesV3; core/storage/walstore_map_checkpoint_v3.go:prepareOwnedMapCheckpointV3 core/storage/chunk_coverage_test.go:TestChunkCoverageCheckpointKeepsAllAcrossAPageBoundary STUB MoveWide2 WAL suffix restores local bits core/storage/walstore_map_checkpoint_v3.go:recordMapReplayV3 core/storage/chunk_coverage_test.go:TestChunkCoverageAcknowledgedWriteSurvivesReplay STUB SlotFence marker excludes legacy seeding and cross-epoch initialization core/storage/chunk_coverage.go:WALStore.InitializeChunkCoverage core/storage/chunk_coverage_test.go:TestChunkCoverageMarkedEpochNeverReseedsPresence; core/storage/chunk_coverage_test.go:TestChunkCoverageMarkerWithoutBitmapCannotReadPresence STUB