From cbd442612e8ade1255cc49ff11a65f6a2344584f Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 06:16:11 -0800 Subject: [PATCH] v1.1 upgrade: seed whole local chunks after a clean stop - layout: LocalRoot.ReportCleanStop is told, on each attempt of the claim's own check, whether the HEAD the claim is built on is a committed, idle detach (DetachedBy) carrying this root's claim id; the committing attempt's report is the last. Never judged on Start's first read. - durable: startLayoutRoot returns that clean stop; the provider carries it into ChunkLayerConfig.CleanStop. - storage: upgradeChunkRecordSeeded seeds only an unmarked store whose layout claim id is the proof's and whose synced position (the pages' valid-through) is the proof's; the attached HEAD at another position is logged and never seeded on. A whole local chunk steps Rebuilt all, Hash, Commit and takes HEAD's hash (a chunk HEAD does not name: the zero chunk's). The upgrade's order is unchanged. - invariants: INV-CHUNK-RECORD-SEED-001. - tests: the attach takes the proof from its config (TestV11AttachSeedsFromTheCleanStopInItsConfig); startLayoutRoot reports it (TestStartLayoutRootReportsTheCleanStop). Co-Authored-By: Claude Opus 5.5 --- .../core/frontend/chunkstore/layout/start.go | 25 +++++- .../core/frontend/durable/provider_chunk.go | 4 +- .../core/frontend/durable/provider_layout.go | 20 +++-- .../durable/provider_layout_cleanstop_test.go | 69 ++++++++++++++ .../durable/provider_layout_crash_test.go | 2 +- .../core/storage/chunk_record_open.go | 3 +- .../core/storage/chunk_record_upgrade.go | 89 +++++++++++++++++-- .../storage/chunk_record_v11_seed_test.go | 67 ++++++++++++++ seaweed-block/core/storage/chunk_seam.go | 5 ++ seaweed-block/docs/design/invariants.md | 1 + 10 files changed, 268 insertions(+), 17 deletions(-) create mode 100644 seaweed-block/core/frontend/durable/provider_layout_cleanstop_test.go create mode 100644 seaweed-block/core/storage/chunk_record_v11_seed_test.go diff --git a/seaweed-block/core/frontend/chunkstore/layout/start.go b/seaweed-block/core/frontend/chunkstore/layout/start.go index acc1cca61c..e43643c389 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/start.go +++ b/seaweed-block/core/frontend/chunkstore/layout/start.go @@ -121,7 +121,30 @@ func Start(ctx context.Context, st StartStore, lease LeaseWait, line HolderID, l // another lineage's claim or a higher published position after the // read above refuses, never writes over the newer HEAD. me := HolderID{Epoch: line.Epoch, Holder: line.Holder, ClaimID: local.ClaimID} - return RunClaim(ctx, st, lease, me, func(h Head) error { return startCheck(h, line, local) }) + // The clean stop is judged on the very HEAD the claim's update is built + // on, never on the read above: each attempt reports its own, so the + // committing attempt's report is the last. + return RunClaim(ctx, st, lease, me, func(h Head) error { + if local.ReportCleanStop != nil { + local.ReportCleanStop(nil) + } + if err := startCheck(h, line, local); err != nil { + return err + } + if local.ReportCleanStop != nil { + local.ReportCleanStop(cleanStopOf(h, local.ClaimID)) + } + return nil + }) +} + +// cleanStopOf is the clean stop h proves for the lineage claimID: h is a +// committed, idle detach (DetachedBy) carrying claimID; nil otherwise. +func cleanStopOf(h Head, claimID string) *CleanStop { + if !DetachedBy(h, HolderID{Epoch: h.Epoch, Holder: h.Holder, ClaimID: claimID}) { + return nil + } + return &CleanStop{Position: h.Position, ClaimID: h.ClaimID, Gen: h.Gen} } // startCheck refuses a local root that cannot start on h: an old copy of diff --git a/seaweed-block/core/frontend/durable/provider_chunk.go b/seaweed-block/core/frontend/durable/provider_chunk.go index f84121b9fc..a47cf57d84 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk.go +++ b/seaweed-block/core/frontend/durable/provider_chunk.go @@ -488,13 +488,14 @@ func (p *DurableProvider) newChunkLayer(ctx context.Context, volumeID string, h holder := p.chunkHolder(proj) var inner storage.ChunkRemote var layoutHead layout.Head + var cleanStop *storage.ChunkCleanStop var err error st, e := p.cfg.ChunkLayoutHeadFor(volumeID) if e != nil { return nil, e } sctx, scancel := context.WithTimeout(ctx, chunkAttachTimeout) - layoutHead, err = startLayoutRoot(sctx, ws, st, layout.HolderID{Epoch: proj.Epoch, Holder: holder}) + layoutHead, cleanStop, err = startLayoutRoot(sctx, ws, st, layout.HolderID{Epoch: proj.Epoch, Holder: holder}) scancel() if err != nil { return nil, err @@ -543,6 +544,7 @@ func (p *DurableProvider) newChunkLayer(ctx context.Context, volumeID string, h Epoch: lin.epoch, Holder: holder, FreshFromHead: h.fresh, + CleanStop: cleanStop, CreatedThisStart: h.fresh && h.createdThisStart, ReadMissTimeout: p.cfg.ChunkReadMissTimeout, HydrationWorkers: p.cfg.ChunkHydrationWorkers, diff --git a/seaweed-block/core/frontend/durable/provider_layout.go b/seaweed-block/core/frontend/durable/provider_layout.go index b03f178b8a..0c193859d9 100644 --- a/seaweed-block/core/frontend/durable/provider_layout.go +++ b/seaweed-block/core/frontend/durable/provider_layout.go @@ -69,13 +69,23 @@ func canStartFrom(ws startRoot, fresh bool, h layout.Head) (startPath, error) { return startSeed, ws.CanSeedChunkFrontier(h.Position) } -func startLayoutRoot(ctx context.Context, ws *storage.WALStore, st layout.StartStore, line layout.HolderID) (layout.Head, error) { +// startLayoutRoot starts the local root on HEAD and returns the claimed HEAD +// with the clean stop of this root's lineage the claim was built on (nil: +// none), for the chunk layer's v1.0.x upgrade. +func startLayoutRoot(ctx context.Context, ws *storage.WALStore, st layout.StartStore, line layout.HolderID) (layout.Head, *storage.ChunkCleanStop, error) { id, fresh, ok := ws.LayoutIdentity() if !ok { - return layout.Head{}, errors.New("durable: legacy root has no layout identity; recreate it") + return layout.Head{}, nil, errors.New("durable: legacy root has no layout identity; recreate it") } position, _, _ := ws.Boundaries() - h, err := layout.Start(ctx, st, grantedLayoutLine(line), line, layout.LocalRoot{Geometry: layout.Geometry{SizeBytes: uint64(ws.NumBlocks()) * uint64(ws.BlockSize()), BlockSize: uint32(ws.BlockSize()), ChunkBytes: uint64(ws.ChunkBlocks()) * uint64(ws.BlockSize())}, ClaimID: id, Fresh: fresh, Position: position, CanStartFrom: func(h layout.Head) error { _, err := canStartFrom(ws, fresh, h); return err }}) + var proof *storage.ChunkCleanStop + report := func(c *layout.CleanStop) { + proof = nil + if c != nil { + proof = &storage.ChunkCleanStop{Position: c.Position, ClaimID: c.ClaimID} + } + } + h, err := layout.Start(ctx, st, grantedLayoutLine(line), line, layout.LocalRoot{Geometry: layout.Geometry{SizeBytes: uint64(ws.NumBlocks()) * uint64(ws.BlockSize()), BlockSize: uint32(ws.BlockSize()), ChunkBytes: uint64(ws.ChunkBlocks()) * uint64(ws.BlockSize())}, ClaimID: id, Fresh: fresh, Position: position, CanStartFrom: func(h layout.Head) error { _, err := canStartFrom(ws, fresh, h); return err }, ReportCleanStop: report}) if err != nil { if errors.Is(err, layout.ErrNotHolder) || errors.Is(err, layout.ErrStaleEpoch) || errors.Is(err, layout.ErrPrecondition) { // A HEAD held by another holder at our granted epoch, or any @@ -87,9 +97,9 @@ func startLayoutRoot(ctx context.Context, ws *storage.WALStore, st layout.StartS err = errors.Join(err, storage.ErrChunkLayerFenced, errChunkForeignClaim) } } - return layout.Head{}, fmt.Errorf("durable: layout Start: %w", err) + return layout.Head{}, nil, fmt.Errorf("durable: layout Start: %w", err) } - return h, nil + return h, proof, nil } // LayoutHolder returns only the identity of the successfully attached Start. diff --git a/seaweed-block/core/frontend/durable/provider_layout_cleanstop_test.go b/seaweed-block/core/frontend/durable/provider_layout_cleanstop_test.go new file mode 100644 index 0000000000..76dfbf8ec9 --- /dev/null +++ b/seaweed-block/core/frontend/durable/provider_layout_cleanstop_test.go @@ -0,0 +1,69 @@ +package durable + +import ( + "context" + "path/filepath" + "testing" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// startLayoutRoot hands the chunk layer the clean stop its claim was built +// on: a restart at a higher epoch on HEAD detached (committed, idle) by this +// root's lineage reports HEAD's position and the lineage; a restart that +// continues its own live claim reports none. +func TestStartLayoutRootReportsTheCleanStop(t *testing.T) { + ctx := context.Background() + cat, err := chunkstore.NewBCatalog(chunkstore.NewMemFiler(), &layoutCrashBlobs{b: map[string][]byte{}}, "/clean-stop") + if err != nil { + t.Fatal(err) + } + id, err := layout.NewVolumeID() + if err != nil { + t.Fatal(err) + } + ref := chunkstore.VolumeRef{Name: "v", ID: id} + if _, err := cat.CreateVolume(ctx, ref, layout.Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}); err != nil { + t.Fatal(err) + } + st, err := cat.Store(ref) + if err != nil { + t.Fatal(err) + } + ws, err := storage.CreateWALStoreWithOptions(filepath.Join(t.TempDir(), "store"), 64, 4096, storage.WALStoreOptions{ChunkBlocks: 4}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = ws.Close() }) + if err := ws.SetLayoutIdentity("k1", true); err != nil { + t.Fatal(err) + } + h, proof, err := startLayoutRoot(ctx, ws, st, layout.HolderID{Epoch: 1, Holder: "s/r"}) + if err != nil { + t.Fatalf("first claim: %v", err) + } + if proof != nil { + t.Fatalf("a claim of an unclaimed HEAD reported a clean stop %+v", proof) + } + // HEAD detached by this lineage at position 0, committed and idle. + rn := layout.RootName{Hash: layout.Sum([]byte("image"))} + det := h + det.State, det.Current = layout.StateDetached, &rn + if err := st.UpdateHead(ctx, h.Gen, det, layout.CauseCommit); err != nil { + t.Fatal(err) + } + if err := ws.SetLayoutIdentity("k1", false); err != nil { + t.Fatal(err) + } + if _, proof, err = startLayoutRoot(ctx, ws, st, layout.HolderID{Epoch: 2, Holder: "s/r"}); err != nil { + t.Fatalf("restart: %v", err) + } + if proof == nil || *proof != (storage.ChunkCleanStop{Position: det.Position, ClaimID: "k1"}) { + t.Fatalf("clean stop %+v, want {%d k1}", proof, det.Position) + } + if _, proof, err = startLayoutRoot(ctx, ws, st, layout.HolderID{Epoch: 2, Holder: "s/r"}); err != nil || proof != nil { + t.Fatalf("a restart continuing its own live claim: %+v %v, want no clean stop", proof, err) + } +} diff --git a/seaweed-block/core/frontend/durable/provider_layout_crash_test.go b/seaweed-block/core/frontend/durable/provider_layout_crash_test.go index 7fe30eeb16..1e3c70ad2d 100644 --- a/seaweed-block/core/frontend/durable/provider_layout_crash_test.go +++ b/seaweed-block/core/frontend/durable/provider_layout_crash_test.go @@ -83,7 +83,7 @@ func TestLayoutStartUnclaimedHeadRefusesFreshRootWithLocalWrites(t *testing.T) { if _, err := ws.Write(1, make([]byte, 4096)); !errors.Is(err, storage.ErrLayoutFresh) { t.Fatalf("guest write before claim: %v; want ErrLayoutFresh", err) } - if _, err := startLayoutRoot(ctx, ws, st, layout.HolderID{Epoch: 1, Holder: "s/r"}); !errors.Is(err, layout.ErrCannotStartFrom) { + if _, _, err := startLayoutRoot(ctx, ws, st, layout.HolderID{Epoch: 1, Holder: "s/r"}); !errors.Is(err, layout.ErrCannotStartFrom) { t.Fatalf("dirty fresh root: %v; want ErrCannotStartFrom", err) } after, found, err := st.ReadHead(ctx) diff --git a/seaweed-block/core/storage/chunk_record_open.go b/seaweed-block/core/storage/chunk_record_open.go index 39d48f9a83..4574eabc93 100644 --- a/seaweed-block/core/storage/chunk_record_open.go +++ b/seaweed-block/core/storage/chunk_record_open.go @@ -52,7 +52,8 @@ func (l *chunkLayerImpl) openChunkRecordV11() (*chunkRecordShadow, error) { // the pages are valid through it). _, err := s.Sync() if err == nil { - err = upgradeChunkRecordWith(l.ctx, s, epoch, l.attachProgress.add) + seed := &upgradeSeed{proof: l.cfg.CleanStop, head: l.head, zero: l.zeroChunkSum()} + err = upgradeChunkRecordSeeded(l.ctx, s, epoch, seed, l.attachProgress.add) } if h := testAfterChunkRecordUpgrade; h != nil { h() // tests: the upgrade returned, the barrier is still released diff --git a/seaweed-block/core/storage/chunk_record_upgrade.go b/seaweed-block/core/storage/chunk_record_upgrade.go index 290c838920..48bd87b7b1 100644 --- a/seaweed-block/core/storage/chunk_record_upgrade.go +++ b/seaweed-block/core/storage/chunk_record_upgrade.go @@ -6,6 +6,7 @@ import ( "context" "errors" "fmt" + "log" "os" "path/filepath" "strconv" @@ -100,15 +101,31 @@ func upgradeChunkRecord(ctx context.Context, s *WALStore, epoch uint64) error { // upgradeChunkRecordWith is upgradeChunkRecord reporting each page's entries // as it is written to progress (an attach's volume-sized work; nil for none). func upgradeChunkRecordWith(ctx context.Context, s *WALStore, epoch uint64, progress func(uint64)) error { + return upgradeChunkRecordSeeded(ctx, s, epoch, nil, progress) +} + +// upgradeChunkRecordSeeded is upgradeChunkRecordWith with a clean-stop seed +// (nil: none). An unmarked store whose seed holds (cleanStopHashes) writes +// every whole local chunk as hash-known and published with HEAD's hash, so the +// compare pass has nothing left to do; the seed changes only the pages' +// content, never the upgrade's order. A marked store never seeds. +func upgradeChunkRecordSeeded(ctx context.Context, s *WALStore, epoch uint64, seed *upgradeSeed, progress func(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) + // prepare writes the pages, valid through the store's synced position; with + // seeding on, the seed is judged at that same position. + seeding := false prepare := func(r ChunkCoverageReader) error { pos, _, _ := s.Boundaries() - return writeChunkRecordPagesFrom(dir, chunks, pos, r, progress) + var hashOf func(uint64) [32]byte + if seeding { + hashOf = cleanStopHashes(seed, pos) + } + return writeChunkRecordPagesFrom(dir, chunks, pos, r, hashOf, progress) } if marked, e := s.ChunkStateMarker(); marked { if e != epoch { @@ -142,7 +159,7 @@ func upgradeChunkRecordWith(ctx context.Context, s *WALStore, epoch uint64, prog }); err != nil { return fmt.Errorf("storage: chunk record upgrade: log suffix: %w", err) } - seed := func(chunk, blocks uint64) (ChunkCoverageSeed, error) { + coverage := func(chunk, blocks uint64) (ChunkCoverageSeed, error) { if !legacy.absent[chunk] { return ChunkCoverageSeed{All: true}, nil } @@ -154,7 +171,8 @@ func upgradeChunkRecordWith(ctx context.Context, s *WALStore, epoch uint64, prog } return ChunkCoverageSeed{Blocks: local}, nil } - if err := s.InitializeChunkCoverage(ctx, epoch, seed, prepare); err != nil { + seeding = seedsLineage(s, seed) + if err := s.InitializeChunkCoverage(ctx, epoch, coverage, prepare); err != nil { return err } if err := completeChunkRecord(s, dir, epoch, chunks); err != nil { @@ -180,14 +198,61 @@ type upgradeSeed struct { zero [32]byte } -// upgradeChunkRecordSeeded is upgradeChunkRecordWith with a clean-stop seed. -func upgradeChunkRecordSeeded(ctx context.Context, s *WALStore, epoch uint64, seed *upgradeSeed, progress func(uint64)) error { - return upgradeChunkRecordWith(ctx, s, epoch, progress) +// seedsLineage is the seed's lineage condition (the model's SameEpoch, by +// lineage): a proof is present and its claim id is this root's own layout +// claim id. Another lineage's detach is not this store's clean stop. +func seedsLineage(s *WALStore, seed *upgradeSeed) bool { + if seed == nil || seed.proof == nil { + log.Printf("level=INFO storage: chunk record upgrade: no clean-stop seed: no proof of a clean stop") + return false + } + claim, _, ok := s.LayoutIdentity() + if !ok || claim != seed.proof.ClaimID { + log.Printf("level=INFO storage: chunk record upgrade: no clean-stop seed: the proof's lineage %q is not this root's %q", seed.proof.ClaimID, claim) + return false + } + return true } +// cleanStopHashes is the seed's position condition (the model's hpos = L): the +// proof's position is the store's synced position pos, after recovery and its +// replay, the position the pages are valid through (never the checkpoint +// position or a log scan). A write acknowledged after the detach leaves the +// store above the proof: no seed. It returns HEAD's hash of each chunk (a +// chunk HEAD does not name is zero in HEAD), or nil for no seed. +func cleanStopHashes(seed *upgradeSeed, pos uint64) func(uint64) [32]byte { + if seed.proof.Position != pos { + log.Printf("level=INFO storage: chunk record upgrade: no clean-stop seed: the store is at %d, the clean stop at %d", pos, seed.proof.Position) + return nil + } + // The claim changes no position: a HEAD the layer attached to at another + // position than the proof's is a defect upstream, never seeded on. + if seed.head.RemoteLSN != seed.proof.Position { + log.Printf("level=WARN storage: chunk record upgrade: no clean-stop seed: HEAD at %d, its clean-stop proof at %d", seed.head.RemoteLSN, seed.proof.Position) + return nil + } + log.Printf("level=INFO storage: chunk record upgrade: clean-stop seed at %d: whole local chunks take HEAD's hash", pos) + head, zero := seed.head, seed.zero + return func(chunk uint64) [32]byte { + if ref, ok := head.Chunks[chunk]; ok { + return ref.SHA256 + } + return zero + } +} + +// seedSteps take a whole local chunk to hash-known and published, through the +// kernel: its coverage (Rebuilt all, unknown), its hash, its commit. +var seedSteps = []struct { + ev chunkkernel.Event + want chunkkernel.Kind +}{{chunkkernel.Hash, chunkkernel.HashUnpublished}, {chunkkernel.Commit, chunkkernel.HashPublished}} + // 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, progress func(uint64)) error { +// chunk's state from its coverage by the kernel's Rebuilt event. With hashOf +// (the clean-stop seed), a whole local chunk is then hashed and committed with +// hashOf's hash. +func writeChunkRecordPagesFrom(dir string, chunks, pos uint64, r ChunkCoverageReader, hashOf func(uint64) [32]byte, progress func(uint64)) 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 { @@ -200,6 +265,14 @@ func writeChunkRecordPagesFrom(dir string, chunks, pos uint64, r ChunkCoverageRe if err != nil { return fmt.Errorf("storage: chunk record: chunk %d: %w", chunk, err) } + if hashOf != nil && cov == CoverageAll { + for _, st := range seedSteps { + if res, _, err = chunkkernel.Step(res.State, st.ev, chunkkernel.Arg{Value: "-"}); err != nil || res.State.Kind != st.want { + return fmt.Errorf("storage: chunk record: seed chunk %d: %s gave %s: %v", chunk, st.ev, res.State.Kind, err) + } + } + p.Entries[i].Hash = hashOf(chunk) + } if p.Entries[i].State, err = chunkRecordStateCode(res.State.Kind); err != nil { return err } diff --git a/seaweed-block/core/storage/chunk_record_v11_seed_test.go b/seaweed-block/core/storage/chunk_record_v11_seed_test.go new file mode 100644 index 0000000000..464ba35cd2 --- /dev/null +++ b/seaweed-block/core/storage/chunk_record_v11_seed_test.go @@ -0,0 +1,67 @@ +package storage + +import ( + "crypto/sha256" + "testing" + + "github.com/seaweedfs/seaweed-block/core/chunkkernel" +) + +// The attach takes the clean stop from its config: a v1.0.x store holding +// HEAD's image (chunks 1 and 2 written; every other chunk zero, so not named +// in HEAD), synced at HEAD's position, upgrades with every chunk hash-known and published with its +// content's hash; without the proof every chunk is unknown, for the pass. +func TestV11AttachSeedsFromTheCleanStopInItsConfig(t *testing.T) { + for _, tc := range []struct { + name string + proof bool + want chunkkernel.Kind + }{{"with the proof", true, chunkkernel.HashPublished}, {"without", false, chunkkernel.Unknown}} { + t.Run(tc.name, func(t *testing.T) { + withV11Format(t) + s, _ := v11Store(t) + if err := s.SetLayoutIdentity("claim-a", false); err != nil { + t.Fatal(err) + } + n := int(s.NumBlocks()) + src := make([]byte, n*ctBlockSize) + written := []int{} + for lba := ctChunkBlocks; lba < 3*ctChunkBlocks; lba++ { // chunks 1 and 2 + copy(src[lba*ctBlockSize:], makeBlock(ctBlockSize, byte(0x40+lba))) + written = append(written, lba) + } + for _, lba := range written { + if _, err := s.Write(uint32(lba), src[lba*ctBlockSize:(lba+1)*ctBlockSize]); err != nil { + t.Fatal(err) + } + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + pos := syncedPos(s) + f := newFakeChunkRemote() + f.seedHead(t, src, pos, 1) + cfg := ctConfig(2) + cfg.Bitmap = nil + if tc.proof { + cfg.CleanStop = &ChunkCleanStop{Position: pos, ClaimID: "claim-a"} + } + l := mustAttach(t, s, f, cfg).(*chunkLayerImpl) + for c := uint64(0); c < l.numChunks; c++ { + if k := shadowKind(l, c); k != tc.want { + t.Fatalf("chunk %d opened %s, want %s", c, k, tc.want) + } + if !tc.proof { + continue + } + l.shadow.rec.mu.Lock() + got := l.shadow.rec.hashes[c] + l.shadow.rec.mu.Unlock() + first := int(c) * ctChunkBlocks * ctBlockSize + if want := sha256.Sum256(src[first : first+ctChunkBlocks*ctBlockSize]); got != want { + t.Fatalf("chunk %d seeded with %x, want its content's %x", c, got[:4], want[:4]) + } + } + }) + } +} diff --git a/seaweed-block/core/storage/chunk_seam.go b/seaweed-block/core/storage/chunk_seam.go index af2ebb9211..f3b29d4e40 100644 --- a/seaweed-block/core/storage/chunk_seam.go +++ b/seaweed-block/core/storage/chunk_seam.go @@ -322,6 +322,11 @@ type chunkLayerConfig struct { // HEAD (every block absent, read lazily). False means an existing local // volume. Never inferred from the local contents. FreshFromHead bool + // CleanStop is the clean stop of this root's lineage that the start's + // claim was built on (nil: none). The v1.0.x upgrade seeds every whole + // local chunk with HEAD's hash only when it holds at the store's synced + // position (upgradeChunkRecordSeeded). + CleanStop *ChunkCleanStop // CreatedThisStart says this process start created the local store (an // in-memory fact, never persisted). RULE-FRESH-KNOWN-ZERO samples only // with it and FreshFromHead: a fresh marker left by an earlier start, an diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index dadfbbb081..e768eecec0 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -626,6 +626,7 @@ The "Machine / transition" column refers to Part A. Notes under a table record w | `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`, `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-RECORD-SEED-001` | The v1.0.x upgrade seeds a whole local chunk as published with HEAD's hash only on an unmarked store, with a clean stop read on the HEAD the claim was built on (an idle detach of the store's lineage) at the store's synced position; otherwise it is unknown. | M1 Opened (v1.1 upgrade at open, after a clean stop) | `core/frontend/chunkstore/layout/start.go` `Start` (`ReportCleanStop`); `core/storage/chunk_record_upgrade.go` `upgradeChunkRecordSeeded`, `seedsLineage`, `cleanStopHashes` | `TestStart_ReportsTheCleanStopItClaimedFrom`, `TestStart_TheCleanStopIsTheClaimsOwnRead`, `TestStart_NoCleanStopWithoutADetachOfThisLineage` (`core/frontend/chunkstore/layout/start_cleanstop_test.go`); `TestUpgradeSeedsAfterACleanStop`, `TestUpgradeSeedNeedsTheStoreAtTheProofPosition`, `TestUpgradeSeedNeedsTheStoresLineage`, `TestUpgradeSeedNeedsAProofHEADStillShows`, `TestUpgradeSeedCrashAtEachStep` (`core/storage/chunk_record_seed_test.go`); `TestV11AttachSeedsFromTheCleanStopInItsConfig` (`core/storage/chunk_record_v11_seed_test.go`); `TestStartLayoutRootReportsTheCleanStop` (`core/frontend/durable/provider_layout_cleanstop_test.go`) | UpgradeWide3 rows 122 and 123 (`Proof`, `SameEpoch` judged on the HEAD the claim is built on; the claim is a stutter on image and position), 126 to 128 (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 hash only with its evidence; a page dirties only on a state or hash change and is written by its count or age (an evict's at once), in snapshot order, after the WAL is synced through the position it shows; G <= min(applied, dirty-from, WAL synced). | M3 Serving (chunk record runtime) | `core/storage/chunk_record_runtime.go` `chunkRecordRuntime.Apply`, `Due`, `WriteDue`, `WriteThrough`, `Flush`, `writeSegmentLocked` (`syncThrough`), `writeHeaderLocked` (`durable`) | `TestRecordRuntimeAppliesTheKernel`, `TestRecordRuntimeEvictWritesThePageFirst`, `TestRecordRuntimeSchedulePerPage`, `TestRecordRuntimeFlushIsLoadedBack`, `TestRecordRuntimeWriteThrough`, `TestRecordRuntimeAnUnchangedStateWritesNothing`, `TestRecordRuntimeHeaderMovesUnderWrites`, `TestRecordRuntimeEvictDuringAFlushLandsLast`, `TestRecordRuntimePageWritesFollowChangesNotSize`, `TestRecordRuntimePageWritersPublishInOrder`, `TestRecordRuntimeHashEvidence`, `TestRecordRuntimeCopiesItsInputs`, `TestRecordRuntimeAPageChangedAtOpenHoldsG` (`core/storage/chunk_record_runtime_test.go`); the WAL bound: `TestV11NoPageClaimsMoreThanTheDurableWAL`, `TestV11APageNeverShowsAWriteTheWALCanLose` (`core/storage/chunk_record_v11_review_test.go`, `chunk_record_v11_hold_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-SHADOW-001` | While serving, the chunk record follows the engine's events via the kernel; an event bound to a captured version is skipped, never refused, after a write; at each barrier every chunk the engine captures is a record candidate. It decides nothing; on v1.0 it writes no page. | M3 Serving (chunk record shadow) | `core/storage/chunk_record_shadow.go` `newChunkRecordShadow`, `chunkRecordShadow.check`; `core/storage/chunk_layer.go` `noteMutation`, `fillOnce`, `EvictChunk`, `recoveredLocked`, `BeforeCheckpointAdvance`, `shadowCommit`, `shadowCommitCaptured` (also from `resolvePending`, `SettleDetach`); `core/storage/chunk_cut_payload.go` `markEqualNow`; `core/storage/chunk_record_runtime.go` `ApplyIf` | `TestShadowWriteCoverageFollowsTheStoreBitmap`, `TestShadowFillRacedByAWriteEndsUnknown`, `TestShadowCutOfAPartialChunkKeepsItPartial`, `TestShadowAttachKeepsACheckpointedWriteACandidate`, `TestShadowWriteRacingHashAndCommitIsSkippedNotRefused`, `TestShadowEvictEdges`, `TestShadowRecordWritesNoPage`, `TestShadowCheckerIsExactAndCatchesAMissingWrite`, `TestShadowRecoverChangesOnlyTheRecoveredChunks`, `TestShadowBaseInstallCompletingChangesEveryChunk`, `TestShadowDelayedSettlementCommitsTheCapturedChunks`, `TestShadowProductionCheckDoesNotScanTheRecord`, `TestShadowScratchExemptionIsBoundToItsCapturedVersion` (`core/storage/chunk_record_shadow_test.go`); every test of the package runs with the shadow strict, misses and extra record candidates both (`TestMain`, `core/storage/chunk_record_shadow_main_test.go`) | chunk-kernel/2 (the per-chunk state models are not in this repository) | ACTIVE |