From a2441488eb1e04b4fc9b506afef8580c840e63e8 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 23 Nov 2026 17:01:17 -0800 Subject: [PATCH 1/6] test: red test for a fresh volume's first cut scanning every chunk A store created empty against a HEAD never claimed, with two chunks written (one checkpointed out of the WAL), must have two first-cut candidates and publish both; today all chunks start Unknown and every chunk of the volume is scanned. Two tests that pass today pin the scope: a store created against a claimed HEAD, and a restore target, keep every locally held chunk a candidate. Co-Authored-By: Claude Opus 5.5 --- .../durable/first_cut_known_zero_test.go | 167 ++++++++++++++++++ 1 file changed, 167 insertions(+) create mode 100644 seaweed-block/core/frontend/durable/first_cut_known_zero_test.go diff --git a/seaweed-block/core/frontend/durable/first_cut_known_zero_test.go b/seaweed-block/core/frontend/durable/first_cut_known_zero_test.go new file mode 100644 index 0000000000..610216aa3a --- /dev/null +++ b/seaweed-block/core/frontend/durable/first_cut_known_zero_test.go @@ -0,0 +1,167 @@ +package durable_test + +// The first cut of a volume. A local store created empty against a HEAD +// that was never claimed and holds no segments knows every chunk it has not +// written is zero, so its first cut scans only the chunks written since; a +// store whose relation to HEAD is not known (a claimed HEAD, a restore or +// fork target, a store an earlier release created) keeps scanning every +// chunk it holds locally. + +import ( + "bytes" + "context" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// fcutChunks is chunkProvider's chunk count: pcBlocks blocks of pcChunkBlocks. +const fcutChunks = pcBlocks / pcChunkBlocks + +func fcutProvider(t *testing.T, root string, remote storage.ChunkRemote) *durable.DurableProvider { + return chunkProvider(t, root, remote, v1View(), 0) +} + +// fcutCheckpointedPast waits until the store's checkpoint has moved past +// from, so a write made after from has left the WAL's dirty map. +func fcutCheckpointedPast(t *testing.T, st storage.LogicalStorage, from uint64) { + t.Helper() + ws := st.(*storage.WALStore) + waitFor(t, 10*time.Second, "the WAL checkpoint past the write", func() bool { return ws.CheckpointLSN() > from }) +} + +// fcutStats returns v1's chunk-layer counters. +func fcutStats(t *testing.T, p *durable.DurableProvider) storage.ChunkLayerStats { + t.Helper() + for _, st := range p.DurableStatuses() { + if st.VolumeID == "v1" && st.Chunk != nil && st.Chunk.Attached { + return st.Chunk.Stats + } + } + t.Fatal("v1 has no attached chunk layer") + return storage.ChunkLayerStats{} +} + +func fcutOpen(t *testing.T, ctx context.Context, p *durable.DurableProvider) storage.LogicalStorage { + t.Helper() + st, err := p.EnsureStorage("v1") + if err != nil { + t.Fatal(err) + } + if _, err := p.RecoverVolume(ctx, "v1"); err != nil { + t.Fatal(err) + } + return st +} + +func fcutWrite(t *testing.T, ctx context.Context, p *durable.DurableProvider, lba int, fill byte) []byte { + t.Helper() + data := bytes.Repeat([]byte{fill}, 4096) + b := p.Backend("v1") + if n, err := b.Write(ctx, int64(lba)*4096, data); err != nil || n != len(data) { + t.Fatalf("write lba %d: %d %v", lba, n, err) + } + if err := b.Sync(ctx); err != nil { + t.Fatal(err) + } + return data +} + +// fcutHeadBlock reads block lba from the published HEAD (zero if its chunk +// is not named). +func fcutHeadBlock(t *testing.T, ctx context.Context, remote *storage.MemChunkRemote, lba int) []byte { + t.Helper() + head, err := remote.GetHead(ctx) + if err != nil { + t.Fatal(err) + } + ref, ok := head.Chunks[uint64(lba/pcChunkBlocks)] + if !ok { + return make([]byte, 4096) + } + c, err := remote.Get(ctx, ref.Key) + if err != nil { + t.Fatal(err) + } + off := (lba % pcChunkBlocks) * 4096 + return c[off : off+4096] +} + +// TestRedFirstCutOfAFreshVolumeScansOnlyWrittenChunks: a store created +// empty against a HEAD never claimed, with two chunks written (one of them +// already checkpointed out of the WAL), has two first-cut candidates, and +// its first cut publishes both. Today every chunk of the volume is a +// candidate (all 16 start Unknown). +func TestRedFirstCutOfAFreshVolumeScansOnlyWrittenChunks(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + remote := storage.NewMemChunkRemote() + p := fcutProvider(t, t.TempDir(), remote) + st := fcutOpen(t, ctx, p) + cp0 := st.(*storage.WALStore).CheckpointLSN() + a := fcutWrite(t, ctx, p, pcChunkBlocks*1+1, 0x31) // chunk 1, checkpointed below + fcutCheckpointedPast(t, st, cp0) + b := fcutWrite(t, ctx, p, pcChunkBlocks*9+3, 0x39) // chunk 9, still in the WAL + if got := fcutStats(t, p).DirtyChunks; got != 2 { + t.Errorf("before the first cut: %d candidate chunks; want 2 (the written ones), not all %d", got, fcutChunks) + } + if _, err := p.CaptureVolume(ctx, "v1"); err != nil { + t.Fatal(err) + } + if got := fcutStats(t, p).LastCut.CandidateChunks; got != 2 { + t.Errorf("first cut: %d candidate chunks; want 2", got) + } + if !bytes.Equal(fcutHeadBlock(t, ctx, remote, pcChunkBlocks*1+1), a) || !bytes.Equal(fcutHeadBlock(t, ctx, remote, pcChunkBlocks*9+3), b) { + t.Fatal("the first cut did not publish both written blocks") + } +} + +// TestFirstCutAgainstAClaimedHeadScansEveryChunk: a store created empty +// against a HEAD another store already claimed (no segments yet) keeps +// every chunk a candidate. Passes today; pins the fix's scope. +func TestFirstCutAgainstAClaimedHeadScansEveryChunk(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + remote := storage.NewMemChunkRemote() + first := fcutProvider(t, t.TempDir(), remote) + fcutOpen(t, ctx, first) + if err := first.Close(); err != nil { + t.Fatal(err) + } + if head, err := remote.GetHead(ctx); err != nil || head.Gen == 0 || len(head.Segments) != 0 { + t.Fatalf("setup: HEAD %+v %v; want a claimed HEAD with no segments", head, err) + } + p := fcutProvider(t, t.TempDir(), remote) + fcutOpen(t, ctx, p) + if got := fcutStats(t, p).DirtyChunks; got != fcutChunks { + t.Fatalf("store created against a claimed HEAD: %d candidate chunks; want all %d", got, fcutChunks) + } +} + +// TestFirstCutOfARestoreTargetKeepsItsHydrationPath: a store created on a +// new root against a HEAD that names chunks hydrates them (they are +// absent, not candidates) and keeps every other chunk a candidate. Passes +// today; pins the fix's scope. +func TestFirstCutOfARestoreTargetKeepsItsHydrationPath(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + remote := storage.NewMemChunkRemote() + first := fcutProvider(t, t.TempDir(), remote) + fcutOpen(t, ctx, first) + fcutWrite(t, ctx, first, pcChunkBlocks*3, 0x33) + fcutWrite(t, ctx, first, pcChunkBlocks*7, 0x37) + if _, err := first.CaptureVolume(ctx, "v1"); err != nil { + t.Fatal(err) + } + if err := first.Close(); err != nil { + t.Fatal(err) + } + p := fcutProvider(t, t.TempDir(), remote) + fcutOpen(t, ctx, p) + s := fcutStats(t, p) + if s.AbsentChunks != 2 || s.DirtyChunks != fcutChunks-2 { + t.Fatalf("restore target: %d absent, %d candidate chunks; want 2 absent and %d candidates", s.AbsentChunks, s.DirtyChunks, fcutChunks-2) + } +} From 02c153b06606bef5d030283d7bca9324dffe90b0 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 23 Nov 2026 19:39:25 -0800 Subject: [PATCH 2/6] fix: a fresh store's chunks that its claimed HEAD does not name start known-zero A fresh store (its .chunkfresh marker present at the attach, no BASE) has never had a write or a fill reach it, so every chunk its claimed HEAD does not name is zero on both sides. Its attach samples, under the capture barrier, the token of each such chunk whose owned-map entry is still the creation value, and clears only their UNKNOWN through the cut's own map publication, before the attach commit. The first cut of a fresh volume, hand-over target or restore target then scans only the chunks written since, not every chunk of the volume. Chunks HEAD names stay absent and are hydrated from HEAD. The premise is enforced: every implementation other than walstore-chunk, explicit as well as auto, refuses a root carrying chunk metadata, so no plain walstore write can reach a store whose marker says none did. Co-Authored-By: Claude Opus 5.5 --- .../durable/first_cut_known_zero_test.go | 77 +++++++--- .../durable/known_zero_premise_test.go | 141 ++++++++++++++++++ .../core/frontend/durable/provider.go | 14 +- .../core/storage/chunk_fresh_known_zero.go | 41 +++++ .../storage/chunk_fresh_known_zero_test.go | 68 +++++++++ seaweed-block/core/storage/chunk_layer.go | 5 + seaweed-block/core/storage/chunk_seam.go | 11 +- seaweed-block/docs/design/invariants.md | 5 +- 8 files changed, 330 insertions(+), 32 deletions(-) create mode 100644 seaweed-block/core/frontend/durable/known_zero_premise_test.go create mode 100644 seaweed-block/core/storage/chunk_fresh_known_zero.go create mode 100644 seaweed-block/core/storage/chunk_fresh_known_zero_test.go diff --git a/seaweed-block/core/frontend/durable/first_cut_known_zero_test.go b/seaweed-block/core/frontend/durable/first_cut_known_zero_test.go index 610216aa3a..50e535ac3b 100644 --- a/seaweed-block/core/frontend/durable/first_cut_known_zero_test.go +++ b/seaweed-block/core/frontend/durable/first_cut_known_zero_test.go @@ -1,15 +1,16 @@ package durable_test -// The first cut of a volume. A local store created empty against a HEAD -// that was never claimed and holds no segments knows every chunk it has not -// written is zero, so its first cut scans only the chunks written since; a -// store whose relation to HEAD is not known (a claimed HEAD, a restore or -// fork target, a store an earlier release created) keeps scanning every -// chunk it holds locally. +// The first cut of a volume. A fresh local store (its first attach not yet +// committed) knows every chunk its claimed HEAD does not name is zero on both +// sides, so its first cut scans only the chunks written since; a +// store that is not fresh (one an earlier release created, or any store +// after its first attach commit) keeps its chunks' state as persisted. Chunks +// HEAD names stay absent and are hydrated from HEAD. import ( "bytes" "context" + "errors" "testing" "time" @@ -118,10 +119,12 @@ func TestRedFirstCutOfAFreshVolumeScansOnlyWrittenChunks(t *testing.T) { } } -// TestFirstCutAgainstAClaimedHeadScansEveryChunk: a store created empty -// against a HEAD another store already claimed (no segments yet) keeps -// every chunk a candidate. Passes today; pins the fix's scope. -func TestFirstCutAgainstAClaimedHeadScansEveryChunk(t *testing.T) { +// TestFirstCutAgainstAClaimedHeadCertifiesUnnamedChunks: a store created +// empty against a HEAD another store already claimed (no data published) is +// fresh too: every chunk that HEAD does not name starts equal to it (both +// zero), so the first cut has no candidates. General form of the rule: the +// premise is the store's fresh marker, not the HEAD's history. +func TestFirstCutAgainstAClaimedHeadCertifiesUnnamedChunks(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() remote := storage.NewMemChunkRemote() @@ -130,28 +133,28 @@ func TestFirstCutAgainstAClaimedHeadScansEveryChunk(t *testing.T) { if err := first.Close(); err != nil { t.Fatal(err) } - if head, err := remote.GetHead(ctx); err != nil || head.Gen == 0 || len(head.Segments) != 0 { - t.Fatalf("setup: HEAD %+v %v; want a claimed HEAD with no segments", head, err) + if head, err := remote.GetHead(ctx); err != nil || head.Gen == 0 || len(head.Chunks) != 0 { + t.Fatalf("setup: HEAD %+v %v; want a claimed HEAD naming no chunk", head, err) } p := fcutProvider(t, t.TempDir(), remote) fcutOpen(t, ctx, p) - if got := fcutStats(t, p).DirtyChunks; got != fcutChunks { - t.Fatalf("store created against a claimed HEAD: %d candidate chunks; want all %d", got, fcutChunks) + if got := fcutStats(t, p).DirtyChunks; got != 0 { + t.Fatalf("fresh store against a claimed HEAD naming nothing: %d candidate chunks; want 0", got) } } -// TestFirstCutOfARestoreTargetKeepsItsHydrationPath: a store created on a -// new root against a HEAD that names chunks hydrates them (they are -// absent, not candidates) and keeps every other chunk a candidate. Passes -// today; pins the fix's scope. +// TestFirstCutOfARestoreTargetKeepsItsHydrationPath: a fresh store against a +// HEAD that names chunks keeps those chunks absent (hydrated from HEAD; a +// read returns HEAD's data, never zeros) and starts every other chunk equal +// to HEAD (zero), so its first cut has no candidates. func TestFirstCutOfARestoreTargetKeepsItsHydrationPath(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() remote := storage.NewMemChunkRemote() first := fcutProvider(t, t.TempDir(), remote) fcutOpen(t, ctx, first) - fcutWrite(t, ctx, first, pcChunkBlocks*3, 0x33) - fcutWrite(t, ctx, first, pcChunkBlocks*7, 0x37) + a := fcutWrite(t, ctx, first, pcChunkBlocks*3, 0x33) + b := fcutWrite(t, ctx, first, pcChunkBlocks*7, 0x37) if _, err := first.CaptureVolume(ctx, "v1"); err != nil { t.Fatal(err) } @@ -160,8 +163,36 @@ func TestFirstCutOfARestoreTargetKeepsItsHydrationPath(t *testing.T) { } p := fcutProvider(t, t.TempDir(), remote) fcutOpen(t, ctx, p) - s := fcutStats(t, p) - if s.AbsentChunks != 2 || s.DirtyChunks != fcutChunks-2 { - t.Fatalf("restore target: %d absent, %d candidate chunks; want 2 absent and %d candidates", s.AbsentChunks, s.DirtyChunks, fcutChunks-2) + if s := fcutStats(t, p); s.AbsentChunks != 2 || s.DirtyChunks != 0 { + t.Fatalf("restore target: %d absent, %d candidate chunks; want 2 absent and 0 candidates", s.AbsentChunks, s.DirtyChunks) + } + got := make([]byte, 4096) + for lba, want := range map[int][]byte{pcChunkBlocks * 3: a, pcChunkBlocks * 7: b} { + if n, err := p.Backend("v1").Read(ctx, int64(lba)*4096, got); err != nil || n != len(got) || !bytes.Equal(got, want) { + t.Fatalf("restore target read of HEAD-named block %d: %d %v, data equal %v; want HEAD's data, not zeros", lba, n, err, bytes.Equal(got, want)) + } + } +} + +// TestExplicitWALStoreRefusesAFreshChunkRoot: a root carrying chunk metadata +// (here the fresh marker of a store that never attached) is refused by an +// explicitly configured plain walstore as by auto, so no write can reach a +// store whose marker says none ever did. +func TestExplicitWALStoreRefusesAFreshChunkRoot(t *testing.T) { + root := t.TempDir() + p := fcutProvider(t, root, storage.NewMemChunkRemote()) + if _, err := p.EnsureStorage("v1"); err != nil { + t.Fatal(err) + } + if err := p.Close(); err != nil { + t.Fatal(err) + } + plain, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplWALStore, StorageRoot: root, BlockSize: 4096, NumBlocks: pcBlocks}, v1View()) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = plain.Close() }) + if _, err := plain.EnsureStorage("v1"); !errors.Is(err, durable.ErrImplKindMismatch) { + t.Fatalf("explicit walstore on a fresh chunk root: %v; want ErrImplKindMismatch", err) } } diff --git a/seaweed-block/core/frontend/durable/known_zero_premise_test.go b/seaweed-block/core/frontend/durable/known_zero_premise_test.go new file mode 100644 index 0000000000..1e6859a450 --- /dev/null +++ b/seaweed-block/core/frontend/durable/known_zero_premise_test.go @@ -0,0 +1,141 @@ +package durable + +import ( + "bytes" + "context" + "errors" + "os" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// kzProvider is a walstore-chunk provider for v1 (256 blocks, 16 per +// chunk: 16 chunks) over root and remote. +func kzProvider(t *testing.T, root string, remote storage.ChunkRemote) *DurableProvider { + t.Helper() + id := frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 3, EndpointVersion: 1} + p, err := NewDurableProvider(ProviderConfig{ + Impl: ImplWALStoreChunk, StorageRoot: root, BlockSize: 4096, NumBlocks: 256, ChunkBlocks: 16, + ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }, + }, precopyQueueView{id}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = p.Close() }) + return p +} + +func kzCandidates(t *testing.T, p *DurableProvider) int { + t.Helper() + for _, st := range p.DurableStatuses() { + if st.VolumeID == "v1" && st.Chunk != nil && st.Chunk.Attached { + return st.Chunk.Stats.DirtyChunks + } + } + t.Fatal("v1 has no attached chunk layer") + return -1 +} + +// The premise of RULE-FRESH-KNOWN-ZERO: until the attach commit retires the +// fresh marker, no write reaches the store. Held at that boundary (after the +// claim and the certification, before the commit), a frontend write is not +// admitted (it may wait; here it is bounded) and appends no WAL record. After +// the commit the store has no candidates: nothing was written. +func TestNoWriteReachesAFreshStoreBeforeItsAttachCommit(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + p := kzProvider(t, t.TempDir(), storage.NewMemChunkRemote()) + st, err := p.EnsureStorage("v1") + if err != nil { + t.Fatal(err) + } + ws := st.(*storage.WALStore) + var writeErr error + var nextAtBoundary uint64 + held := false + p.testBeforeChunkFreshRetire = func() error { + held = true + wctx, wcancel := context.WithTimeout(ctx, 300*time.Millisecond) + defer wcancel() + _, writeErr = p.Backend("v1").Write(wctx, 0, bytes.Repeat([]byte{0x5a}, 4096)) + nextAtBoundary = ws.NextLSN() + return nil + } + if _, err := p.RecoverVolume(ctx, "v1"); err != nil { + t.Fatal(err) + } + p.testBeforeChunkFreshRetire = nil + if !held { + t.Fatal("the attach did not reach its commit boundary") + } + if writeErr == nil || nextAtBoundary != 1 { + t.Fatalf("at the commit boundary a frontend write returned %v and the WAL's next LSN was %d; want refused, 1", writeErr, nextAtBoundary) + } + if got := kzCandidates(t, p); got != 0 { + t.Fatalf("after the commit: %d candidate chunks; want 0 (nothing was written)", got) + } +} + +// A first start that crashes before its attach commit (the commit fails, the +// process ends) leaves the fresh marker: the next start decides again on its +// own claim. It still has no candidates, and a write after it is published +// by the next cut. +func TestFreshAttachCrashBeforeCommitDecidesAgain(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + root, remote := t.TempDir(), storage.NewMemChunkRemote() + p := kzProvider(t, root, remote) + if _, err := p.EnsureStorage("v1"); err != nil { + t.Fatal(err) + } + crash := errors.New("crash before the attach commit") + p.testBeforeChunkFreshRetire = func() error { return crash } + if _, err := p.RecoverVolume(ctx, "v1"); !errors.Is(err, crash) { + t.Fatalf("first start: %v; want the injected crash", err) + } + if err := p.Close(); err != nil { + t.Fatal(err) + } + if _, err := os.Stat(chunkFreshMarker(p.volumePath("v1"))); err != nil { + t.Fatalf("fresh marker after the crash: %v; want it kept", err) + } + + p2 := kzProvider(t, root, remote) + if _, err := p2.EnsureStorage("v1"); err != nil { + t.Fatal(err) + } + if _, err := p2.RecoverVolume(ctx, "v1"); err != nil { + t.Fatal(err) + } + if got := kzCandidates(t, p2); got != 0 { + t.Fatalf("second start: %d candidate chunks; want 0", got) + } + want := bytes.Repeat([]byte{0x6b}, 4096) + if _, err := p2.Backend("v1").Write(ctx, 5*16*4096, want); err != nil { + t.Fatal(err) + } + if err := p2.Backend("v1").Sync(ctx); err != nil { + t.Fatal(err) + } + if _, err := p2.CaptureVolume(ctx, "v1"); err != nil { + t.Fatal(err) + } + head, err := remote.GetHead(ctx) + if err != nil { + t.Fatal(err) + } + ref, ok := head.Chunks[5] + if !ok { + t.Fatal("the cut after the second start did not publish chunk 5") + } + chunk, err := remote.Get(ctx, ref.Key) + if err != nil || !bytes.Equal(chunk[:4096], want) { + t.Fatalf("published chunk 5: %v, data equal %v", err, err == nil && bytes.Equal(chunk[:4096], want)) + } + if got := kzCandidates(t, p2); got != 0 { + t.Fatalf("after the cut: %d candidate chunks; want 0", got) + } +} diff --git a/seaweed-block/core/frontend/durable/provider.go b/seaweed-block/core/frontend/durable/provider.go index a6af566c84..eb631a06a4 100644 --- a/seaweed-block/core/frontend/durable/provider.go +++ b/seaweed-block/core/frontend/durable/provider.go @@ -809,17 +809,19 @@ func (p *DurableProvider) openOrCreate(volumeID string) (*volHandle, error) { if err != nil { return nil, fmt.Errorf("durable: stat %s: %w", path, err) } - if p.cfg.Impl == ImplAuto { + if p.cfg.Impl != ImplWALStoreChunk { // A walstore-chunk volume shares walstore's on-disk format, and its // authoritative bytes may live only in the remote HEAD. Opened as - // plain walstore it would serve local (possibly absent) extents, so - // auto refuses any root carrying chunk metadata; it never deletes - // or converts it. + // plain walstore it would serve local (possibly absent) extents, and + // a write through it would reach a store whose fresh marker still + // says no write ever did (RULE-FRESH-KNOWN-ZERO). So every other + // implementation, auto or explicit, refuses a root carrying chunk + // metadata; it never deletes or converts it. if side, err := chunkSidecars(path); err != nil { return nil, err } else if len(side) > 0 { - return nil, fmt.Errorf("%w: %s is a chunk-managed volume (%s present); auto cannot open it: set --durable-impl=walstore-chunk with its remote configuration", - ErrImplKindMismatch, path, strings.Join(side, ", ")) + return nil, fmt.Errorf("%w: %s is a chunk-managed volume (%s present); %s cannot open it: set --durable-impl=walstore-chunk with its remote configuration", + ErrImplKindMismatch, path, strings.Join(side, ", "), p.cfg.Impl) } } diff --git a/seaweed-block/core/storage/chunk_fresh_known_zero.go b/seaweed-block/core/storage/chunk_fresh_known_zero.go new file mode 100644 index 0000000000..d695f17997 --- /dev/null +++ b/seaweed-block/core/storage/chunk_fresh_known_zero.go @@ -0,0 +1,41 @@ +package storage + +// RULE-FRESH-KNOWN-ZERO (INV-CUT-BITMAP-001). A fresh store (FreshFromHead +// still true at its attach: the .chunkfresh marker is present and no BASE +// is installed) has never had a write or a fill reach it: frontend I/O is +// admitted only after the attach commit retires the marker, a chunk volume +// takes no replication apply, no cut or hydration can resolve the layer +// before that commit, and no other implementation opens a root that carries +// chunk metadata. Its extent therefore holds the creation bytes (zeros) in +// every chunk, and a chunk the claimed HEAD does not name is zero there too: +// the two are equal, so the chunk need not be a cut candidate. +// +// freshKnownZeroCandidates samples, under the attach's capture barrier, the +// mutation token of every chunk the claimed HEAD does not name whose owned +// map entry is still its creation value {LSN 0, Unknown}; the entry test is +// an extra exclusion, not the premise. attachChunkLayer then clears only the +// UNKNOWN bit of those whose token is unchanged, through the cut's own +// persistCapturedMapV3, before the provider's attach commit. A failed map +// publication leaves them UNKNOWN on disk (conservative). +func (l *chunkLayerImpl) freshKnownZeroCandidates(head chunkHead) map[uint64]uint64 { + s := l.s + if s.v3 == nil || s.v3.ownedMap == nil { + return nil + } + s.mu.RLock() + defer s.mu.RUnlock() + out := map[uint64]uint64{} + for idx := uint64(0); idx < l.numChunks && idx < uint64(len(s.v3.mapEntries)); idx++ { + if _, named := head.Chunks[idx]; named { + continue + } + if e := s.v3.mapEntries[idx]; e.LSN != 0 || !e.Unknown { + continue + } + out[idx] = l.chunkVersion(idx) + } + if len(out) == 0 { + return nil + } + return out +} diff --git a/seaweed-block/core/storage/chunk_fresh_known_zero_test.go b/seaweed-block/core/storage/chunk_fresh_known_zero_test.go new file mode 100644 index 0000000000..da243a67b9 --- /dev/null +++ b/seaweed-block/core/storage/chunk_fresh_known_zero_test.go @@ -0,0 +1,68 @@ +package storage + +import ( + "bytes" + "testing" +) + +// fkzConfig is a fresh attach's config (FreshFromHead) or an existing +// store's. +func fkzConfig(fresh bool) chunkLayerConfig { + cfg := ctConfig(1) + cfg.FreshFromHead = fresh + return cfg +} + +func fkzCandidates(l chunkLayer) int { return l.Stats().DirtyChunks } + +// A fresh attach certifies every chunk the claimed HEAD does not name whose +// owned-map entry is still the creation value; a chunk whose entry recorded +// a write (LSN >= 1) is never certified and stays a candidate, even where +// that LSN is not above HEAD's RemoteLSN (so "LSN above HEAD" alone would +// not make it one): here HEAD is at 100 and the write at 1. +func TestFreshKnownZeroNeverCertifiesARecordedWrite(t *testing.T) { + s, _ := newChunkTestStore(t) + if _, err := s.Write(uint32(2*ctChunkBlocks+1), bytes.Repeat([]byte{0x22}, ctBlockSize)); err != nil { + t.Fatal(err) + } + remote := newFakeChunkRemote() + remote.head = chunkHead{Gen: 1, Epoch: 1, RemoteLSN: 100, State: ChunkHeadActive} + l := mustAttach(t, s, remote, fkzConfig(true)) + if got := fkzCandidates(l); got != 1 { + t.Fatalf("fresh attach after a recorded write to chunk 2: %d candidates; want 1 (that chunk only)", got) + } +} + +// Without the fresh premise (an existing store) nothing is certified: every +// chunk keeps its persisted UNKNOWN. +func TestFreshKnownZeroNotWithoutTheFreshPremise(t *testing.T) { + s, _ := newChunkTestStore(t) + l := mustAttach(t, s, newFakeChunkRemote(), fkzConfig(false)) + if got, want := fkzCandidates(l), int(l.(*chunkLayerImpl).numChunks); got != want { + t.Fatalf("existing-store attach: %d candidates; want all %d", got, want) + } +} + +// The certification clears only chunks whose mutation token is unchanged +// since it was sampled under the attach barrier: a write landing between the +// sample and the clear keeps its chunk a candidate. +func TestFreshKnownZeroSkipsAChunkWrittenAfterTheSample(t *testing.T) { + s, _ := newChunkTestStore(t) + raw, err := attachChunkLayerImpl(s, newFakeChunkRemote(), fkzConfig(true)) + if err != nil { + t.Fatal(err) + } + l := raw.(*chunkLayerImpl) + t.Cleanup(func() { _ = l.Close() }) + if len(l.freshKnownZero) == 0 { + t.Fatal("no chunk sampled for certification") + } + if _, err := s.Write(uint32(3*ctChunkBlocks), bytes.Repeat([]byte{0x33}, ctBlockSize)); err != nil { + t.Fatal(err) + } + l.persistCapturedMapV3(l.freshKnownZero) + l.freshKnownZero = nil + if got := fkzCandidates(l); got != 1 { + t.Fatalf("a write between the sample and the clear: %d candidates; want 1 (the written chunk)", got) + } +} diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index 02954e75e2..e2a7562eb2 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -62,6 +62,10 @@ type chunkLayerImpl struct { remote chunkRemote cfg chunkLayerConfig + // freshKnownZero: the mutation tokens RULE-FRESH-KNOWN-ZERO sampled at a + // fresh attach; applied and cleared by attachChunkLayer. + freshKnownZero map[uint64]uint64 + blockSize int chunkBlocks uint64 numChunks uint64 @@ -287,6 +291,7 @@ func attachChunkLayerImpl(s *WALStore, remote chunkRemote, cfg chunkLayerConfig) l.absentGen[idx]++ } l.presenceVer++ + l.freshKnownZero = l.freshKnownZeroCandidates(head) } else if err := l.loadPresence(); err != nil { l.cancel() return nil, err diff --git a/seaweed-block/core/storage/chunk_seam.go b/seaweed-block/core/storage/chunk_seam.go index ae9344d73b..e6e5adee6c 100644 --- a/seaweed-block/core/storage/chunk_seam.go +++ b/seaweed-block/core/storage/chunk_seam.go @@ -653,5 +653,14 @@ var ( // attachChunkLayer attaches a chunk layer to an open store (chunk_layer.go). func attachChunkLayer(s *WALStore, remote chunkRemote, cfg chunkLayerConfig) (chunkLayer, error) { - return attachChunkLayerImpl(s, remote, cfg) + l, err := attachChunkLayerImpl(s, remote, cfg) + if err != nil { + return nil, err + } + // RULE-FRESH-KNOWN-ZERO: outside the capture barrier, as for a cut. + if impl, ok := l.(*chunkLayerImpl); ok && impl.freshKnownZero != nil { + impl.persistCapturedMapV3(impl.freshKnownZero) + impl.freshKnownZero = nil + } + return l, nil } diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 2878cca9bb..fa1c220b56 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -497,7 +497,7 @@ Tests: `TestSnapshotSchedule_SlotsAreOffsetPerVolume`, `_FailureIsTypedAndBacksO ## Part B. Invariant ledger -322 rows: 252 ACTIVE, 67 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 307 new. +323 rows: 253 ACTIVE, 67 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 308 new. The "Machine / transition" column refers to Part A. Notes under a table record what a row does not cover and, for kept rows, what was narrowed from the internal ledger. @@ -822,7 +822,8 @@ Notes: | `INV-CUT-RECONCILING-001` | ARCHIVED: the legacy bitmap/reconciler is retired. Native owned-map validation and fail-closed attach admission replace its dirty-coverage protection; a provided legacy bitmap is ignored. | M5 native map admission | `core/storage/chunk_layer.go` `AttachChunkLayer` | `TestChunkAttachRefusesAnUnmappedNativeStore`; `TestChunkLayerV3_IgnoresProvidedLegacyBitmap` (`core/storage/chunk_layer_map_only_v3_test.go`) | legacy reconciliation transition retired | ARCHIVED | | `INV-CUT-STAGED-REUSE-001` | Completed uploads survive a refused point in-process, under their intents. A chunk pre-copied outside the barrier is used only if HEAD generation is unchanged and no write and no same-open `Recover` touched it after staging; otherwise it is copied again in the native COW window. | M5 Stage → Copy | `core/storage/chunk_layer.go` `captureLocked`, `stage` | `TestChunkStageV3_SpillBudgetTriggersPrecopy` (`core/storage/chunk_cut_progress_test.go`); `TestChunkStageV3_AbortedPointReusesUploads` (`core/storage/chunk_cut_progress_test.go`); `TestChunkPrecopy_RedirtiedStagedChunkIsRecopied` (`core/storage/chunk_layer_precopy_test.go`); `TestNativeReplacementRecoverInvalidatesStagedImage` (`core/storage/legacy_replacement_v3_test.go`); `TestChunkStageV3_MidUploadAbortReducesRetryBytes` (`core/storage/chunk_abort_upload_bytes_test.go`); `TestCutRevokedMidUploadKeepsItsUploads` (`core/storage/chunk_cut_revoke_reuse_test.go`) | `CutPipeline` `HeadImage` | ACTIVE | | `INV-CUT-STAGED-COUNT-001` | `Stats.StagedChunks` counts each chunk staging finished (remembered for reuse) in every cut attempt, an interrupted round included, and only grows; a re-staged chunk counts again; it is in-process. A cut's `PayloadNs` includes its staging rounds whether or not they uploaded. | M5 Stage (before the barrier) | `core/storage/chunk_cut_payload.go` `rememberPayload`, `streamCutPayloads`; `core/storage/chunk_layer.go` `captureLocked` | `TestChunkStage_StagedChunksCountsFailedAttempts`, `TestChunkStage_StagedChunksCountsAnInterruptedRound`, `TestChunkStage_PayloadTimeCountsStagingWithoutUploads` (`core/storage/chunk_stage_accounting_test.go`) | — | ACTIVE | -| `INV-CUT-BITMAP-001` | The owned map never under-reports: its checkpoint coverage is durable before WAL recycling; UNKNOWN is cleared only after definite HEAD publication and an unchanged capture token. | M5 CAS → Settled; M1 InExtent → Checkpointed | `core/storage/walstore_map_checkpoint_v3.go` `publishCheckpointV3`; `core/storage/chunk_layer_map_v3.go` `persistCapturedMapV3` | `TestWALStoreV3_AutomaticMapCheckpoint` (`core/storage/walstore_map_checkpoint_v3_test.go`); `TestChunkLayerV3_ChangedCaptureTokenKeepsUNKNOWN` (`core/storage/chunk_layer_map_v3_test.go`) | `CutCapture` `HeadImage` | ACTIVE | +| `INV-CUT-BITMAP-001` | The owned map never under-reports: its checkpoint coverage is durable before WAL recycling; UNKNOWN is cleared only after definite HEAD publication (a cut, or a fresh store's claim: `INV-CUT-FRESH-KNOWN-ZERO-001`) and an unchanged capture token. | M5 CAS → Settled; M1 InExtent → Checkpointed | `core/storage/walstore_map_checkpoint_v3.go` `publishCheckpointV3`; `core/storage/chunk_layer_map_v3.go` `persistCapturedMapV3` | `TestWALStoreV3_AutomaticMapCheckpoint` (`core/storage/walstore_map_checkpoint_v3_test.go`); `TestChunkLayerV3_ChangedCaptureTokenKeepsUNKNOWN` (`core/storage/chunk_layer_map_v3_test.go`) | `CutCapture` `HeadImage` | ACTIVE | +| `INV-CUT-FRESH-KNOWN-ZERO-001` | A fresh store's attach (marker present, no BASE) clears UNKNOWN for each chunk its claimed HEAD does not name whose entry is still {LSN 0, UNKNOWN} and whose token is unchanged. Premise: no write, fill or other implementation reaches a store before that attach commits. | M1 Recovering → Serving (fresh attach, before its commit) | `core/storage/chunk_fresh_known_zero.go` `freshKnownZeroCandidates`; `core/storage/chunk_seam.go` `attachChunkLayer`; `core/frontend/durable/provider.go` `openOrCreate` (non-chunk implementations refuse chunk roots) | `TestRedFirstCutOfAFreshVolumeScansOnlyWrittenChunks`, `TestFirstCutAgainstAClaimedHeadCertifiesUnnamedChunks`, `TestFirstCutOfARestoreTargetKeepsItsHydrationPath`, `TestExplicitWALStoreRefusesAFreshChunkRoot` (`core/frontend/durable/first_cut_known_zero_test.go`); `TestNoWriteReachesAFreshStoreBeforeItsAttachCommit`, `TestFreshAttachCrashBeforeCommitDecidesAgain` (`core/frontend/durable/known_zero_premise_test.go`); `TestFreshKnownZeroNeverCertifiesARecordedWrite`, `TestFreshKnownZeroNotWithoutTheFreshPremise`, `TestFreshKnownZeroSkipsAChunkWrittenAfterTheSample` (`core/storage/chunk_fresh_known_zero_test.go`) | `KnownZero` | ACTIVE | | `INV-CUT-RECOVER-BARRIER-001` | Native `Recover` aborts and drains OPEN COW owners before lower locks, with admission held through recovery and a hook snapshot recheck. No recovered record above H can enter a HEAD labelled H. | M5 Quiesce; M1 Recovering | `core/storage/walstore.go` `WALStore.Recover`; `chunk_cut_cow.go` `holdChunkDestructive` | `TestCutCOWV3_RecoveryAndCloseDrainSavingOwner` (`core/storage/chunk_cut_cow_lifetime_test.go`); `TestCutCOWV3_DestructiveSnapshotRetriesFirstAttachment` (`core/storage/chunk_cut_cow_lifetime_test.go`); `TestCutCOWV3_RecoveryAndCloseDrainSavingOwner` (`core/storage/chunk_cut_cow_lifetime_test.go`) | — | ACTIVE | | `INV-CUT-UPLOAD-FROM-BUFFER` | CopyFinish owns an immutable at-H slot. Every PUT retry sends that slot, without rereading local bytes; transient failures keep the point until the caller deadline, window abort or 30-second object deadline. Guest writes to a copied chunk need no save. | M5 Copy -> Upload | `chunk_cut_cow.go` `copyCOWEntry`; `chunk_upload.go` `putCaptured` | `TestCutUploadRetriesPastThreeAttemptsAtSamePoint`, `TestChunkCutUploadDeadlineBoundRetainsDirt`, `TestCutCOWV3_PutRetryUsesFrozenSlot` (`core/storage/chunk_cut_alignment_test.go`) | CutCOW2 BufFrozen; separate upload action extension pending | ACTIVE | | `INV-CUT-NO-WAL-PIN` | A cut window pins no WAL space and does not defer the flusher. Logical readers validate their resolved record and retry against the dirty map/extent after retirement and reuse. | M1 Checkpoint / M5 Copy | `walstore_v3.go` `readDirtyV3`; `flusher.go` `flushOnceInternal` | `TestCutCOWV3_CaptureDoesNotPinWAL` (`core/storage/chunk_cut_alignment_test.go`) | CutFlush refinement; native real ring-reuse control | ACTIVE | From 9c60d8c24748022793f67aab2e7569a499799c7c Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 23 Nov 2026 19:51:40 -0800 Subject: [PATCH 3/6] fix: known-zero needs this start's create; retire the marker before the marking Two parts of the rule are added. Certification needs the store to have been created by this process start (an in-memory bit, never persisted): a fresh marker left by an earlier start, an older binary or another opener is never trusted, so a first start that dies before its attach commit pays one scan. And the order is: the attach commit retires the marker, then the marking is made durable, then the volume serves; a crash between the first two leaves no marker and every chunk UNKNOWN (one scan). The user guide states that every explicit implementation other than walstore-chunk refuses a chunk root. Co-Authored-By: Claude Opus 5.5 --- .../durable/known_zero_premise_test.go | 94 ++++++++++++++++--- .../core/frontend/durable/provider.go | 8 +- .../core/frontend/durable/provider_chunk.go | 13 +++ .../core/storage/chunk_fresh_known_zero.go | 27 ++++-- .../storage/chunk_fresh_known_zero_test.go | 30 +++++- seaweed-block/core/storage/chunk_layer.go | 6 +- seaweed-block/core/storage/chunk_seam.go | 16 ++-- seaweed-block/docs/design/invariants.md | 2 +- seaweed-block/docs/standalone-deployment.md | 2 +- 9 files changed, 157 insertions(+), 41 deletions(-) diff --git a/seaweed-block/core/frontend/durable/known_zero_premise_test.go b/seaweed-block/core/frontend/durable/known_zero_premise_test.go index 1e6859a450..f170ff1d3b 100644 --- a/seaweed-block/core/frontend/durable/known_zero_premise_test.go +++ b/seaweed-block/core/frontend/durable/known_zero_premise_test.go @@ -79,11 +79,11 @@ func TestNoWriteReachesAFreshStoreBeforeItsAttachCommit(t *testing.T) { } } -// A first start that crashes before its attach commit (the commit fails, the -// process ends) leaves the fresh marker: the next start decides again on its -// own claim. It still has no candidates, and a write after it is published -// by the next cut. -func TestFreshAttachCrashBeforeCommitDecidesAgain(t *testing.T) { +// RULE-FRESH-KNOWN-ZERO needs THIS start's create: a first start that +// crashes before its attach commit leaves the fresh marker, but the next +// start did not create the store, so it certifies nothing (one scan: every +// chunk a candidate), and its next cut still publishes a write. +func TestFreshKnownZeroNotAfterARestartBeforeTheAttachCommit(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() root, remote := t.TempDir(), storage.NewMemChunkRemote() @@ -102,7 +102,6 @@ func TestFreshAttachCrashBeforeCommitDecidesAgain(t *testing.T) { if _, err := os.Stat(chunkFreshMarker(p.volumePath("v1"))); err != nil { t.Fatalf("fresh marker after the crash: %v; want it kept", err) } - p2 := kzProvider(t, root, remote) if _, err := p2.EnsureStorage("v1"); err != nil { t.Fatal(err) @@ -110,17 +109,84 @@ func TestFreshAttachCrashBeforeCommitDecidesAgain(t *testing.T) { if _, err := p2.RecoverVolume(ctx, "v1"); err != nil { t.Fatal(err) } - if got := kzCandidates(t, p2); got != 0 { - t.Fatalf("second start: %d candidate chunks; want 0", got) + if got := kzCandidates(t, p2); got != 16 { + t.Fatalf("second start: %d candidate chunks; want all 16 (it did not create the store)", got) } + kzWriteAndPublish(t, ctx, p2, remote) +} + +// The same after a restart between the create and any attach (test #13). +func TestFreshKnownZeroNotAfterARestartBeforeAnyAttach(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + root, remote := t.TempDir(), storage.NewMemChunkRemote() + p := kzProvider(t, root, remote) + if _, err := p.EnsureStorage("v1"); err != nil { + t.Fatal(err) + } + if err := p.Close(); err != nil { + t.Fatal(err) + } + p2 := kzProvider(t, root, remote) + if _, err := p2.EnsureStorage("v1"); err != nil { + t.Fatal(err) + } + if _, err := p2.RecoverVolume(ctx, "v1"); err != nil { + t.Fatal(err) + } + if got := kzCandidates(t, p2); got != 16 { + t.Fatalf("restart before any attach: %d candidate chunks; want all 16", got) + } +} + +// The order: the attach commit retires the marker, THEN the marking is made +// durable, THEN the volume serves. A crash between the first two leaves no +// marker and every chunk UNKNOWN: the next start scans every chunk once, and +// is correct. (Marking before the retirement would leave certified chunks +// behind a marker a later start could trust.) +func TestFreshKnownZeroCrashBetweenMarkerRetireAndMarking(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + root, remote := t.TempDir(), storage.NewMemChunkRemote() + p := kzProvider(t, root, remote) + if _, err := p.EnsureStorage("v1"); err != nil { + t.Fatal(err) + } + crash := errors.New("crash after the marker retirement, before the marking") + p.testAfterChunkFreshRetire = func() error { return crash } + if _, err := p.RecoverVolume(ctx, "v1"); !errors.Is(err, crash) { + t.Fatalf("first start: %v; want the injected crash", err) + } + if err := p.Close(); err != nil { + t.Fatal(err) + } + if _, err := os.Stat(chunkFreshMarker(p.volumePath("v1"))); !os.IsNotExist(err) { + t.Fatalf("fresh marker after the crash: %v; want it retired", err) + } + p2 := kzProvider(t, root, remote) + if _, err := p2.EnsureStorage("v1"); err != nil { + t.Fatal(err) + } + if _, err := p2.RecoverVolume(ctx, "v1"); err != nil { + t.Fatal(err) + } + if got := kzCandidates(t, p2); got != 16 { + t.Fatalf("restart after a crash between marker retirement and marking: %d candidate chunks; want all 16 (one scan)", got) + } + kzWriteAndPublish(t, ctx, p2, remote) +} + +// kzWriteAndPublish writes chunk 5, cuts, and checks HEAD publishes it. +func kzWriteAndPublish(t *testing.T, ctx context.Context, p *DurableProvider, remote *storage.MemChunkRemote) { + t.Helper() want := bytes.Repeat([]byte{0x6b}, 4096) - if _, err := p2.Backend("v1").Write(ctx, 5*16*4096, want); err != nil { + if _, err := p.Backend("v1").Write(ctx, 5*16*4096, want); err != nil { t.Fatal(err) } - if err := p2.Backend("v1").Sync(ctx); err != nil { + if err := p.Backend("v1").Sync(ctx); err != nil { t.Fatal(err) } - if _, err := p2.CaptureVolume(ctx, "v1"); err != nil { + if _, err := p.CaptureVolume(ctx, "v1"); err != nil { t.Fatal(err) } head, err := remote.GetHead(ctx) @@ -129,13 +195,13 @@ func TestFreshAttachCrashBeforeCommitDecidesAgain(t *testing.T) { } ref, ok := head.Chunks[5] if !ok { - t.Fatal("the cut after the second start did not publish chunk 5") + t.Fatal("the cut did not publish chunk 5") } chunk, err := remote.Get(ctx, ref.Key) if err != nil || !bytes.Equal(chunk[:4096], want) { - t.Fatalf("published chunk 5: %v, data equal %v", err, err == nil && bytes.Equal(chunk[:4096], want)) + t.Fatalf("published chunk 5: %v", err) } - if got := kzCandidates(t, p2); got != 0 { + if got := kzCandidates(t, p); got != 0 { t.Fatalf("after the cut: %d candidate chunks; want 0", got) } } diff --git a/seaweed-block/core/frontend/durable/provider.go b/seaweed-block/core/frontend/durable/provider.go index eb631a06a4..8b91b95326 100644 --- a/seaweed-block/core/frontend/durable/provider.go +++ b/seaweed-block/core/frontend/durable/provider.go @@ -267,6 +267,9 @@ type DurableProvider struct { // testBeforeChunkFreshRetire holds the real post-presence/pre-marker boundary. testBeforeChunkFreshRetire func() error + // testAfterChunkFreshRetire runs after the attach commit retired the + // fresh marker, before the known-zero marking is made durable. + testAfterChunkFreshRetire func() error // testWALStoreFactory selects a dark store only in provider caller controls. // No production option, flag or environment variable installs it. @@ -298,6 +301,9 @@ type volHandle struct { // after the first attach succeeded, so an interrupted initialization // is still fresh after a restart. fresh bool + // createdThisStart: this process start created the store (in memory, + // never persisted); RULE-FRESH-KNOWN-ZERO needs it with fresh. + createdThisStart bool attachMu sync.Mutex // serializes recovery and attach of this volume // recoverGen numbers this volume's RecoverVolume calls (written under // attachMu and p.mu). waitGen is the generation of the live authority @@ -864,7 +870,7 @@ func (p *DurableProvider) openOrCreate(volumeID string) (*volHandle, error) { } h, err := p.createFresh(volumeID, path, impl) if err == nil && p.cfg.Impl == ImplWALStoreChunk { - h.fresh = true + h.fresh, h.createdThisStart = true, true } return h, err } diff --git a/seaweed-block/core/frontend/durable/provider_chunk.go b/seaweed-block/core/frontend/durable/provider_chunk.go index f4a2680e6f..f98d76e33d 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk.go +++ b/seaweed-block/core/frontend/durable/provider_chunk.go @@ -321,6 +321,18 @@ func (p *DurableProvider) attachChunk(ctx context.Context, volumeID string, h *v } else if err := commit(); err != nil { return err } + // RULE-FRESH-KNOWN-ZERO order: the marker is retired (above), THEN the + // marking is made durable, THEN the volume serves (after this attach). + if h.fresh { + if hook := p.testAfterChunkFreshRetire; hook != nil { + if err := hook(); err != nil { + return err + } + } + } + if kz, ok := layer.(interface{ ApplyFreshKnownZero() }); ok { + kz.ApplyFreshKnownZero() + } p.mu.Lock() defer p.mu.Unlock() if p.closed { @@ -418,6 +430,7 @@ func (p *DurableProvider) newChunkLayer(ctx context.Context, volumeID string, h Epoch: lin.epoch, Holder: holder, FreshFromHead: h.fresh, + CreatedThisStart: h.fresh && h.createdThisStart, ReadMissTimeout: p.cfg.ChunkReadMissTimeout, HydrationWorkers: p.cfg.ChunkHydrationWorkers, HydrationQueueDepth: p.cfg.ChunkHydrationQueueDepth, diff --git a/seaweed-block/core/storage/chunk_fresh_known_zero.go b/seaweed-block/core/storage/chunk_fresh_known_zero.go index d695f17997..66cd6c2fe3 100644 --- a/seaweed-block/core/storage/chunk_fresh_known_zero.go +++ b/seaweed-block/core/storage/chunk_fresh_known_zero.go @@ -1,8 +1,9 @@ package storage -// RULE-FRESH-KNOWN-ZERO (INV-CUT-BITMAP-001). A fresh store (FreshFromHead -// still true at its attach: the .chunkfresh marker is present and no BASE -// is installed) has never had a write or a fill reach it: frontend I/O is +// RULE-FRESH-KNOWN-ZERO (INV-CUT-FRESH-KNOWN-ZERO-001). A store this process +// start created (CreatedThisStart, in memory) that is still fresh at its +// attach (FreshFromHead: the .chunkfresh marker is present and no BASE is +// installed) has never had a write or a fill reach it: frontend I/O is // admitted only after the attach commit retires the marker, a chunk volume // takes no replication apply, no cut or hydration can resolve the layer // before that commit, and no other implementation opens a root that carries @@ -13,10 +14,12 @@ package storage // freshKnownZeroCandidates samples, under the attach's capture barrier, the // mutation token of every chunk the claimed HEAD does not name whose owned // map entry is still its creation value {LSN 0, Unknown}; the entry test is -// an extra exclusion, not the premise. attachChunkLayer then clears only the -// UNKNOWN bit of those whose token is unchanged, through the cut's own -// persistCapturedMapV3, before the provider's attach commit. A failed map -// publication leaves them UNKNOWN on disk (conservative). +// an extra exclusion, not the premise. ApplyFreshKnownZero then clears only +// the UNKNOWN bit of those whose token is unchanged, through the cut's own +// persistCapturedMapV3. The order is: the attach commit retires the marker, +// THEN the marking is made durable, THEN the volume serves. A crash between +// the first two leaves no marker and every chunk UNKNOWN (one scan); a +// failed map publication leaves them UNKNOWN on disk (conservative). func (l *chunkLayerImpl) freshKnownZeroCandidates(head chunkHead) map[uint64]uint64 { s := l.s if s.v3 == nil || s.v3.ownedMap == nil { @@ -39,3 +42,13 @@ func (l *chunkLayerImpl) freshKnownZeroCandidates(head chunkHead) map[uint64]uin } return out } + +// ApplyFreshKnownZero makes the fresh attach's certification durable: called +// once, by the provider, after the attach commit retired the fresh marker and +// before the volume serves, outside the capture barrier (as for a cut). +func (l *chunkLayerImpl) ApplyFreshKnownZero() { + if tokens := l.freshKnownZero; tokens != nil { + l.freshKnownZero = nil + l.persistCapturedMapV3(tokens) + } +} diff --git a/seaweed-block/core/storage/chunk_fresh_known_zero_test.go b/seaweed-block/core/storage/chunk_fresh_known_zero_test.go index da243a67b9..3b0ff9fc53 100644 --- a/seaweed-block/core/storage/chunk_fresh_known_zero_test.go +++ b/seaweed-block/core/storage/chunk_fresh_known_zero_test.go @@ -9,10 +9,19 @@ import ( // store's. func fkzConfig(fresh bool) chunkLayerConfig { cfg := ctConfig(1) - cfg.FreshFromHead = fresh + cfg.FreshFromHead, cfg.CreatedThisStart = fresh, fresh return cfg } +// fkzAttach attaches and applies the certification, as the provider does +// after its attach commit. +func fkzAttach(t *testing.T, s *WALStore, r chunkRemote, cfg chunkLayerConfig) chunkLayer { + t.Helper() + l := mustAttach(t, s, r, cfg) + l.(*chunkLayerImpl).ApplyFreshKnownZero() + return l +} + func fkzCandidates(l chunkLayer) int { return l.Stats().DirtyChunks } // A fresh attach certifies every chunk the claimed HEAD does not name whose @@ -27,7 +36,7 @@ func TestFreshKnownZeroNeverCertifiesARecordedWrite(t *testing.T) { } remote := newFakeChunkRemote() remote.head = chunkHead{Gen: 1, Epoch: 1, RemoteLSN: 100, State: ChunkHeadActive} - l := mustAttach(t, s, remote, fkzConfig(true)) + l := fkzAttach(t, s, remote, fkzConfig(true)) if got := fkzCandidates(l); got != 1 { t.Fatalf("fresh attach after a recorded write to chunk 2: %d candidates; want 1 (that chunk only)", got) } @@ -37,7 +46,7 @@ func TestFreshKnownZeroNeverCertifiesARecordedWrite(t *testing.T) { // chunk keeps its persisted UNKNOWN. func TestFreshKnownZeroNotWithoutTheFreshPremise(t *testing.T) { s, _ := newChunkTestStore(t) - l := mustAttach(t, s, newFakeChunkRemote(), fkzConfig(false)) + l := fkzAttach(t, s, newFakeChunkRemote(), fkzConfig(false)) if got, want := fkzCandidates(l), int(l.(*chunkLayerImpl).numChunks); got != want { t.Fatalf("existing-store attach: %d candidates; want all %d", got, want) } @@ -60,9 +69,20 @@ func TestFreshKnownZeroSkipsAChunkWrittenAfterTheSample(t *testing.T) { if _, err := s.Write(uint32(3*ctChunkBlocks), bytes.Repeat([]byte{0x33}, ctBlockSize)); err != nil { t.Fatal(err) } - l.persistCapturedMapV3(l.freshKnownZero) - l.freshKnownZero = nil + l.ApplyFreshKnownZero() if got := fkzCandidates(l); got != 1 { t.Fatalf("a write between the sample and the clear: %d candidates; want 1 (the written chunk)", got) } } + +// A fresh marker alone is not trusted: an attach whose store this start did +// not create (CreatedThisStart false) certifies nothing. +func TestFreshKnownZeroNeedsThisStartsCreate(t *testing.T) { + s, _ := newChunkTestStore(t) + cfg := fkzConfig(true) + cfg.CreatedThisStart = false + l := fkzAttach(t, s, newFakeChunkRemote(), cfg) + if got, want := fkzCandidates(l), int(l.(*chunkLayerImpl).numChunks); got != want { + t.Fatalf("fresh attach of a store this start did not create: %d candidates; want all %d", got, want) + } +} diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index e2a7562eb2..ddd5015a30 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -63,7 +63,7 @@ type chunkLayerImpl struct { cfg chunkLayerConfig // freshKnownZero: the mutation tokens RULE-FRESH-KNOWN-ZERO sampled at a - // fresh attach; applied and cleared by attachChunkLayer. + // fresh attach; applied once by ApplyFreshKnownZero. freshKnownZero map[uint64]uint64 blockSize int @@ -291,7 +291,9 @@ func attachChunkLayerImpl(s *WALStore, remote chunkRemote, cfg chunkLayerConfig) l.absentGen[idx]++ } l.presenceVer++ - l.freshKnownZero = l.freshKnownZeroCandidates(head) + if cfg.CreatedThisStart { + l.freshKnownZero = l.freshKnownZeroCandidates(head) + } } else if err := l.loadPresence(); err != nil { l.cancel() return nil, err diff --git a/seaweed-block/core/storage/chunk_seam.go b/seaweed-block/core/storage/chunk_seam.go index e6e5adee6c..b6c36729b8 100644 --- a/seaweed-block/core/storage/chunk_seam.go +++ b/seaweed-block/core/storage/chunk_seam.go @@ -343,6 +343,11 @@ type chunkLayerConfig struct { // HEAD (every block absent, read lazily). False means an existing local // volume. Never inferred from the local contents. FreshFromHead bool + // 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 + // older binary or another opener is never trusted. + CreatedThisStart bool // RestoreGuard binds fresh attachment to the HEAD the provider claimed // and durably seeded. A changed read refuses before hooks/readiness; the // next recovery must repeat claim and seed. Nil is for direct layer users. @@ -653,14 +658,5 @@ var ( // attachChunkLayer attaches a chunk layer to an open store (chunk_layer.go). func attachChunkLayer(s *WALStore, remote chunkRemote, cfg chunkLayerConfig) (chunkLayer, error) { - l, err := attachChunkLayerImpl(s, remote, cfg) - if err != nil { - return nil, err - } - // RULE-FRESH-KNOWN-ZERO: outside the capture barrier, as for a cut. - if impl, ok := l.(*chunkLayerImpl); ok && impl.freshKnownZero != nil { - impl.persistCapturedMapV3(impl.freshKnownZero) - impl.freshKnownZero = nil - } - return l, nil + return attachChunkLayerImpl(s, remote, cfg) } diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index fa1c220b56..4a11b1ae9a 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -823,7 +823,7 @@ Notes: | `INV-CUT-STAGED-REUSE-001` | Completed uploads survive a refused point in-process, under their intents. A chunk pre-copied outside the barrier is used only if HEAD generation is unchanged and no write and no same-open `Recover` touched it after staging; otherwise it is copied again in the native COW window. | M5 Stage → Copy | `core/storage/chunk_layer.go` `captureLocked`, `stage` | `TestChunkStageV3_SpillBudgetTriggersPrecopy` (`core/storage/chunk_cut_progress_test.go`); `TestChunkStageV3_AbortedPointReusesUploads` (`core/storage/chunk_cut_progress_test.go`); `TestChunkPrecopy_RedirtiedStagedChunkIsRecopied` (`core/storage/chunk_layer_precopy_test.go`); `TestNativeReplacementRecoverInvalidatesStagedImage` (`core/storage/legacy_replacement_v3_test.go`); `TestChunkStageV3_MidUploadAbortReducesRetryBytes` (`core/storage/chunk_abort_upload_bytes_test.go`); `TestCutRevokedMidUploadKeepsItsUploads` (`core/storage/chunk_cut_revoke_reuse_test.go`) | `CutPipeline` `HeadImage` | ACTIVE | | `INV-CUT-STAGED-COUNT-001` | `Stats.StagedChunks` counts each chunk staging finished (remembered for reuse) in every cut attempt, an interrupted round included, and only grows; a re-staged chunk counts again; it is in-process. A cut's `PayloadNs` includes its staging rounds whether or not they uploaded. | M5 Stage (before the barrier) | `core/storage/chunk_cut_payload.go` `rememberPayload`, `streamCutPayloads`; `core/storage/chunk_layer.go` `captureLocked` | `TestChunkStage_StagedChunksCountsFailedAttempts`, `TestChunkStage_StagedChunksCountsAnInterruptedRound`, `TestChunkStage_PayloadTimeCountsStagingWithoutUploads` (`core/storage/chunk_stage_accounting_test.go`) | — | ACTIVE | | `INV-CUT-BITMAP-001` | The owned map never under-reports: its checkpoint coverage is durable before WAL recycling; UNKNOWN is cleared only after definite HEAD publication (a cut, or a fresh store's claim: `INV-CUT-FRESH-KNOWN-ZERO-001`) and an unchanged capture token. | M5 CAS → Settled; M1 InExtent → Checkpointed | `core/storage/walstore_map_checkpoint_v3.go` `publishCheckpointV3`; `core/storage/chunk_layer_map_v3.go` `persistCapturedMapV3` | `TestWALStoreV3_AutomaticMapCheckpoint` (`core/storage/walstore_map_checkpoint_v3_test.go`); `TestChunkLayerV3_ChangedCaptureTokenKeepsUNKNOWN` (`core/storage/chunk_layer_map_v3_test.go`) | `CutCapture` `HeadImage` | ACTIVE | -| `INV-CUT-FRESH-KNOWN-ZERO-001` | A fresh store's attach (marker present, no BASE) clears UNKNOWN for each chunk its claimed HEAD does not name whose entry is still {LSN 0, UNKNOWN} and whose token is unchanged. Premise: no write, fill or other implementation reaches a store before that attach commits. | M1 Recovering → Serving (fresh attach, before its commit) | `core/storage/chunk_fresh_known_zero.go` `freshKnownZeroCandidates`; `core/storage/chunk_seam.go` `attachChunkLayer`; `core/frontend/durable/provider.go` `openOrCreate` (non-chunk implementations refuse chunk roots) | `TestRedFirstCutOfAFreshVolumeScansOnlyWrittenChunks`, `TestFirstCutAgainstAClaimedHeadCertifiesUnnamedChunks`, `TestFirstCutOfARestoreTargetKeepsItsHydrationPath`, `TestExplicitWALStoreRefusesAFreshChunkRoot` (`core/frontend/durable/first_cut_known_zero_test.go`); `TestNoWriteReachesAFreshStoreBeforeItsAttachCommit`, `TestFreshAttachCrashBeforeCommitDecidesAgain` (`core/frontend/durable/known_zero_premise_test.go`); `TestFreshKnownZeroNeverCertifiesARecordedWrite`, `TestFreshKnownZeroNotWithoutTheFreshPremise`, `TestFreshKnownZeroSkipsAChunkWrittenAfterTheSample` (`core/storage/chunk_fresh_known_zero_test.go`) | `KnownZero` | ACTIVE | +| `INV-CUT-FRESH-KNOWN-ZERO-001` | A store this start created (in memory) and still fresh at its attach (marker present, no BASE) starts known-zero for each chunk its claimed HEAD does not name whose entry is still {LSN 0, UNKNOWN}. Order: retire the marker, then make the marking durable, then serve. | M1 Recovering → Serving (fresh attach: commit, marking, then serving) | `core/storage/chunk_fresh_known_zero.go` `freshKnownZeroCandidates`, `ApplyFreshKnownZero`; `core/frontend/durable/provider_chunk.go` `attachChunk`; `core/frontend/durable/provider.go` `openOrCreate` (`createdThisStart`; non-chunk implementations refuse chunk roots) | `TestRedFirstCutOfAFreshVolumeScansOnlyWrittenChunks`, `TestFirstCutAgainstAClaimedHeadCertifiesUnnamedChunks`, `TestFirstCutOfARestoreTargetKeepsItsHydrationPath`, `TestExplicitWALStoreRefusesAFreshChunkRoot` (`core/frontend/durable/first_cut_known_zero_test.go`); `TestNoWriteReachesAFreshStoreBeforeItsAttachCommit`, `TestFreshKnownZeroNotAfterARestartBeforeTheAttachCommit`, `TestFreshKnownZeroNotAfterARestartBeforeAnyAttach`, `TestFreshKnownZeroCrashBetweenMarkerRetireAndMarking` (`core/frontend/durable/known_zero_premise_test.go`); `TestFreshKnownZeroNeverCertifiesARecordedWrite`, `TestFreshKnownZeroNotWithoutTheFreshPremise`, `TestFreshKnownZeroSkipsAChunkWrittenAfterTheSample`, `TestFreshKnownZeroNeedsThisStartsCreate` (`core/storage/chunk_fresh_known_zero_test.go`) | `KnownZero`. Premise: no write, fill or other implementation reaches a store before its attach commit; a marker an earlier start, an older binary or another opener left is never trusted (created-this-start is in memory). A crash between retirement and marking costs one scan. | ACTIVE | | `INV-CUT-RECOVER-BARRIER-001` | Native `Recover` aborts and drains OPEN COW owners before lower locks, with admission held through recovery and a hook snapshot recheck. No recovered record above H can enter a HEAD labelled H. | M5 Quiesce; M1 Recovering | `core/storage/walstore.go` `WALStore.Recover`; `chunk_cut_cow.go` `holdChunkDestructive` | `TestCutCOWV3_RecoveryAndCloseDrainSavingOwner` (`core/storage/chunk_cut_cow_lifetime_test.go`); `TestCutCOWV3_DestructiveSnapshotRetriesFirstAttachment` (`core/storage/chunk_cut_cow_lifetime_test.go`); `TestCutCOWV3_RecoveryAndCloseDrainSavingOwner` (`core/storage/chunk_cut_cow_lifetime_test.go`) | — | ACTIVE | | `INV-CUT-UPLOAD-FROM-BUFFER` | CopyFinish owns an immutable at-H slot. Every PUT retry sends that slot, without rereading local bytes; transient failures keep the point until the caller deadline, window abort or 30-second object deadline. Guest writes to a copied chunk need no save. | M5 Copy -> Upload | `chunk_cut_cow.go` `copyCOWEntry`; `chunk_upload.go` `putCaptured` | `TestCutUploadRetriesPastThreeAttemptsAtSamePoint`, `TestChunkCutUploadDeadlineBoundRetainsDirt`, `TestCutCOWV3_PutRetryUsesFrozenSlot` (`core/storage/chunk_cut_alignment_test.go`) | CutCOW2 BufFrozen; separate upload action extension pending | ACTIVE | | `INV-CUT-NO-WAL-PIN` | A cut window pins no WAL space and does not defer the flusher. Logical readers validate their resolved record and retry against the dirty map/extent after retirement and reuse. | M1 Checkpoint / M5 Copy | `walstore_v3.go` `readDirtyV3`; `flusher.go` `flushOnceInternal` | `TestCutCOWV3_CaptureDoesNotPinWAL` (`core/storage/chunk_cut_alignment_test.go`) | CutFlush refinement; native real ring-reuse control | ACTIVE | diff --git a/seaweed-block/docs/standalone-deployment.md b/seaweed-block/docs/standalone-deployment.md index c04d06e2e4..1b150ca45a 100644 --- a/seaweed-block/docs/standalone-deployment.md +++ b/seaweed-block/docs/standalone-deployment.md @@ -202,7 +202,7 @@ with `move target node "s2" is not registered`. | `SWB_HEARTBEAT_INTERVAL` | `--heartbeat-interval` | `2s` | Heartbeat interval | | `SWB_RECOVER_TIMEOUT` | `--recover-timeout` | `30s` | Time to become promotion-ready before reporting `recovery_timeout` | | `SWB_DURABLE_ROOT` | `--durable-root` | empty (in memory, not durable) | Storage directory; writable by the service user | -| `SWB_DURABLE_IMPL` | `--durable-impl` | empty (auto) | Auto creates new volumes as `walstore`, opens existing ones with their on-disk format, and refuses a `walstore-chunk` root. Explicit: `walstore`, `walstore-chunk` (workspace, proof of concept), `smartwal` (experimental). The examples set `walstore`. | +| `SWB_DURABLE_IMPL` | `--durable-impl` | empty (auto) | Auto creates new volumes as `walstore`, opens existing ones with their on-disk format, and refuses a `walstore-chunk` root; so does every explicit value other than `walstore-chunk` (a chunk root holds data that may live only in the remote HEAD: open it with `--durable-impl=walstore-chunk` and its remote configuration). Explicit: `walstore`, `walstore-chunk` (workspace, proof of concept), `smartwal` (experimental). The examples set `walstore`. | | `SWB_DURABLE_BLOCKS` | `--durable-blocks` | `2048` | Blocks on first create | | `SWB_DURABLE_BLOCKSIZE` | `--durable-blocksize` | `4096` | Block size on first create | | `SWB_NVME_LISTEN` | `--nvme-listen` | empty (off) | NVMe/TCP target; loopback only, no authentication | From 520fb10cf4e245ff82f07f0bfbb70cab9b55b9dd Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 23 Nov 2026 19:51:58 -0800 Subject: [PATCH 4/6] durable: gofmt the provider handle struct Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/frontend/durable/provider.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/seaweed-block/core/frontend/durable/provider.go b/seaweed-block/core/frontend/durable/provider.go index 8b91b95326..e62a49182d 100644 --- a/seaweed-block/core/frontend/durable/provider.go +++ b/seaweed-block/core/frontend/durable/provider.go @@ -300,11 +300,11 @@ type volHandle struct { // volume file, written before the file is created and removed only // after the first attach succeeded, so an interrupted initialization // is still fresh after a restart. - fresh bool + fresh bool // createdThisStart: this process start created the store (in memory, // never persisted); RULE-FRESH-KNOWN-ZERO needs it with fresh. createdThisStart bool - attachMu sync.Mutex // serializes recovery and attach of this volume + attachMu sync.Mutex // serializes recovery and attach of this volume // recoverGen numbers this volume's RecoverVolume calls (written under // attachMu and p.mu). waitGen is the generation of the live authority // wait, 0 if none: a recovered volume whose layer waits for master From 2d65269fce63e974adb73a30128395c8783f89a7 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 23 Nov 2026 20:27:11 -0800 Subject: [PATCH 5/6] fix: report how many chunks a fresh attach certified known-zero ApplyFreshKnownZero now records the count in Stats.KnownZeroChunks and logs it; when some sampled chunks stay unknown (a failed map publication or a raced write) the log says the first cut will scan them, so a lab run that sees a full first scan has the reason in the status and log. Co-Authored-By: Claude Opus 5.5 --- .../durable/known_zero_premise_test.go | 5 ++++ .../core/storage/chunk_fresh_known_zero.go | 30 +++++++++++++++++-- .../storage/chunk_fresh_known_zero_test.go | 12 +++++++- seaweed-block/core/storage/chunk_seam.go | 1 + seaweed-block/docs/status-schema.md | 1 + 5 files changed, 45 insertions(+), 4 deletions(-) diff --git a/seaweed-block/core/frontend/durable/known_zero_premise_test.go b/seaweed-block/core/frontend/durable/known_zero_premise_test.go index f170ff1d3b..f0bad655cb 100644 --- a/seaweed-block/core/frontend/durable/known_zero_premise_test.go +++ b/seaweed-block/core/frontend/durable/known_zero_premise_test.go @@ -77,6 +77,11 @@ func TestNoWriteReachesAFreshStoreBeforeItsAttachCommit(t *testing.T) { if got := kzCandidates(t, p); got != 0 { t.Fatalf("after the commit: %d candidate chunks; want 0 (nothing was written)", got) } + for _, st := range p.DurableStatuses() { + if st.VolumeID == "v1" && st.Chunk != nil && st.Chunk.Stats.KnownZeroChunks != 16 { + t.Fatalf("status KnownZeroChunks %d; want 16", st.Chunk.Stats.KnownZeroChunks) + } + } } // RULE-FRESH-KNOWN-ZERO needs THIS start's create: a first start that diff --git a/seaweed-block/core/storage/chunk_fresh_known_zero.go b/seaweed-block/core/storage/chunk_fresh_known_zero.go index 66cd6c2fe3..1989229980 100644 --- a/seaweed-block/core/storage/chunk_fresh_known_zero.go +++ b/seaweed-block/core/storage/chunk_fresh_known_zero.go @@ -1,5 +1,7 @@ package storage +import "log" + // RULE-FRESH-KNOWN-ZERO (INV-CUT-FRESH-KNOWN-ZERO-001). A store this process // start created (CreatedThisStart, in memory) that is still fresh at its // attach (FreshFromHead: the .chunkfresh marker is present and no BASE is @@ -46,9 +48,31 @@ func (l *chunkLayerImpl) freshKnownZeroCandidates(head chunkHead) map[uint64]uin // ApplyFreshKnownZero makes the fresh attach's certification durable: called // once, by the provider, after the attach commit retired the fresh marker and // before the volume serves, outside the capture barrier (as for a cut). +// It counts the chunks it certified in Stats.KnownZeroChunks and logs the +// outcome: a failed map publication or a raced write leaves chunks UNKNOWN, +// and the first cut then scans them (the log says why). func (l *chunkLayerImpl) ApplyFreshKnownZero() { - if tokens := l.freshKnownZero; tokens != nil { - l.freshKnownZero = nil - l.persistCapturedMapV3(tokens) + tokens := l.freshKnownZero + if tokens == nil { + return + } + l.freshKnownZero = nil + l.persistCapturedMapV3(tokens) + s := l.s + s.mu.RLock() + certified := 0 + for idx := range tokens { + if idx < uint64(len(s.v3.mapEntries)) && !s.v3.mapEntries[idx].Unknown { + certified++ + } + } + s.mu.RUnlock() + l.stMu.Lock() + l.stats.KnownZeroChunks = uint64(certified) + l.stMu.Unlock() + if certified == len(tokens) { + log.Printf("storage: fresh attach: %d chunks HEAD does not name start known-zero", certified) + } else { + log.Printf("storage: fresh attach: %d of %d chunks HEAD does not name start known-zero; the rest stay unknown (map publication failed or a write raced) and the first cut scans them", certified, len(tokens)) } } diff --git a/seaweed-block/core/storage/chunk_fresh_known_zero_test.go b/seaweed-block/core/storage/chunk_fresh_known_zero_test.go index 3b0ff9fc53..8be9b51de3 100644 --- a/seaweed-block/core/storage/chunk_fresh_known_zero_test.go +++ b/seaweed-block/core/storage/chunk_fresh_known_zero_test.go @@ -40,6 +40,9 @@ func TestFreshKnownZeroNeverCertifiesARecordedWrite(t *testing.T) { if got := fkzCandidates(l); got != 1 { t.Fatalf("fresh attach after a recorded write to chunk 2: %d candidates; want 1 (that chunk only)", got) } + if got, want := l.Stats().KnownZeroChunks, uint64(l.(*chunkLayerImpl).numChunks-1); got != want { + t.Fatalf("KnownZeroChunks %d; want %d", got, want) + } } // Without the fresh premise (an existing store) nothing is certified: every @@ -50,6 +53,9 @@ func TestFreshKnownZeroNotWithoutTheFreshPremise(t *testing.T) { if got, want := fkzCandidates(l), int(l.(*chunkLayerImpl).numChunks); got != want { t.Fatalf("existing-store attach: %d candidates; want all %d", got, want) } + if got := l.Stats().KnownZeroChunks; got != 0 { + t.Fatalf("KnownZeroChunks %d without the fresh premise; want 0", got) + } } // The certification clears only chunks whose mutation token is unchanged @@ -63,7 +69,8 @@ func TestFreshKnownZeroSkipsAChunkWrittenAfterTheSample(t *testing.T) { } l := raw.(*chunkLayerImpl) t.Cleanup(func() { _ = l.Close() }) - if len(l.freshKnownZero) == 0 { + sampled := len(l.freshKnownZero) + if sampled == 0 { t.Fatal("no chunk sampled for certification") } if _, err := s.Write(uint32(3*ctChunkBlocks), bytes.Repeat([]byte{0x33}, ctBlockSize)); err != nil { @@ -73,6 +80,9 @@ func TestFreshKnownZeroSkipsAChunkWrittenAfterTheSample(t *testing.T) { if got := fkzCandidates(l); got != 1 { t.Fatalf("a write between the sample and the clear: %d candidates; want 1 (the written chunk)", got) } + if got := l.Stats().KnownZeroChunks; got != uint64(sampled-1) { + t.Fatalf("KnownZeroChunks %d; want %d (every sampled chunk but the written one)", got, sampled-1) + } } // A fresh marker alone is not trusted: an attach whose store this start did diff --git a/seaweed-block/core/storage/chunk_seam.go b/seaweed-block/core/storage/chunk_seam.go index b6c36729b8..e1081f5421 100644 --- a/seaweed-block/core/storage/chunk_seam.go +++ b/seaweed-block/core/storage/chunk_seam.go @@ -524,6 +524,7 @@ type chunkLayerStats struct { PendingUnresolved bool // an unresolved HEAD proposal is held now DirtyChunks int // chunks dirty since the last HEAD (not counting those awaiting reconciliation): candidates, not progress StagedChunks uint64 // chunks staged by every cut attempt, failed ones included (in-process) + KnownZeroChunks uint64 // chunks this layer's fresh attach certified known-zero (RULE-FRESH-KNOWN-ZERO); 0 otherwise Reconciling bool // the dirty set is being reconciled against HEAD; no cut publishes meanwhile ReconcileDone int // chunks compared so far ReconcileTotal int // chunks to compare diff --git a/seaweed-block/docs/status-schema.md b/seaweed-block/docs/status-schema.md index 8e38ecfade..ee2e0c58ac 100644 --- a/seaweed-block/docs/status-schema.md +++ b/seaweed-block/docs/status-schema.md @@ -229,6 +229,7 @@ Durable store state of the served volume. Go type `volume.durableStatusBody`. | `Volumes[].Chunk.Stats.PendingUnresolved` | bool | an unresolved HEAD proposal is held now | | `Volumes[].Chunk.Stats.DirtyChunks` | int | chunks dirty since the last HEAD (not counting those awaiting reconciliation): candidates, not progress | | `Volumes[].Chunk.Stats.StagedChunks` | uint64 | chunks staged by every cut attempt, failed ones included (in-process) | +| `Volumes[].Chunk.Stats.KnownZeroChunks` | uint64 | chunks this layer's fresh attach certified known-zero (RULE-FRESH-KNOWN-ZERO); 0 otherwise | | `Volumes[].Chunk.Stats.Reconciling` | bool | the dirty set is being reconciled against HEAD; no cut publishes meanwhile | | `Volumes[].Chunk.Stats.ReconcileDone` | int | chunks compared so far | | `Volumes[].Chunk.Stats.ReconcileTotal` | int | chunks to compare | From 45134d4581332b4198ba8f760dd4a5e7ad529f69 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 23 Nov 2026 22:07:05 -0800 Subject: [PATCH 6/6] test: no fetch and no fill reaches a fresh store before its attach commit A restore target whose HEAD names two chunks, held at the attach commit boundary: a frontend read of a HEAD-named block is not served, the remote serves no chunk read, and after the commit both named chunks are still absent with no fetch started (no fill wrote the extent); the read then returns HEAD's data. A shortfall in the fresh attach's certification is logged as a warning. Co-Authored-By: Claude Opus 5.5 --- .../durable/known_zero_premise_test.go | 81 +++++++++++++++++++ .../core/storage/chunk_fresh_known_zero.go | 2 +- seaweed-block/docs/design/invariants.md | 2 +- 3 files changed, 83 insertions(+), 2 deletions(-) diff --git a/seaweed-block/core/frontend/durable/known_zero_premise_test.go b/seaweed-block/core/frontend/durable/known_zero_premise_test.go index f0bad655cb..d9d7636534 100644 --- a/seaweed-block/core/frontend/durable/known_zero_premise_test.go +++ b/seaweed-block/core/frontend/durable/known_zero_premise_test.go @@ -5,6 +5,7 @@ import ( "context" "errors" "os" + "sync/atomic" "testing" "time" @@ -210,3 +211,83 @@ func kzWriteAndPublish(t *testing.T, ctx context.Context, p *DurableProvider, re t.Fatalf("after the cut: %d candidate chunks; want 0", got) } } + +// kzCountingRemote counts chunk reads (Get) of the remote it wraps. +type kzCountingRemote struct { + storage.ChunkRemote + gets atomic.Int64 +} + +func (r *kzCountingRemote) Get(ctx context.Context, key string) ([]byte, error) { + r.gets.Add(1) + return r.ChunkRemote.Get(ctx, key) +} + +// The premise again, for fills (test #12): until the attach commit retires +// the fresh marker, no fetch and no extent write reaches the store. A restore +// target whose HEAD names two chunks is held at the commit boundary; a +// frontend read of a HEAD-named block there is not served (it may wait; +// here it is bounded), the remote serves no chunk read, and after the +// commit both named chunks are still absent with no fetch started: no fill +// wrote the extent. After that the read returns HEAD's data. +func TestNoFetchOrFillReachesAFreshStoreBeforeItsAttachCommit(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + mem := storage.NewMemChunkRemote() + src := kzProvider(t, t.TempDir(), mem) + if _, err := src.EnsureStorage("v1"); err != nil { + t.Fatal(err) + } + if _, err := src.RecoverVolume(ctx, "v1"); err != nil { + t.Fatal(err) + } + want := bytes.Repeat([]byte{0x3c}, 4096) + for _, chunk := range []int64{3, 7} { + if _, err := src.Backend("v1").Write(ctx, chunk*16*4096, want); err != nil { + t.Fatal(err) + } + } + if err := src.Backend("v1").Sync(ctx); err != nil { + t.Fatal(err) + } + if _, err := src.CaptureVolume(ctx, "v1"); err != nil { + t.Fatal(err) + } + if err := src.Close(); err != nil { + t.Fatal(err) + } + + remote := &kzCountingRemote{ChunkRemote: mem} + p := kzProvider(t, t.TempDir(), remote) + if _, err := p.EnsureStorage("v1"); err != nil { + t.Fatal(err) + } + var readErr error + var getsAtBoundary int64 = -1 + p.testBeforeChunkFreshRetire = func() error { + before := remote.gets.Load() + rctx, rcancel := context.WithTimeout(ctx, 300*time.Millisecond) + defer rcancel() + _, readErr = p.Backend("v1").Read(rctx, 3*16*4096, make([]byte, 4096)) + getsAtBoundary = remote.gets.Load() - before + return nil + } + if _, err := p.RecoverVolume(ctx, "v1"); err != nil { + t.Fatal(err) + } + p.testBeforeChunkFreshRetire = nil + if readErr == nil || getsAtBoundary != 0 { + t.Fatalf("at the commit boundary a frontend read of a HEAD-named block returned %v and the remote served %d chunk reads; want refused, 0", readErr, getsAtBoundary) + } + for _, st := range p.DurableStatuses() { + if st.VolumeID == "v1" && st.Chunk != nil { + if h := st.Chunk.Stats.Hydration; st.Chunk.Stats.AbsentChunks != 2 || h.Fetches != 0 || h.Completed != 0 { + t.Fatalf("after the commit: %d absent chunks, %d fetches, %d completed; want 2 absent and no fetch (no fill before the commit)", st.Chunk.Stats.AbsentChunks, h.Fetches, h.Completed) + } + } + } + got := make([]byte, 4096) + if n, err := p.Backend("v1").Read(ctx, 3*16*4096, got); err != nil || n != len(got) || !bytes.Equal(got, want) { + t.Fatalf("read after the commit: %d %v, data equal %v; want HEAD's data", n, err, bytes.Equal(got, want)) + } +} diff --git a/seaweed-block/core/storage/chunk_fresh_known_zero.go b/seaweed-block/core/storage/chunk_fresh_known_zero.go index 1989229980..f2fba525e2 100644 --- a/seaweed-block/core/storage/chunk_fresh_known_zero.go +++ b/seaweed-block/core/storage/chunk_fresh_known_zero.go @@ -73,6 +73,6 @@ func (l *chunkLayerImpl) ApplyFreshKnownZero() { if certified == len(tokens) { log.Printf("storage: fresh attach: %d chunks HEAD does not name start known-zero", certified) } else { - log.Printf("storage: fresh attach: %d of %d chunks HEAD does not name start known-zero; the rest stay unknown (map publication failed or a write raced) and the first cut scans them", certified, len(tokens)) + log.Printf("storage: WARNING: fresh attach: %d of %d chunks HEAD does not name start known-zero; the rest stay unknown (map publication failed or a write raced) and the first cut scans them", certified, len(tokens)) } } diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 4a11b1ae9a..5b18f829fd 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -823,7 +823,7 @@ Notes: | `INV-CUT-STAGED-REUSE-001` | Completed uploads survive a refused point in-process, under their intents. A chunk pre-copied outside the barrier is used only if HEAD generation is unchanged and no write and no same-open `Recover` touched it after staging; otherwise it is copied again in the native COW window. | M5 Stage → Copy | `core/storage/chunk_layer.go` `captureLocked`, `stage` | `TestChunkStageV3_SpillBudgetTriggersPrecopy` (`core/storage/chunk_cut_progress_test.go`); `TestChunkStageV3_AbortedPointReusesUploads` (`core/storage/chunk_cut_progress_test.go`); `TestChunkPrecopy_RedirtiedStagedChunkIsRecopied` (`core/storage/chunk_layer_precopy_test.go`); `TestNativeReplacementRecoverInvalidatesStagedImage` (`core/storage/legacy_replacement_v3_test.go`); `TestChunkStageV3_MidUploadAbortReducesRetryBytes` (`core/storage/chunk_abort_upload_bytes_test.go`); `TestCutRevokedMidUploadKeepsItsUploads` (`core/storage/chunk_cut_revoke_reuse_test.go`) | `CutPipeline` `HeadImage` | ACTIVE | | `INV-CUT-STAGED-COUNT-001` | `Stats.StagedChunks` counts each chunk staging finished (remembered for reuse) in every cut attempt, an interrupted round included, and only grows; a re-staged chunk counts again; it is in-process. A cut's `PayloadNs` includes its staging rounds whether or not they uploaded. | M5 Stage (before the barrier) | `core/storage/chunk_cut_payload.go` `rememberPayload`, `streamCutPayloads`; `core/storage/chunk_layer.go` `captureLocked` | `TestChunkStage_StagedChunksCountsFailedAttempts`, `TestChunkStage_StagedChunksCountsAnInterruptedRound`, `TestChunkStage_PayloadTimeCountsStagingWithoutUploads` (`core/storage/chunk_stage_accounting_test.go`) | — | ACTIVE | | `INV-CUT-BITMAP-001` | The owned map never under-reports: its checkpoint coverage is durable before WAL recycling; UNKNOWN is cleared only after definite HEAD publication (a cut, or a fresh store's claim: `INV-CUT-FRESH-KNOWN-ZERO-001`) and an unchanged capture token. | M5 CAS → Settled; M1 InExtent → Checkpointed | `core/storage/walstore_map_checkpoint_v3.go` `publishCheckpointV3`; `core/storage/chunk_layer_map_v3.go` `persistCapturedMapV3` | `TestWALStoreV3_AutomaticMapCheckpoint` (`core/storage/walstore_map_checkpoint_v3_test.go`); `TestChunkLayerV3_ChangedCaptureTokenKeepsUNKNOWN` (`core/storage/chunk_layer_map_v3_test.go`) | `CutCapture` `HeadImage` | ACTIVE | -| `INV-CUT-FRESH-KNOWN-ZERO-001` | A store this start created (in memory) and still fresh at its attach (marker present, no BASE) starts known-zero for each chunk its claimed HEAD does not name whose entry is still {LSN 0, UNKNOWN}. Order: retire the marker, then make the marking durable, then serve. | M1 Recovering → Serving (fresh attach: commit, marking, then serving) | `core/storage/chunk_fresh_known_zero.go` `freshKnownZeroCandidates`, `ApplyFreshKnownZero`; `core/frontend/durable/provider_chunk.go` `attachChunk`; `core/frontend/durable/provider.go` `openOrCreate` (`createdThisStart`; non-chunk implementations refuse chunk roots) | `TestRedFirstCutOfAFreshVolumeScansOnlyWrittenChunks`, `TestFirstCutAgainstAClaimedHeadCertifiesUnnamedChunks`, `TestFirstCutOfARestoreTargetKeepsItsHydrationPath`, `TestExplicitWALStoreRefusesAFreshChunkRoot` (`core/frontend/durable/first_cut_known_zero_test.go`); `TestNoWriteReachesAFreshStoreBeforeItsAttachCommit`, `TestFreshKnownZeroNotAfterARestartBeforeTheAttachCommit`, `TestFreshKnownZeroNotAfterARestartBeforeAnyAttach`, `TestFreshKnownZeroCrashBetweenMarkerRetireAndMarking` (`core/frontend/durable/known_zero_premise_test.go`); `TestFreshKnownZeroNeverCertifiesARecordedWrite`, `TestFreshKnownZeroNotWithoutTheFreshPremise`, `TestFreshKnownZeroSkipsAChunkWrittenAfterTheSample`, `TestFreshKnownZeroNeedsThisStartsCreate` (`core/storage/chunk_fresh_known_zero_test.go`) | `KnownZero`. Premise: no write, fill or other implementation reaches a store before its attach commit; a marker an earlier start, an older binary or another opener left is never trusted (created-this-start is in memory). A crash between retirement and marking costs one scan. | ACTIVE | +| `INV-CUT-FRESH-KNOWN-ZERO-001` | A store this start created (in memory) and still fresh at its attach (marker present, no BASE) starts known-zero for each chunk its claimed HEAD does not name whose entry is still {LSN 0, UNKNOWN}. Order: retire the marker, then make the marking durable, then serve. | M1 Recovering → Serving (fresh attach: commit, marking, then serving) | `core/storage/chunk_fresh_known_zero.go` `freshKnownZeroCandidates`, `ApplyFreshKnownZero`; `core/frontend/durable/provider_chunk.go` `attachChunk`; `core/frontend/durable/provider.go` `openOrCreate` (`createdThisStart`; non-chunk implementations refuse chunk roots) | `TestRedFirstCutOfAFreshVolumeScansOnlyWrittenChunks`, `TestFirstCutAgainstAClaimedHeadCertifiesUnnamedChunks`, `TestFirstCutOfARestoreTargetKeepsItsHydrationPath`, `TestExplicitWALStoreRefusesAFreshChunkRoot` (`core/frontend/durable/first_cut_known_zero_test.go`); `TestNoWriteReachesAFreshStoreBeforeItsAttachCommit`, `TestNoFetchOrFillReachesAFreshStoreBeforeItsAttachCommit`, `TestFreshKnownZeroNotAfterARestartBeforeTheAttachCommit`, `TestFreshKnownZeroNotAfterARestartBeforeAnyAttach`, `TestFreshKnownZeroCrashBetweenMarkerRetireAndMarking` (`core/frontend/durable/known_zero_premise_test.go`); `TestFreshKnownZeroNeverCertifiesARecordedWrite`, `TestFreshKnownZeroNotWithoutTheFreshPremise`, `TestFreshKnownZeroSkipsAChunkWrittenAfterTheSample`, `TestFreshKnownZeroNeedsThisStartsCreate` (`core/storage/chunk_fresh_known_zero_test.go`) | `KnownZero`. Premise: no write, fill or other implementation reaches a store before its attach commit; a marker an earlier start, an older binary or another opener left is never trusted (created-this-start is in memory). A crash between retirement and marking costs one scan. | ACTIVE | | `INV-CUT-RECOVER-BARRIER-001` | Native `Recover` aborts and drains OPEN COW owners before lower locks, with admission held through recovery and a hook snapshot recheck. No recovered record above H can enter a HEAD labelled H. | M5 Quiesce; M1 Recovering | `core/storage/walstore.go` `WALStore.Recover`; `chunk_cut_cow.go` `holdChunkDestructive` | `TestCutCOWV3_RecoveryAndCloseDrainSavingOwner` (`core/storage/chunk_cut_cow_lifetime_test.go`); `TestCutCOWV3_DestructiveSnapshotRetriesFirstAttachment` (`core/storage/chunk_cut_cow_lifetime_test.go`); `TestCutCOWV3_RecoveryAndCloseDrainSavingOwner` (`core/storage/chunk_cut_cow_lifetime_test.go`) | — | ACTIVE | | `INV-CUT-UPLOAD-FROM-BUFFER` | CopyFinish owns an immutable at-H slot. Every PUT retry sends that slot, without rereading local bytes; transient failures keep the point until the caller deadline, window abort or 30-second object deadline. Guest writes to a copied chunk need no save. | M5 Copy -> Upload | `chunk_cut_cow.go` `copyCOWEntry`; `chunk_upload.go` `putCaptured` | `TestCutUploadRetriesPastThreeAttemptsAtSamePoint`, `TestChunkCutUploadDeadlineBoundRetainsDirt`, `TestCutCOWV3_PutRetryUsesFrozenSlot` (`core/storage/chunk_cut_alignment_test.go`) | CutCOW2 BufFrozen; separate upload action extension pending | ACTIVE | | `INV-CUT-NO-WAL-PIN` | A cut window pins no WAL space and does not defer the flusher. Logical readers validate their resolved record and retry against the dirty map/extent after retirement and reuse. | M1 Checkpoint / M5 Copy | `walstore_v3.go` `readDirtyV3`; `flusher.go` `flushOnceInternal` | `TestCutCOWV3_CaptureDoesNotPinWAL` (`core/storage/chunk_cut_alignment_test.go`) | CutFlush refinement; native real ring-reuse control | ACTIVE |