From 1210ce60c7976dc37aaa3b5cdca685eb630ea5e9 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 30 Nov 2026 08:33:15 -0800 Subject: [PATCH 1/5] storage: upgrade a v1.0.x volume's chunk state at open After Recover, with extent draining held and before the chunk layer attaches: seed the store's bitmap from the presence file (present chunks whole; absent chunks with the file's local blocks and those of log entries not yet applied), write the record's pages from the prepared coverage with each chunk classified by the kernel's Rebuilt event, let the store publish the bitmap and fence both slots, write the header, remove the presence file. Each step repeats; a complete record only has the presence file removed. Co-Authored-By: Claude Opus 5.5 --- .../core/storage/chunk_record_upgrade.go | 194 ++++++++++++++++++ .../core/storage/chunk_record_upgrade_test.go | 141 +++++++++++++ seaweed-block/docs/design/invariants.md | 1 + 3 files changed, 336 insertions(+) create mode 100644 seaweed-block/core/storage/chunk_record_upgrade.go create mode 100644 seaweed-block/core/storage/chunk_record_upgrade_test.go diff --git a/seaweed-block/core/storage/chunk_record_upgrade.go b/seaweed-block/core/storage/chunk_record_upgrade.go new file mode 100644 index 0000000000..413069da38 --- /dev/null +++ b/seaweed-block/core/storage/chunk_record_upgrade.go @@ -0,0 +1,194 @@ +package storage + +import ( + "bufio" + "bytes" + "context" + "errors" + "fmt" + "os" + "path/filepath" + "strconv" + "strings" + + "github.com/seaweedfs/seaweed-block/core/chunkkernel" +) + +// Kernel states as page bytes. Zero is never a state: a zeroed page fails. +var chunkRecordStateCodes = map[chunkkernel.Kind]uint8{ + chunkkernel.Absent: 1, + chunkkernel.Partial: 2, + chunkkernel.Unknown: 3, + chunkkernel.HashUnpublished: 4, + chunkkernel.HashPublished: 5, +} + +func chunkRecordStateCode(k chunkkernel.Kind) (uint8, error) { + c, ok := chunkRecordStateCodes[k] + if !ok { + return 0, fmt.Errorf("storage: chunk record: no code for kernel state %q", k) + } + return c, nil +} + +func chunkRecordKind(code uint8) (chunkkernel.Kind, error) { + for k, c := range chunkRecordStateCodes { + if c == code { + return k, nil + } + } + return "", fmt.Errorf("%w: state code %d", errChunkRecordCheck, code) +} + +// coverageArg is the kernel's argument for a coverage. +func coverageArg(c LocalCoverage) chunkkernel.Arg { + switch c { + case CoverageAll: + return chunkkernel.Arg{Value: "all"} + case CoverageSome: + return chunkkernel.Arg{Value: "some"} + } + return chunkkernel.Arg{Value: "none"} +} + +// legacyPresence is a v1.0.x presence file: the chunks it calls absent and +// the blocks of absent chunks it calls local. +type legacyPresence struct { + absent map[uint64]bool + local map[uint64]bool +} + +func readLegacyPresence(path string) (legacyPresence, error) { + p := legacyPresence{absent: map[uint64]bool{}, local: map[uint64]bool{}} + data, err := os.ReadFile(path) + if errors.Is(err, os.ErrNotExist) { + return p, nil + } + if err != nil { + return p, fmt.Errorf("storage: chunk presence: %w", err) + } + sc := bufio.NewScanner(bytes.NewReader(data)) + for sc.Scan() { + kind, num, ok := strings.Cut(sc.Text(), " ") + n, perr := strconv.ParseUint(num, 10, 64) + if !ok || perr != nil || (kind != "absent" && kind != "local") { + return p, fmt.Errorf("storage: chunk presence: bad line %q", sc.Text()) + } + if kind == "absent" { + p.absent[n] = true + } else { + p.local[n] = true + } + } + return p, sc.Err() +} + +func chunkPresencePath(storePath string) string { return storePath + ".chunkpresence" } + +// upgradeChunkRecord is the one-way upgrade of a v1.0.x volume's per-chunk +// state, at open: after Recover and Sync, with extent draining held, before +// the chunk layer attaches. It reads no chunk data. In order: +// +// 1. the seed: a chunk the presence file calls present is wholly local; an +// absent one has the blocks the file calls local plus those of log +// entries not yet applied to the extent (the legacy layer would mark them +// local when they are applied); +// 2. the store persists the bitmap and hands back its prepared coverage; the +// pages are written from it, each chunk classified by the kernel's +// Rebuilt event (none: absent, some: partial, all: hash unknown); +// 3. the store publishes the bitmap and fences both descriptor slots; +// 4. the record's header (completeChunkRecord: pages current with the +// store, G its synced position); +// 5. the presence file is removed. +// +// Each step can be repeated. A store whose record is already complete only +// has its presence file removed. +func upgradeChunkRecord(ctx context.Context, s *WALStore, epoch uint64) error { + cb := s.ChunkBlocks() + if cb == 0 { + return errors.New("storage: chunk record upgrade needs an owned chunk map") + } + chunks := (uint64(s.NumBlocks()) + cb - 1) / cb + dir, presence := chunkRecordDir(s.path), chunkPresencePath(s.path) + if marked, e := s.ChunkStateMarker(); marked && e == epoch { + pos, _, _ := s.Boundaries() + got, err := loadChunkRecord(dir, chunks, marked, e, pos) + if err != nil { + return err + } + if got.Complete { + return removeLegacyPresence(presence) + } + } + legacy, err := readLegacyPresence(presence) + if err != nil { + return err + } + if err := s.ScanLBAs(s.CheckpointLSN()+1, func(e RecoveryEntry) error { + if legacy.absent[uint64(e.LBA)/cb] { + legacy.local[uint64(e.LBA)] = true + } + return nil + }); err != nil { + return fmt.Errorf("storage: chunk record upgrade: log suffix: %w", err) + } + seed := func(chunk, blocks uint64) (ChunkCoverageSeed, error) { + if !legacy.absent[chunk] { + return ChunkCoverageSeed{All: true}, nil + } + var local []uint64 + for b := uint64(0); b < blocks; b++ { + if legacy.local[chunk*cb+b] { + local = append(local, b) + } + } + return ChunkCoverageSeed{Blocks: local}, nil + } + prepare := func(r ChunkCoverageReader) error { + pos, _, _ := s.Boundaries() + return writeChunkRecordPagesFrom(dir, chunks, pos, r) + } + if err := s.InitializeChunkCoverage(ctx, epoch, seed, prepare); err != nil { + return err + } + if err := completeChunkRecord(s, dir, epoch, chunks); err != nil { + return err + } + return removeLegacyPresence(presence) +} + +// writeChunkRecordPagesFrom writes every page, valid through pos, with each +// chunk's state from its coverage by the kernel's Rebuilt event. +func writeChunkRecordPagesFrom(dir string, chunks, pos uint64, r ChunkCoverageReader) error { + 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 { + chunk := seg*chunkRecordSegment + uint64(i) + cov, _, err := r.Coverage(chunk) + if err != nil { + return err + } + res, _, err := chunkkernel.Step(chunkkernel.State{Kind: chunkkernel.Absent}, chunkkernel.Rebuilt, coverageArg(cov)) + if err != nil { + return fmt.Errorf("storage: chunk record: chunk %d: %w", chunk, err) + } + if p.Entries[i].State, err = chunkRecordStateCode(res.State.Kind); err != nil { + return err + } + } + if err := writeChunkRecordPage(dir, p); err != nil { + return err + } + } + return nil +} + +func removeLegacyPresence(path string) error { + if err := os.Remove(path); err != nil && !errors.Is(err, os.ErrNotExist) { + return fmt.Errorf("storage: chunk presence: remove: %w", err) + } + if err := syncDir(filepath.Dir(path)); err != nil { + return fmt.Errorf("storage: chunk presence: fsync directory: %w", err) + } + return nil +} diff --git a/seaweed-block/core/storage/chunk_record_upgrade_test.go b/seaweed-block/core/storage/chunk_record_upgrade_test.go new file mode 100644 index 0000000000..5a3058d322 --- /dev/null +++ b/seaweed-block/core/storage/chunk_record_upgrade_test.go @@ -0,0 +1,141 @@ +package storage + +import ( + "context" + "errors" + "os" + "testing" + + "github.com/seaweedfs/seaweed-block/core/chunkkernel" +) + +// 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. +func legacyVolume(t *testing.T) string { + t.Helper() + s, path := newMappedCheckpointStoreV3(t) + writeSynced(t, s, 1, 1) + writeSynced(t, s, 9, 9) + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(chunkPresencePath(path), []byte("absent 2\nabsent 3\nabsent 5\nlocal 9\n"), 0o644); err != nil { + t.Fatal(err) + } + writeSynced(t, s, 13, 13) // in the log only + crashStore(t, s) + return path +} + +// openForUpgrade opens a store as the upgrade does: recovered, extent +// draining held, no chunk layer. +func openForUpgrade(t *testing.T, path string) *WALStore { + t.Helper() + s, err := openWALStoreV3MapInternalForTest(path, true) + if err != nil { + t.Fatal(err) + } + s.DisableAutoFlushForRecoveryTest() + s.HoldExtentDrainUntilChunkLayer() + t.Cleanup(func() { s.Close() }) + if _, err := s.Recover(); err != nil { + t.Fatal(err) + } + return s +} + +func recordKinds(t *testing.T, s *WALStore) []chunkkernel.Kind { + t.Helper() + marked, epoch := s.ChunkStateMarker() + got, err := loadChunkRecord(chunkRecordDir(s.path), 16, marked, epoch, syncedPos(s)) + if err != nil || !got.Complete { + t.Fatalf("record not complete: %+v %v", got, err) + } + var kinds []chunkkernel.Kind + for _, e := range got.Pages[0].Entries { + k, err := chunkRecordKind(e.State) + if err != nil { + t.Fatal(err) + } + kinds = append(kinds, k) + } + return kinds +} + +func checkUpgradedKinds(t *testing.T, s *WALStore) { + t.Helper() + kinds := recordKinds(t, s) + want := map[int]chunkkernel.Kind{2: chunkkernel.Partial, 3: chunkkernel.Partial, 5: chunkkernel.Absent} + for c, k := range kinds { + w, ok := want[c] + if !ok { + w = chunkkernel.Unknown // present: whole, hash unknown + } + if k != w { + t.Fatalf("chunk %d is %s, want %s", c, k, w) + } + } + if _, err := os.Stat(chunkPresencePath(s.path)); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("legacy presence still there: %v", err) + } +} + +// A v1.0.x volume upgrades at open: present chunks whole and unknown, absent +// ones partial with their local blocks (from the file and from the log not yet +// applied) or absent; the record is complete and the presence file gone. +func TestUpgradeChunkRecordFromLegacyPresence(t *testing.T) { + path := legacyVolume(t) + s := openForUpgrade(t, path) + if err := upgradeChunkRecord(context.Background(), s, 7); err != nil { + t.Fatal(err) + } + checkUpgradedKinds(t, s) + if c, _, err := s.Coverage(3); err != nil || c != CoverageSome { + t.Fatalf("chunk 3 coverage %d %v: the log's block was lost", c, err) + } +} + +// A crash before the store's fence: the record is not used, the presence file +// is still there, and the next open upgrades again. +func TestUpgradeChunkRecordCrashBeforeTheFence(t *testing.T) { + path := legacyVolume(t) + s := openForUpgrade(t, path) + writes := 0 + s.v3.testBeforeSlotWrite = func() error { + writes++ + return errors.New("crash before the descriptor slots") + } + if err := upgradeChunkRecord(context.Background(), s, 7); err == nil { + t.Fatal("the upgrade completed without its fence") + } + if _, err := os.Stat(chunkPresencePath(path)); err != nil { + t.Fatalf("presence removed before the fence: %v", err) + } + crashStore(t, s) + 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. +func TestUpgradeChunkRecordCrashAfterTheHeader(t *testing.T) { + path := legacyVolume(t) + s := openForUpgrade(t, path) + if err := upgradeChunkRecord(context.Background(), s, 7); err != nil { + t.Fatal(err) + } + crashStore(t, s) + if err := os.WriteFile(chunkPresencePath(path), []byte("absent 2\n"), 0o644); err != nil { + t.Fatal(err) // as if the removal had not happened + } + next := openForUpgrade(t, path) + if err := upgradeChunkRecord(context.Background(), next, 7); err != nil { + t.Fatal(err) + } + checkUpgradedKinds(t, next) +} diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index adaf34bcb1..72ead8fb89 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -616,6 +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 at open classifies each chunk by the kernel from its seeded coverage (present: all; absent: the file's local blocks plus unapplied log blocks), writes pages before the store's fence, the header after it, and removes the presence file last; each step repeats. | M1 Opened (v1.1 upgrade at open) | `core/storage/chunk_record_upgrade.go` `upgradeChunkRecord`, `writeChunkRecordPagesFrom` | `TestUpgradeChunkRecordFromLegacyPresence`, `TestUpgradeChunkRecordCrashBeforeTheFence`, `TestUpgradeChunkRecordCrashAfterTheHeader` (`core/storage/chunk_record_upgrade_test.go`) | UpgradeWide3 (pages, field, header, presence removed); 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 | From 013b6222fe4a71e0b917cb8af0f8502e8b70ff57 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 30 Nov 2026 08:40:47 -0800 Subject: [PATCH 2/5] test(storage): after the marker the presence file is not evidence Two reds: a completed upgrade with a damaged header re-reads the presence file; an upgrade at another epoch than the store's marker is taken. Co-Authored-By: Claude Opus 5.5 --- .../core/storage/chunk_record_upgrade_test.go | 48 +++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/seaweed-block/core/storage/chunk_record_upgrade_test.go b/seaweed-block/core/storage/chunk_record_upgrade_test.go index 5a3058d322..70b24ab03f 100644 --- a/seaweed-block/core/storage/chunk_record_upgrade_test.go +++ b/seaweed-block/core/storage/chunk_record_upgrade_test.go @@ -139,3 +139,51 @@ func TestUpgradeChunkRecordCrashAfterTheHeader(t *testing.T) { } checkUpgradedKinds(t, next) } + +// After the marker the presence file is not evidence: a completed upgrade +// whose header is damaged, with a presence file that would say "nothing +// absent" (here: one that does not even parse), upgrades again from the +// store's bitmap; an absent chunk stays absent. +func TestUpgradeChunkRecordAfterTheMarkerIgnoresThePresenceFile(t *testing.T) { + path := legacyVolume(t) + s := openForUpgrade(t, path) + if err := upgradeChunkRecord(context.Background(), s, 7); err != nil { + t.Fatal(err) + } + crashStore(t, s) + if err := os.WriteFile(chunkRecordDir(path)+"/"+chunkRecordHeaderName, []byte("damaged"), 0o644); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(chunkPresencePath(path), []byte("not a presence file\n"), 0o644); err != nil { + t.Fatal(err) + } + next := openForUpgrade(t, path) + if err := upgradeChunkRecord(context.Background(), next, 7); err != nil { + t.Fatalf("the upgrade read the presence file after the marker: %v", err) + } + checkUpgradedKinds(t, next) + if c, _, err := next.Coverage(5); err != nil || c != CoverageNone { + t.Fatalf("absent chunk 5 coverage %d %v: it would read local bytes, not the remote", c, err) + } +} + +// A store marked at one epoch is not upgraded at another: refused, and its +// bitmap unchanged. +func TestUpgradeChunkRecordAtAnotherEpochIsRefused(t *testing.T) { + path := legacyVolume(t) + s := openForUpgrade(t, path) + if err := upgradeChunkRecord(context.Background(), s, 7); err != nil { + t.Fatal(err) + } + crashStore(t, s) + next := openForUpgrade(t, path) + if err := upgradeChunkRecord(context.Background(), next, 8); err == nil { + t.Fatal("an upgrade at another epoch was taken") + } + if c, _, err := next.Coverage(5); err != nil || c != CoverageNone { + t.Fatalf("absent chunk 5 coverage %d %v after a refused upgrade", c, err) + } + if marked, e := next.ChunkStateMarker(); !marked || e != 7 { + t.Fatalf("marker %v/%d after a refused upgrade", marked, e) + } +} From 930f74ea95690d1a9904ac8dc37fb47311ebb40b Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 30 Nov 2026 08:41:19 -0800 Subject: [PATCH 3/5] storage: the presence file is evidence only before the marker A store marked at this epoch is never seeded from the presence file: a complete record only has the file removed, an incomplete one gets its pages again from the store's bitmap through the boundary's same-epoch retry, with a seed that refuses. A store marked at another epoch is refused, typed. Co-Authored-By: Claude Opus 5.5 --- .../core/storage/chunk_record_upgrade.go | 44 +++++++++++++++---- seaweed-block/docs/design/invariants.md | 2 +- 2 files changed, 36 insertions(+), 10 deletions(-) diff --git a/seaweed-block/core/storage/chunk_record_upgrade.go b/seaweed-block/core/storage/chunk_record_upgrade.go index 413069da38..3ddfdd4656 100644 --- a/seaweed-block/core/storage/chunk_record_upgrade.go +++ b/seaweed-block/core/storage/chunk_record_upgrade.go @@ -85,6 +85,14 @@ func readLegacyPresence(path string) (legacyPresence, error) { func chunkPresencePath(storePath string) string { return storePath + ".chunkpresence" } +// ErrChunkRecordOtherEpoch refuses an upgrade of a store already marked at +// another local-work epoch: that store belongs to the attach after a move. +var ErrChunkRecordOtherEpoch = errors.New("storage: chunk record: store marked at another local-work epoch") + +// errPresenceAfterMarker: the presence file is never a seed once the store is +// marked; reaching the seed then is a defect. +var errPresenceAfterMarker = errors.New("storage: chunk record: the presence file is not evidence after the marker") + // upgradeChunkRecord is the one-way upgrade of a v1.0.x volume's per-chunk // state, at open: after Recover and Sync, with extent draining held, before // the chunk layer attaches. It reads no chunk data. In order: @@ -101,8 +109,16 @@ func chunkPresencePath(storePath string) string { return storePath + ".chunkpres // store, G its synced position); // 5. the presence file is removed. // -// Each step can be repeated. A store whose record is already complete only -// has its presence file removed. +// Each step can be repeated. +// +// THE PRESENCE FILE IS EVIDENCE ONLY BEFORE THE MARKER. Once the store is +// marked, its bitmap is the durable fact and a missing presence file would +// read as "nothing absent": absent chunks would serve local bytes never +// fetched. So: a store marked at this epoch is never seeded from the file; a +// complete record only has the file removed, an incomplete one gets its pages +// again from the store's bitmap (the same-epoch retry of the store's boundary, +// which takes no seed). A store marked at another epoch is refused. Only an +// unmarked store is seeded from the presence file. func upgradeChunkRecord(ctx context.Context, s *WALStore, epoch uint64) error { cb := s.ChunkBlocks() if cb == 0 { @@ -110,15 +126,29 @@ func upgradeChunkRecord(ctx context.Context, s *WALStore, epoch uint64) error { } chunks := (uint64(s.NumBlocks()) + cb - 1) / cb dir, presence := chunkRecordDir(s.path), chunkPresencePath(s.path) - if marked, e := s.ChunkStateMarker(); marked && e == epoch { + prepare := func(r ChunkCoverageReader) error { + pos, _, _ := s.Boundaries() + return writeChunkRecordPagesFrom(dir, chunks, pos, r) + } + if marked, e := s.ChunkStateMarker(); marked { + if e != epoch { + return fmt.Errorf("%w: marked %d, upgrade asked at %d", ErrChunkRecordOtherEpoch, e, epoch) + } pos, _, _ := s.Boundaries() got, err := loadChunkRecord(dir, chunks, marked, e, pos) if err != nil { return err } - if got.Complete { - return removeLegacyPresence(presence) + if !got.Complete { + noSeed := func(uint64, uint64) (ChunkCoverageSeed, error) { return ChunkCoverageSeed{}, errPresenceAfterMarker } + if err := s.InitializeChunkCoverage(ctx, epoch, noSeed, prepare); err != nil { + return err + } + if err := completeChunkRecord(s, dir, epoch, chunks); err != nil { + return err + } } + return removeLegacyPresence(presence) } legacy, err := readLegacyPresence(presence) if err != nil { @@ -144,10 +174,6 @@ func upgradeChunkRecord(ctx context.Context, s *WALStore, epoch uint64) error { } return ChunkCoverageSeed{Blocks: local}, nil } - prepare := func(r ChunkCoverageReader) error { - pos, _, _ := s.Boundaries() - return writeChunkRecordPagesFrom(dir, chunks, pos, r) - } if err := s.InitializeChunkCoverage(ctx, epoch, seed, prepare); err != nil { return err } diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 72ead8fb89..ee8096fedc 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 at open classifies each chunk by the kernel from its seeded coverage (present: all; absent: the file's local blocks plus unapplied log blocks), writes pages before the store's fence, the header after it, and removes the presence file last; each step repeats. | M1 Opened (v1.1 upgrade at open) | `core/storage/chunk_record_upgrade.go` `upgradeChunkRecord`, `writeChunkRecordPagesFrom` | `TestUpgradeChunkRecordFromLegacyPresence`, `TestUpgradeChunkRecordCrashBeforeTheFence`, `TestUpgradeChunkRecordCrashAfterTheHeader` (`core/storage/chunk_record_upgrade_test.go`) | UpgradeWide3 (pages, field, header, presence removed); 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`, `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 | From d6d4e48229899a2926d4ef38dd2f0b4c87d27b9e Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 30 Nov 2026 08:46:04 -0800 Subject: [PATCH 4/5] 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 | From ab3a2feb30e3904a698bd6bed30e434ce84a4206 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 30 Nov 2026 13:44:14 -0800 Subject: [PATCH 5/5] storage: the upgrade uses the record's state codes from the runtime file Co-Authored-By: Claude Opus 5.5 --- .../core/storage/chunk_record_upgrade.go | 26 ------------------- 1 file changed, 26 deletions(-) diff --git a/seaweed-block/core/storage/chunk_record_upgrade.go b/seaweed-block/core/storage/chunk_record_upgrade.go index 3ddfdd4656..93784758f2 100644 --- a/seaweed-block/core/storage/chunk_record_upgrade.go +++ b/seaweed-block/core/storage/chunk_record_upgrade.go @@ -14,32 +14,6 @@ import ( "github.com/seaweedfs/seaweed-block/core/chunkkernel" ) -// Kernel states as page bytes. Zero is never a state: a zeroed page fails. -var chunkRecordStateCodes = map[chunkkernel.Kind]uint8{ - chunkkernel.Absent: 1, - chunkkernel.Partial: 2, - chunkkernel.Unknown: 3, - chunkkernel.HashUnpublished: 4, - chunkkernel.HashPublished: 5, -} - -func chunkRecordStateCode(k chunkkernel.Kind) (uint8, error) { - c, ok := chunkRecordStateCodes[k] - if !ok { - return 0, fmt.Errorf("storage: chunk record: no code for kernel state %q", k) - } - return c, nil -} - -func chunkRecordKind(code uint8) (chunkkernel.Kind, error) { - for k, c := range chunkRecordStateCodes { - if c == code { - return k, nil - } - } - return "", fmt.Errorf("%w: state code %d", errChunkRecordCheck, code) -} - // coverageArg is the kernel's argument for a coverage. func coverageArg(c LocalCoverage) chunkkernel.Arg { switch c {