From 1b3a4b6a3eb30768905b99156626c8d3e1de79b9 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 30 Nov 2026 02:43:52 -0800 Subject: [PATCH 01/17] storage: fence chunk-state upgrades across both descriptor slots --- .../core/storage/chunk_state_upgrade.go | 96 +++++++++++ .../core/storage/chunk_state_upgrade_test.go | 153 ++++++++++++++++++ seaweed-block/core/storage/descriptor_v3.go | 4 + seaweed-block/core/storage/superblock_v3.go | 16 +- seaweed-block/core/storage/walstore_v3.go | 4 + 5 files changed, 272 insertions(+), 1 deletion(-) create mode 100644 seaweed-block/core/storage/chunk_state_upgrade.go create mode 100644 seaweed-block/core/storage/chunk_state_upgrade_test.go diff --git a/seaweed-block/core/storage/chunk_state_upgrade.go b/seaweed-block/core/storage/chunk_state_upgrade.go new file mode 100644 index 0000000000..509dafe429 --- /dev/null +++ b/seaweed-block/core/storage/chunk_state_upgrade.go @@ -0,0 +1,96 @@ +package storage + +import ( + "errors" + "fmt" +) + +// FenceChunkStateUpgrade is the store's completion boundary for the chunk-state +// format upgrade. The caller must persist the new bitmap and record pages first. +// Success means BOTH descriptor slots carry the format marker and local-work +// epoch, each published through the store's fsync leaf and read back. Only then +// may the caller write the complete record header or remove legacy presence. +// +// A failed publication/readback latches the store until reopen. A retry after +// reopen completes a half fence. Before completion the legacy presence and its +// WAL dependencies must remain intact, and no acknowledgement may depend only +// on the new bitmap. This method changes neither the WAL bounds nor map roots. +func (s *WALStore) FenceChunkStateUpgrade(epoch uint64) error { + v := s.v3 + if v == nil || epoch == 0 || epoch > counterMaxV3 { + return errors.New("storage: chunk-state upgrade requires a v3 store and a nonzero valid epoch") + } + release := s.holdChunkDestructive(true) + defer release() + s.lifecycleMu.RLock() + defer s.lifecycleMu.RUnlock() + v.syncMu.Lock() + defer v.syncMu.Unlock() + s.mu.Lock() + defer s.mu.Unlock() + if s.closed { + return errors.New("storage: chunk-state upgrade after Close") + } + if v.ownedMap == nil { + return errors.New("storage: chunk-state upgrade requires an owned map") + } + p := v.pub + p.descMu.Lock() + defer p.descMu.Unlock() + if p.failed != nil { + return p.failed + } + if err := s.stickyIOFault(); err != nil { + return err + } + if p.cur.LocalWorkEpoch > epoch { + return fmt.Errorf("%w: local-work epoch moved backwards", errDescriptorTransition) + } + if p.cur.BaseState != BaseNone || (p.otherValid && p.other.Nonce != p.cur.Nonce) { + return fmt.Errorf("%w: chunk-state upgrade during BASE install or reset", errDescriptorTransition) + } + if p.io.readSlot == nil { + return errors.New("storage: chunk-state upgrade has no descriptor reader") + } + for !chunkStateSlotMatches(p.cur, epoch) || !p.otherValid || !chunkStateSlotMatches(p.other, epoch) { + if _, err := p.publishLockedCoreV3(func(n *descriptorV3) error { + n.ChunkStateFormat, n.LocalWorkEpoch = 1, epoch + return nil + }, nil, false); err != nil { + return err + } + } + // The descriptor lock excludes other publications across both observations. + for _, off := range []int64{slotAOffsetV3, slotBOffsetV3} { + raw := make([]byte, slotSizeV3) + err := p.io.readSlot(off, raw) + var d descriptorV3 + if err == nil { + d, err = decodeSlotV3(raw, p.accept) + } + if err == nil && !chunkStateSlotMatches(d, epoch) { + err = errors.New("chunk-state marker or epoch not read back") + } + if err == nil { + want := p.cur + if (off == slotAOffsetV3) != (p.curSlot == slotA) { + want = p.other + } + if d != want { + err = errors.New("descriptor readback differs from publication") + } + } + if err != nil { + p.failed = fmt.Errorf("%w: upgrade slot %d readback: %w", ErrDescriptorPublishUncertain, off, err) + if p.io.latch != nil { + p.io.latch(p.failed) + } + return p.failed + } + } + return nil +} + +func chunkStateSlotMatches(d descriptorV3, epoch uint64) bool { + return d.ChunkStateFormat == 1 && d.LocalWorkEpoch == epoch +} diff --git a/seaweed-block/core/storage/chunk_state_upgrade_test.go b/seaweed-block/core/storage/chunk_state_upgrade_test.go new file mode 100644 index 0000000000..e648abf0f2 --- /dev/null +++ b/seaweed-block/core/storage/chunk_state_upgrade_test.go @@ -0,0 +1,153 @@ +package storage + +import ( + "encoding/binary" + "errors" + "hash/crc32" + "testing" +) + +// The upgrade's one store-owned completion boundary. The page writer may +// publish its complete header only after this method succeeds. +type chunkStateUpgradeFencer interface { + FenceChunkStateUpgrade(epoch uint64) error +} + +func TestChunkStateUpgradeFencesBothSlotsBeforeCompletion(t *testing.T) { + s, path := newMappedCheckpointStoreV3(t) + fencer, ok := any(s).(chunkStateUpgradeFencer) + if !ok { + t.Fatal("store has no two-slot chunk-state upgrade fence") + } + if err := fencer.FenceChunkStateUpgrade(7); err != nil { + t.Fatal(err) + } + // These bytes are reserved in the frozen v1.0 decoder. Both slots must + // carry the marker: that reader otherwise opens the unmarked fallback. + for _, off := range []int64{slotAOffsetV3, slotBOffsetV3} { + raw := make([]byte, slotSizeV3) + if _, err := s.fd.ReadAt(raw, off); err != nil { + t.Fatal(err) + } + if binary.LittleEndian.Uint16(raw[306:308]) != 1 || binary.LittleEndian.Uint64(raw[312:320]) != 7 { + t.Fatalf("slot at %d does not fence the old reader at local-work epoch 7", off) + } + if got, want := binary.LittleEndian.Uint32(raw[slotCRCOffsetV3:]), crc32.Checksum(raw[:slotCRCOffsetV3], crc32cTable); got != want { + t.Fatalf("slot at %d checksum %x, want %x", off, got, want) + } + } + if err := s.Close(); err != nil { + t.Fatal(err) + } + reopened, err := openWALStoreV3MapInternalForTest(path, true) + if err != nil { + t.Fatal(err) + } + defer reopened.Close() + retry, ok := any(reopened).(chunkStateUpgradeFencer) + if !ok { + t.Fatal("reopened store lost the fence API") + } + before := reopened.v3.pub.current().SlotGen + if err := retry.FenceChunkStateUpgrade(7); err != nil { + t.Fatal(err) + } + if got := reopened.v3.pub.current().SlotGen; got != before { + t.Fatalf("identical fence retry republished slots: generation %d -> %d", before, got) + } +} + +func TestChunkStateUpgradeUncertainSecondSlotRequiresReopen(t *testing.T) { + s, path := newMappedCheckpointStoreV3(t) + writes := 0 + injected := errors.New("second slot unavailable") + s.v3.testBeforeSlotWrite = func() error { + writes++ + if writes == 2 { + return injected + } + return nil + } + tail := s.v3.pub.current().RetainedTail + if err := s.FenceChunkStateUpgrade(7); !errors.Is(err, ErrDescriptorPublishUncertain) { + t.Fatalf("uncertain second slot answered %v", err) + } + if writes != 2 { + t.Fatalf("slot writes=%d, want 2", writes) + } + if s.v3.pub.current().RetainedTail != tail { + t.Fatal("upgrade trimmed legacy WAL dependencies") + } + s.v3.testBeforeSlotWrite = nil + if err := s.FenceChunkStateUpgrade(7); !errors.Is(err, ErrDescriptorPublishUncertain) { + t.Fatalf("retry on latched store answered %v", err) + } + // Close is allowed to report the latched fault. Only reopen resolves it. + _ = s.Close() + reopened, err := openWALStoreV3MapInternalForTest(path, true) + if err != nil { + t.Fatal(err) + } + defer reopened.Close() + if err := reopened.FenceChunkStateUpgrade(7); err != nil { + t.Fatal(err) + } + for _, off := range []int64{slotAOffsetV3, slotBOffsetV3} { + raw := make([]byte, slotSizeV3) + if _, err := reopened.fd.ReadAt(raw, off); err != nil { + t.Fatal(err) + } + if binary.LittleEndian.Uint64(raw[312:320]) != 7 { + t.Fatalf("reopen left slot %d unfenced", off) + } + } +} + +func TestChunkStateUpgradeFailureNeverCompletesUntilReopen(t *testing.T) { + for _, point := range []string{"write1", "write2", "sync1", "sync2", "read1", "read2"} { + t.Run(point, func(t *testing.T) { + s, path := newMappedCheckpointStoreV3(t) + injected := errors.New("injected " + point) + write, sync, read := 0, 0, 0 + originalSync, originalRead := s.v3.pub.io.fsync, s.v3.pub.io.readSlot + s.v3.testBeforeSlotWrite = func() error { + write++ + if (point == "write1" && write == 1) || (point == "write2" && write == 2) { + return injected + } + return nil + } + s.v3.pub.io.fsync = func() error { + sync++ + if (point == "sync1" && sync == 1) || (point == "sync2" && sync == 2) { + return injected + } + return originalSync() + } + s.v3.pub.io.readSlot = func(off int64, raw []byte) error { + read++ + if (point == "read1" && read == 1) || (point == "read2" && read == 2) { + return injected + } + return originalRead(off, raw) + } + if err := s.FenceChunkStateUpgrade(7); !errors.Is(err, ErrDescriptorPublishUncertain) { + t.Fatalf("fault was counted as completion or not latched: %v", err) + } + s.v3.testBeforeSlotWrite = nil + s.v3.pub.io.fsync, s.v3.pub.io.readSlot = originalSync, originalRead + if err := s.FenceChunkStateUpgrade(7); !errors.Is(err, ErrDescriptorPublishUncertain) { + t.Fatalf("latched fence answered %v", err) + } + _ = s.Close() + next, err := openWALStoreV3MapInternalForTest(path, true) + if err != nil { + t.Fatal(err) + } + defer next.Close() + if err := next.FenceChunkStateUpgrade(7); err != nil { + t.Fatal(err) + } + }) + } +} diff --git a/seaweed-block/core/storage/descriptor_v3.go b/seaweed-block/core/storage/descriptor_v3.go index 8989612a6e..75e3acd374 100644 --- a/seaweed-block/core/storage/descriptor_v3.go +++ b/seaweed-block/core/storage/descriptor_v3.go @@ -43,6 +43,7 @@ var ( // v3 publisher does it itself. type descriptorIOV3 struct { writeSlot func(off int64, b []byte) error + readSlot func(off int64, b []byte) error fsync func() error syncFile func(write, sync func() error) error sticky func() error @@ -305,6 +306,9 @@ func checkCountersV3(d *descriptorV3) error { func mergeDescriptorV3(cur, next *descriptorV3) error { return mergeDescriptorV3Mode(cur, next, false) } func mergeDescriptorV3Mode(cur, next *descriptorV3, reset bool) error { + if next.ChunkStateFormat < cur.ChunkStateFormat || next.LocalWorkEpoch < cur.LocalWorkEpoch { + return fmt.Errorf("%w: chunk-state format or epoch moved backwards", errDescriptorTransition) + } if next.ImplKind != cur.ImplKind || next.ImplVersion != cur.ImplVersion || next.UUID != cur.UUID || next.CreatedAt != cur.CreatedAt || !sameGeometryV3(*cur, *next) { return errDescriptorIdentityChange diff --git a/seaweed-block/core/storage/superblock_v3.go b/seaweed-block/core/storage/superblock_v3.go index da6cab7cc2..27c7199b56 100644 --- a/seaweed-block/core/storage/superblock_v3.go +++ b/seaweed-block/core/storage/superblock_v3.go @@ -103,6 +103,11 @@ type descriptorV3 struct { WMode WMode MigrationPhase MigrationPhase + // ChunkStateFormat marks the one-way chunk-state upgrade. Zero is the + // legacy layout; format 1 carries the epoch of local work. + ChunkStateFormat uint16 + LocalWorkEpoch uint64 + // The layout identity of this local root: the claim id its marker // carries (written before any claim) and whether the root is fresh // (until its restore base is durable). Bytes 88-122 of the slot. @@ -123,7 +128,7 @@ var crc32cTable = crc32.MakeTable(crc32.Castagnoli) // reservedRangesV3 are the [start, end) byte ranges that must be zero. var reservedRangesV3 = [][2]int{ - {9, 12}, {122, 128}, {164, 168}, {240, 256}, {273, 280}, {306, slotCRCOffsetV3}, + {9, 12}, {122, 128}, {164, 168}, {240, 256}, {273, 280}, {308, 312}, {320, slotCRCOffsetV3}, } // encode serializes d into one sealed slot. It does not validate; callers @@ -170,6 +175,8 @@ func (d *descriptorV3) encode() []byte { copy(b[288:304], d.BaseInstallID[:]) b[304] = uint8(d.WMode) b[305] = uint8(d.MigrationPhase) + le.PutUint16(b[306:], d.ChunkStateFormat) + le.PutUint64(b[312:], d.LocalWorkEpoch) le.PutUint32(b[slotCRCOffsetV3:], crc32.Checksum(b[:slotCRCOffsetV3], crc32cTable)) return b } @@ -240,6 +247,8 @@ func decodeSlotV3(b []byte, accept slotImplAcceptor) (descriptorV3, error) { copy(d.BaseInstallID[:], b[288:304]) d.WMode = WMode(b[304]) d.MigrationPhase = MigrationPhase(b[305]) + d.ChunkStateFormat = le.Uint16(b[306:]) + d.LocalWorkEpoch = le.Uint64(b[312:]) if err := d.validate(accept); err != nil { return descriptorV3{}, err } @@ -284,6 +293,11 @@ func invalidV3(format string, args ...any) error { // validate applies the field rules of DESIGN 2.1/2.2 that need no sidecar. func (d *descriptorV3) validate(accept slotImplAcceptor) error { + if (d.ChunkStateFormat == 0 && d.LocalWorkEpoch != 0) || + (d.ChunkStateFormat == 1 && (d.LocalWorkEpoch == 0 || d.LocalWorkEpoch > counterMaxV3)) || + d.ChunkStateFormat > 1 { + return invalidV3("chunk-state format %d epoch %d", d.ChunkStateFormat, d.LocalWorkEpoch) + } if accept == nil { accept = ossSlotImplAcceptor } diff --git a/seaweed-block/core/storage/walstore_v3.go b/seaweed-block/core/storage/walstore_v3.go index d559e4c061..bfb526efe3 100644 --- a/seaweed-block/core/storage/walstore_v3.go +++ b/seaweed-block/core/storage/walstore_v3.go @@ -418,6 +418,10 @@ func openWALStoreV3File(path string, f *os.File, requireMap bool, opts WALStoreO v := &walStoreV3State{} v.layoutFresh.Store(d.LayoutSet && d.LayoutFresh) v.pub = newDescriptorPublisherV3(d, id, other, descriptorIOV3{ + readSlot: func(off int64, buf []byte) error { + _, err := f.ReadAt(buf, off) + return err + }, writeSlot: func(off int64, buf []byte) error { if h := s.v3.testBeforeSlotWrite; h != nil { if err := h(); err != nil { From dd9ed22f0a972834e7bb0bfa0c5af5dd86f0a56a Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 30 Nov 2026 02:45:39 -0800 Subject: [PATCH 02/17] test: restart the upgrade fence after a legacy publication --- .../core/storage/chunk_state_upgrade_test.go | 57 +++++++++++++++++++ 1 file changed, 57 insertions(+) diff --git a/seaweed-block/core/storage/chunk_state_upgrade_test.go b/seaweed-block/core/storage/chunk_state_upgrade_test.go index e648abf0f2..5acd4ad299 100644 --- a/seaweed-block/core/storage/chunk_state_upgrade_test.go +++ b/seaweed-block/core/storage/chunk_state_upgrade_test.go @@ -4,6 +4,7 @@ import ( "encoding/binary" "errors" "hash/crc32" + "os" "testing" ) @@ -151,3 +152,59 @@ func TestChunkStateUpgradeFailureNeverCompletesUntilReopen(t *testing.T) { }) } } + +func TestChunkStateUpgradeOldReaderPublicationRestartsTheFence(t *testing.T) { + s, path := newMappedCheckpointStoreV3(t) + oldPair := make([]byte, 2*slotSizeV3) + if _, err := s.fd.ReadAt(oldPair, 0); err != nil { + t.Fatal(err) + } + // A crash after the first new slot leaves the old fallback readable. + writes := 0 + s.v3.testBeforeSlotWrite = func() error { + writes++ + if writes == 2 { + return errors.New("crash before second slot") + } + return nil + } + if err := s.FenceChunkStateUpgrade(7); err == nil { + t.Fatal("half fence succeeded") + } + _ = s.Close() + // Model the old reader's metadata publication: it copies its old selected + // descriptor (which has no marker) to both slots. It leaves map/WAL bytes + // untouched. The actual legacy slot bytes were captured before the attempt. + f, err := os.OpenFile(path, os.O_RDWR, 0) + if err != nil { + t.Fatal(err) + } + if _, err = f.WriteAt(oldPair, 0); err == nil { + err = f.Sync() + } + closeErr := f.Close() + if err != nil { + t.Fatal(err) + } + if closeErr != nil { + t.Fatal(closeErr) + } + next, err := openWALStoreV3MapInternalForTest(path, true) + if err != nil { + t.Fatal(err) + } + defer next.Close() + if d := next.v3.pub.current(); d.ChunkStateFormat != 0 || d.LocalWorkEpoch != 0 { + t.Fatal("new reader trusted the marker erased by an old publication") + } + // The page owner must rebuild from legacy presence before calling the + // boundary again; the store must not remember completion in process memory. + writes = 0 + next.v3.testBeforeSlotWrite = func() error { writes++; return nil } + if err := next.FenceChunkStateUpgrade(7); err != nil { + t.Fatal(err) + } + if writes != 2 { + t.Fatalf("erased marker did not restart both-slot fence: %d writes", writes) + } +} From c13cb1641ab444b5f6cc552e901642cb361f9ad8 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 30 Nov 2026 03:05:46 -0800 Subject: [PATCH 03/17] docs: register the inactive chunk-state upgrade fence invariant --- seaweed-block/docs/design/invariants.md | 1 + 1 file changed, 1 insertion(+) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 814a71adc9..6b0f7fc9df 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -611,6 +611,7 @@ The "Machine / transition" column refers to Part A. Notes under a table record w | `INV-WAL-V3-WRITE-AHEAD-001` | No extent byte reaches the disk before its WAL record is durable: the flusher writes an extent only from dirty entries at or below the synced (acknowledged) WAL frontier; Recover and the install log fsync their records before raising it. | M1 Serving (flusher extent write) | `core/storage/flusher.go` `flushOnceInternal`; `walstore_v3.go` `recoverV3` (descriptor publish fsync before `wack`); `install_log_v3.go` | `TestRedCrashKeepingAnUnsyncedExtentWriteLeavesLocalAndHEADApart` (`core/storage/chunk_u1_reorder_test.go`); `TestFlusherWriteAheadNeverFlushingGuestReachesExtentAtPressure` (`core/storage/flusher_write_ahead_test.go`) | A checkpoint may pass a synced record superseded by an unsynced newer one only because the cycle's sync covers the whole file, WAL included (one file, one descriptor: `INV-WAL-FLUSH-SYNC-COVERS-WAL-001`); separating WAL and extent, or a range sync, must first change the checkpoint bound | ACTIVE | | `INV-WAL-V3-CAPTURE-CANDIDATES-001` | A retained WAL entry already covered by HEAD is not dirt since HEAD. New post-HEAD WAL entries, UNKNOWN map chunks and map max-LSN above HEAD remain capture candidates, except as `INV-WAL-V3-CAPTURE-COMPARED-001`. | M5 candidate selection | `chunk_layer.go` `captureCandidates` | `TestChunkLayerV3CapturedUncheckpointedWALIsCleanUntilRewritten`, `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, `TestBaseInstallV3CompletePersistsTheMapUnknownOfBaseWrites` | Conservative reachability unchanged; narrower redundant work | ACTIVE | | `INV-WAL-V3-CAPTURE-COMPARED-001` | A chunk known equal to HEAD is neither staged nor compared again while its mutation version and HEAD ref match; own-batch chunks remain candidates. An interrupted or refused cut retains these proofs and requeues only unproven chunks. All candidate paths use one predicate. | M5 candidate selection | `core/storage/chunk_layer.go` `knownEqualToHeadLocked`, `captureCandidates`, `captureLocked`, `recordCapturedEqualMarks`, `stage`, `requeueCut`; `chunk_cut_payload.go` `markEqualNow` | `TestFreshFromHeadReadBackLeavesNoCutCandidates`, `TestFreshFromHeadFilledThenWrittenIsACandidate`, `TestEveryLocalWriteAfterACleanFillMakesTheChunkACandidate`, `TestABaseInstallAfterCleanFillsEndsTheirRecords`, `TestACleanFillRecordEndsWithItsHeadRef`, `TestARestoreTargetThatOnlyReadCutsNothing`, `TestARerunAfterAFailedCutComparesOnlyWhatDiffers`, `TestWithoutAFailedCutEveryUnknownChunkIsCompared`, `TestACutOffCompareKeepsItsWorkAndTheRerunComparesOnlyTheRest`, `TestFilledChunksAreFirstCutCandidatesAfterARestart`, `TestEveryDirtyMapInsertNotesTheChunkMutation`, `TestOwnBatch_BoundedBatchesReplaceEveryForeignKey`; `TestRefusedFullCutStagesOnlyTheUnmarkedChunk` (`core/storage/chunk_staging_equal_test.go`); `TestCopyErrorKeepsCapturedEqualMarks`, `TestInterruptedStagingKeepsEqualWork` (`core/storage/chunk_copy_error_equal_test.go`); `TestTimedOutRequestsThenRefusedCommitKeepEqualWork` (`core/frontend/chunkstore/layout_staging_retry_test.go`); also in `core/storage/chunk_fresh_readback_candidates_test.go`, `core/frontend/durable/first_cut_known_zero_test.go`, `core/storage/chunk_compare_progress_test.go`, `core/storage/chunk_mutation_note_guard_test.go`, `core/storage/chunk_own_test.go` | EqualMarks.MarkSound, EqualMarks.NoRecompare (must-violate rows 102-104); conservative reachability unchanged | ACTIVE | +| `INV-CHUNK-STATE-UPGRADE-FENCE-001` | The chunk-state upgrade fence succeeds only after both descriptor slots are fsynced and read back with the format marker and local-work epoch; uncertain writes or readback latch the store until reopen. | M1 format upgrade (caller not wired) | `core/storage/chunk_state_upgrade.go` `WALStore.FenceChunkStateUpgrade` | `TestChunkStateUpgradeFencesBothSlotsBeforeCompletion`, `TestChunkStateUpgradeUncertainSecondSlotRequiresReopen`, `TestChunkStateUpgradeFailureNeverCompletesUntilReopen`, `TestChunkStateUpgradeOldReaderPublicationRestartsTheFence` (`core/storage/chunk_state_upgrade_test.go`; single-publication and unlatched-readback mutant controls) | `CHUNK-STATE-r3` section 18; `SlotFence` rows 146-149 | STUB | | `INV-WAL-V3-DESCRIPTOR-001` | A v3 descriptor slot is used only if it is valid: a matching CRC32C (Castagnoli), every reserved byte zero, an accepted impl, a nonzero slotGen at most 2^64-2, a nonzero nonce, and geometry consistent under checked arithmetic. | M1 Opened (v3 descriptor selection) | `core/storage/superblock_v3.go` `decodeSlotV3`, `descriptorV3.validate`, `checkedAddV3` | `TestSlotV3VectorsDecodeAsExpected`, `TestSlotV3CounterExhaustion` (`core/storage/superblock_v3_test.go`) | — | STUB | | `INV-WAL-V3-DESCRIPTOR-BASE-001` | A valid v3 descriptor slot has CheckpointLSN ≤ mapCoveredCheckpoint ≤ W, and BASE fields that follow the rules of its BASE state. | M1 Opened (v3 descriptor selection) | `core/storage/superblock_v3.go` `descriptorV3.validate` | `TestSlotV3VectorsDecodeAsExpected`, `TestSlotV3InstalledMayHaveCursorBelowTail` (`core/storage/superblock_v3_test.go`) | — | STUB | | `INV-WAL-V3-DESCRIPTOR-SELECT-001` | Of the two v3 descriptor slots, open selects the valid selectable slot with the higher slotGen, and never a prepared migration slot. | M1 Opened (v3 descriptor selection) | `core/storage/superblock_v3.go` `selectSlotV3` | `TestSlotV3Selection` (`core/storage/superblock_v3_test.go`); `TestWALStoreV3CloseKeepsTheNewestSlotAAndItsW` (`core/storage/walstore_close_v3_test.go`) | — | ACTIVE | From 6c5a1b42e4de6131c8760100def4834dc561abc6 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 30 Nov 2026 03:09:02 -0800 Subject: [PATCH 04/17] docs: trace the chunk-state slot fence to its model rules --- seaweed-block/.github/model-code-trace.tsv | 2 ++ seaweed-block/docs/design/model-code-trace-slot-fence.tsv | 6 ++++++ 2 files changed, 8 insertions(+) create mode 100644 seaweed-block/docs/design/model-code-trace-slot-fence.tsv diff --git a/seaweed-block/.github/model-code-trace.tsv b/seaweed-block/.github/model-code-trace.tsv index 24b2a86e81..635123eff3 100644 --- a/seaweed-block/.github/model-code-trace.tsv +++ b/seaweed-block/.github/model-code-trace.tsv @@ -115,6 +115,8 @@ core/storage/chunk_layer.go HolderInterface.StopCommit core/storage/chunk_layer.go MoveAdmission.Detach core/storage/chunk_layer.go MoveAdmission.Publish core/storage/chunk_layer.go SnapshotRemoval.Write +core/storage/chunk_state_upgrade.go SlotFence.Publish +core/storage/chunk_state_upgrade.go SlotFence.Sync core/transport/catchup_sender.go ReplicationPeer.CatchUp core/transport/rebuild_sender.go ReplicationPeer.Rebuild core/transport/replica.go FencingRound.Recv diff --git a/seaweed-block/docs/design/model-code-trace-slot-fence.tsv b/seaweed-block/docs/design/model-code-trace-slot-fence.tsv new file mode 100644 index 0000000000..b1c37a4121 --- /dev/null +++ b/seaweed-block/docs/design/model-code-trace-slot-fence.tsv @@ -0,0 +1,6 @@ +model item kind go_function tests status note +SlotFence 146: both marked slots before completion rule core/storage/chunk_state_upgrade.go:WALStore.FenceChunkStateUpgrade core/storage/chunk_state_upgrade_test.go:TestChunkStateUpgradeFencesBothSlotsBeforeCompletion,core/storage/chunk_state_upgrade_test.go:TestChunkStateUpgradeUncertainSecondSlotRequiresReopen STUB Store completion boundary only; record-header caller remains unwired. Single-publication mutant fails. +SlotFence 147: count a slot only after sync and readback rule core/storage/descriptor_v3.go:descriptorPublisherV3.publishLockedCoreV3; core/storage/chunk_state_upgrade.go:WALStore.FenceChunkStateUpgrade core/storage/chunk_state_upgrade_test.go:TestChunkStateUpgradeFailureNeverCompletesUntilReopen STUB Six injected write/sync/readback failures refuse completion and latch until reopen; unlatched-readback mutant fails. +SlotFence 148: preserve the minimum decoded-slot WAL tail premise core/storage/descriptor_v3.go:descriptorPublisherV3.reuseFloorLocked; core/storage/wal_io_v3.go:walWriterV3.append core/storage/descriptor_v3_test.go:TestDescriptorV3FullRingRolloverAdvancesTheFloorWithoutAnyChange; core/storage/chunk_state_upgrade_test.go:TestChunkStateUpgradeUncertainSecondSlotRequiresReopen CONFIRMED Existing writer uses the minimum retained tail of both decoded slots; half-upgrade boundary changes no WAL bounds. +SlotFence 149: reject cached pages behind store positions integration OWED New record-page reader is stacked in PR 816; no assertion here that the store-fence component implements the page-position check. This premise must be confirmed in integrated code before activation. +SlotFence reopen after an old writer erases the marker witness core/storage/walstore_v3.go:openWALStoreV3File; core/storage/chunk_state_upgrade.go:WALStore.FenceChunkStateUpgrade core/storage/chunk_state_upgrade_test.go:TestChunkStateUpgradeOldReaderPublicationRestartsTheFence STUB Captured legacy descriptor bytes simulate the old metadata publication; no released binary execution claimed. Caller must rebuild legacy-derived pages before completing again. From e7b3851f3885e4800e4350ba20175f573a9ff33b Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 30 Nov 2026 03:41:30 -0800 Subject: [PATCH 05/17] test: classify the chunk-state fence as a control operation --- seaweed-block/core/storage/layout_fresh_mutators_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/seaweed-block/core/storage/layout_fresh_mutators_test.go b/seaweed-block/core/storage/layout_fresh_mutators_test.go index 0578fd70ba..d7bf9d5382 100644 --- a/seaweed-block/core/storage/layout_fresh_mutators_test.go +++ b/seaweed-block/core/storage/layout_fresh_mutators_test.go @@ -24,7 +24,7 @@ var walStoreMethods = map[string]string{ "BeginBaseInstall": "base", "CommitChunkAttachV3": "base", "SeedChunkFrontier": "base", "SyncInstallLog": "base", "AdvanceWALTail": "replication", "FormatV3": "base", "Recover": "recovery", "RecoverContext": "recovery (observed Recover; does not admit guest writes)", - "SetLayoutIdentity": "control", "SetWMode": "control", "SetMultiBlockRecords": "control", "SetRecoveryRetentionLSNs": "control", + "FenceChunkStateUpgrade": "control (format upgrade; no guest write or layout-fresh release)", "SetLayoutIdentity": "control", "SetWMode": "control", "SetMultiBlockRecords": "control", "SetRecoveryRetentionLSNs": "control", "SetRecycleFloorSource": "control", "AllowBaseRetirementV3": "control", "DeferBaseRetirementV3": "control", "HoldExtentDrainUntilChunkLayer": "control (holds the extent drain until the chunk layer attaches)", "DisableAutoFlushForRecoveryTest": "test control", "ResetFlusherForMeasurement": "test control", "Sync": "control", "Close": "control", From b62d2d99d5fd6fac4f27f589684c903a45386f92 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 30 Nov 2026 02:57:42 -0800 Subject: [PATCH 06/17] test(storage): an unfinished chunk record behind the store is never trusted The record pages, their header, and a reader. The red: pages are written, the fence is left half done, a writer that does not keep the pages acknowledges a write, and the new version opens again with the store still marked; the reader takes the pages that miss that write. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/storage/chunk_record.go | 229 ++++++++++++++++++ .../core/storage/chunk_record_test.go | 212 ++++++++++++++++ 2 files changed, 441 insertions(+) create mode 100644 seaweed-block/core/storage/chunk_record.go create mode 100644 seaweed-block/core/storage/chunk_record_test.go diff --git a/seaweed-block/core/storage/chunk_record.go b/seaweed-block/core/storage/chunk_record.go new file mode 100644 index 0000000000..edd0ca025b --- /dev/null +++ b/seaweed-block/core/storage/chunk_record.go @@ -0,0 +1,229 @@ +package storage + +import ( + "encoding/binary" + "errors" + "fmt" + "hash/crc32" + "os" + "path/filepath" +) + +// The persisted per-chunk record: one page per segment of +// chunkRecordSegment chunks and one header. A page carries each chunk's state +// and hash and the store position it is valid through; the header carries the +// local-work epoch and G, the position every page is valid through. +const chunkRecordSegment = 10000 + +var ( + chunkRecordPageMagic = [8]byte{'S', 'W', 'C', 'R', 'P', 'G', '0', '1'} + chunkRecordHeaderMagic = [8]byte{'S', 'W', 'C', 'R', 'H', 'D', '0', '1'} + + // errChunkRecordCheck: a page or header failed its check. + errChunkRecordCheck = errors.New("storage: chunk record: check failed") +) + +const chunkRecordEntryBytes = 1 + 32 + +type chunkRecordEntry struct { + State uint8 + Hash [32]byte +} + +type chunkRecordPage struct { + Segment uint64 + ValidThrough uint64 + Entries []chunkRecordEntry +} + +type chunkRecordHeader struct { + Epoch uint64 + Chunks uint64 + G uint64 +} + +func chunkRecordDir(storePath string) string { return storePath + ".chunkrecord" } + +func chunkRecordPageName(seg uint64) string { return fmt.Sprintf("page-%08d", seg) } + +const chunkRecordHeaderName = "header" + +func chunkRecordSegments(chunks uint64) uint64 { + return (chunks + chunkRecordSegment - 1) / chunkRecordSegment +} + +func encodeChunkRecordPage(p *chunkRecordPage) []byte { + le := binary.LittleEndian + b := make([]byte, 8+8+8+4, 8+8+8+4+len(p.Entries)*chunkRecordEntryBytes+4) + copy(b, chunkRecordPageMagic[:]) + le.PutUint64(b[8:], p.Segment) + le.PutUint64(b[16:], p.ValidThrough) + le.PutUint32(b[24:], uint32(len(p.Entries))) + for _, e := range p.Entries { + b = append(b, e.State) + b = append(b, e.Hash[:]...) + } + return le.AppendUint32(b, crc32.Checksum(b, crc32cTable)) +} + +func decodeChunkRecordPage(b []byte, seg uint64) (*chunkRecordPage, error) { + le := binary.LittleEndian + if len(b) < 8+8+8+4+4 || [8]byte(b[:8]) != chunkRecordPageMagic { + return nil, errChunkRecordCheck + } + body := b[:len(b)-4] + if crc32.Checksum(body, crc32cTable) != le.Uint32(b[len(b)-4:]) { + return nil, errChunkRecordCheck + } + n := int(le.Uint32(b[24:])) + if len(body) != 28+n*chunkRecordEntryBytes || le.Uint64(b[8:]) != seg { + return nil, errChunkRecordCheck + } + p := &chunkRecordPage{Segment: seg, ValidThrough: le.Uint64(b[16:]), Entries: make([]chunkRecordEntry, n)} + for i := range p.Entries { + at := 28 + i*chunkRecordEntryBytes + p.Entries[i].State = b[at] + copy(p.Entries[i].Hash[:], b[at+1:at+chunkRecordEntryBytes]) + } + return p, nil +} + +func encodeChunkRecordHeader(h chunkRecordHeader) []byte { + le := binary.LittleEndian + b := make([]byte, 8+24) + copy(b, chunkRecordHeaderMagic[:]) + le.PutUint64(b[8:], h.Epoch) + le.PutUint64(b[16:], h.Chunks) + le.PutUint64(b[24:], h.G) + return le.AppendUint32(b, crc32.Checksum(b, crc32cTable)) +} + +func decodeChunkRecordHeader(b []byte) (chunkRecordHeader, error) { + le := binary.LittleEndian + if len(b) != 8+24+4 || [8]byte(b[:8]) != chunkRecordHeaderMagic || + crc32.Checksum(b[:32], crc32cTable) != le.Uint32(b[32:]) { + return chunkRecordHeader{}, errChunkRecordCheck + } + return chunkRecordHeader{Epoch: le.Uint64(b[8:]), Chunks: le.Uint64(b[16:]), G: le.Uint64(b[24:])}, nil +} + +// writeChunkRecordFile writes one page or the header as one durable step: +// a temporary file, its fsync, a rename and the directory's fsync. +func writeChunkRecordFile(dir, name string, b []byte) error { + if err := os.MkdirAll(dir, 0o755); err != nil { + return fmt.Errorf("storage: chunk record: %w", err) + } + if err := writeFileDurable(filepath.Join(dir, name), b); err != nil { + return fmt.Errorf("storage: chunk record: %w", err) + } + if err := syncDir(dir); err != nil { + return fmt.Errorf("storage: chunk record: fsync directory: %w", err) + } + return nil +} + +func writeChunkRecordPage(dir string, p *chunkRecordPage) error { + return writeChunkRecordFile(dir, chunkRecordPageName(p.Segment), encodeChunkRecordPage(p)) +} + +// completeChunkRecord writes the record's header, which makes the record +// complete. It is written only after the store's fence: both descriptor slots +// carry the chunk-state marker at this epoch, synced and read back. Before +// it, an old version may still open the store from an unmarked slot. +func completeChunkRecord(s *WALStore, dir string, h chunkRecordHeader) error { + if err := s.FenceChunkStateUpgrade(h.Epoch); err != nil { + return err + } + return writeChunkRecordFile(dir, chunkRecordHeaderName, encodeChunkRecordHeader(h)) +} + +// chunkRecordLoad is what a restart may take from the record. +type chunkRecordLoad struct { + // Complete: the header is valid and its epoch is the store's marked + // epoch. Pages then hold every segment whose page passed its check; + // Damaged names the rest, to be rebuilt from the store's bitmap. + Complete bool + Header chunkRecordHeader + Pages map[uint64]*chunkRecordPage + Damaged []uint64 + // Discarded says why an unfinished record was not used: the upgrade + // builds it again from the legacy presence. + Discarded string +} + +// loadChunkRecord reads the record of a store. marked and epoch are the +// store's descriptor marker; storePos is the store's last durable position +// after recovery (its replayed log included). +// +// An unfinished record (no valid header) is used only when every page is +// present, passes its check, and is valid through storePos: a page behind +// the store missed writes, for example those an old version acknowledged and +// checkpointed between the pages and the fence, so it is never trusted. A +// store without the marker discards any record: an old version published +// after the pages. +func loadChunkRecord(dir string, chunks uint64, marked bool, epoch, storePos uint64) (chunkRecordLoad, error) { + var out chunkRecordLoad + if !marked { + out.Discarded = "store not marked" + return out, nil + } + h, hdrErr := readChunkRecordHeader(dir) + if hdrErr != nil && !errors.Is(hdrErr, errChunkRecordCheck) && !errors.Is(hdrErr, os.ErrNotExist) { + return out, hdrErr + } + complete := hdrErr == nil && h.Epoch == epoch && h.Chunks == chunks + pages := make(map[uint64]*chunkRecordPage) + var damaged []uint64 + for seg := uint64(0); seg < chunkRecordSegments(chunks); seg++ { + b, err := os.ReadFile(filepath.Join(dir, chunkRecordPageName(seg))) + if err != nil && !errors.Is(err, os.ErrNotExist) { + return out, fmt.Errorf("storage: chunk record: %w", err) + } + var p *chunkRecordPage + if err == nil { + p, err = decodeChunkRecordPage(b, seg) + } + if err == nil && len(p.Entries) != chunkRecordSegmentLen(chunks, seg) { + err = errChunkRecordCheck + } + if err != nil { + if !complete { + out.Discarded = fmt.Sprintf("unfinished record: page %d missing or damaged", seg) + return out, nil + } + damaged = append(damaged, seg) + continue + } + pages[seg] = p + } + out.Complete, out.Header, out.Pages, out.Damaged = complete, h, pages, damaged + if !complete { + out.Header = chunkRecordHeader{} + } + return out, nil +} + +func readChunkRecordHeader(dir string) (chunkRecordHeader, error) { + b, err := os.ReadFile(filepath.Join(dir, chunkRecordHeaderName)) + if err != nil { + return chunkRecordHeader{}, err + } + return decodeChunkRecordHeader(b) +} + +func chunkRecordSegmentLen(chunks, seg uint64) int { + if rest := chunks - seg*chunkRecordSegment; rest < chunkRecordSegment { + return int(rest) + } + return chunkRecordSegment +} + +// ChunkStateMarker reports the store's chunk-state upgrade marker: whether its +// descriptor carries the format and the epoch of local work. +func (s *WALStore) ChunkStateMarker() (marked bool, epoch uint64) { + if s.v3 == nil || s.v3.pub == nil { + return false, 0 + } + d := s.v3.pub.current() + return d.ChunkStateFormat == 1, d.LocalWorkEpoch +} diff --git a/seaweed-block/core/storage/chunk_record_test.go b/seaweed-block/core/storage/chunk_record_test.go new file mode 100644 index 0000000000..4f1c8050d5 --- /dev/null +++ b/seaweed-block/core/storage/chunk_record_test.go @@ -0,0 +1,212 @@ +package storage + +import ( + "errors" + "os" + "path/filepath" + "strings" + "testing" +) + +// recordPagesAt writes a full set of pages for s, valid through pos, as the +// upgrade writes them before the store's fence. +func recordPagesAt(t *testing.T, s *WALStore, dir string, pos uint64) uint64 { + t.Helper() + chunks := uint64(s.NumBlocks()) / s.ChunkBlocks() + for seg := uint64(0); seg < chunkRecordSegments(chunks); seg++ { + p := &chunkRecordPage{Segment: seg, ValidThrough: pos, Entries: make([]chunkRecordEntry, chunkRecordSegmentLen(chunks, seg))} + for i := range p.Entries { + p.Entries[i] = chunkRecordEntry{State: 2, Hash: [32]byte{byte(i)}} + } + if err := writeChunkRecordPage(dir, p); err != nil { + t.Fatal(err) + } + } + return chunks +} + +// halfFence leaves s with one descriptor slot marked: the second slot's +// write fails, as a crash between the two would leave it. +func halfFence(t *testing.T, s *WALStore, epoch uint64) { + t.Helper() + writes := 0 + s.v3.testBeforeSlotWrite = func() error { + writes++ + if writes == 2 { + return errors.New("crash before the second slot") + } + return nil + } + if err := s.FenceChunkStateUpgrade(epoch); err == nil { + t.Fatal("half fence succeeded") + } +} + +func crashStore(t *testing.T, s *WALStore) { + t.Helper() + crashRecoveryHardeningStore(t, s) + s.mu.Lock() + s.closed = true + s.mu.Unlock() +} + +func reopenRecovered(t *testing.T, path string) *WALStore { + t.Helper() + r, err := openWALStoreV3MapInternalForTest(path, true) + if err != nil { + t.Fatal(err) + } + r.DisableAutoFlushForRecoveryTest() + t.Cleanup(func() { r.Close() }) + if _, err := r.Recover(); err != nil { + t.Fatal(err) + } + return r +} + +// The pages are written, the fence is half done, and then a writer that does +// not keep the pages (the old version, opening from its unmarked slot) +// acknowledges a write before the new version opens again. The store is still +// marked, so only the position check can tell that the pages miss the write. +func TestUnfinishedRecordPagesBehindTheStoreAreNotTrusted(t *testing.T) { + s, path := newMappedCheckpointStoreV3(t) + writeSynced(t, s, 1, 2) + dir := chunkRecordDir(path) + chunks := recordPagesAt(t, s, dir, s.NextLSN()-1) + halfFence(t, s, 7) + _ = s.Close() + + old := reopenRecovered(t, path) + writeSynced(t, old, 3, 3) // acknowledged; the pages do not know it + crashStore(t, old) + + next := reopenRecovered(t, path) + marked, epoch := next.ChunkStateMarker() + if !marked || epoch != 7 { + t.Fatalf("store marker %v/%d; the control needs the half-fenced marked slot", marked, epoch) + } + got, err := loadChunkRecord(dir, chunks, marked, epoch, next.NextLSN()-1) + if err != nil { + t.Fatal(err) + } + if got.Pages != nil || got.Complete || !strings.Contains(got.Discarded, "valid through") { + t.Fatalf("pages that miss an acknowledged write were trusted: %+v", got) + } +} + +// The same window, with the old version's checkpoint: its publication drops +// the marker, so the whole record is discarded. +func TestUnfinishedRecordAfterAnOldCheckpointIsDiscarded(t *testing.T) { + s, path := newMappedCheckpointStoreV3(t) + writeSynced(t, s, 1, 2) + oldPair := make([]byte, 2*slotSizeV3) + if _, err := s.fd.ReadAt(oldPair, 0); err != nil { + t.Fatal(err) + } + dir := chunkRecordDir(path) + chunks := recordPagesAt(t, s, dir, s.NextLSN()-1) + halfFence(t, s, 7) + _ = s.Close() + f, err := os.OpenFile(path, os.O_RDWR, 0) + if err != nil { + t.Fatal(err) + } + if _, err = f.WriteAt(oldPair, 0); err == nil { + err = f.Sync() + } + if cerr := f.Close(); err == nil { + err = cerr + } + if err != nil { + t.Fatal(err) + } + old := reopenRecovered(t, path) + writeSynced(t, old, 3, 3) + if err := old.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + if err := old.Close(); err != nil { + t.Fatal(err) + } + + next := reopenRecovered(t, path) + marked, epoch := next.ChunkStateMarker() + got, err := loadChunkRecord(dir, chunks, marked, epoch, next.NextLSN()-1) + if err != nil { + t.Fatal(err) + } + if got.Pages != nil || got.Complete { + t.Fatalf("record trusted after the old version's checkpoint: %+v", got) + } +} + +// Pages current with the store, and the fence done: the header completes the +// record and a restart takes every page. +func TestCurrentPagesCompleteAfterTheFence(t *testing.T) { + s, path := newMappedCheckpointStoreV3(t) + writeSynced(t, s, 1, 2) + dir := chunkRecordDir(path) + pos := s.NextLSN() - 1 + chunks := recordPagesAt(t, s, dir, pos) + if err := completeChunkRecord(s, dir, chunkRecordHeader{Epoch: 7, Chunks: chunks, G: pos}); err != nil { + t.Fatal(err) + } + marked, epoch := s.ChunkStateMarker() + got, err := loadChunkRecord(dir, chunks, marked, epoch, s.NextLSN()-1) + if err != nil { + t.Fatal(err) + } + if !got.Complete || got.Header.G != pos || len(got.Pages) != int(chunkRecordSegments(chunks)) || len(got.Damaged) != 0 { + t.Fatalf("complete record not loaded: %+v", got) + } +} + +// The header is never written before both slots are fenced. +func TestRecordHeaderWaitsForTheFence(t *testing.T) { + s, path := newMappedCheckpointStoreV3(t) + dir := chunkRecordDir(path) + chunks := recordPagesAt(t, s, dir, s.NextLSN()-1) + writes := 0 + s.v3.testBeforeSlotWrite = func() error { + writes++ + if writes == 2 { + return errors.New("second slot fails") + } + return nil + } + if err := completeChunkRecord(s, dir, chunkRecordHeader{Epoch: 7, Chunks: chunks}); err == nil { + t.Fatal("header written with one slot fenced") + } + if _, err := os.Stat(filepath.Join(dir, chunkRecordHeaderName)); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("header exists before the fence: %v", err) + } +} + +// In a complete record a damaged page is named for rebuild; in an unfinished +// one any damaged page discards the record. +func TestDamagedPage(t *testing.T) { + s, path := newMappedCheckpointStoreV3(t) + dir := chunkRecordDir(path) + pos := s.NextLSN() - 1 + chunks := recordPagesAt(t, s, dir, pos) + page := filepath.Join(dir, chunkRecordPageName(0)) + b, err := os.ReadFile(page) + if err != nil { + t.Fatal(err) + } + b[30] ^= 1 + if err := os.WriteFile(page, b, 0o644); err != nil { + t.Fatal(err) + } + got, err := loadChunkRecord(dir, chunks, true, 7, pos) + if err != nil || got.Pages != nil || got.Discarded == "" { + t.Fatalf("unfinished record with a damaged page: %+v %v", got, err) + } + if err := completeChunkRecord(s, dir, chunkRecordHeader{Epoch: 7, Chunks: chunks, G: pos}); err != nil { + t.Fatal(err) + } + got, err = loadChunkRecord(dir, chunks, true, 7, pos) + if err != nil || !got.Complete || len(got.Damaged) != 1 || got.Damaged[0] != 0 { + t.Fatalf("complete record with a damaged page: %+v %v", got, err) + } +} From 78819fc994d385b707527e66c8332e793f6afb36 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 30 Nov 2026 02:57:44 -0800 Subject: [PATCH 07/17] storage: the record reader checks the store's position before the pages An unfinished record is used only when every page is valid through the store's last durable position after recovery; a page behind it missed writes, for example ones an old version acknowledged between the pages and the fence, and the upgrade builds the record again from the presence. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/storage/chunk_record.go | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/seaweed-block/core/storage/chunk_record.go b/seaweed-block/core/storage/chunk_record.go index edd0ca025b..7ebb042bca 100644 --- a/seaweed-block/core/storage/chunk_record.go +++ b/seaweed-block/core/storage/chunk_record.go @@ -194,6 +194,10 @@ func loadChunkRecord(dir string, chunks uint64, marked bool, epoch, storePos uin damaged = append(damaged, seg) continue } + if !complete && p.ValidThrough < storePos { + out.Discarded = fmt.Sprintf("unfinished record: page %d valid through %d, store at %d", seg, p.ValidThrough, storePos) + return out, nil + } pages[seg] = p } out.Complete, out.Header, out.Pages, out.Damaged = complete, h, pages, damaged From 0a2d86dc444e2a575c83ea4538e6111cdd1fa80f Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 30 Nov 2026 03:05:47 -0800 Subject: [PATCH 08/17] docs(invariants): the chunk record's position check, as a STUB row Co-Authored-By: Claude Opus 5.5 --- seaweed-block/docs/design/invariants.md | 1 + 1 file changed, 1 insertion(+) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 6b0f7fc9df..eb32db7b31 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -614,6 +614,7 @@ The "Machine / transition" column refers to Part A. Notes under a table record w | `INV-CHUNK-STATE-UPGRADE-FENCE-001` | The chunk-state upgrade fence succeeds only after both descriptor slots are fsynced and read back with the format marker and local-work epoch; uncertain writes or readback latch the store until reopen. | M1 format upgrade (caller not wired) | `core/storage/chunk_state_upgrade.go` `WALStore.FenceChunkStateUpgrade` | `TestChunkStateUpgradeFencesBothSlotsBeforeCompletion`, `TestChunkStateUpgradeUncertainSecondSlotRequiresReopen`, `TestChunkStateUpgradeFailureNeverCompletesUntilReopen`, `TestChunkStateUpgradeOldReaderPublicationRestartsTheFence` (`core/storage/chunk_state_upgrade_test.go`; single-publication and unlatched-readback mutant controls) | `CHUNK-STATE-r3` section 18; `SlotFence` rows 146-149 | STUB | | `INV-WAL-V3-DESCRIPTOR-001` | A v3 descriptor slot is used only if it is valid: a matching CRC32C (Castagnoli), every reserved byte zero, an accepted impl, a nonzero slotGen at most 2^64-2, a nonzero nonce, and geometry consistent under checked arithmetic. | M1 Opened (v3 descriptor selection) | `core/storage/superblock_v3.go` `decodeSlotV3`, `descriptorV3.validate`, `checkedAddV3` | `TestSlotV3VectorsDecodeAsExpected`, `TestSlotV3CounterExhaustion` (`core/storage/superblock_v3_test.go`) | — | STUB | | `INV-WAL-V3-DESCRIPTOR-BASE-001` | A valid v3 descriptor slot has CheckpointLSN ≤ mapCoveredCheckpoint ≤ W, and BASE fields that follow the rules of its BASE state. | M1 Opened (v3 descriptor selection) | `core/storage/superblock_v3.go` `descriptorV3.validate` | `TestSlotV3VectorsDecodeAsExpected`, `TestSlotV3InstalledMayHaveCursorBelowTail` (`core/storage/superblock_v3_test.go`) | — | STUB | +| `INV-CHUNK-RECORD-PAGES-CURRENT-001` | An unfinished chunk record (no valid header) is used only when every page is present, passes its check and is valid through the store's durable position after recovery; an unmarked store discards it; the header follows the store's two-slot fence. | M1 Opened (chunk record load, v1.1 upgrade) | `core/storage/chunk_record.go` `loadChunkRecord`, `completeChunkRecord` | `TestUnfinishedRecordPagesBehindTheStoreAreNotTrusted`, `TestUnfinishedRecordAfterAnOldCheckpointIsDiscarded`, `TestRecordHeaderWaitsForTheFence`, `TestDamagedPage` (`core/storage/chunk_record_test.go`) | SlotFence `PagesCurrent`, `FenceHolds` (the per-chunk state models are not in this repository) | STUB | | `INV-WAL-V3-DESCRIPTOR-SELECT-001` | Of the two v3 descriptor slots, open selects the valid selectable slot with the higher slotGen, and never a prepared migration slot. | M1 Opened (v3 descriptor selection) | `core/storage/superblock_v3.go` `selectSlotV3` | `TestSlotV3Selection` (`core/storage/superblock_v3_test.go`); `TestWALStoreV3CloseKeepsTheNewestSlotAAndItsW` (`core/storage/walstore_close_v3_test.go`) | — | ACTIVE | | `INV-WAL-V3-DESCRIPTOR-CONFLICT-001` | Open is refused when both v3 descriptor slots are valid but carry the same slotGen with different bytes, or disagree on the UUID or the geometry. | M1 Opened (v3 descriptor selection) | `core/storage/superblock_v3.go` `selectSlotV3`, `sameGeometryV3` | `TestSlotV3Selection` (`core/storage/superblock_v3_test.go`) | — | ACTIVE | | `INV-WAL-V3-RECORD-001` | An impl-3 WAL record has a fixed 62-byte prefix, 70 bytes of overhead in all, a CRC32C (Castagnoli) and an explicit EntrySize. | M1 v3 record framing | `core/storage/wal_entry_v3.go` `encodeWALEntryV3`, `payloadSizeV3` | `TestWALEntryV3_CanonicalBarrierBytes`, `TestWALEntryV3_TypeFootprints` | `WALRecovery` abstract record validity; physical byte rules are code-test obligations | ACTIVE | From 0e1b46eed4b50aa6ced38290b5e80761eaeb1cf7 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 30 Nov 2026 03:09:26 -0800 Subject: [PATCH 09/17] test(storage): stale pages are never completed; positions ahead are refused Three reds on the production store: a header written over pages that miss an old writer's acknowledged write after a half fence; an unfinished record whose pages are ahead of the recovered store; a complete record whose header position is ahead of it. Co-Authored-By: Claude Opus 5.5 --- .../core/storage/chunk_record_test.go | 61 +++++++++++++++++++ 1 file changed, 61 insertions(+) diff --git a/seaweed-block/core/storage/chunk_record_test.go b/seaweed-block/core/storage/chunk_record_test.go index 4f1c8050d5..7ef8f96c2d 100644 --- a/seaweed-block/core/storage/chunk_record_test.go +++ b/seaweed-block/core/storage/chunk_record_test.go @@ -210,3 +210,64 @@ func TestDamagedPage(t *testing.T) { t.Fatalf("complete record with a damaged page: %+v %v", got, err) } } + +// Stale pages cannot be completed: the fence keeps the old version out from +// then on, but the pages already miss its write; the header is refused. +func TestStalePagesAreNeverCompleted(t *testing.T) { + s, path := newMappedCheckpointStoreV3(t) + writeSynced(t, s, 1, 2) + dir := chunkRecordDir(path) + chunks := recordPagesAt(t, s, dir, s.NextLSN()-1) + halfFence(t, s, 7) + _ = s.Close() + old := reopenRecovered(t, path) + writeSynced(t, old, 3, 3) + crashStore(t, old) + + next := reopenRecovered(t, path) + if err := completeChunkRecord(next, dir, chunkRecordHeader{Epoch: 7, Chunks: chunks, G: next.NextLSN() - 1}); err == nil { + t.Fatal("a header was written over pages that miss an acknowledged write") + } + if _, err := os.Stat(filepath.Join(dir, chunkRecordHeaderName)); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("header exists over stale pages: %v", err) + } +} + +// A position ahead of the recovered store is not durable evidence: an +// unfinished record with a page ahead is not used. +func TestUnfinishedPagesAheadOfTheStoreAreNotTrusted(t *testing.T) { + s, path := newMappedCheckpointStoreV3(t) + writeSynced(t, s, 1, 2) + dir := chunkRecordDir(path) + pos := s.NextLSN() - 1 + chunks := recordPagesAt(t, s, dir, pos+5) + got, err := loadChunkRecord(dir, chunks, true, 7, pos) + if err != nil { + t.Fatal(err) + } + if got.Pages != nil || got.Discarded == "" { + t.Fatalf("pages ahead of the store were trusted: %+v", got) + } +} + +// A complete record whose header position is ahead of the store is not used. +func TestCompleteRecordAheadOfTheStoreIsNotTrusted(t *testing.T) { + s, path := newMappedCheckpointStoreV3(t) + writeSynced(t, s, 1, 2) + dir := chunkRecordDir(path) + pos := s.NextLSN() - 1 + chunks := recordPagesAt(t, s, dir, pos) + if err := completeChunkRecord(s, dir, chunkRecordHeader{Epoch: 7, Chunks: chunks, G: pos}); err != nil { + t.Fatal(err) + } + if err := writeChunkRecordFile(dir, chunkRecordHeaderName, encodeChunkRecordHeader(chunkRecordHeader{Epoch: 7, Chunks: chunks, G: pos + 5})); err != nil { + t.Fatal(err) + } + got, err := loadChunkRecord(dir, chunks, true, 7, pos) + if err != nil { + t.Fatal(err) + } + if got.Complete || got.Pages != nil { + t.Fatalf("a header ahead of the store was trusted: %+v", got) + } +} From 5b95b66f8d34efca309336a099080680612fc623 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 30 Nov 2026 03:12:12 -0800 Subject: [PATCH 10/17] storage: the record's header is written only over current pages; positions ahead are refused completeChunkRecord fences, reads the store's durable position after the fence, and writes the header (G = that position) only when every page is present, passes its check and is valid through exactly that position. The loader refuses positions ahead of the recovered store: an unfinished record must equal it, a complete record's G may not pass it, a page ahead of it is damaged. Pages carry the segment's candidate count, the segment name its published marks refer to, and the kernel table version (chunk-kernel/2). Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/storage/chunk_record.go | 263 ++++++++++++------ .../core/storage/chunk_record_test.go | 67 ++++- seaweed-block/docs/design/invariants.md | 2 +- 3 files changed, 236 insertions(+), 96 deletions(-) diff --git a/seaweed-block/core/storage/chunk_record.go b/seaweed-block/core/storage/chunk_record.go index 7ebb042bca..92d7dbc204 100644 --- a/seaweed-block/core/storage/chunk_record.go +++ b/seaweed-block/core/storage/chunk_record.go @@ -7,23 +7,38 @@ import ( "hash/crc32" "os" "path/filepath" + "slices" ) // The persisted per-chunk record: one page per segment of // chunkRecordSegment chunks and one header. A page carries each chunk's state -// and hash and the store position it is valid through; the header carries the -// local-work epoch and G, the position every page is valid through. +// (a state of the chunk kernel's table) and hash, the store position it is +// valid through, the segment's candidate count and the segment name its +// chunks' published marks refer to. The header carries the local-work epoch +// and G, the position every page is valid through. const chunkRecordSegment = 10000 +// chunkRecordKernelTable is the version of the chunk kernel's table whose +// states the pages carry: chunk-kernel/2. +const chunkRecordKernelTable = 2 + var ( - chunkRecordPageMagic = [8]byte{'S', 'W', 'C', 'R', 'P', 'G', '0', '1'} - chunkRecordHeaderMagic = [8]byte{'S', 'W', 'C', 'R', 'H', 'D', '0', '1'} + chunkRecordPageMagic = [8]byte{'S', 'W', 'C', 'R', 'P', 'G', '0', '2'} + chunkRecordHeaderMagic = [8]byte{'S', 'W', 'C', 'R', 'H', 'D', '0', '2'} // errChunkRecordCheck: a page or header failed its check. errChunkRecordCheck = errors.New("storage: chunk record: check failed") + // errChunkRecordNotCurrent: the pages are not valid through exactly the + // store's durable position, so the header is not written. + errChunkRecordNotCurrent = errors.New("storage: chunk record: pages not current with the store") ) -const chunkRecordEntryBytes = 1 + 32 +const ( + chunkRecordEntryBytes = 1 + 32 + chunkRecordMaxSegName = 1024 + chunkRecordPageFixed = 8 + 8 + 8 + 2 + 4 + 2 // magic, segment, valid, table, candidates, name length + chunkRecordHeaderBytes = 8 + 2 + 8 + 8 + 8 + 4 +) type chunkRecordEntry struct { State uint8 @@ -31,9 +46,11 @@ type chunkRecordEntry struct { } type chunkRecordPage struct { - Segment uint64 - ValidThrough uint64 - Entries []chunkRecordEntry + Segment uint64 + ValidThrough uint64 + Candidates uint32 + PublishedSegment string + Entries []chunkRecordEntry } type chunkRecordHeader struct { @@ -52,59 +69,87 @@ func chunkRecordSegments(chunks uint64) uint64 { return (chunks + chunkRecordSegment - 1) / chunkRecordSegment } -func encodeChunkRecordPage(p *chunkRecordPage) []byte { +func chunkRecordSegmentLen(chunks, seg uint64) int { + if rest := chunks - seg*chunkRecordSegment; rest < chunkRecordSegment { + return int(rest) + } + return chunkRecordSegment +} + +func encodeChunkRecordPage(p *chunkRecordPage) ([]byte, error) { + if len(p.PublishedSegment) > chunkRecordMaxSegName { + return nil, fmt.Errorf("storage: chunk record: segment name of %d bytes", len(p.PublishedSegment)) + } le := binary.LittleEndian - b := make([]byte, 8+8+8+4, 8+8+8+4+len(p.Entries)*chunkRecordEntryBytes+4) - copy(b, chunkRecordPageMagic[:]) - le.PutUint64(b[8:], p.Segment) - le.PutUint64(b[16:], p.ValidThrough) - le.PutUint32(b[24:], uint32(len(p.Entries))) + b := make([]byte, 0, chunkRecordPageFixed+len(p.PublishedSegment)+4+len(p.Entries)*chunkRecordEntryBytes+4) + b = append(b, chunkRecordPageMagic[:]...) + b = le.AppendUint64(b, p.Segment) + b = le.AppendUint64(b, p.ValidThrough) + b = le.AppendUint16(b, chunkRecordKernelTable) + b = le.AppendUint32(b, p.Candidates) + b = le.AppendUint16(b, uint16(len(p.PublishedSegment))) + b = append(b, p.PublishedSegment...) + b = le.AppendUint32(b, uint32(len(p.Entries))) for _, e := range p.Entries { b = append(b, e.State) b = append(b, e.Hash[:]...) } - return le.AppendUint32(b, crc32.Checksum(b, crc32cTable)) + return le.AppendUint32(b, crc32.Checksum(b, crc32cTable)), nil } func decodeChunkRecordPage(b []byte, seg uint64) (*chunkRecordPage, error) { le := binary.LittleEndian - if len(b) < 8+8+8+4+4 || [8]byte(b[:8]) != chunkRecordPageMagic { + if len(b) < chunkRecordPageFixed+4+4 || [8]byte(b[:8]) != chunkRecordPageMagic { return nil, errChunkRecordCheck } body := b[:len(b)-4] if crc32.Checksum(body, crc32cTable) != le.Uint32(b[len(b)-4:]) { return nil, errChunkRecordCheck } - n := int(le.Uint32(b[24:])) - if len(body) != 28+n*chunkRecordEntryBytes || le.Uint64(b[8:]) != seg { + if le.Uint64(b[8:]) != seg || le.Uint16(b[24:]) != chunkRecordKernelTable { return nil, errChunkRecordCheck } - p := &chunkRecordPage{Segment: seg, ValidThrough: le.Uint64(b[16:]), Entries: make([]chunkRecordEntry, n)} + p := &chunkRecordPage{Segment: seg, ValidThrough: le.Uint64(b[16:]), Candidates: le.Uint32(b[26:])} + at := chunkRecordPageFixed + nameLen := int(le.Uint16(b[30:])) + if nameLen > chunkRecordMaxSegName || len(body) < at+nameLen+4 { + return nil, errChunkRecordCheck + } + p.PublishedSegment = string(b[at : at+nameLen]) + at += nameLen + n := int(le.Uint32(b[at:])) + at += 4 + if len(body) != at+n*chunkRecordEntryBytes { + return nil, errChunkRecordCheck + } + p.Entries = make([]chunkRecordEntry, n) for i := range p.Entries { - at := 28 + i*chunkRecordEntryBytes p.Entries[i].State = b[at] copy(p.Entries[i].Hash[:], b[at+1:at+chunkRecordEntryBytes]) + at += chunkRecordEntryBytes } return p, nil } func encodeChunkRecordHeader(h chunkRecordHeader) []byte { le := binary.LittleEndian - b := make([]byte, 8+24) - copy(b, chunkRecordHeaderMagic[:]) - le.PutUint64(b[8:], h.Epoch) - le.PutUint64(b[16:], h.Chunks) - le.PutUint64(b[24:], h.G) + b := make([]byte, 0, chunkRecordHeaderBytes) + b = append(b, chunkRecordHeaderMagic[:]...) + b = le.AppendUint16(b, chunkRecordKernelTable) + b = le.AppendUint64(b, h.Epoch) + b = le.AppendUint64(b, h.Chunks) + b = le.AppendUint64(b, h.G) return le.AppendUint32(b, crc32.Checksum(b, crc32cTable)) } func decodeChunkRecordHeader(b []byte) (chunkRecordHeader, error) { le := binary.LittleEndian - if len(b) != 8+24+4 || [8]byte(b[:8]) != chunkRecordHeaderMagic || - crc32.Checksum(b[:32], crc32cTable) != le.Uint32(b[32:]) { + if len(b) != chunkRecordHeaderBytes || [8]byte(b[:8]) != chunkRecordHeaderMagic || + crc32.Checksum(b[:len(b)-4], crc32cTable) != le.Uint32(b[len(b)-4:]) || + le.Uint16(b[8:]) != chunkRecordKernelTable { return chunkRecordHeader{}, errChunkRecordCheck } - return chunkRecordHeader{Epoch: le.Uint64(b[8:]), Chunks: le.Uint64(b[16:]), G: le.Uint64(b[24:])}, nil + return chunkRecordHeader{Epoch: le.Uint64(b[10:]), Chunks: le.Uint64(b[18:]), G: le.Uint64(b[26:])}, nil } // writeChunkRecordFile writes one page or the header as one durable step: @@ -123,31 +168,84 @@ func writeChunkRecordFile(dir, name string, b []byte) error { } func writeChunkRecordPage(dir string, p *chunkRecordPage) error { - return writeChunkRecordFile(dir, chunkRecordPageName(p.Segment), encodeChunkRecordPage(p)) -} - -// completeChunkRecord writes the record's header, which makes the record -// complete. It is written only after the store's fence: both descriptor slots -// carry the chunk-state marker at this epoch, synced and read back. Before -// it, an old version may still open the store from an unmarked slot. -func completeChunkRecord(s *WALStore, dir string, h chunkRecordHeader) error { - if err := s.FenceChunkStateUpgrade(h.Epoch); err != nil { + b, err := encodeChunkRecordPage(p) + if err != nil { return err } + return writeChunkRecordFile(dir, chunkRecordPageName(p.Segment), b) +} + +// readChunkRecordPages reads every page of a record of chunks chunks. A +// missing page or one that fails its check is named in bad. +func readChunkRecordPages(dir string, chunks uint64) (map[uint64]*chunkRecordPage, []uint64, error) { + pages := make(map[uint64]*chunkRecordPage) + var bad []uint64 + for seg := uint64(0); seg < chunkRecordSegments(chunks); seg++ { + b, err := os.ReadFile(filepath.Join(dir, chunkRecordPageName(seg))) + if err != nil && !errors.Is(err, os.ErrNotExist) { + return nil, nil, fmt.Errorf("storage: chunk record: %w", err) + } + var p *chunkRecordPage + if err == nil { + p, err = decodeChunkRecordPage(b, seg) + } + if err == nil && len(p.Entries) != chunkRecordSegmentLen(chunks, seg) { + err = errChunkRecordCheck + } + if err != nil { + bad = append(bad, seg) + continue + } + pages[seg] = p + } + return pages, bad, nil +} + +// completeChunkRecord ends the upgrade: it writes the record's header, which +// makes the record complete. In order: +// +// 1. the store's fence: both descriptor slots carry the chunk-state marker at +// epoch, synced and read back; from here no old version opens the store; +// 2. the store's durable position P, read after the fence; +// 3. every page present, passing its check, and valid through exactly P: a +// page behind P misses writes made before the fence (an old version's +// among them), a page ahead of P claims writes that are not durable; +// 4. the header, with G = P. +// +// Writes after step 2 are this version's: a restart takes each chunk whose +// store position is above its page's as changed. +func completeChunkRecord(s *WALStore, dir string, epoch, chunks uint64) error { + if err := s.FenceChunkStateUpgrade(epoch); err != nil { + return err + } + pos := s.NextLSN() - 1 + pages, bad, err := readChunkRecordPages(dir, chunks) + if err != nil { + return err + } + if len(bad) != 0 { + return fmt.Errorf("%w: page %d missing or damaged", errChunkRecordNotCurrent, bad[0]) + } + for seg := uint64(0); seg < chunkRecordSegments(chunks); seg++ { + if v := pages[seg].ValidThrough; v != pos { + return fmt.Errorf("%w: page %d valid through %d, store at %d", errChunkRecordNotCurrent, seg, v, pos) + } + } + h := chunkRecordHeader{Epoch: epoch, Chunks: chunks, G: pos} return writeChunkRecordFile(dir, chunkRecordHeaderName, encodeChunkRecordHeader(h)) } // chunkRecordLoad is what a restart may take from the record. type chunkRecordLoad struct { - // Complete: the header is valid and its epoch is the store's marked - // epoch. Pages then hold every segment whose page passed its check; - // Damaged names the rest, to be rebuilt from the store's bitmap. + // Complete: the header is valid, its epoch is the store's marked epoch + // and its G is not ahead of the store. Pages then hold every segment + // whose page passed its check and is not ahead of the store; Damaged + // names the rest, to be rebuilt from the store's bitmap. Complete bool Header chunkRecordHeader Pages map[uint64]*chunkRecordPage Damaged []uint64 - // Discarded says why an unfinished record was not used: the upgrade - // builds it again from the legacy presence. + // Discarded says why the record was not used at all. Discarded string } @@ -155,12 +253,20 @@ type chunkRecordLoad struct { // store's descriptor marker; storePos is the store's last durable position // after recovery (its replayed log included). // -// An unfinished record (no valid header) is used only when every page is -// present, passes its check, and is valid through storePos: a page behind -// the store missed writes, for example those an old version acknowledged and -// checkpointed between the pages and the fence, so it is never trusted. A -// store without the marker discards any record: an old version published -// after the pages. +// - A store without the marker discards any record: an old version +// published after the pages, and the upgrade starts again from the legacy +// presence. +// - An unfinished record (no valid header) is used only when every page is +// present, passes its check, and is valid through exactly storePos. A page +// behind missed writes, for example those an old version acknowledged +// between the pages and the fence; a page ahead claims writes that are not +// durable. Either way the upgrade builds the record again. +// - A complete record whose G is ahead of storePos is not used. A page ahead +// of storePos is damaged. A page behind it is taken: it is valid through +// the larger of G and its own position, and only this version can have +// written since (the fence keeps an old version out). The caller takes each +// chunk whose store position is above that as changed; the pages are not +// current by themselves. func loadChunkRecord(dir string, chunks uint64, marked bool, epoch, storePos uint64) (chunkRecordLoad, error) { var out chunkRecordLoad if !marked { @@ -172,38 +278,36 @@ func loadChunkRecord(dir string, chunks uint64, marked bool, epoch, storePos uin return out, hdrErr } complete := hdrErr == nil && h.Epoch == epoch && h.Chunks == chunks - pages := make(map[uint64]*chunkRecordPage) - var damaged []uint64 - for seg := uint64(0); seg < chunkRecordSegments(chunks); seg++ { - b, err := os.ReadFile(filepath.Join(dir, chunkRecordPageName(seg))) - if err != nil && !errors.Is(err, os.ErrNotExist) { - return out, fmt.Errorf("storage: chunk record: %w", err) - } - var p *chunkRecordPage - if err == nil { - p, err = decodeChunkRecordPage(b, seg) - } - if err == nil && len(p.Entries) != chunkRecordSegmentLen(chunks, seg) { - err = errChunkRecordCheck - } - if err != nil { - if !complete { - out.Discarded = fmt.Sprintf("unfinished record: page %d missing or damaged", seg) - return out, nil - } - damaged = append(damaged, seg) - continue - } - if !complete && p.ValidThrough < storePos { - out.Discarded = fmt.Sprintf("unfinished record: page %d valid through %d, store at %d", seg, p.ValidThrough, storePos) + if complete && h.G > storePos { + out.Discarded = fmt.Sprintf("header valid through %d, store at %d", h.G, storePos) + return out, nil + } + pages, bad, err := readChunkRecordPages(dir, chunks) + if err != nil { + return out, err + } + if !complete { + if len(bad) != 0 { + out.Discarded = fmt.Sprintf("unfinished record: page %d missing or damaged", bad[0]) return out, nil } - pages[seg] = p + for seg := uint64(0); seg < chunkRecordSegments(chunks); seg++ { + if v := pages[seg].ValidThrough; v != storePos { + out.Discarded = fmt.Sprintf("unfinished record: page %d valid through %d, store at %d", seg, v, storePos) + return out, nil + } + } + out.Pages = pages + return out, nil } - out.Complete, out.Header, out.Pages, out.Damaged = complete, h, pages, damaged - if !complete { - out.Header = chunkRecordHeader{} + for seg, p := range pages { + if p.ValidThrough > storePos { + delete(pages, seg) + bad = append(bad, seg) + } } + slices.Sort(bad) + out.Complete, out.Header, out.Pages, out.Damaged = true, h, pages, bad return out, nil } @@ -215,13 +319,6 @@ func readChunkRecordHeader(dir string) (chunkRecordHeader, error) { return decodeChunkRecordHeader(b) } -func chunkRecordSegmentLen(chunks, seg uint64) int { - if rest := chunks - seg*chunkRecordSegment; rest < chunkRecordSegment { - return int(rest) - } - return chunkRecordSegment -} - // ChunkStateMarker reports the store's chunk-state upgrade marker: whether its // descriptor carries the format and the epoch of local work. func (s *WALStore) ChunkStateMarker() (marked bool, epoch uint64) { diff --git a/seaweed-block/core/storage/chunk_record_test.go b/seaweed-block/core/storage/chunk_record_test.go index 7ef8f96c2d..c8bdc38c8e 100644 --- a/seaweed-block/core/storage/chunk_record_test.go +++ b/seaweed-block/core/storage/chunk_record_test.go @@ -18,6 +18,7 @@ func recordPagesAt(t *testing.T, s *WALStore, dir string, pos uint64) uint64 { for i := range p.Entries { p.Entries[i] = chunkRecordEntry{State: 2, Hash: [32]byte{byte(i)}} } + p.Candidates, p.PublishedSegment = 3, "seg/v1-0001" if err := writeChunkRecordPage(dir, p); err != nil { t.Fatal(err) } @@ -148,7 +149,7 @@ func TestCurrentPagesCompleteAfterTheFence(t *testing.T) { dir := chunkRecordDir(path) pos := s.NextLSN() - 1 chunks := recordPagesAt(t, s, dir, pos) - if err := completeChunkRecord(s, dir, chunkRecordHeader{Epoch: 7, Chunks: chunks, G: pos}); err != nil { + if err := completeChunkRecord(s, dir, 7, chunks); err != nil { t.Fatal(err) } marked, epoch := s.ChunkStateMarker() @@ -174,7 +175,7 @@ func TestRecordHeaderWaitsForTheFence(t *testing.T) { } return nil } - if err := completeChunkRecord(s, dir, chunkRecordHeader{Epoch: 7, Chunks: chunks}); err == nil { + if err := completeChunkRecord(s, dir, 7, chunks); err == nil { t.Fatal("header written with one slot fenced") } if _, err := os.Stat(filepath.Join(dir, chunkRecordHeaderName)); !errors.Is(err, os.ErrNotExist) { @@ -190,21 +191,30 @@ func TestDamagedPage(t *testing.T) { pos := s.NextLSN() - 1 chunks := recordPagesAt(t, s, dir, pos) page := filepath.Join(dir, chunkRecordPageName(0)) - b, err := os.ReadFile(page) - if err != nil { - t.Fatal(err) - } - b[30] ^= 1 - if err := os.WriteFile(page, b, 0o644); err != nil { - t.Fatal(err) + damage := func() { + t.Helper() + b, err := os.ReadFile(page) + if err != nil { + t.Fatal(err) + } + b[40] ^= 1 + if err := os.WriteFile(page, b, 0o644); err != nil { + t.Fatal(err) + } } + damage() got, err := loadChunkRecord(dir, chunks, true, 7, pos) if err != nil || got.Pages != nil || got.Discarded == "" { t.Fatalf("unfinished record with a damaged page: %+v %v", got, err) } - if err := completeChunkRecord(s, dir, chunkRecordHeader{Epoch: 7, Chunks: chunks, G: pos}); err != nil { + if err := completeChunkRecord(s, dir, 7, chunks); !errors.Is(err, errChunkRecordNotCurrent) { + t.Fatalf("a record with a damaged page was completed: %v", err) + } + recordPagesAt(t, s, dir, pos) + if err := completeChunkRecord(s, dir, 7, chunks); err != nil { t.Fatal(err) } + damage() got, err = loadChunkRecord(dir, chunks, true, 7, pos) if err != nil || !got.Complete || len(got.Damaged) != 1 || got.Damaged[0] != 0 { t.Fatalf("complete record with a damaged page: %+v %v", got, err) @@ -225,7 +235,7 @@ func TestStalePagesAreNeverCompleted(t *testing.T) { crashStore(t, old) next := reopenRecovered(t, path) - if err := completeChunkRecord(next, dir, chunkRecordHeader{Epoch: 7, Chunks: chunks, G: next.NextLSN() - 1}); err == nil { + if err := completeChunkRecord(next, dir, 7, chunks); err == nil { t.Fatal("a header was written over pages that miss an acknowledged write") } if _, err := os.Stat(filepath.Join(dir, chunkRecordHeaderName)); !errors.Is(err, os.ErrNotExist) { @@ -257,7 +267,7 @@ func TestCompleteRecordAheadOfTheStoreIsNotTrusted(t *testing.T) { dir := chunkRecordDir(path) pos := s.NextLSN() - 1 chunks := recordPagesAt(t, s, dir, pos) - if err := completeChunkRecord(s, dir, chunkRecordHeader{Epoch: 7, Chunks: chunks, G: pos}); err != nil { + if err := completeChunkRecord(s, dir, 7, chunks); err != nil { t.Fatal(err) } if err := writeChunkRecordFile(dir, chunkRecordHeaderName, encodeChunkRecordHeader(chunkRecordHeader{Epoch: 7, Chunks: chunks, G: pos + 5})); err != nil { @@ -271,3 +281,36 @@ func TestCompleteRecordAheadOfTheStoreIsNotTrusted(t *testing.T) { t.Fatalf("a header ahead of the store was trusted: %+v", got) } } + +// In a complete record a page ahead of the store is damaged; a page behind G +// is taken (valid through G); the V4 fields round-trip. +func TestCompleteRecordPagePositions(t *testing.T) { + s, path := newMappedCheckpointStoreV3(t) + writeSynced(t, s, 1, 2) + dir := chunkRecordDir(path) + pos := s.NextLSN() - 1 + chunks := recordPagesAt(t, s, dir, pos) + if err := completeChunkRecord(s, dir, 7, chunks); err != nil { + t.Fatal(err) + } + ahead := &chunkRecordPage{Segment: 0, ValidThrough: pos + 1, Entries: make([]chunkRecordEntry, chunkRecordSegmentLen(chunks, 0))} + if err := writeChunkRecordPage(dir, ahead); err != nil { + t.Fatal(err) + } + got, err := loadChunkRecord(dir, chunks, true, 7, pos) + if err != nil || !got.Complete || len(got.Damaged) != 1 || got.Damaged[0] != 0 { + t.Fatalf("page ahead of the store in a complete record: %+v %v", got, err) + } + behind := &chunkRecordPage{Segment: 0, ValidThrough: pos - 1, Candidates: 9, PublishedSegment: "seg/x", Entries: make([]chunkRecordEntry, chunkRecordSegmentLen(chunks, 0))} + if err := writeChunkRecordPage(dir, behind); err != nil { + t.Fatal(err) + } + writeSynced(t, s, 3, 3) + got, err = loadChunkRecord(dir, chunks, true, 7, s.NextLSN()-1) + if err != nil || !got.Complete || len(got.Damaged) != 0 { + t.Fatalf("cold page behind G not taken: %+v %v", got, err) + } + if p := got.Pages[0]; p.Candidates != 9 || p.PublishedSegment != "seg/x" || p.ValidThrough != pos-1 { + t.Fatalf("page fields: %+v", p) + } +} diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index eb32db7b31..a513466252 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -614,7 +614,7 @@ The "Machine / transition" column refers to Part A. Notes under a table record w | `INV-CHUNK-STATE-UPGRADE-FENCE-001` | The chunk-state upgrade fence succeeds only after both descriptor slots are fsynced and read back with the format marker and local-work epoch; uncertain writes or readback latch the store until reopen. | M1 format upgrade (caller not wired) | `core/storage/chunk_state_upgrade.go` `WALStore.FenceChunkStateUpgrade` | `TestChunkStateUpgradeFencesBothSlotsBeforeCompletion`, `TestChunkStateUpgradeUncertainSecondSlotRequiresReopen`, `TestChunkStateUpgradeFailureNeverCompletesUntilReopen`, `TestChunkStateUpgradeOldReaderPublicationRestartsTheFence` (`core/storage/chunk_state_upgrade_test.go`; single-publication and unlatched-readback mutant controls) | `CHUNK-STATE-r3` section 18; `SlotFence` rows 146-149 | STUB | | `INV-WAL-V3-DESCRIPTOR-001` | A v3 descriptor slot is used only if it is valid: a matching CRC32C (Castagnoli), every reserved byte zero, an accepted impl, a nonzero slotGen at most 2^64-2, a nonzero nonce, and geometry consistent under checked arithmetic. | M1 Opened (v3 descriptor selection) | `core/storage/superblock_v3.go` `decodeSlotV3`, `descriptorV3.validate`, `checkedAddV3` | `TestSlotV3VectorsDecodeAsExpected`, `TestSlotV3CounterExhaustion` (`core/storage/superblock_v3_test.go`) | — | STUB | | `INV-WAL-V3-DESCRIPTOR-BASE-001` | A valid v3 descriptor slot has CheckpointLSN ≤ mapCoveredCheckpoint ≤ W, and BASE fields that follow the rules of its BASE state. | M1 Opened (v3 descriptor selection) | `core/storage/superblock_v3.go` `descriptorV3.validate` | `TestSlotV3VectorsDecodeAsExpected`, `TestSlotV3InstalledMayHaveCursorBelowTail` (`core/storage/superblock_v3_test.go`) | — | STUB | -| `INV-CHUNK-RECORD-PAGES-CURRENT-001` | An unfinished chunk record (no valid header) is used only when every page is present, passes its check and is valid through the store's durable position after recovery; an unmarked store discards it; the header follows the store's two-slot fence. | M1 Opened (chunk record load, v1.1 upgrade) | `core/storage/chunk_record.go` `loadChunkRecord`, `completeChunkRecord` | `TestUnfinishedRecordPagesBehindTheStoreAreNotTrusted`, `TestUnfinishedRecordAfterAnOldCheckpointIsDiscarded`, `TestRecordHeaderWaitsForTheFence`, `TestDamagedPage` (`core/storage/chunk_record_test.go`) | SlotFence `PagesCurrent`, `FenceHolds` (the per-chunk state models are not in this repository) | STUB | +| `INV-CHUNK-RECORD-PAGES-CURRENT-001` | An unfinished chunk record is used, and its header written, only when every page passes its check and is valid through exactly the store's durable position after recovery (behind: missed writes; ahead: not durable); an unmarked store discards it; the header follows the two-slot fence. | M1 Opened (chunk record load, v1.1 upgrade) | `core/storage/chunk_record.go` `loadChunkRecord`, `completeChunkRecord` | `TestUnfinishedRecordPagesBehindTheStoreAreNotTrusted`, `TestUnfinishedRecordAfterAnOldCheckpointIsDiscarded`, `TestStalePagesAreNeverCompleted`, `TestUnfinishedPagesAheadOfTheStoreAreNotTrusted`, `TestCompleteRecordAheadOfTheStoreIsNotTrusted`, `TestCompleteRecordPagePositions`, `TestRecordHeaderWaitsForTheFence`, `TestDamagedPage` (`core/storage/chunk_record_test.go`) | SlotFence `PagesCurrent`, `FenceHolds`; pages carry chunk-kernel/2 states (the per-chunk state models are not in this repository) | STUB | | `INV-WAL-V3-DESCRIPTOR-SELECT-001` | Of the two v3 descriptor slots, open selects the valid selectable slot with the higher slotGen, and never a prepared migration slot. | M1 Opened (v3 descriptor selection) | `core/storage/superblock_v3.go` `selectSlotV3` | `TestSlotV3Selection` (`core/storage/superblock_v3_test.go`); `TestWALStoreV3CloseKeepsTheNewestSlotAAndItsW` (`core/storage/walstore_close_v3_test.go`) | — | ACTIVE | | `INV-WAL-V3-DESCRIPTOR-CONFLICT-001` | Open is refused when both v3 descriptor slots are valid but carry the same slotGen with different bytes, or disagree on the UUID or the geometry. | M1 Opened (v3 descriptor selection) | `core/storage/superblock_v3.go` `selectSlotV3`, `sameGeometryV3` | `TestSlotV3Selection` (`core/storage/superblock_v3_test.go`) | — | ACTIVE | | `INV-WAL-V3-RECORD-001` | An impl-3 WAL record has a fixed 62-byte prefix, 70 bytes of overhead in all, a CRC32C (Castagnoli) and an explicit EntrySize. | M1 v3 record framing | `core/storage/wal_entry_v3.go` `encodeWALEntryV3`, `payloadSizeV3` | `TestWALEntryV3_CanonicalBarrierBytes`, `TestWALEntryV3_TypeFootprints` | `WALRecovery` abstract record validity; physical byte rules are code-test obligations | ACTIVE | From 38077535e7730299b2bca1d91c64fcc0f9ee5794 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 30 Nov 2026 03:22:46 -0800 Subject: [PATCH 11/17] test(storage): the record's header is not written ahead of the synced store Co-Authored-By: Claude Opus 5.5 --- .../core/storage/chunk_record_test.go | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/seaweed-block/core/storage/chunk_record_test.go b/seaweed-block/core/storage/chunk_record_test.go index c8bdc38c8e..069c226b09 100644 --- a/seaweed-block/core/storage/chunk_record_test.go +++ b/seaweed-block/core/storage/chunk_record_test.go @@ -314,3 +314,21 @@ func TestCompleteRecordPagePositions(t *testing.T) { t.Fatalf("page fields: %+v", p) } } + +// A write assigned but not synced is not durable: pages written through it +// are ahead of the synced store, and the header is refused. +func TestRecordHeaderIsNotWrittenAheadOfTheSyncedStore(t *testing.T) { + s, path := newMappedCheckpointStoreV3(t) + writeSynced(t, s, 1, 2) + if _, err := s.Write(3, blk(3)); err != nil { // assigned, not synced + t.Fatal(err) + } + dir := chunkRecordDir(path) + chunks := recordPagesAt(t, s, dir, s.NextLSN()-1) + if err := completeChunkRecord(s, dir, 7, chunks); err == nil { + t.Fatal("a header was written through a write that is not durable") + } + if _, err := os.Stat(filepath.Join(dir, chunkRecordHeaderName)); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("header exists ahead of the synced store: %v", err) + } +} From 5b0c9816325f853350fdba6aed8995af57ee0ad7 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 30 Nov 2026 03:24:14 -0800 Subject: [PATCH 12/17] storage: the record's completion reads the synced position, at open completeChunkRecord takes P from the store's synced position, not the assigned one, and refuses while a write is assigned but not synced: the completion runs at open, after recovery and before guest I/O. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/storage/chunk_record.go | 18 ++++++++++++------ .../core/storage/chunk_record_test.go | 14 ++++++++++---- seaweed-block/docs/design/invariants.md | 2 +- 3 files changed, 23 insertions(+), 11 deletions(-) diff --git a/seaweed-block/core/storage/chunk_record.go b/seaweed-block/core/storage/chunk_record.go index 92d7dbc204..e5f13d230f 100644 --- a/seaweed-block/core/storage/chunk_record.go +++ b/seaweed-block/core/storage/chunk_record.go @@ -206,19 +206,25 @@ func readChunkRecordPages(dir string, chunks uint64) (map[uint64]*chunkRecordPag // // 1. the store's fence: both descriptor slots carry the chunk-state marker at // epoch, synced and read back; from here no old version opens the store; -// 2. the store's durable position P, read after the fence; +// 2. the store's durable position P (its synced position), read after the +// fence; a write assigned but not yet synced refuses the completion, which +// therefore runs at open, after recovery and before guest I/O; // 3. every page present, passing its check, and valid through exactly P: a // page behind P misses writes made before the fence (an old version's // among them), a page ahead of P claims writes that are not durable; // 4. the header, with G = P. // -// Writes after step 2 are this version's: a restart takes each chunk whose -// store position is above its page's as changed. +// Writes after step 2 are this version's (the fence keeps an old version +// out): a restart takes each chunk whose store position is above its page's +// as changed. func completeChunkRecord(s *WALStore, dir string, epoch, chunks uint64) error { if err := s.FenceChunkStateUpgrade(epoch); err != nil { return err } - pos := s.NextLSN() - 1 + pos, _, _ := s.Boundaries() + if assigned := s.NextLSN() - 1; assigned != pos { + return fmt.Errorf("%w: writes through %d assigned, synced through %d; complete the record at open, before guest I/O", errChunkRecordNotCurrent, assigned, pos) + } pages, bad, err := readChunkRecordPages(dir, chunks) if err != nil { return err @@ -250,8 +256,8 @@ type chunkRecordLoad struct { } // loadChunkRecord reads the record of a store. marked and epoch are the -// store's descriptor marker; storePos is the store's last durable position -// after recovery (its replayed log included). +// store's descriptor marker; storePos is the store's synced position after +// recovery (its replayed log included). // // - A store without the marker discards any record: an old version // published after the pages, and the upgrade starts again from the legacy diff --git a/seaweed-block/core/storage/chunk_record_test.go b/seaweed-block/core/storage/chunk_record_test.go index 069c226b09..fd251732de 100644 --- a/seaweed-block/core/storage/chunk_record_test.go +++ b/seaweed-block/core/storage/chunk_record_test.go @@ -43,6 +43,12 @@ func halfFence(t *testing.T, s *WALStore, epoch uint64) { } } +// syncedPos is the store's synced position, the one the loader compares. +func syncedPos(s *WALStore) uint64 { + r, _, _ := s.Boundaries() + return r +} + func crashStore(t *testing.T, s *WALStore) { t.Helper() crashRecoveryHardeningStore(t, s) @@ -86,7 +92,7 @@ func TestUnfinishedRecordPagesBehindTheStoreAreNotTrusted(t *testing.T) { if !marked || epoch != 7 { t.Fatalf("store marker %v/%d; the control needs the half-fenced marked slot", marked, epoch) } - got, err := loadChunkRecord(dir, chunks, marked, epoch, next.NextLSN()-1) + got, err := loadChunkRecord(dir, chunks, marked, epoch, syncedPos(next)) if err != nil { t.Fatal(err) } @@ -132,7 +138,7 @@ func TestUnfinishedRecordAfterAnOldCheckpointIsDiscarded(t *testing.T) { next := reopenRecovered(t, path) marked, epoch := next.ChunkStateMarker() - got, err := loadChunkRecord(dir, chunks, marked, epoch, next.NextLSN()-1) + got, err := loadChunkRecord(dir, chunks, marked, epoch, syncedPos(next)) if err != nil { t.Fatal(err) } @@ -153,7 +159,7 @@ func TestCurrentPagesCompleteAfterTheFence(t *testing.T) { t.Fatal(err) } marked, epoch := s.ChunkStateMarker() - got, err := loadChunkRecord(dir, chunks, marked, epoch, s.NextLSN()-1) + got, err := loadChunkRecord(dir, chunks, marked, epoch, syncedPos(s)) if err != nil { t.Fatal(err) } @@ -306,7 +312,7 @@ func TestCompleteRecordPagePositions(t *testing.T) { t.Fatal(err) } writeSynced(t, s, 3, 3) - got, err = loadChunkRecord(dir, chunks, true, 7, s.NextLSN()-1) + got, err = loadChunkRecord(dir, chunks, true, 7, syncedPos(s)) if err != nil || !got.Complete || len(got.Damaged) != 0 { t.Fatalf("cold page behind G not taken: %+v %v", got, err) } diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index a513466252..64c084fcad 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -614,7 +614,7 @@ The "Machine / transition" column refers to Part A. Notes under a table record w | `INV-CHUNK-STATE-UPGRADE-FENCE-001` | The chunk-state upgrade fence succeeds only after both descriptor slots are fsynced and read back with the format marker and local-work epoch; uncertain writes or readback latch the store until reopen. | M1 format upgrade (caller not wired) | `core/storage/chunk_state_upgrade.go` `WALStore.FenceChunkStateUpgrade` | `TestChunkStateUpgradeFencesBothSlotsBeforeCompletion`, `TestChunkStateUpgradeUncertainSecondSlotRequiresReopen`, `TestChunkStateUpgradeFailureNeverCompletesUntilReopen`, `TestChunkStateUpgradeOldReaderPublicationRestartsTheFence` (`core/storage/chunk_state_upgrade_test.go`; single-publication and unlatched-readback mutant controls) | `CHUNK-STATE-r3` section 18; `SlotFence` rows 146-149 | STUB | | `INV-WAL-V3-DESCRIPTOR-001` | A v3 descriptor slot is used only if it is valid: a matching CRC32C (Castagnoli), every reserved byte zero, an accepted impl, a nonzero slotGen at most 2^64-2, a nonzero nonce, and geometry consistent under checked arithmetic. | M1 Opened (v3 descriptor selection) | `core/storage/superblock_v3.go` `decodeSlotV3`, `descriptorV3.validate`, `checkedAddV3` | `TestSlotV3VectorsDecodeAsExpected`, `TestSlotV3CounterExhaustion` (`core/storage/superblock_v3_test.go`) | — | STUB | | `INV-WAL-V3-DESCRIPTOR-BASE-001` | A valid v3 descriptor slot has CheckpointLSN ≤ mapCoveredCheckpoint ≤ W, and BASE fields that follow the rules of its BASE state. | M1 Opened (v3 descriptor selection) | `core/storage/superblock_v3.go` `descriptorV3.validate` | `TestSlotV3VectorsDecodeAsExpected`, `TestSlotV3InstalledMayHaveCursorBelowTail` (`core/storage/superblock_v3_test.go`) | — | STUB | -| `INV-CHUNK-RECORD-PAGES-CURRENT-001` | An unfinished chunk record is used, and its header written, only when every page passes its check and is valid through exactly the store's durable position after recovery (behind: missed writes; ahead: not durable); an unmarked store discards it; the header follows the two-slot fence. | M1 Opened (chunk record load, v1.1 upgrade) | `core/storage/chunk_record.go` `loadChunkRecord`, `completeChunkRecord` | `TestUnfinishedRecordPagesBehindTheStoreAreNotTrusted`, `TestUnfinishedRecordAfterAnOldCheckpointIsDiscarded`, `TestStalePagesAreNeverCompleted`, `TestUnfinishedPagesAheadOfTheStoreAreNotTrusted`, `TestCompleteRecordAheadOfTheStoreIsNotTrusted`, `TestCompleteRecordPagePositions`, `TestRecordHeaderWaitsForTheFence`, `TestDamagedPage` (`core/storage/chunk_record_test.go`) | SlotFence `PagesCurrent`, `FenceHolds`; pages carry chunk-kernel/2 states (the per-chunk state models are not in this repository) | STUB | +| `INV-CHUNK-RECORD-PAGES-CURRENT-001` | An unfinished chunk record is used, and its header written, only when every page passes its check and is valid through exactly the store's synced position after recovery (behind: missed writes; ahead: not durable); an unmarked store discards it; the header follows the two-slot fence. | M1 Opened (chunk record load, v1.1 upgrade) | `core/storage/chunk_record.go` `loadChunkRecord`, `completeChunkRecord` | `TestUnfinishedRecordPagesBehindTheStoreAreNotTrusted`, `TestUnfinishedRecordAfterAnOldCheckpointIsDiscarded`, `TestStalePagesAreNeverCompleted`, `TestUnfinishedPagesAheadOfTheStoreAreNotTrusted`, `TestCompleteRecordAheadOfTheStoreIsNotTrusted`, `TestCompleteRecordPagePositions`, `TestRecordHeaderWaitsForTheFence`, `TestRecordHeaderIsNotWrittenAheadOfTheSyncedStore`, `TestDamagedPage` (`core/storage/chunk_record_test.go`) | SlotFence `PagesCurrent`, `FenceHolds`; pages carry chunk-kernel/2 states (the per-chunk state models are not in this repository) | STUB | | `INV-WAL-V3-DESCRIPTOR-SELECT-001` | Of the two v3 descriptor slots, open selects the valid selectable slot with the higher slotGen, and never a prepared migration slot. | M1 Opened (v3 descriptor selection) | `core/storage/superblock_v3.go` `selectSlotV3` | `TestSlotV3Selection` (`core/storage/superblock_v3_test.go`); `TestWALStoreV3CloseKeepsTheNewestSlotAAndItsW` (`core/storage/walstore_close_v3_test.go`) | — | ACTIVE | | `INV-WAL-V3-DESCRIPTOR-CONFLICT-001` | Open is refused when both v3 descriptor slots are valid but carry the same slotGen with different bytes, or disagree on the UUID or the geometry. | M1 Opened (v3 descriptor selection) | `core/storage/superblock_v3.go` `selectSlotV3`, `sameGeometryV3` | `TestSlotV3Selection` (`core/storage/superblock_v3_test.go`) | — | ACTIVE | | `INV-WAL-V3-RECORD-001` | An impl-3 WAL record has a fixed 62-byte prefix, 70 bytes of overhead in all, a CRC32C (Castagnoli) and an explicit EntrySize. | M1 v3 record framing | `core/storage/wal_entry_v3.go` `encodeWALEntryV3`, `payloadSizeV3` | `TestWALEntryV3_CanonicalBarrierBytes`, `TestWALEntryV3_TypeFootprints` | `WALRecovery` abstract record validity; physical byte rules are code-test obligations | ACTIVE | From 84fcbe99a07c0ffee44947dc64cf86a8b1b43d19 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 30 Nov 2026 03:43:32 -0800 Subject: [PATCH 13/17] test(storage): the census registers ChunkStateMarker as a read Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/storage/layout_fresh_mutators_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/seaweed-block/core/storage/layout_fresh_mutators_test.go b/seaweed-block/core/storage/layout_fresh_mutators_test.go index d7bf9d5382..4a4c8ca324 100644 --- a/seaweed-block/core/storage/layout_fresh_mutators_test.go +++ b/seaweed-block/core/storage/layout_fresh_mutators_test.go @@ -28,7 +28,7 @@ var walStoreMethods = map[string]string{ "SetRecycleFloorSource": "control", "AllowBaseRetirementV3": "control", "DeferBaseRetirementV3": "control", "HoldExtentDrainUntilChunkLayer": "control (holds the extent drain until the chunk layer attaches)", "DisableAutoFlushForRecoveryTest": "test control", "ResetFlusherForMeasurement": "test control", "Sync": "control", "Close": "control", - "AllBlocks": "read", "AppliedLSNs": "read", "CanSeedChunkFrontier": "read (the seed precondition, no write)", "BlockSize": "read", "StoreID": "read (the superblock UUID)", "ChunkBlocks": "read (immutable local map shape)", "Boundaries": "read", "CheckpointLSN": "read", + "AllBlocks": "read", "AppliedLSNs": "read", "CanSeedChunkFrontier": "read (the seed precondition, no write)", "BlockSize": "read", "StoreID": "read (the superblock UUID)", "ChunkBlocks": "read (immutable local map shape)", "ChunkStateMarker": "read (the descriptor's chunk-state marker)", "Boundaries": "read", "CheckpointLSN": "read", "CheckpointLSNForPOC": "read", "CheckpointPersistence": "read", "ChunkMapStatsV3": "read", "DataSyncPolicy": "read", "DurabilityLatency": "read", "ExtentDrainHeld": "read", "FlushCount": "read", "FlusherInstrumentation": "read", "HolesSuspected": "read", "InstalledBaseLSN": "read", "LayoutIdentity": "read", "NextLSN": "read", "NumBlocks": "read", From 57f12f6b3260864cdf10aed722f6593d24a586e3 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 30 Nov 2026 06:18:47 -0800 Subject: [PATCH 14/17] test: inventory persisted address widths and pin wide WAL addresses --- .../core/storage/lba_width_contract_test.go | 42 +++++++++++++++++++ .../docs/design/lba-width-census.tsv | 19 +++++++++ 2 files changed, 61 insertions(+) create mode 100644 seaweed-block/core/storage/lba_width_contract_test.go create mode 100644 seaweed-block/docs/design/lba-width-census.tsv diff --git a/seaweed-block/core/storage/lba_width_contract_test.go b/seaweed-block/core/storage/lba_width_contract_test.go new file mode 100644 index 0000000000..92397865eb --- /dev/null +++ b/seaweed-block/core/storage/lba_width_contract_test.go @@ -0,0 +1,42 @@ +package storage + +import ( + "bytes" + "testing" +) + +// The default WAL codec already has 64-bit addresses. Keep that format stable +// while the public storage contract and the volume admission are widened. +// This is codec coverage, not a claim that a 64-TiB volume can serve today. +func TestWALV3AddressWidthCovers64TiB(t *testing.T) { + const blocks uint64 = (64 << 40) / 4096 + for _, lba := range []uint64{(1 << 32) - 1, 1 << 32, blocks - 1} { + e := v3TestBarrier() + e.Type, e.LBA, e.Length = walEntryWrite, lba, 4096 + e.Data = bytes.Repeat([]byte{0x6d}, 4096) + raw, err := encodeWALEntryV3(e, 4096, blocks) + if err != nil { + t.Fatal(err) + } + got, err := decodeWALEntryV3(raw, 4096, blocks) + if err != nil || got.LBA != lba || !bytes.Equal(got.Data, e.Data) { + t.Fatalf("64-bit address changed: want=%d got=%d err=%v", lba, got.LBA, err) + } + } + e := v3TestBarrier() + e.Type, e.LBA, e.BatchCount = walEntryWriteBatch, (1<<32)-1, 2 + e.Data = bytes.Repeat([]byte{0x91}, 8192) + e.Length = uint32(len(e.Data)) + raw, err := encodeWALEntryV3(e, 4096, blocks) + if err != nil { + t.Fatal(err) + } + got, err := decodeWALEntryV3(raw, 4096, blocks) + if err != nil || got.LBA != e.LBA || got.BatchCount != 2 { + t.Fatalf("batch crossing uint32 changed: %+v err=%v", got, err) + } + e.LBA = blocks - 1 + if _, err := encodeWALEntryV3(e, 4096, blocks); err == nil { + t.Fatal("batch beyond volume admitted") + } +} diff --git a/seaweed-block/docs/design/lba-width-census.tsv b/seaweed-block/docs/design/lba-width-census.tsv new file mode 100644 index 0000000000..ffcc1573a7 --- /dev/null +++ b/seaweed-block/docs/design/lba-width-census.tsv @@ -0,0 +1,19 @@ +version component placement field bits source action +lba-width-census/1 walstore-v3 disk walEntryV3.LBA 64 core/storage/wal_entry_v3.go:127 LE uint64 bytes 18:26; preserve existing encoding +lba-width-census/1 walstore-v3 disk descriptorV3.VolumeSize/BaseCursor 64 core/storage/superblock_v3.go:141 Byte size and BASE cursor already uint64 +lba-width-census/1 walstore-v3 disk map page index 64 core/storage/chunk_lsn_map_v3.go:86 LE uint64 bytes 48:56; block/chunk identity is implicit in page and entry ordinal +lba-width-census/1 walstore-v3 disk map root chunks/chunkBlocks/pages 64 core/storage/chunk_lsn_map_v3.go:120 LE uint64 at 48/56/72; entries carry LSN not LBA +lba-width-census/1 walstore-v3 disk presence absent/local index 64 core/storage/chunk_layer.go:2003 Canonical decimal parsed with bitSize 64; new bitmap replaces this in the single upgrade +lba-width-census/1 chunk-record disk-proposed page segment / header chunks 64 core/storage/chunk_record.go (#816) page Segment and header Chunks already uint64; chunk within segment implicit; candidates uint32 is bounded count not LBA +lba-width-census/1 remote-layout disk segment shard/chunk index/root shard 64 core/frontend/chunkstore/layout/layout.go:181 uint64 uvarint; no new remote format needed for address width +lba-width-census/1 smartwal disk record.LBA 32 core/storage/smartwal/record.go:79 LE uint32 bytes 4:8; requires versioned widening and explicit legacy policy +lba-width-census/1 smartwal disk header.NumBlocks 32 core/storage/smartwal/superblock.go:90 LE uint32 bytes 28:32; widen with its record codec, not independently +lba-width-census/1 parallelwal disk walRecord.LBA 32 core/storage/parallelwal/record.go:43 LE uint32 bytes 16:20; requires versioned widening and explicit legacy policy +lba-width-census/1 parallelwal disk fileHeader.NumBlocks 32 core/storage/parallelwal/header.go:95 LE uint32 bytes 28:32; widen with its record codec, not independently +lba-width-census/1 storage-contract memory LogicalStorage addresses and NumBlocks 32 core/storage/logical_storage.go:63 Must widen for serving high addresses; current geometry refuses above uint32 +lba-width-census/1 storage-contract memory RecoveryEntry.LBA 32 core/storage/recovery_contract.go:80 Scan/restore narrow existing 64-bit WAL addresses; update every adapter +lba-width-census/1 storage-contract memory BlockMetadata hooks and NumBlocks 32 core/storage/block_metadata.go:15 Enterprise metadata seam must be widened or explicitly refused; no OSS persisted index here +lba-width-census/1 replication wire Entry/base/WAL addresses and counts 32 core/transport/protocol.go:235;core/recovery/wire.go:115 Not disk format; cannot serve large replicated volumes until negotiation/codecs and callers are widened +lba-width-census/1 geometry admission MaxVolumeBytes / ValidateBlockGeometry 32 core/geometry/volume_size.go Existing cap is API capacity, not proof of a narrow default WAL field; keep until full path is qualified +lba-width-census/1 memorywal-and-BlockStore memory maps and addresses 32 core/storage/memorywal/store.go;core/storage/store.go No disk format; adapters still must satisfy widened contract +lba-width-census/1 v1-bitmap disk-owed per-block local bitmap 64 V1 format slice Global block/chunk/page identity and coverage counts must be uint64; bit within bounded page may stay bounded From 39b6b164ed1b1c1c5ac0f639006db2c0e00935bf Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 30 Nov 2026 06:22:43 -0800 Subject: [PATCH 15/17] docs: keep experimental address codecs outside the widening scope --- seaweed-block/docs/design/lba-width-census.tsv | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/seaweed-block/docs/design/lba-width-census.tsv b/seaweed-block/docs/design/lba-width-census.tsv index ffcc1573a7..726487e2c8 100644 --- a/seaweed-block/docs/design/lba-width-census.tsv +++ b/seaweed-block/docs/design/lba-width-census.tsv @@ -6,10 +6,10 @@ lba-width-census/1 walstore-v3 disk map root chunks/chunkBlocks/pages 64 core/st lba-width-census/1 walstore-v3 disk presence absent/local index 64 core/storage/chunk_layer.go:2003 Canonical decimal parsed with bitSize 64; new bitmap replaces this in the single upgrade lba-width-census/1 chunk-record disk-proposed page segment / header chunks 64 core/storage/chunk_record.go (#816) page Segment and header Chunks already uint64; chunk within segment implicit; candidates uint32 is bounded count not LBA lba-width-census/1 remote-layout disk segment shard/chunk index/root shard 64 core/frontend/chunkstore/layout/layout.go:181 uint64 uvarint; no new remote format needed for address width -lba-width-census/1 smartwal disk record.LBA 32 core/storage/smartwal/record.go:79 LE uint32 bytes 4:8; requires versioned widening and explicit legacy policy -lba-width-census/1 smartwal disk header.NumBlocks 32 core/storage/smartwal/superblock.go:90 LE uint32 bytes 28:32; widen with its record codec, not independently -lba-width-census/1 parallelwal disk walRecord.LBA 32 core/storage/parallelwal/record.go:43 LE uint32 bytes 16:20; requires versioned widening and explicit legacy policy -lba-width-census/1 parallelwal disk fileHeader.NumBlocks 32 core/storage/parallelwal/header.go:95 LE uint32 bytes 28:32; widen with its record codec, not independently +lba-width-census/1 smartwal disk record.LBA 32 core/storage/smartwal/record.go:79 LE uint32 bytes 4:8; do not widen; production reachability audit decides removal in a separate change +lba-width-census/1 smartwal disk header.NumBlocks 32 core/storage/smartwal/superblock.go:90 LE uint32 bytes 28:32; do not widen; keep paired with its record codec pending removal audit +lba-width-census/1 parallelwal disk walRecord.LBA 32 core/storage/parallelwal/record.go:43 LE uint32 bytes 16:20; do not widen; production reachability audit decides removal in a separate change +lba-width-census/1 parallelwal disk fileHeader.NumBlocks 32 core/storage/parallelwal/header.go:95 LE uint32 bytes 28:32; do not widen; keep paired with its record codec pending removal audit lba-width-census/1 storage-contract memory LogicalStorage addresses and NumBlocks 32 core/storage/logical_storage.go:63 Must widen for serving high addresses; current geometry refuses above uint32 lba-width-census/1 storage-contract memory RecoveryEntry.LBA 32 core/storage/recovery_contract.go:80 Scan/restore narrow existing 64-bit WAL addresses; update every adapter lba-width-census/1 storage-contract memory BlockMetadata hooks and NumBlocks 32 core/storage/block_metadata.go:15 Enterprise metadata seam must be widened or explicitly refused; no OSS persisted index here From 9947e8567d4678b349e152c623be3e42345c95d6 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 30 Nov 2026 06:39:41 -0800 Subject: [PATCH 16/17] docs: close the integrated chunk-page position trace --- seaweed-block/docs/design/model-code-trace-slot-fence.tsv | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/seaweed-block/docs/design/model-code-trace-slot-fence.tsv b/seaweed-block/docs/design/model-code-trace-slot-fence.tsv index b1c37a4121..5b4663a6c9 100644 --- a/seaweed-block/docs/design/model-code-trace-slot-fence.tsv +++ b/seaweed-block/docs/design/model-code-trace-slot-fence.tsv @@ -1,6 +1,6 @@ model item kind go_function tests status note -SlotFence 146: both marked slots before completion rule core/storage/chunk_state_upgrade.go:WALStore.FenceChunkStateUpgrade core/storage/chunk_state_upgrade_test.go:TestChunkStateUpgradeFencesBothSlotsBeforeCompletion,core/storage/chunk_state_upgrade_test.go:TestChunkStateUpgradeUncertainSecondSlotRequiresReopen STUB Store completion boundary only; record-header caller remains unwired. Single-publication mutant fails. +SlotFence 146: both marked slots before completion rule core/storage/chunk_state_upgrade.go:WALStore.FenceChunkStateUpgrade; core/storage/chunk_record.go:completeChunkRecord core/storage/chunk_state_upgrade_test.go:TestChunkStateUpgradeFencesBothSlotsBeforeCompletion,core/storage/chunk_state_upgrade_test.go:TestChunkStateUpgradeUncertainSecondSlotRequiresReopen; core/storage/chunk_record_test.go:TestRecordHeaderWaitsForTheFence STUB Store completion boundary precedes the record header; daemon upgrade caller remains unwired. Single-publication mutant fails. SlotFence 147: count a slot only after sync and readback rule core/storage/descriptor_v3.go:descriptorPublisherV3.publishLockedCoreV3; core/storage/chunk_state_upgrade.go:WALStore.FenceChunkStateUpgrade core/storage/chunk_state_upgrade_test.go:TestChunkStateUpgradeFailureNeverCompletesUntilReopen STUB Six injected write/sync/readback failures refuse completion and latch until reopen; unlatched-readback mutant fails. SlotFence 148: preserve the minimum decoded-slot WAL tail premise core/storage/descriptor_v3.go:descriptorPublisherV3.reuseFloorLocked; core/storage/wal_io_v3.go:walWriterV3.append core/storage/descriptor_v3_test.go:TestDescriptorV3FullRingRolloverAdvancesTheFloorWithoutAnyChange; core/storage/chunk_state_upgrade_test.go:TestChunkStateUpgradeUncertainSecondSlotRequiresReopen CONFIRMED Existing writer uses the minimum retained tail of both decoded slots; half-upgrade boundary changes no WAL bounds. -SlotFence 149: reject cached pages behind store positions integration OWED New record-page reader is stacked in PR 816; no assertion here that the store-fence component implements the page-position check. This premise must be confirmed in integrated code before activation. +SlotFence 149: reject cached pages behind store positions integration core/storage/chunk_record.go:loadChunkRecord; core/storage/chunk_record.go:completeChunkRecord core/storage/chunk_record_test.go:TestUnfinishedRecordPagesBehindTheStoreAreNotTrusted; core/storage/chunk_record_test.go:TestUnfinishedRecordAfterAnOldCheckpointIsDiscarded; core/storage/chunk_record_test.go:TestStalePagesAreNeverCompleted; core/storage/chunk_record_test.go:TestUnfinishedPagesAheadOfTheStoreAreNotTrusted; core/storage/chunk_record_test.go:TestRecordHeaderIsNotWrittenAheadOfTheSyncedStore STUB Record component rejects unfinished pages behind/ahead of the synced recovered store position and refuses a stale completion header. Omitting the unfinished-page position check fails the acknowledged-write control. Daemon upgrade caller remains unwired. SlotFence reopen after an old writer erases the marker witness core/storage/walstore_v3.go:openWALStoreV3File; core/storage/chunk_state_upgrade.go:WALStore.FenceChunkStateUpgrade core/storage/chunk_state_upgrade_test.go:TestChunkStateUpgradeOldReaderPublicationRestartsTheFence STUB Captured legacy descriptor bytes simulate the old metadata publication; no released binary execution claimed. Caller must rebuild legacy-derived pages before completing again. From d2a79d43f2e0135ec5e067c39c635c018076c378 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 30 Nov 2026 06:51:02 -0800 Subject: [PATCH 17/17] fix: freshly sync reopened upgrade fences and cover payload checks --- .../core/storage/chunk_record_test.go | 38 +++++++ .../core/storage/chunk_state_upgrade.go | 20 +++- .../core/storage/chunk_state_upgrade_test.go | 103 ++++++++++++++++++ seaweed-block/docs/design/invariants.md | 3 +- .../design/model-code-trace-slot-fence.tsv | 4 +- 5 files changed, 163 insertions(+), 5 deletions(-) diff --git a/seaweed-block/core/storage/chunk_record_test.go b/seaweed-block/core/storage/chunk_record_test.go index fd251732de..0a8b776eb6 100644 --- a/seaweed-block/core/storage/chunk_record_test.go +++ b/seaweed-block/core/storage/chunk_record_test.go @@ -2,8 +2,10 @@ package storage import ( "errors" + "fmt" "os" "path/filepath" + "reflect" "strings" "testing" ) @@ -338,3 +340,39 @@ func TestRecordHeaderIsNotWrittenAheadOfTheSyncedStore(t *testing.T) { t.Fatalf("header exists ahead of the synced store: %v", err) } } + +func TestRecordEntryPayloadRoundTripsAcrossSegments(t *testing.T) { + const chunks = uint64(chunkRecordSegment + 2) + dir := filepath.Join(t.TempDir(), "record") + expected := map[uint64]*chunkRecordPage{} + for seg := uint64(0); seg < chunkRecordSegments(chunks); seg++ { + p := &chunkRecordPage{Segment: seg, ValidThrough: 17, PublishedSegment: fmt.Sprintf("segment-%d", seg), Entries: make([]chunkRecordEntry, chunkRecordSegmentLen(chunks, seg))} + for i := range p.Entries { + index := seg*chunkRecordSegment + uint64(i) + p.Entries[i].State = uint8(index % 5) + for j := range p.Entries[i].Hash { + p.Entries[i].Hash[j] = byte(index*37 + uint64(j)*13 + index/251) + } + } + p.Candidates = uint32(len(p.Entries)) + expected[seg] = p + if err := writeChunkRecordPage(dir, p); err != nil { + t.Fatal(err) + } + } + if err := writeChunkRecordFile(dir, chunkRecordHeaderName, encodeChunkRecordHeader(chunkRecordHeader{Epoch: 7, Chunks: chunks, G: 17})); err != nil { + t.Fatal(err) + } + got, err := loadChunkRecord(dir, chunks, true, 7, 17) + if err != nil || !got.Complete || len(got.Damaged) != 0 { + t.Fatalf("load: %+v %v", got, err) + } + if !reflect.DeepEqual(got.Pages, expected) { + t.Fatal("entry state/hash or segment payload changed during persisted round trip") + } + // Explicitly keep the two neighboring entries at the segment boundary distinct. + left, right := got.Pages[0].Entries[chunkRecordSegment-1], got.Pages[1].Entries[0] + if left == right { + t.Fatal("boundary fixture did not distinguish adjacent entries") + } +} diff --git a/seaweed-block/core/storage/chunk_state_upgrade.go b/seaweed-block/core/storage/chunk_state_upgrade.go index 509dafe429..1435102dfb 100644 --- a/seaweed-block/core/storage/chunk_state_upgrade.go +++ b/seaweed-block/core/storage/chunk_state_upgrade.go @@ -8,11 +8,13 @@ import ( // FenceChunkStateUpgrade is the store's completion boundary for the chunk-state // format upgrade. The caller must persist the new bitmap and record pages first. // Success means BOTH descriptor slots carry the format marker and local-work -// epoch, each published through the store's fsync leaf and read back. Only then +// epoch, confirmed through the store's fsync leaf and read back. Only then // may the caller write the complete record header or remove legacy presence. // // A failed publication/readback latches the store until reopen. A retry after -// reopen completes a half fence. Before completion the legacy presence and its +// reopen completes a half fence. An already-matching pair is freshly synced: +// process reopen may retain bytes from an earlier failed sync in the OS cache. +// Before completion the legacy presence and its // WAL dependencies must remain intact, and no acknowledgement may depend only // on the new bitmap. This method changes neither the WAL bounds nor map roots. func (s *WALStore) FenceChunkStateUpgrade(epoch uint64) error { @@ -52,6 +54,7 @@ func (s *WALStore) FenceChunkStateUpgrade(epoch uint64) error { if p.io.readSlot == nil { return errors.New("storage: chunk-state upgrade has no descriptor reader") } + published := false for !chunkStateSlotMatches(p.cur, epoch) || !p.otherValid || !chunkStateSlotMatches(p.other, epoch) { if _, err := p.publishLockedCoreV3(func(n *descriptorV3) error { n.ChunkStateFormat, n.LocalWorkEpoch = 1, epoch @@ -59,6 +62,19 @@ func (s *WALStore) FenceChunkStateUpgrade(epoch uint64) error { }, nil, false); err != nil { return err } + published = true + } + if !published { + // Reading matching slots after process reopen proves only their bytes, + // not the durability of a previous failed publication. Confirm the pair + // through the same serialized file-sync leaf without changing its fields. + if err := p.io.syncFile(func() error { return nil }, p.io.fsync); err != nil { + p.failed = fmt.Errorf("%w: upgrade pair confirmation: %w", ErrDescriptorPublishUncertain, err) + if p.io.latch != nil { + p.io.latch(p.failed) + } + return p.failed + } } // The descriptor lock excludes other publications across both observations. for _, off := range []int64{slotAOffsetV3, slotBOffsetV3} { diff --git a/seaweed-block/core/storage/chunk_state_upgrade_test.go b/seaweed-block/core/storage/chunk_state_upgrade_test.go index 5acd4ad299..ae1ab77693 100644 --- a/seaweed-block/core/storage/chunk_state_upgrade_test.go +++ b/seaweed-block/core/storage/chunk_state_upgrade_test.go @@ -3,6 +3,7 @@ package storage import ( "encoding/binary" "errors" + "fmt" "hash/crc32" "os" "testing" @@ -208,3 +209,105 @@ func TestChunkStateUpgradeOldReaderPublicationRestartsTheFence(t *testing.T) { t.Fatalf("erased marker did not restart both-slot fence: %d writes", writes) } } + +func TestChunkStateUpgradeReopenedCachedPairNeedsFreshSync(t *testing.T) { + s, path := newMappedCheckpointStoreV3(t) + originalSync := s.v3.pub.io.fsync + syncs := 0 + s.v3.pub.io.fsync = func() error { + syncs++ + if syncs == 2 { + return errors.New("second sync did not confirm persistence") + } + return originalSync() + } + if err := s.FenceChunkStateUpgrade(7); !errors.Is(err, ErrDescriptorPublishUncertain) { + t.Fatalf("second-sync failure completed: %v", err) + } + crashStore(t, s) // process-only close; deliberately retain the OS cache + next, err := openWALStoreV3MapInternalForTest(path, true) + if err != nil { + t.Fatal(err) + } + next.DisableAutoFlushForRecoveryTest() + t.Cleanup(func() { next.Close() }) + p := next.v3.pub + if !p.otherValid || !chunkStateSlotMatches(p.cur, 7) || !chunkStateSlotMatches(p.other, 7) { + t.Fatal("control did not retain both newly written slot images") + } + calls := 0 + realSync := p.io.fsync + p.io.fsync = func() error { calls++; return errors.New("fresh confirmation failed") } + if err := next.FenceChunkStateUpgrade(7); !errors.Is(err, ErrDescriptorPublishUncertain) || calls != 1 { + t.Fatalf("cached reopened pair completed without a fresh sync: calls=%d err=%v", calls, err) + } + p.io.fsync = realSync + if err := next.FenceChunkStateUpgrade(7); !errors.Is(err, ErrDescriptorPublishUncertain) { + t.Fatalf("failed fresh confirmation was not latched: %v", err) + } + crashStore(t, next) + final, err := openWALStoreV3MapInternalForTest(path, true) + if err != nil { + t.Fatal(err) + } + final.DisableAutoFlushForRecoveryTest() + t.Cleanup(func() { final.Close() }) + calls = 0 + original := final.v3.pub.io.fsync + final.v3.pub.io.fsync = func() error { calls++; return original() } + before := final.v3.pub.current().SlotGen + if err := final.FenceChunkStateUpgrade(7); err != nil || calls != 1 { + t.Fatalf("fresh confirmation did not complete: calls=%d err=%v", calls, err) + } + if final.v3.pub.current().SlotGen != before { + t.Fatal("confirmation changed descriptor generation") + } +} + +func TestChunkStateUpgradeRejectsSuccessfulWrongReadback(t *testing.T) { + for _, point := range []string{"corrupt-checksum", "wrong-marker", "wrong-epoch", "unequal-valid-descriptor"} { + for _, slot := range []int64{slotAOffsetV3, slotBOffsetV3} { + t.Run(fmt.Sprintf("%s/slot-%d", point, slot), func(t *testing.T) { + s, _ := newMappedCheckpointStoreV3(t) + read := s.v3.pub.io.readSlot + s.v3.pub.io.readSlot = func(off int64, b []byte) error { + if err := read(off, b); err != nil { + return err + } + if off != slot { + return nil + } + if point == "corrupt-checksum" { + b[slotCRCOffsetV3] ^= 1 + return nil + } + d, err := decodeSlotV3(b, s.v3.pub.accept) + if err != nil { + t.Fatal(err) + } + switch point { + case "wrong-marker": + d.ChunkStateFormat, d.LocalWorkEpoch = 0, 0 + case "wrong-epoch": + d.LocalWorkEpoch++ + case "unequal-valid-descriptor": + d.SlotGen++ + } + raw := d.encode() + if _, err := decodeSlotV3(raw, s.v3.pub.accept); err != nil { + t.Fatalf("wrong-content control must be valid: %v", err) + } + copy(b, raw) + return nil + } + if err := s.FenceChunkStateUpgrade(7); !errors.Is(err, ErrDescriptorPublishUncertain) { + t.Fatalf("successful wrong readback completed: %v", err) + } + s.v3.pub.io.readSlot = read + if err := s.FenceChunkStateUpgrade(7); !errors.Is(err, ErrDescriptorPublishUncertain) { + t.Fatalf("wrong readback did not latch: %v", err) + } + }) + } + } +} diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 64c084fcad..9501b8829e 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -611,10 +611,11 @@ The "Machine / transition" column refers to Part A. Notes under a table record w | `INV-WAL-V3-WRITE-AHEAD-001` | No extent byte reaches the disk before its WAL record is durable: the flusher writes an extent only from dirty entries at or below the synced (acknowledged) WAL frontier; Recover and the install log fsync their records before raising it. | M1 Serving (flusher extent write) | `core/storage/flusher.go` `flushOnceInternal`; `walstore_v3.go` `recoverV3` (descriptor publish fsync before `wack`); `install_log_v3.go` | `TestRedCrashKeepingAnUnsyncedExtentWriteLeavesLocalAndHEADApart` (`core/storage/chunk_u1_reorder_test.go`); `TestFlusherWriteAheadNeverFlushingGuestReachesExtentAtPressure` (`core/storage/flusher_write_ahead_test.go`) | A checkpoint may pass a synced record superseded by an unsynced newer one only because the cycle's sync covers the whole file, WAL included (one file, one descriptor: `INV-WAL-FLUSH-SYNC-COVERS-WAL-001`); separating WAL and extent, or a range sync, must first change the checkpoint bound | ACTIVE | | `INV-WAL-V3-CAPTURE-CANDIDATES-001` | A retained WAL entry already covered by HEAD is not dirt since HEAD. New post-HEAD WAL entries, UNKNOWN map chunks and map max-LSN above HEAD remain capture candidates, except as `INV-WAL-V3-CAPTURE-COMPARED-001`. | M5 candidate selection | `chunk_layer.go` `captureCandidates` | `TestChunkLayerV3CapturedUncheckpointedWALIsCleanUntilRewritten`, `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, `TestBaseInstallV3CompletePersistsTheMapUnknownOfBaseWrites` | Conservative reachability unchanged; narrower redundant work | ACTIVE | | `INV-WAL-V3-CAPTURE-COMPARED-001` | A chunk known equal to HEAD is neither staged nor compared again while its mutation version and HEAD ref match; own-batch chunks remain candidates. An interrupted or refused cut retains these proofs and requeues only unproven chunks. All candidate paths use one predicate. | M5 candidate selection | `core/storage/chunk_layer.go` `knownEqualToHeadLocked`, `captureCandidates`, `captureLocked`, `recordCapturedEqualMarks`, `stage`, `requeueCut`; `chunk_cut_payload.go` `markEqualNow` | `TestFreshFromHeadReadBackLeavesNoCutCandidates`, `TestFreshFromHeadFilledThenWrittenIsACandidate`, `TestEveryLocalWriteAfterACleanFillMakesTheChunkACandidate`, `TestABaseInstallAfterCleanFillsEndsTheirRecords`, `TestACleanFillRecordEndsWithItsHeadRef`, `TestARestoreTargetThatOnlyReadCutsNothing`, `TestARerunAfterAFailedCutComparesOnlyWhatDiffers`, `TestWithoutAFailedCutEveryUnknownChunkIsCompared`, `TestACutOffCompareKeepsItsWorkAndTheRerunComparesOnlyTheRest`, `TestFilledChunksAreFirstCutCandidatesAfterARestart`, `TestEveryDirtyMapInsertNotesTheChunkMutation`, `TestOwnBatch_BoundedBatchesReplaceEveryForeignKey`; `TestRefusedFullCutStagesOnlyTheUnmarkedChunk` (`core/storage/chunk_staging_equal_test.go`); `TestCopyErrorKeepsCapturedEqualMarks`, `TestInterruptedStagingKeepsEqualWork` (`core/storage/chunk_copy_error_equal_test.go`); `TestTimedOutRequestsThenRefusedCommitKeepEqualWork` (`core/frontend/chunkstore/layout_staging_retry_test.go`); also in `core/storage/chunk_fresh_readback_candidates_test.go`, `core/frontend/durable/first_cut_known_zero_test.go`, `core/storage/chunk_compare_progress_test.go`, `core/storage/chunk_mutation_note_guard_test.go`, `core/storage/chunk_own_test.go` | EqualMarks.MarkSound, EqualMarks.NoRecompare (must-violate rows 102-104); conservative reachability unchanged | ACTIVE | -| `INV-CHUNK-STATE-UPGRADE-FENCE-001` | The chunk-state upgrade fence succeeds only after both descriptor slots are fsynced and read back with the format marker and local-work epoch; uncertain writes or readback latch the store until reopen. | M1 format upgrade (caller not wired) | `core/storage/chunk_state_upgrade.go` `WALStore.FenceChunkStateUpgrade` | `TestChunkStateUpgradeFencesBothSlotsBeforeCompletion`, `TestChunkStateUpgradeUncertainSecondSlotRequiresReopen`, `TestChunkStateUpgradeFailureNeverCompletesUntilReopen`, `TestChunkStateUpgradeOldReaderPublicationRestartsTheFence` (`core/storage/chunk_state_upgrade_test.go`; single-publication and unlatched-readback mutant controls) | `CHUNK-STATE-r3` section 18; `SlotFence` rows 146-149 | STUB | +| `INV-CHUNK-STATE-UPGRADE-FENCE-001` | The chunk-state upgrade fence succeeds only after both descriptor slots are fsynced and read back with the format marker and local-work epoch; matching reopened slots require a fresh sync; uncertain writes or readback latch until reopen. | M1 format upgrade (caller not wired) | `core/storage/chunk_state_upgrade.go` `WALStore.FenceChunkStateUpgrade` | `TestChunkStateUpgradeFencesBothSlotsBeforeCompletion`, `TestChunkStateUpgradeUncertainSecondSlotRequiresReopen`, `TestChunkStateUpgradeFailureNeverCompletesUntilReopen`, `TestChunkStateUpgradeOldReaderPublicationRestartsTheFence`, `TestChunkStateUpgradeReopenedCachedPairNeedsFreshSync`, `TestChunkStateUpgradeRejectsSuccessfulWrongReadback` (`core/storage/chunk_state_upgrade_test.go`; single-publication and unlatched-readback mutant controls) | `CHUNK-STATE-r3` section 18; `SlotFence` rows 146-149 | STUB | | `INV-WAL-V3-DESCRIPTOR-001` | A v3 descriptor slot is used only if it is valid: a matching CRC32C (Castagnoli), every reserved byte zero, an accepted impl, a nonzero slotGen at most 2^64-2, a nonzero nonce, and geometry consistent under checked arithmetic. | M1 Opened (v3 descriptor selection) | `core/storage/superblock_v3.go` `decodeSlotV3`, `descriptorV3.validate`, `checkedAddV3` | `TestSlotV3VectorsDecodeAsExpected`, `TestSlotV3CounterExhaustion` (`core/storage/superblock_v3_test.go`) | — | STUB | | `INV-WAL-V3-DESCRIPTOR-BASE-001` | A valid v3 descriptor slot has CheckpointLSN ≤ mapCoveredCheckpoint ≤ W, and BASE fields that follow the rules of its BASE state. | M1 Opened (v3 descriptor selection) | `core/storage/superblock_v3.go` `descriptorV3.validate` | `TestSlotV3VectorsDecodeAsExpected`, `TestSlotV3InstalledMayHaveCursorBelowTail` (`core/storage/superblock_v3_test.go`) | — | STUB | | `INV-CHUNK-RECORD-PAGES-CURRENT-001` | An unfinished chunk record is used, and its header written, only when every page passes its check and is valid through exactly the store's synced position after recovery (behind: missed writes; ahead: not durable); an unmarked store discards it; the header follows the two-slot fence. | M1 Opened (chunk record load, v1.1 upgrade) | `core/storage/chunk_record.go` `loadChunkRecord`, `completeChunkRecord` | `TestUnfinishedRecordPagesBehindTheStoreAreNotTrusted`, `TestUnfinishedRecordAfterAnOldCheckpointIsDiscarded`, `TestStalePagesAreNeverCompleted`, `TestUnfinishedPagesAheadOfTheStoreAreNotTrusted`, `TestCompleteRecordAheadOfTheStoreIsNotTrusted`, `TestCompleteRecordPagePositions`, `TestRecordHeaderWaitsForTheFence`, `TestRecordHeaderIsNotWrittenAheadOfTheSyncedStore`, `TestDamagedPage` (`core/storage/chunk_record_test.go`) | SlotFence `PagesCurrent`, `FenceHolds`; pages carry chunk-kernel/2 states (the per-chunk state models are not in this repository) | STUB | +| `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-WAL-V3-DESCRIPTOR-SELECT-001` | Of the two v3 descriptor slots, open selects the valid selectable slot with the higher slotGen, and never a prepared migration slot. | M1 Opened (v3 descriptor selection) | `core/storage/superblock_v3.go` `selectSlotV3` | `TestSlotV3Selection` (`core/storage/superblock_v3_test.go`); `TestWALStoreV3CloseKeepsTheNewestSlotAAndItsW` (`core/storage/walstore_close_v3_test.go`) | — | ACTIVE | | `INV-WAL-V3-DESCRIPTOR-CONFLICT-001` | Open is refused when both v3 descriptor slots are valid but carry the same slotGen with different bytes, or disagree on the UUID or the geometry. | M1 Opened (v3 descriptor selection) | `core/storage/superblock_v3.go` `selectSlotV3`, `sameGeometryV3` | `TestSlotV3Selection` (`core/storage/superblock_v3_test.go`) | — | ACTIVE | | `INV-WAL-V3-RECORD-001` | An impl-3 WAL record has a fixed 62-byte prefix, 70 bytes of overhead in all, a CRC32C (Castagnoli) and an explicit EntrySize. | M1 v3 record framing | `core/storage/wal_entry_v3.go` `encodeWALEntryV3`, `payloadSizeV3` | `TestWALEntryV3_CanonicalBarrierBytes`, `TestWALEntryV3_TypeFootprints` | `WALRecovery` abstract record validity; physical byte rules are code-test obligations | ACTIVE | diff --git a/seaweed-block/docs/design/model-code-trace-slot-fence.tsv b/seaweed-block/docs/design/model-code-trace-slot-fence.tsv index 5b4663a6c9..c90c2f9fe3 100644 --- a/seaweed-block/docs/design/model-code-trace-slot-fence.tsv +++ b/seaweed-block/docs/design/model-code-trace-slot-fence.tsv @@ -1,6 +1,6 @@ model item kind go_function tests status note -SlotFence 146: both marked slots before completion rule core/storage/chunk_state_upgrade.go:WALStore.FenceChunkStateUpgrade; core/storage/chunk_record.go:completeChunkRecord core/storage/chunk_state_upgrade_test.go:TestChunkStateUpgradeFencesBothSlotsBeforeCompletion,core/storage/chunk_state_upgrade_test.go:TestChunkStateUpgradeUncertainSecondSlotRequiresReopen; core/storage/chunk_record_test.go:TestRecordHeaderWaitsForTheFence STUB Store completion boundary precedes the record header; daemon upgrade caller remains unwired. Single-publication mutant fails. -SlotFence 147: count a slot only after sync and readback rule core/storage/descriptor_v3.go:descriptorPublisherV3.publishLockedCoreV3; core/storage/chunk_state_upgrade.go:WALStore.FenceChunkStateUpgrade core/storage/chunk_state_upgrade_test.go:TestChunkStateUpgradeFailureNeverCompletesUntilReopen STUB Six injected write/sync/readback failures refuse completion and latch until reopen; unlatched-readback mutant fails. +SlotFence 146: both marked slots before completion rule core/storage/chunk_state_upgrade.go:WALStore.FenceChunkStateUpgrade; core/storage/chunk_record.go:completeChunkRecord core/storage/chunk_state_upgrade_test.go:TestChunkStateUpgradeFencesBothSlotsBeforeCompletion,core/storage/chunk_state_upgrade_test.go:TestChunkStateUpgradeUncertainSecondSlotRequiresReopen; core/storage/chunk_state_upgrade_test.go:TestChunkStateUpgradeReopenedCachedPairNeedsFreshSync; core/storage/chunk_record_test.go:TestRecordHeaderWaitsForTheFence STUB Store completion boundary precedes the record header; matching reopened pairs require a fresh serialized sync. Daemon upgrade caller remains unwired. Single-publication mutant fails. +SlotFence 147: count a slot only after sync and readback rule core/storage/descriptor_v3.go:descriptorPublisherV3.publishLockedCoreV3; core/storage/chunk_state_upgrade.go:WALStore.FenceChunkStateUpgrade core/storage/chunk_state_upgrade_test.go:TestChunkStateUpgradeFailureNeverCompletesUntilReopen; core/storage/chunk_state_upgrade_test.go:TestChunkStateUpgradeRejectsSuccessfulWrongReadback STUB Write/sync/readback failures and successful wrong-content readbacks latch until reopen; corrupt checksum and valid-but-unequal descriptor mutants fail. SlotFence 148: preserve the minimum decoded-slot WAL tail premise core/storage/descriptor_v3.go:descriptorPublisherV3.reuseFloorLocked; core/storage/wal_io_v3.go:walWriterV3.append core/storage/descriptor_v3_test.go:TestDescriptorV3FullRingRolloverAdvancesTheFloorWithoutAnyChange; core/storage/chunk_state_upgrade_test.go:TestChunkStateUpgradeUncertainSecondSlotRequiresReopen CONFIRMED Existing writer uses the minimum retained tail of both decoded slots; half-upgrade boundary changes no WAL bounds. SlotFence 149: reject cached pages behind store positions integration core/storage/chunk_record.go:loadChunkRecord; core/storage/chunk_record.go:completeChunkRecord core/storage/chunk_record_test.go:TestUnfinishedRecordPagesBehindTheStoreAreNotTrusted; core/storage/chunk_record_test.go:TestUnfinishedRecordAfterAnOldCheckpointIsDiscarded; core/storage/chunk_record_test.go:TestStalePagesAreNeverCompleted; core/storage/chunk_record_test.go:TestUnfinishedPagesAheadOfTheStoreAreNotTrusted; core/storage/chunk_record_test.go:TestRecordHeaderIsNotWrittenAheadOfTheSyncedStore STUB Record component rejects unfinished pages behind/ahead of the synced recovered store position and refuses a stale completion header. Omitting the unfinished-page position check fails the acknowledged-write control. Daemon upgrade caller remains unwired. SlotFence reopen after an old writer erases the marker witness core/storage/walstore_v3.go:openWALStoreV3File; core/storage/chunk_state_upgrade.go:WALStore.FenceChunkStateUpgrade core/storage/chunk_state_upgrade_test.go:TestChunkStateUpgradeOldReaderPublicationRestartsTheFence STUB Captured legacy descriptor bytes simulate the old metadata publication; no released binary execution claimed. Caller must rebuild legacy-derived pages before completing again.