From b77b5acaff01e046a5c1dfdc80d3a4f6f0dcd655 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 17 Nov 2026 02:59:30 -0800 Subject: [PATCH] fix: bound map allocation before root I/O and pin digest controls --- .../core/storage/chunk_lsn_map_v3.go | 8 +- .../storage/chunk_lsn_map_v3_review_test.go | 82 +++++++++++++++++++ seaweed-block/docs/design/invariants.md | 2 +- 3 files changed, 90 insertions(+), 2 deletions(-) create mode 100644 seaweed-block/core/storage/chunk_lsn_map_v3_review_test.go diff --git a/seaweed-block/core/storage/chunk_lsn_map_v3.go b/seaweed-block/core/storage/chunk_lsn_map_v3.go index 8414efe0e2..29afa9d65a 100644 --- a/seaweed-block/core/storage/chunk_lsn_map_v3.go +++ b/seaweed-block/core/storage/chunk_lsn_map_v3.go @@ -152,6 +152,10 @@ func readChunkLSNMapV3(f *os.File, d descriptorV3, cb uint64) ([]chunkLSNEntryV3 if d.MapGeneration == 0 || d.MapGeneration > counterMaxV3 || d.MapCoveredCheckpoint > counterMaxV3 || d.UUID == [16]byte{} || d.MapLineage == [16]byte{} { return nil, nil, ErrMapInvalid } + // Reject an impossible entry allocation before root allocation or file I/O. + if s.chunks > uint64(int(^uint(0)>>1))/16 { + return nil, nil, ErrMapInvalid + } info, e := f.Stat() if e != nil { return nil, nil, e @@ -174,7 +178,7 @@ func readChunkLSNMapV3(f *os.File, d descriptorV3, cb uint64) ([]chunkLSNEntryV3 } // Root is file-bounded before page and entry allocations; every page needs // 4096 distinct bytes. Reject impossible geometry before allocating entries. - if s.pages > size/4096 || s.chunks > uint64(int(^uint(0)>>1))/16 { + if s.pages > size/4096 { return nil, nil, ErrMapInvalid } entries := make([]chunkLSNEntryV3, 0, int(s.chunks)) @@ -284,6 +288,8 @@ func openChunkLSNMapV3(path string, d descriptorV3, cb uint64) (*chunkLSNMapV3, // Prepare persists pages -> page fsync -> root -> root fsync -> directory fsync. // It returns a pinned tuple, never a descriptor publication or reuse authority. +// Preflight and Stat errors do not latch. Once the append transaction starts, +// an error latches and refuses subsequent persistence I/O until reopen. // No pages are reclaimed in this append-only implementation. func (m *chunkLSNMapV3) Prepare(g, C uint64, entries []chunkLSNEntryV3, prior *chunkMapCandidateV3) (out *chunkMapCandidateV3, err error) { m.mu.Lock() diff --git a/seaweed-block/core/storage/chunk_lsn_map_v3_review_test.go b/seaweed-block/core/storage/chunk_lsn_map_v3_review_test.go new file mode 100644 index 0000000000..8048b45142 --- /dev/null +++ b/seaweed-block/core/storage/chunk_lsn_map_v3_review_test.go @@ -0,0 +1,82 @@ +package storage + +import ( + "crypto/sha256" + "errors" + "os" + "path/filepath" + "testing" +) + +func TestChunkLSNMapV3_EntryBoundBeforeRootIO(t *testing.T) { + d := mapDescriptorV3(t) + d.BlockSize = 1 + d.VolumeSize = uint64(int(^uint(0)>>1))/16 + 1 + f, err := os.Create(filepath.Join(t.TempDir(), "closed-map")) + if err != nil { + t.Fatal(err) + } + if err = f.Close(); err != nil { + t.Fatal(err) + } + // The geometry must be refused before even Stat, without allocating a root. + _, _, err = readChunkLSNMapV3(f, d, 1) + if !errors.Is(err, ErrMapInvalid) { + t.Fatalf("entry bound must precede file I/O: %v", err) + } +} + +func TestChunkLSNMapV3_WholePageHashIsNotBodyDigest(t *testing.T) { + d := mapDescriptorV3(t) + m, err := createChunkLSNMapV3(filepath.Join(t.TempDir(), "map"), d, 1) + if err != nil { + t.Fatal(err) + } + defer m.Close() + c, err := m.Prepare(1, 7, []chunkLSNEntryV3{{LSN: 7}}, nil) + if err != nil { + t.Fatal(err) + } + page := make([]byte, 4096) + if _, err = m.fd.ReadAt(page, int64(c.refs[0].Offset)); err != nil { + t.Fatal(err) + } + // Deliberately wrong: SHA-256 of all 4096 bytes, including the embedded hash, + // instead of the domain-separated 4064-byte body required by the byte contract. + whole := sha256.Sum256(page) + if whole == c.refs[0].Hash { + t.Fatal("whole-page digest unexpectedly matches body digest") + } + copy(page[4064:], whole[:]) + if _, err = m.fd.WriteAt(page, int64(c.refs[0].Offset)); err != nil { + t.Fatal(err) + } + root, err := encodeMapRootV3(d, 1, 1, 7, []mapPageRefV3{{Offset: c.refs[0].Offset, Hash: whole}}) + if err != nil { + t.Fatal(err) + } + if _, err = m.fd.WriteAt(root, int64(c.rootOffset)); err != nil { + t.Fatal(err) + } + d = c.descriptor(d) + // Root, reference and embedded digest agree. Only page-body validation rejects it. + d.MapRootHash = mapDigestV3(mapRootDomainV3, root[:128]) + if _, _, err = readChunkLSNMapV3(m.fd, d, 1); !errors.Is(err, ErrMapInvalid) { + t.Fatalf("whole-page hash accepted: %v", err) + } +} + +func TestChunkLSNMapV3_PreflightErrorDoesNotLatch(t *testing.T) { + d := mapDescriptorV3(t) + m, err := createChunkLSNMapV3(filepath.Join(t.TempDir(), "map"), d, 1) + if err != nil { + t.Fatal(err) + } + defer m.Close() + if c, err := m.Prepare(0, 7, []chunkLSNEntryV3{{LSN: 7}}, nil); c != nil || !errors.Is(err, ErrMapInvalid) { + t.Fatalf("invalid generation = %v, %v", c, err) + } + if c, err := m.Prepare(1, 7, []chunkLSNEntryV3{{LSN: 7}}, nil); err != nil || c == nil { + t.Fatalf("valid retry after preflight error = %v, %v", c, err) + } +} diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 56ebbd07e6..5fbf1688a2 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -283,7 +283,7 @@ The "Machine / transition" column refers to Part A. Notes under a table record w | `INV-WAL-V3-LSN-ORDER-001` | A dark v3 writer accepts only a first LSN above its highest consumed LSN; a batch consumes its whole validated range. Equal/lower requests return ErrWALLSNOrder before any pwrite or cursor change. Constructor coverage and a recovered kept frontier count as consumed; a fenced-away suffix does not. | M1 (dark append only) | `core/storage/wal_io_v3.go` `append`, `newWALWriterV3`, `restoreScanV3` | `TestWALLSNOrderV3_RefusesDuplicateAndLower`, `TestWALLSNOrderV3_BatchConsumesFullRange`, `TestWALLSNOrderV3_RestoreUsesKeptNotDroppedFrontier`, `TestWALLSNOrderV3_DescriptorFloorIsAlreadyConsumed`, `TestWALIOV3_ValidatedFrontierIntervals`, `TestWALIOV3_ConcurrentAppendsHaveUniqueCursors` | Physical LSN-strict prefix is a contract constraint; r16 model correspondence is pending | 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; lifecycle caller wiring pending) | `core/storage/chunk_map_publication_v3.go`; `core/storage/descriptor_v3.go` `publishLockedWithMapV3` | `TestMapPublicationV3_HeldPublicationsBothOrders`, `TestMapPublicationV3_IsolatedMergedCoverageAndWPositive`, `TestMapPublicationV3_ProofEpochAndMutationRefusal`, `TestMapPublicationV3_UncertainFinalResponsePinsCandidate`, `TestMapPublicationV3_CoverageWAndNoUnpreparedRoot`, `TestMapPublicationV3_ProofChangedDuringPersistenceRefuses` | WALFormatR5 map coverage / volatile proof epoch; physical caller wiring remains a code obligation | 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; any failure yields no candidate and no retry I/O. Append-only retention preserves both slots and pending candidates. | M1 (dark map preparation only) | `core/storage/chunk_lsn_map_v3.go` `Prepare`, `readChunkLSNMapV3` | `TestChunkLSNMapV3_CanonicalVectors`, `TestChunkLSNMapV3_PersistReloadAndReuse`, `TestChunkLSNMapV3_CorruptionAndBounds`, `TestChunkLSNMapV3_FailureDoesNotPublishOrReuse`, `TestChunkLSNMapV3_OrderOwnedOpenAndClippedPage`, `TestChunkLSNMapV3_RejectsRehashedMalformedRecords` | WALFormatR5 abstract map dependency; physical encoding/digest/order are code obligations | 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. Append-only retention preserves both slots and pending candidates. | M1 (dark map preparation only) | `core/storage/chunk_lsn_map_v3.go` `Prepare`, `readChunkLSNMapV3` | `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 | | `INV-WAL-V3-W-001` | v3 Sync acknowledges only after an fsync covers the batch. In mode C (the default) the slot carries the previous batch's acknowledged W and the batch's single fsync covers WAL and slot; in mode A the WAL fsync precedes a slot publication with W = H. Recovery refuses (`wal_corrupt`) when the contiguous prefix R above max(CheckpointLSN, BaseLSN) is below W* = max(slot W, max trusted DurableLSN). Mode C's only unprotected acknowledged data is the newest batch, against media corruption before the next Sync or the idle refresh; `SetWMode` and the refresh close that window. | M1 Recovering → Serving \| RecoveryFailed; M1 write lifecycle: Appended → Synced (v3) | `core/storage/walstore_v3.go` `WALStore.syncWALBatchV3`, `refreshW`, `SetWMode`, `recoverV3`, `appendWriteV3`; `core/storage/recovery_v3.go` `decideRecoveryV3`, `contiguousPrefixV3` | `TestWALStoreV3RecoversEveryAcknowledgedWriteInBothModes`, `TestWALStoreV3ModeCWindowIsExactlyTheNewestBatch`, `TestWALStoreV3RefreshAndSetWModeCloseTheWindow`, `TestWALStoreV3TornUnsyncedTailIsNeverAFalseCorrupt`, `TestWALStoreV3AppendWriteErrorLatchesTheStore`, `TestWALStoreV3FlusherWritesTheExtentButHoldsTheCheckpointUntilTheMap`, `TestWALStoreV3SyncRechecksTheFaultAtTheAckBoundary`, `TestWALStoreV3SetWModeWaitsForAHeldBatch`, `TestWALStoreV3NoBatchAcksUnderAStaleModeAfterSetWMode`, `TestWALStoreV3SetWModeCrashCases` (`core/storage/walstore_v3_test.go`); `TestRecoveryV3Decision`, `TestRecoveryV3ContiguousPrefix` (`core/storage/recovery_v3_test.go`) | `WALFormat` composed model (claude05, r14 run) | STUB | | `INV-WAL-V3-FENCE-001` | Before any append after a v3 recovery, the store zeroes exactly the logical WAL interval [E, floor+WALSize) (floor = both slots' same-nonce reuse floor) split at the physical wrap, fsyncs it through the leaf, then publishes retainedHead = E; no byte before E or outside the interval changes, so records dropped by one recovery never resurface after a second crash. | M1 Recovering → Serving (v3) | `core/storage/walstore_v3.go` `WALStore.fenceV3`, `recoverV3`; `core/storage/recovery_v3.go` `fenceRangesV3` | `TestWALStoreV3DroppedRecordsNeverResurfaceAfterASecondCrash`, `TestWALStoreV3NoFenceResurrectsInBothModes`, `TestWALStoreV3FenceTouchesNoByteBeforeTheHead`, `TestWALStoreV3RecoversAHistoryEndingAtTheLastRepresentableCursor` (`core/storage/walstore_v3_test.go`); `TestRecoveryV3FenceRangesAreExact` (`core/storage/recovery_v3_test.go`) | `WALFormat` `NoResurrection` (claude05) | STUB |