From 1210ce60c7976dc37aaa3b5cdca685eb630ea5e9 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 30 Nov 2026 08:33:15 -0800 Subject: [PATCH] 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 |