From d6d4e48229899a2926d4ef38dd2f0b4c87d27b9e Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 30 Nov 2026 08:46:04 -0800 Subject: [PATCH] test(storage): the upgrade's exact bitmap, crash points and complete retry The bitmap is pinned block by block (the file's local block, a single and a batch log suffix, their non-local neighbours). The crash before the fence is the injected one at the first slot write, with the pages complete, no header and the presence file there at that point; a crash after the fence and before the header completes on reopen; a retry over a complete record writes no page, no header and no descriptor slot (file identity checked). Co-Authored-By: Claude Opus 5.5 --- .../core/storage/chunk_record_upgrade_test.go | 149 ++++++++++++++++-- seaweed-block/docs/design/invariants.md | 2 +- 2 files changed, 139 insertions(+), 12 deletions(-) diff --git a/seaweed-block/core/storage/chunk_record_upgrade_test.go b/seaweed-block/core/storage/chunk_record_upgrade_test.go index 70b24ab03f..159bb14058 100644 --- a/seaweed-block/core/storage/chunk_record_upgrade_test.go +++ b/seaweed-block/core/storage/chunk_record_upgrade_test.go @@ -10,9 +10,10 @@ import ( ) // legacyVolume builds a v1.0.x volume: 64 blocks of 4 in 16 chunks. Chunks -// 2, 3 and 5 are absent in the presence file; chunk 2 has its block 9 local -// there; chunk 3 gets block 13 from a log entry not yet applied to the extent -// (above the checkpoint). Every other chunk is present. +// 2, 3 and 5 are absent in the presence file; chunk 2 has its block 9 (offset +// 1) local there; chunk 3 gets block 13 from one log entry and blocks 14 and +// 15 from a batch, none applied to the extent (above the checkpoint); its +// block 12 is not local. Every other chunk is present. func legacyVolume(t *testing.T) string { t.Helper() s, path := newMappedCheckpointStoreV3(t) @@ -25,6 +26,12 @@ func legacyVolume(t *testing.T) string { t.Fatal(err) } writeSynced(t, s, 13, 13) // in the log only + if _, err := s.WriteBatch(14, [][]byte{blk(14), blk(15)}); err != nil { + t.Fatal(err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } crashStore(t, s) return path } @@ -64,8 +71,38 @@ func recordKinds(t *testing.T, s *WALStore) []chunkkernel.Kind { return kinds } +// wantLocal is each absent chunk's exact local offsets; every other chunk is +// wholly local. +var wantLocal = map[uint64][]uint64{2: {1}, 3: {1, 2, 3}, 5: nil} + +// checkLocalBits pins the store's bitmap block by block. +func checkLocalBits(t *testing.T, s *WALStore) { + t.Helper() + s.mu.RLock() + defer s.mu.RUnlock() + for c := uint64(0); c < 16; c++ { + e := s.v3.mapEntries[c] + if e.Local == nil { + t.Fatalf("chunk %d has no bitmap", c) + } + want, absent := wantLocal[c] + for b := uint64(0); b < 4; b++ { + local := !absent + for _, w := range want { + if w == b { + local = true + } + } + if got := e.Local.all || e.Local.has(b); got != local { + t.Fatalf("chunk %d block %d local=%v, want %v", c, b, got, local) + } + } + } +} + func checkUpgradedKinds(t *testing.T, s *WALStore) { t.Helper() + checkLocalBits(t, s) kinds := recordKinds(t, s) want := map[int]chunkkernel.Kind{2: chunkkernel.Partial, 3: chunkkernel.Partial, 5: chunkkernel.Absent} for c, k := range kinds { @@ -97,21 +134,33 @@ func TestUpgradeChunkRecordFromLegacyPresence(t *testing.T) { } } -// A crash before the store's fence: the record is not used, the presence file -// is still there, and the next open upgrades again. +// A crash before the store's fence, at its first descriptor slot write: the +// pages are complete, the header absent, the presence file there; the next +// open upgrades again. func TestUpgradeChunkRecordCrashBeforeTheFence(t *testing.T) { path := legacyVolume(t) s := openForUpgrade(t, path) + crash := errors.New("crash before the descriptor slots") writes := 0 s.v3.testBeforeSlotWrite = func() error { writes++ - return errors.New("crash before the descriptor slots") + pages, bad, err := readChunkRecordPages(chunkRecordDir(path), 16) + if err != nil || len(bad) != 0 || len(pages) != 1 || len(pages[0].Entries) != 16 { + t.Errorf("at the first slot write the pages are not complete: %v %v", bad, err) + } + if _, err := os.Stat(chunkRecordDir(path) + "/" + chunkRecordHeaderName); !errors.Is(err, os.ErrNotExist) { + t.Errorf("header before the fence: %v", err) + } + if _, err := os.Stat(chunkPresencePath(path)); err != nil { + t.Errorf("presence gone before the fence: %v", err) + } + return crash } - if err := upgradeChunkRecord(context.Background(), s, 7); err == nil { - t.Fatal("the upgrade completed without its fence") + if err := upgradeChunkRecord(context.Background(), s, 7); !errors.Is(err, crash) { + t.Fatalf("the upgrade answered %v, want the injected crash", err) } - if _, err := os.Stat(chunkPresencePath(path)); err != nil { - t.Fatalf("presence removed before the fence: %v", err) + if writes != 1 { + t.Fatalf("slot writes %d, want the first one only", writes) } crashStore(t, s) next := openForUpgrade(t, path) @@ -121,8 +170,45 @@ func TestUpgradeChunkRecordCrashBeforeTheFence(t *testing.T) { checkUpgradedKinds(t, next) } +// A crash after the fence and before the header: both slots marked, no +// header, the presence file there; the next open completes from the store's +// bitmap. +func TestUpgradeChunkRecordCrashAfterTheFence(t *testing.T) { + path := legacyVolume(t) + s := openForUpgrade(t, path) + header := chunkRecordDir(path) + "/" + chunkRecordHeaderName + if err := os.MkdirAll(header, 0o755); err != nil { // the header's write fails + t.Fatal(err) + } + if err := upgradeChunkRecord(context.Background(), s, 7); err == nil { + t.Fatal("the control needs a failed header write") + } + for _, off := range []int64{slotAOffsetV3, slotBOffsetV3} { + raw := make([]byte, slotSizeV3) + if _, err := s.fd.ReadAt(raw, off); err != nil { + t.Fatal(err) + } + if d, err := decodeSlotV3(raw, nil); err != nil || d.ChunkStateFormat != 1 || d.LocalWorkEpoch != 7 { + t.Fatalf("slot %d not fenced before the header: %+v %v", off, d, err) + } + } + if _, err := os.Stat(chunkPresencePath(path)); err != nil { + t.Fatalf("presence gone before the header: %v", err) + } + crashStore(t, s) + if err := os.Remove(header); err != nil { + t.Fatal(err) + } + next := openForUpgrade(t, path) + if err := upgradeChunkRecord(context.Background(), next, 7); err != nil { + t.Fatal(err) + } + checkUpgradedKinds(t, next) +} + // A crash after the header and before the presence file is removed: the next -// open finds the record complete and only removes the file. +// open finds the record complete and only removes the file: no page, no +// header and no descriptor slot is written. func TestUpgradeChunkRecordCrashAfterTheHeader(t *testing.T) { path := legacyVolume(t) s := openForUpgrade(t, path) @@ -133,10 +219,51 @@ func TestUpgradeChunkRecordCrashAfterTheHeader(t *testing.T) { if err := os.WriteFile(chunkPresencePath(path), []byte("absent 2\n"), 0o644); err != nil { t.Fatal(err) // as if the removal had not happened } + type recordFile struct { + bytes string + info os.FileInfo + } + snapshot := func() map[string]recordFile { + out := map[string]recordFile{} + ents, err := os.ReadDir(chunkRecordDir(path)) + if err != nil { + t.Fatal(err) + } + for _, e := range ents { + name := chunkRecordDir(path) + "/" + e.Name() + b, err := os.ReadFile(name) + if err != nil { + t.Fatal(err) + } + info, err := os.Stat(name) + if err != nil { + t.Fatal(err) + } + _ = os.SameFile(info, info) // load the file's identity now, not at comparison + out[e.Name()] = recordFile{string(b), info} + } + return out + } + before := snapshot() next := openForUpgrade(t, path) + gen := next.v3.pub.current().SlotGen + next.v3.testBeforeSlotWrite = func() error { return errors.New("no publication on a complete record") } if err := upgradeChunkRecord(context.Background(), next, 7); err != nil { t.Fatal(err) } + if next.v3.pub.current().SlotGen != gen { + t.Fatal("a descriptor slot was published on a complete record") + } + after := snapshot() + if len(after) != len(before) { + t.Fatalf("record files %d -> %d", len(before), len(after)) + } + for name, b := range before { + a := after[name] + if a.bytes != b.bytes || !os.SameFile(a.info, b.info) || !a.info.ModTime().Equal(b.info.ModTime()) { + t.Fatalf("record file %s rewritten on a complete record", name) + } + } checkUpgradedKinds(t, next) } diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index ee8096fedc..b1ba096fef 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -616,7 +616,7 @@ The "Machine / transition" column refers to Part A. Notes under a table record w | `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-UPGRADE-001` | The v1.0.x upgrade seeds the bitmap from the presence file only on an unmarked store; marked at this epoch it rebuilds pages from the store's bitmap, at another epoch it refuses; pages precede the fence, the header follows it, the presence file goes last. | M1 Opened (v1.1 upgrade at open) | `core/storage/chunk_record_upgrade.go` `upgradeChunkRecord`, `writeChunkRecordPagesFrom` | `TestUpgradeChunkRecordFromLegacyPresence`, `TestUpgradeChunkRecordCrashBeforeTheFence`, `TestUpgradeChunkRecordCrashAfterTheHeader`, `TestUpgradeChunkRecordAfterTheMarkerIgnoresThePresenceFile`, `TestUpgradeChunkRecordAtAnotherEpochIsRefused` (`core/storage/chunk_record_upgrade_test.go`) | UpgradeWide3 (pages, field, header, presence removed); ChunkUpgrade row 118; chunk-kernel/2 `Rebuilt` (the per-chunk state models are not in this repository) | STUB | +| `INV-CHUNK-RECORD-UPGRADE-001` | The v1.0.x upgrade seeds the bitmap from the presence file only on an unmarked store; marked at this epoch it rebuilds pages from the store's bitmap, at another epoch it refuses; pages precede the fence, the header follows it, the presence file goes last. | M1 Opened (v1.1 upgrade at open) | `core/storage/chunk_record_upgrade.go` `upgradeChunkRecord`, `writeChunkRecordPagesFrom` | `TestUpgradeChunkRecordFromLegacyPresence`, `TestUpgradeChunkRecordCrashBeforeTheFence`, `TestUpgradeChunkRecordCrashAfterTheFence`, `TestUpgradeChunkRecordCrashAfterTheHeader`, `TestUpgradeChunkRecordAfterTheMarkerIgnoresThePresenceFile`, `TestUpgradeChunkRecordAtAnotherEpochIsRefused` (`core/storage/chunk_record_upgrade_test.go`) | UpgradeWide3 (pages, field, header, presence removed); ChunkUpgrade row 118; chunk-kernel/2 `Rebuilt` (the per-chunk state models are not in this repository) | STUB | | `INV-CHUNK-UPGRADE-PASS-CURSOR-001` | Upgrade pass: rewinds only at open, before Run; a failed rewind latches it until reopen; the persisted cursor is only ever min(earliest unpublished rewind, last written-through position); a restart resumes there; while it runs, a request needing every hash answers in_progress. | M1 Opened (v1.1 upgrade compare pass) | `core/storage/chunk_upgrade_pass.go` `upgradePass.Run`, `advance`, `Rewind`, `Admit` | `TestUpgradePassCursorFollowsThePagesBehindIt`, `TestUpgradePassRestartContinuesAtTheCursor`, `TestUpgradePassRefusesWithProgress`, `TestUpgradePassRewindAtOpenAfterARebuiltPage`, `TestUpgradePassPauseAndHurry`, `TestUpgradePassFailedRewindLatchesUntilReopen`, `TestUpgradePassRewindOnlyBeforeRun`, `TestUpgradePassKeepsItsCountAcrossRuns`, `TestUpgradePassCursorRuleUnderInterleavings` (`core/storage/chunk_upgrade_pass_test.go`) | UpgradePass `BehindCursorKnown`, `NoWorkTwice`; UpgradeWide3 rows 119 to 124, rewinds at restart only (the per-chunk state models are not in this repository) | STUB | | `INV-CHUNK-RECORD-RUNTIME-001` | While serving: state only via the kernel, a known hash only with its evidence; a page dirties only when a state or hash changes, is written by its own count or age, an evict's at once, in snapshot order; header G = min(applied, dirty pages' dirty-from). | M3 Serving (chunk record runtime) | `core/storage/chunk_record_runtime.go` `chunkRecordRuntime.Apply`, `Due`, `WriteDue`, `WriteThrough`, `Flush` | `TestRecordRuntimeAppliesTheKernel`, `TestRecordRuntimeEvictWritesThePageFirst`, `TestRecordRuntimeSchedulePerPage`, `TestRecordRuntimeFlushIsLoadedBack`, `TestRecordRuntimeWriteThrough`, `TestRecordRuntimeAnUnchangedStateWritesNothing`, `TestRecordRuntimeHeaderMovesUnderWrites`, `TestRecordRuntimeEvictDuringAFlushLandsLast`, `TestRecordRuntimePageWritesFollowChangesNotSize`, `TestRecordRuntimePageWritersPublishInOrder`, `TestRecordRuntimeHashEvidence`, `TestRecordRuntimeCopiesItsInputs`, `TestRecordRuntimeAPageChangedAtOpenHoldsG` (`core/storage/chunk_record_runtime_test.go`) | chunk-kernel/2; ChunkPages rule 1 (pages before the header) and rule 3 (an evict writes its page first) (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 |