From 68a5fde109bec0a01866001ad934f1d2f9d5ee17 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 23 Nov 2026 16:22:34 -0800 Subject: [PATCH 01/35] test(blockvolume): measure HEAD size against volume size (informative) IMPL V1-SPEC r2.94: an env-gated integration test (HEADSZ_RUN=1) that writes one 4 KiB block in every 1 GiB segment of a volume per size in HEADSZ_SIZES, takes a snapshot, then snapshots after one changed block each, and reports per cut the HEAD entry's byte size from the filer, the segments it lists, the cut's timings and the bytes it uploaded. A size the durable root cannot hold is recorded as refused by the headroom check. No assertion on the numbers. The weed cluster helper gains a sized variant; existing callers keep the same 32 x 256 MB volume server. Co-Authored-By: Claude Fable 5.1 --- .../blockvolume/head_size_integration_test.go | 265 ++++++++++++++++++ .../workspace_weed_integration_test.go | 15 +- 2 files changed, 278 insertions(+), 2 deletions(-) create mode 100644 seaweed-block/cmd/blockvolume/head_size_integration_test.go diff --git a/seaweed-block/cmd/blockvolume/head_size_integration_test.go b/seaweed-block/cmd/blockvolume/head_size_integration_test.go new file mode 100644 index 0000000000..bfb8c84446 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/head_size_integration_test.go @@ -0,0 +1,265 @@ +//go:build subprocess && chunkstore_integration + +package main_test + +import ( + "encoding/json" + "fmt" + "io" + "net/http" + "os" + "path/filepath" + "strconv" + "strings" + "testing" + "time" +) + +// HEAD size against volume size (V1-SPEC r2.94), informative: it measures, +// it does not judge. Runs only with HEADSZ_RUN=1, on a host booked for it. +// +// For each size in HEADSZ_SIZES (default 10G,100G,1T): one volume of that +// size; one 4 KiB block written in every 1 GiB segment; a snapshot (cut 1); +// then HEADSZ_CHANGE_CUTS snapshots (default 3), each after changing one +// block. Per cut it records the HEAD entry's byte size as the filer returns +// it, the number of segments HEAD lists, the cut's total and barrier time, +// and the chunks and bytes the cut uploaded. A size the durable root has no +// room for is recorded as refused by the blockvolume's headroom check, never +// shrunk or bypassed. The JSON report goes to HEADSZ_REPORT. +// +// The filer runs on its default store (leveldb2) under the test's directory; +// a filer.toml anywhere weed would read one fails the test before any start, +// so the store measured is the one named in the report. + +const headSegmentBytes = 1 << 30 + +type headSzCut struct { + Cut int `json:"cut"` + ChangedBlocks int `json:"changed_blocks"` + HeadBytes int `json:"head_bytes"` + HeadSegments int `json:"head_segments"` + CutTotalMs float64 `json:"cut_total_ms"` + BarrierPauseMs float64 `json:"cut_barrier_pause_ms"` + UploadedChunks int `json:"uploaded_chunks"` + UploadedBytes int64 `json:"uploaded_bytes"` + SnapshotMs float64 `json:"snapshot_command_ms"` +} + +type headSzSize struct { + Size string `json:"size"` + Bytes uint64 `json:"bytes"` + Segments int `json:"segments"` + Result string `json:"result"` // measured | refused_headroom + Refusal string `json:"refusal,omitempty"` + WriteMs float64 `json:"write_ms,omitempty"` + Cuts []headSzCut `json:"cuts,omitempty"` + HeadPerGiB float64 `json:"head_bytes_per_gib,omitempty"` +} + +type headSzReport struct { + StartedAt time.Time `json:"started_at"` + FilerStore string `json:"filer_store"` + ChunkPath string `json:"chunk_path"` + Sizes []headSzSize `json:"sizes"` +} + +func headSzParse(t *testing.T, s string) uint64 { + t.Helper() + s = strings.ToUpper(strings.TrimSpace(s)) + mul := map[byte]uint64{'G': 1 << 30, 'T': 1 << 40}[s[len(s)-1]] + n, err := strconv.ParseUint(s[:len(s)-1], 10, 64) + if mul == 0 || err != nil || n == 0 { + t.Fatalf("HEADSZ_SIZES: %q is not G or T", s) + } + return n * mul +} + +// headSzAmbientFilerToml fails the test when weed could read a filer.toml +// other than none: its working directory (the cluster dir) and the standard +// configuration directories. +func headSzAmbientFilerToml(t *testing.T, clusterDir string) { + t.Helper() + home, _ := os.UserHomeDir() + for _, d := range []string{clusterDir, filepath.Join(home, ".seaweedfs"), "/usr/local/etc/seaweedfs", "/etc/seaweedfs"} { + if _, err := os.Stat(filepath.Join(d, "filer.toml")); err == nil { + t.Fatalf("a filer.toml in %s would replace the default filer store: remove it or run elsewhere", d) + } + } +} + +func TestHeadSizeAgainstVolumeSize(t *testing.T) { + if os.Getenv("HEADSZ_RUN") != "1" { + t.Skip("HEADSZ_RUN=1 not set") + } + sizes := strings.Split(os.Getenv("HEADSZ_SIZES"), ",") + if os.Getenv("HEADSZ_SIZES") == "" { + sizes = []string{"10G", "100G", "1T"} + } + changeCuts := 3 + if v := os.Getenv("HEADSZ_CHANGE_CUTS"); v != "" { + n, err := strconv.Atoi(v) + if err != nil || n < 0 { + t.Fatalf("HEADSZ_CHANGE_CUTS=%q", v) + } + changeCuts = n + } + h := newPlannedHandoffHarness(t) + clusterDir := filepath.Join(h.dir, "weed") + if err := os.MkdirAll(clusterDir, 0o700); err != nil { + t.Fatal(err) + } + headSzAmbientFilerToml(t, clusterDir) + env := &handoffEnv{h: h, cluster: startWorkspaceWeedWith(t, clusterDir, w4WeedOpts{VolumeSizeLimitMB: 1024, VolumeMax: 64}), + chunkPath: fmt.Sprintf("/headsz-%d", time.Now().UnixNano()), hosts: map[string]bvHost{}} + rep := &headSzReport{StartedAt: time.Now().UTC(), ChunkPath: env.chunkPath, + FilerStore: "leveldb2 (weed filer default store), -defaultStoreDir=" + filepath.Join(clusterDir, "f") + ", no filer.toml"} + defer func() { + if p := os.Getenv("HEADSZ_REPORT"); p != "" { + b, _ := json.MarshalIndent(rep, "", " ") + if err := os.WriteFile(p, append(b, '\n'), 0o644); err != nil { + t.Errorf("HEADSZ_REPORT: %v", err) + } + } + }() + + // one cluster spec with every size's volume; one replica each on s1 + var vols strings.Builder + for i, s := range sizes { + b := headSzParse(t, s) + id := "h" + strings.ToLower(strings.TrimSpace(s)) + env.hosts[id] = bvHost{id: id, server: "s1", replica: fmt.Sprintf("r%d", i+1), volume: id, root: filepath.Join(h.dir, "vol-"+id), + data: handoffAddress(t), ctrl: handoffAddress(t), status: handoffAddress(t), nvme: handoffAddress(t)} + fmt.Fprintf(&vols, " - id: %s\n size_bytes: %d\n replication_factor: 1\n placements:\n - server_id: s1\n replica_id: r%d\n", id, b, i+1) + } + spec := filepath.Join(h.dir, "cluster-spec.yaml") + if err := os.WriteFile(spec, []byte(fmt.Sprintf("nodes:\n - server_id: s1\n data_addr: %s\n ctrl_addr: %s\nvolumes:\n%s", h.dataAddr, h.ctrlAddr, vols.String())), 0o644); err != nil { + t.Fatal(err) + } + mstate := filepath.Join(h.dir, "master") + master := h.start(t, "blockmaster", h.master, "--authority-store", filepath.Join(mstate, "authority"), "--lifecycle-store", filepath.Join(mstate, "lifecycle"), + "--cluster-spec", spec, "--expected-slots-per-volume", "1", "--listen", h.masterAddr, + "--workspace-rpc", "--workspace-head-base-url", "http://"+env.cluster.filerHTTP+env.chunkPath) + master.waitLog(t, 30*time.Second, "blockmaster: lock acquired, reloaded=") + + for _, s := range sizes { + rep.Sizes = append(rep.Sizes, headSzOne(t, env, s, changeCuts)) + } +} + +// headSzOne measures one size; its blockvolume is stopped at the end. +func headSzOne(t *testing.T, env *handoffEnv, size string, changeCuts int) headSzSize { + t.Helper() + bytes := headSzParse(t, size) + id := "h" + strings.ToLower(strings.TrimSpace(size)) + b := env.hosts[id] + row := headSzSize{Size: strings.TrimSpace(size), Bytes: bytes, Segments: int((bytes + headSegmentBytes - 1) / headSegmentBytes)} + env.volExtra = []string{"--durable-blocks", strconv.FormatUint(bytes/4096, 10), "--chunk-capture-interval", "0", "--chunk-snapshot-schedule", "off"} + d := env.h.start(t, "blockvolume-"+id, env.h.volume, env.volArgsFor(b)...) + primary := fmt.Sprintf("blockvolume: volume %s adopted as PRIMARY at %s@", b.volume, b.replica) + end := time.Now().Add(120 * time.Second) + for !d.has(primary) { + select { + case <-d.done: + if l := d.line("bytes free"); l != "" { + row.Result, row.Refusal = "refused_headroom", strings.TrimSpace(l) + return row + } + t.Fatalf("blockvolume %s exited before it adopted its volume: %v", id, d.err) + case <-time.After(200 * time.Millisecond): + } + if time.Now().After(end) { + t.Fatalf("blockvolume %s did not adopt its volume in 120 s", id) + } + } + defer d.term(t, 60*time.Second) + poll(t, 60*time.Second, id+" never reported its frontend ready", func() bool { return volumeFrontendReady(b.status, b.volume) }) + + c := dialNVMe(t, b.nvme, plannedHandoffNQN) + write := func(lba uint64, tag string) { + _ = c.io.SetDeadline(time.Now().Add(60 * time.Second)) + c.write(t, lba, f1Block(id, 0, tag, lba)) + } + start := time.Now() + for seg := 0; seg < row.Segments; seg++ { + write(uint64(seg)*headSegmentBytes/4096, "seg") + } + _ = c.io.SetDeadline(time.Now().Add(60 * time.Second)) + c.flush(t) + row.WriteMs = ms(time.Since(start)) + for cut := 1; cut <= 1+changeCuts; cut++ { + changed := 0 + if cut > 1 { + write(uint64(cut), fmt.Sprintf("change%d", cut)) + _ = c.io.SetDeadline(time.Now().Add(60 * time.Second)) + c.flush(t) + changed = 1 + } + row.Cuts = append(row.Cuts, headSzCutOnce(t, env, b, cut, changed)) + } + row.Result = "measured" + if row.Segments > 0 && len(row.Cuts) > 0 { + row.HeadPerGiB = float64(row.Cuts[0].HeadBytes) / float64(row.Segments) + } + return row +} + +// headSzCutOnce takes one snapshot and reads what it wrote: HEAD from the +// filer, the cut from the volume's durable status. +func headSzCutOnce(t *testing.T, env *handoffEnv, b bvHost, cut, changed int) headSzCut { + t.Helper() + r := headSzCut{Cut: cut, ChangedBlocks: changed} + start := time.Now() + out, errOut := env.h.command(t, "ops", "chunk", "snapshot", "--volume", b.volume, "--status-addr", b.status, + "--name", fmt.Sprintf("headsz-%d", cut), "--request-id", fmt.Sprintf("headsz-%s-%d", b.volume, cut)) + r.SnapshotMs = ms(time.Since(start)) + _, _ = out, errOut + var st struct { + Volumes []struct { + VolumeID string + Chunk *struct { + Stats struct { + LastCut *struct { + TotalNs, BarrierPauseNs int64 + UploadedChunks int + UploadedBytes int64 + } + } + } + } + } + if err := json.Unmarshal(headSzGet(t, "http://"+b.status+"/status/durable?volume="+b.volume, 4<<20), &st); err != nil { + t.Fatalf("durable status of %s: %v", b.volume, err) + } + for _, s := range st.Volumes { + if s.VolumeID == b.volume && s.Chunk != nil && s.Chunk.Stats.LastCut != nil { + l := s.Chunk.Stats.LastCut + r.CutTotalMs, r.BarrierPauseMs = float64(l.TotalNs)/1e6, float64(l.BarrierPauseNs)/1e6 + r.UploadedChunks, r.UploadedBytes = l.UploadedChunks, l.UploadedBytes + } + } + head := headSzGet(t, "http://"+env.cluster.filerHTTP+env.chunkPath+"/"+b.volume+"/HEAD", 256<<20) + r.HeadBytes = len(head) + var doc struct { + Segments map[string]json.RawMessage `json:"segments"` + } + if err := json.Unmarshal(head, &doc); err != nil { + t.Fatalf("HEAD of %s is not JSON (%d bytes): %v", b.volume, len(head), err) + } + r.HeadSegments = len(doc.Segments) + return r +} + +func headSzGet(t *testing.T, u string, limit int64) []byte { + t.Helper() + c := &http.Client{Timeout: 30 * time.Second} + resp, err := c.Get(u) + if err != nil { + t.Fatalf("GET %s: %v", u, err) + } + defer resp.Body.Close() + body, err := io.ReadAll(io.LimitReader(resp.Body, limit)) + if err != nil || resp.StatusCode != http.StatusOK { + t.Fatalf("GET %s: status %d err %v", u, resp.StatusCode, err) + } + return body +} diff --git a/seaweed-block/cmd/blockvolume/workspace_weed_integration_test.go b/seaweed-block/cmd/blockvolume/workspace_weed_integration_test.go index d0bdb10205..26e85326df 100644 --- a/seaweed-block/cmd/blockvolume/workspace_weed_integration_test.go +++ b/seaweed-block/cmd/blockvolume/workspace_weed_integration_test.go @@ -70,6 +70,17 @@ func startWorkspaceWeed(t *testing.T) *w4WeedCluster { // A caller-owned root lets process qualification retain its filer evidence // when external-service cleanup is uncertain. Existing tests keep TempDir. func startWorkspaceWeedAt(t *testing.T, dir string) *w4WeedCluster { + t.Helper() + return startWorkspaceWeedWith(t, dir, w4WeedOpts{VolumeSizeLimitMB: 256, VolumeMax: 32}) +} + +// w4WeedOpts sizes the weed volume server: VolumeMax volumes of +// VolumeSizeLimitMB each (the default holds about 8 GiB of chunks). +type w4WeedOpts struct { + VolumeSizeLimitMB, VolumeMax int +} + +func startWorkspaceWeedWith(t *testing.T, dir string, o w4WeedOpts) *w4WeedCluster { t.Helper() weed := os.Getenv("CHUNKSTORE_WEED") if weed == "" { @@ -110,9 +121,9 @@ func startWorkspaceWeedAt(t *testing.T, dir string) *w4WeedCluster { t.Fatal(err) } } - run("master", "master", "-ip=127.0.0.1", fmt.Sprintf("-port=%d", mp), "-mdir="+filepath.Join(dir, "m"), "-volumeSizeLimitMB=256", "-defaultReplication=000") + run("master", "master", "-ip=127.0.0.1", fmt.Sprintf("-port=%d", mp), "-mdir="+filepath.Join(dir, "m"), fmt.Sprintf("-volumeSizeLimitMB=%d", o.VolumeSizeLimitMB), "-defaultReplication=000") w4WaitTCP(t, c.master, 20*time.Second) - run("volume", "volume", "-ip=127.0.0.1", fmt.Sprintf("-port=%d", vp), "-dir="+filepath.Join(dir, "v"), "-master="+c.master, "-max=32") + run("volume", "volume", "-ip=127.0.0.1", fmt.Sprintf("-port=%d", vp), "-dir="+filepath.Join(dir, "v"), "-master="+c.master, fmt.Sprintf("-max=%d", o.VolumeMax)) run("filer", "filer", "-ip=127.0.0.1", fmt.Sprintf("-port=%d", fp), "-master="+c.master, "-defaultStoreDir="+filepath.Join(dir, "f")) w4WaitTCP(t, c.filerGRPC, 30*time.Second) From 3bd8e3302d699711753a75ddfeaaab6d95927d51 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 23 Nov 2026 16:33:19 -0800 Subject: [PATCH 02/35] fix(blockvolume): a volume record not read in create mode is refused before any store exists INV-VOL-GEOMETRY-FLAGS-RECORD-001: in create mode a ReadVolume error was taken as an absent record, so a wrong --durable-blocks could still create a wrong-size store when the record could not be read. The error is now classified (one type check): the filer failed the read (remote unavailable, deadline) -> exit 75, retried: 'the volume record of V could not be read (); no local store was created; retrying'; the record is there but does not decode -> exit 78, not a retry loop: 'the volume record of V is unreadable (corrupt: ); no local store was created; restore or recreate the record'. An absent record (not found) keeps the create path. A first start with the filer down was already safe: it ends at the startup filer check (exit 1) before this one. Tests: unit, both classes (a failing LookupEntry -> 75 for a wrong and a right flag, the record read; a corrupt VOLUME entry -> 78); TestCorruptRecordIsRefusedBeforeTheStoreIsCreated (filer up, the VOLUME entry undecodable: 78 and no store for both flags; restored: 78 for the wrong flag, the right flag serves); TestFirstStartWithTheFilerDownCreatesNoStore (guard). The ledger row and the operator guide say so. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/cmd/blockvolume/chunk_remote.go | 30 ++++--- .../cmd/blockvolume/chunk_remote_test.go | 61 +++++++++++---- .../geometry_flag_record_integration_test.go | 78 +++++++++++++++++++ seaweed-block/cmd/blockvolume/main.go | 4 +- seaweed-block/docs/design/invariants.md | 2 +- seaweed-block/docs/operator-guide.md | 6 ++ 6 files changed, 155 insertions(+), 26 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/chunk_remote.go b/seaweed-block/cmd/blockvolume/chunk_remote.go index 7be8c7b10c..c54a0f7cfd 100644 --- a/seaweed-block/cmd/blockvolume/chunk_remote.go +++ b/seaweed-block/cmd/blockvolume/chunk_remote.go @@ -223,21 +223,31 @@ const exitGeometryRefused = 78 // geometryFlagsRefusal compares the geometry flags with the volume record // before any local store is created, so a wrong flag never leaves a store of -// the wrong size behind. It returns the refusal line, or "" when the record -// agrees, does not exist yet (the attach check creates it from the flags), -// or cannot be read (the attach check still refuses a mismatch later), and -// when no store is being created (numBlocks 0: an existing store opens with -// its own geometry). -func geometryFlagsRefusal(ctx context.Context, cat *chunkstore.Catalog, volumeID string, numBlocks uint64, blockSize uint32) string { +// the wrong size behind. It returns the refusal line and its exit status: +// exitGeometryRefused (78) when the record disagrees or is there but does not +// decode; exitWorkspaceRetry (75) when the filer could not be read (an +// unknown, never taken as "absent"); ("", 0) when the record agrees, does +// not exist yet (the attach +// check creates it from the flags), or no store is being created (numBlocks +// 0: an existing store opens with its own geometry). +func geometryFlagsRefusal(ctx context.Context, cat *chunkstore.Catalog, volumeID string, numBlocks uint64, blockSize uint32) (string, int) { if numBlocks == 0 { - return "" // an existing store: the flags are not used + return "", 0 // an existing store: the flags are not used } v, ok, err := cat.ReadVolume(ctx, volumeID) - if err != nil || !ok || (v.NumBlocks == numBlocks && v.BlockSize == blockSize) { - return "" + if err != nil && chunkstore.CodeOf(err) == chunkstore.CodeRemoteUnavailable { + return fmt.Sprintf("blockvolume: the volume record of %s could not be read (%v); no local store was created; retrying", volumeID, err), exitWorkspaceRetry + } + if err != nil { + // A record that is there but does not decode stays that way: a + // permanent refusal, not a retry loop. + return fmt.Sprintf("blockvolume: the volume record of %s is unreadable (corrupt: %v); no local store was created; restore or recreate the record", volumeID, err), exitGeometryRefused + } + if !ok || (v.NumBlocks == numBlocks && v.BlockSize == blockSize) { + return "", 0 } return fmt.Sprintf("blockvolume: geometry_mismatch: --durable-blocks %d --durable-blocksize %d disagree with the volume record of %s (%d blocks of %d bytes); no local store was created; start it with the record's geometry", - numBlocks, blockSize, volumeID, v.NumBlocks, v.BlockSize) + numBlocks, blockSize, volumeID, v.NumBlocks, v.BlockSize), exitGeometryRefused } // chunkHolder is how this host names itself in HEAD: / diff --git a/seaweed-block/cmd/blockvolume/chunk_remote_test.go b/seaweed-block/cmd/blockvolume/chunk_remote_test.go index 9b8c1aa1ce..7a2f2cbe4a 100644 --- a/seaweed-block/cmd/blockvolume/chunk_remote_test.go +++ b/seaweed-block/cmd/blockvolume/chunk_remote_test.go @@ -3,6 +3,7 @@ package main import ( "context" "errors" + "path" "strings" "testing" "time" @@ -117,40 +118,46 @@ func TestChunkVolumeRootStaysInsideBase(t *testing.T) { } // Before any local store is created, a geometry flag that disagrees with the -// volume record is refused with a line naming both; a matching record, a -// missing record (the attach check creates it) and an unreadable one (the -// attach check still applies) do not refuse. +// volume record is refused with a line naming both (78); a record the filer +// could not deliver is refused as retryable (75), never taken as "absent"; +// a record that is there but does not decode is refused for good (78); a matching +// record, a missing record (the attach check creates it) and an existing +// store (no create geometry) are not refused. func TestGeometryFlagsRefusalComparesTheRecord(t *testing.T) { ctx := context.Background() cat, err := chunkstore.NewCatalog(chunkstore.NewMemFiler(), defaultChunkPath) if err != nil { t.Fatal(err) } - if got := geometryFlagsRefusal(ctx, cat, "v1", 32768, 4096); got != "" { - t.Fatalf("no record yet: %q", got) + if got, code := geometryFlagsRefusal(ctx, cat, "v1", 32768, 4096); got != "" || code != 0 { + t.Fatalf("no record yet: %q, %d", got, code) } if _, err := cat.EnsureVolume(ctx, "v1", chunkstore.Geometry{NumBlocks: 65536, BlockSize: 4096, ChunkBlocks: 1024}); err != nil { t.Fatal(err) } - if got := geometryFlagsRefusal(ctx, cat, "v1", 65536, 4096); got != "" { - t.Fatalf("matching flags refused: %q", got) + if got, code := geometryFlagsRefusal(ctx, cat, "v1", 65536, 4096); got != "" || code != 0 { + t.Fatalf("matching flags refused: %q, %d", got, code) } for _, c := range []struct { blocks uint64 size uint32 }{{32768, 4096}, {65536, 512}} { - got := geometryFlagsRefusal(ctx, cat, "v1", c.blocks, c.size) + got, code := geometryFlagsRefusal(ctx, cat, "v1", c.blocks, c.size) + if code != exitGeometryRefused { + t.Fatalf("flags %d x %d: exit %d, want %d", c.blocks, c.size, code, exitGeometryRefused) + } for _, want := range []string{"geometry_mismatch", "--durable-blocks", "65536 blocks of 4096 bytes"} { if !strings.Contains(got, want) { t.Fatalf("flags %d x %d: refusal %q lacks %q", c.blocks, c.size, got, want) } } } - if got := geometryFlagsRefusal(ctx, cat, "v1", 0, 0); got != "" { - t.Fatalf("an existing store (no create geometry) must not be refused: %q", got) + if got, code := geometryFlagsRefusal(ctx, cat, "v1", 0, 0); got != "" || code != 0 { + t.Fatalf("an existing store (no create geometry) must not be refused: %q, %d", got, code) } // An unreadable record: the same valid volume over a filer whose - // lookups fail. The record is read (and fails), and nothing is refused. + // lookups fail. The record is read, fails, and the start is refused as + // retryable before anything is created. failing := &lookupFailFiler{MemFiler: chunkstore.NewMemFiler()} failCat, err := chunkstore.NewCatalog(failing, defaultChunkPath) if err != nil { @@ -160,12 +167,40 @@ func TestGeometryFlagsRefusalComparesTheRecord(t *testing.T) { t.Fatal(err) } failing.fail, failing.reads = true, 0 - if got := geometryFlagsRefusal(ctx, failCat, "v1", 32768, 4096); got != "" { - t.Fatalf("an unreadable record must not refuse: %q", got) + for _, blocks := range []uint64{32768, 65536} { // a wrong and a right flag alike + got, code := geometryFlagsRefusal(ctx, failCat, "v1", blocks, 4096) + if code != exitWorkspaceRetry || !strings.Contains(got, "the volume record of v1 could not be read") || !strings.Contains(got, "no local store was created; retrying") { + t.Fatalf("--durable-blocks %d over an unreadable record: %q, exit %d; want a retryable refusal (%d)", blocks, got, code, exitWorkspaceRetry) + } } if failing.reads == 0 { t.Fatal("the unreadable-record case never read the record") } + // A record that is there but does not decode: a permanent refusal + // (78), not a retry loop, for a wrong and a right flag alike. + mem := chunkstore.NewMemFiler() + corruptCat, err := chunkstore.NewCatalog(mem, defaultChunkPath) + if err != nil { + t.Fatal(err) + } + if _, err := corruptCat.EnsureVolume(ctx, "v1", chunkstore.Geometry{NumBlocks: 65536, BlockSize: 4096, ChunkBlocks: 1024}); err != nil { + t.Fatal(err) + } + dir := path.Join(defaultChunkPath, "v1") + e, err := mem.LookupEntry(ctx, dir, "VOLUME") + if err != nil { + t.Fatal(err) + } + e.Content = []byte("{") + if err := mem.UpdateEntry(ctx, dir, e, nil); err != nil { + t.Fatal(err) + } + for _, blocks := range []uint64{32768, 65536} { + got, code := geometryFlagsRefusal(ctx, corruptCat, "v1", blocks, 4096) + if code != exitGeometryRefused || !strings.Contains(got, "the volume record of v1 is unreadable (corrupt:") || !strings.Contains(got, "no local store was created") { + t.Fatalf("--durable-blocks %d over a corrupt record: %q, exit %d; want a permanent refusal (%d)", blocks, got, code, exitGeometryRefused) + } + } } // lookupFailFiler is a MemFiler whose LookupEntry fails once fail is set; it diff --git a/seaweed-block/cmd/blockvolume/geometry_flag_record_integration_test.go b/seaweed-block/cmd/blockvolume/geometry_flag_record_integration_test.go index 4d7d545d8e..bdd1616177 100644 --- a/seaweed-block/cmd/blockvolume/geometry_flag_record_integration_test.go +++ b/seaweed-block/cmd/blockvolume/geometry_flag_record_integration_test.go @@ -3,7 +3,9 @@ package main_test import ( + "context" "os" + "path" "strings" "testing" "time" @@ -57,3 +59,79 @@ func TestWrongGeometryFlagIsRefusedBeforeTheStoreIsCreated(t *testing.T) { t.Fatalf("1.0.1: %s", strings.Join(problems, "; ")) } } + +// INV-VOL-GEOMETRY-FLAGS-RECORD-001, the corrupt record: in create mode, a +// volume record that is there but does not decode is refused for good (exit +// 78) before any local store exists, never taken as "absent" and never +// retried. The filer stays up and answers the startup checks; v2's VOLUME +// entry is made undecodable. A wrong and a right --durable-blocks alike exit +// 78 and leave nothing under --durable-root. With the entry restored the wrong +// flag is refused (78, mismatch) and the right flag serves. (A filer that +// cannot deliver the record is the retryable case, 75: the unit test.) +func TestCorruptRecordIsRefusedBeforeTheStoreIsCreated(t *testing.T) { + env := startSourceWithSnapshot(t, "v2") + env.h.command(t, "ops", "chunk", "restore", "--source", "v1", "--snapshot", "s1", "--target", "v2", + "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath) + b := env.hosts["n-v2"] + right := append([]string{}, env.volArgsFor(b)...) + wrong := append([]string{}, right...) + for i := range wrong { + if wrong[i] == "--durable-blocks" { + wrong[i+1] = "32768" + } + } + ctx := context.Background() + cl := env.cluster.client(t, "") + dir := path.Join(env.chunkPath, "v2") + entry, err := cl.LookupEntry(ctx, dir, "VOLUME") + if err != nil { + t.Fatal(err) + } + record := append([]byte(nil), entry.Content...) + entry.Content = []byte("{") + if err := cl.UpdateEntry(ctx, dir, entry, nil); err != nil { + t.Fatal(err) + } + for _, c := range []struct { + name string + args []string + }{{"wrong", wrong}, {"right", right}} { + d := env.h.start(t, "blockvolume-v2-"+c.name+"-corrupt", env.h.volume, c.args...) + err := d.wait(60 * time.Second) + line := d.line("is unreadable (corrupt:") + entries, _ := os.ReadDir(b.root) + t.Logf("%s flag over a corrupt record: exit %v; %q; files under --durable-root %d", c.name, err, line, len(entries)) + if exitCode(err) != 78 || !strings.Contains(line, "no local store was created") || len(entries) != 0 { + t.Fatalf("1.0.1: a %s-flag first start over a corrupt record must exit 78 before creating anything; exit %v, line %q, %d files", c.name, err, line, len(entries)) + } + } + entry.Content = record + if err := cl.UpdateEntry(ctx, dir, entry, nil); err != nil { + t.Fatal(err) + } + d := env.h.start(t, "blockvolume-v2-wrong-readable", env.h.volume, wrong...) + if err := d.wait(60 * time.Second); exitCode(err) != 78 { + t.Fatalf("with the record readable again, the wrong flag must be refused (78); exit %v", err) + } + served := env.startTarget(t, "v2", "blockvolume-v2-right-readable") + served.kill(t) +} + +// Guard: a first start with the filer stopped ends at the startup filer +// check (exit 1) before the record check and before any store exists. +func TestFirstStartWithTheFilerDownCreatesNoStore(t *testing.T) { + env := startSourceWithSnapshot(t, "v2") + env.h.command(t, "ops", "chunk", "restore", "--source", "v1", "--snapshot", "s1", "--target", "v2", + "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath) + b := env.hosts["n-v2"] + env.cluster.stopProc(t, "filer") + d := env.h.start(t, "blockvolume-v2-filer-down", env.h.volume, env.volArgsFor(b)...) + err := d.wait(120 * time.Second) + env.cluster.restartProc(t, "filer") + w4WaitTCP(t, env.cluster.filerGRPC, 30*time.Second) + entries, _ := os.ReadDir(b.root) + t.Logf("filer down: exit %v; %q; files under --durable-root %d", err, d.line("needs exactly one filer"), len(entries)) + if exitCode(err) != 1 || d.line("needs exactly one filer") == "" || len(entries) != 0 { + t.Fatalf("a first start with the filer down must end at the startup filer check without a store; exit %v, %d files", err, len(entries)) + } +} diff --git a/seaweed-block/cmd/blockvolume/main.go b/seaweed-block/cmd/blockvolume/main.go index cb475edb82..939191bdcc 100644 --- a/seaweed-block/cmd/blockvolume/main.go +++ b/seaweed-block/cmd/blockvolume/main.go @@ -737,7 +737,7 @@ func runVolume(f flags, exits *processExit) int { // between it and the record is the attach check's. if chunkErr == nil && geometryErr == nil && blocks != 0 && chunk.catalog != nil { readCtx, readCancel := context.WithTimeout(context.Background(), 10*time.Second) - refusal := geometryFlagsRefusal(readCtx, chunk.catalog, f.volumeID, uint64(blocks), uint32(blockSize)) + refusal, code := geometryFlagsRefusal(readCtx, chunk.catalog, f.volumeID, uint64(blocks), uint32(blockSize)) readCancel() if refusal != "" { fmt.Fprintln(os.Stderr, refusal) @@ -747,7 +747,7 @@ func runVolume(f flags, exits *processExit) int { shutCancel() } _ = h.Close() - return exitGeometryRefused + return code } } var dp *durable.DurableProvider diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 05b035cfd2..1fdacbf315 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -744,7 +744,7 @@ Notes: | `INV-WS-SEAL-REPLAY-001` | A repeated plain seal, also after restart, succeeds only from a fresh filer HEAD with exact owner/epoch and detachedBy proof. It returns that original HEAD/frontier without a CAS or new generation. An unreadable or mismatched proof cannot be answered from process memory. | M5 PlainStop -> RemoteProof -> SealedReply | `core/frontend/durable/provider_seal_replay.go` `replayPlainSeal`; `core/storage/chunk_seal_replay.go` `ReadDetachedChunkHead`; `cmd/blockvolume/workspace_lease.go` `workspaceDetachedGeneration` | `TestWorkspaceRevocationUsesExactStoredSeal` (`cmd/blockvolume/workspace_proof_test.go`); `TestPlainSealLostAnswerRestartReplaysFilerProof`, `TestPlainSealReplayNeverUsesProcessMemory`, `TestPlainSealReplayDuringDeferredAuthorityStartup` (`core/frontend/durable/provider_plain_seal_replay_test.go`) | `PlainSealReplay` `SuccessNeedsFreshExactProof`, `ValidProofDoesNotNeedProcessMemory` | ACTIVE | | `INV-WS-CAS-UNKNOWN-001` | An unknown HEAD CAS outcome is settled by re-reading HEAD, never by a blind retry; until it is settled the proposal stays pending and its intents stay. | M5 CAS → Pending | `core/storage/chunk_layer.go` `captureLocked`, `resolvePending`; `core/storage/chunk_restore.go` `ClaimChunkHead` | `TestChunkRemote_UncertainCASIsNotPrecondition` (`core/frontend/chunkstore/chunk_remote_test.go`); `TestChunkLayer_C6_UnknownNotAppliedNeverClaimsSuccess` (`core/storage/chunk_layer_contract_test.go`); `TestClaimChunkHeadSettlesUnknownWithoutReplay` (`core/storage/chunk_restore_test.go`); `TestChunkIntent_UncertainCASKeepsIntentUntilSettled` (`core/storage/chunk_layer_intent_test.go`) | — | ACTIVE | | `INV-WS-CLAIM-BEFORE-SERVE-001` | A new holder claims HEAD at its master-issued epoch before I/O opens; a HEAD with a higher epoch, or another holder at the same epoch, fences the claim. | M4 Claiming → Holder \| Fenced | `core/storage/chunk_restore.go` `ClaimChunkHead`; `core/frontend/durable/provider_chunk.go` `newChunkLayer` | `TestClaimChunkHeadRefusesStaleAuthorityAndAdmissionDrift` (`core/storage/chunk_restore_test.go`); `TestRestoreSeedPrecedesTakeoverCAS` (`core/frontend/durable/provider_seed_order_test.go`); `TestWorkspaceMoveRestoresLazilyAndFencesOldHost` (`core/host/master/workspace_restore_test.go`) | `WorkspaceTakeover` `SeedMatchesTakeover` | ACTIVE | -| `INV-VOL-GEOMETRY-FLAGS-RECORD-001` | A create-mode start whose `--durable-blocks`/`--durable-blocksize` disagree with the volume record exits 78 before any local store exists; an existing store is checked only at attach; a missing record keeps the create path; an unreadable record falls to the attach check, never a refusal. | blockvolume startup (before the durable provider) | `cmd/blockvolume/main.go` (create-mode check); `cmd/blockvolume/chunk_remote.go` `geometryFlagsRefusal` | `TestGeometryFlagsRefusalComparesTheRecord` (`cmd/blockvolume/chunk_remote_test.go`); `TestWrongGeometryFlagIsRefusedBeforeTheStoreIsCreated`, `TestWrongGeometryCureAsWritten` (`cmd/blockvolume`, real binaries) | - | ACTIVE | +| `INV-VOL-GEOMETRY-FLAGS-RECORD-001` | A create-mode start whose `--durable-blocks`/`--durable-blocksize` disagree with the volume record exits 78 before any local store exists; an existing store is checked only at attach; an absent record keeps the create path; an unread record exits 75 (filer failed) or 78 (corrupt). | blockvolume startup (before the durable provider) | `cmd/blockvolume/main.go` (create-mode check); `cmd/blockvolume/chunk_remote.go` `geometryFlagsRefusal` | `TestGeometryFlagsRefusalComparesTheRecord` (`cmd/blockvolume/chunk_remote_test.go`); `TestWrongGeometryFlagIsRefusedBeforeTheStoreIsCreated`, `TestCorruptRecordIsRefusedBeforeTheStoreIsCreated`, `TestWrongGeometryCureAsWritten` (`cmd/blockvolume`, real binaries) | - | ACTIVE | | `INV-WS-STALE-LOCAL-ROOT-001` | An existing local root whose HEAD another holder has published, or whose local durable LSN is below HEAD's `remote_lsn` (a rolled-back copy), is not served or cut; the attach fails closed with `ErrChunkStaleLocalRoot`. | M4 Claiming → Refused | `core/frontend/durable/provider_chunk.go` `newChunkLayer` | `TestWALStoreChunk_MoveBackOntoAnOldRootIsRefused`, `TestWALStoreChunk_MoveBackRefusedOnDeferredAttach` (`core/frontend/durable/provider_chunk_moveback_test.go`); `TestLocalReopenRejectsForeignClaimImage` (`core/frontend/durable/provider_reopen_belt_test.go`); `TestRolledBackCopyBelowHeadLSNIsRefused` (`core/frontend/durable/rolled_back_copy_test.go`); `TestCutPublishesOnlyLocallyDurableLSN` (`core/frontend/durable/cut_durable_before_cas_test.go`) | — | ACTIVE | | `INV-WS-ONE-PROCESS-PER-HOST-001` | One host runs at most one live blockvolume per volume: each takes the volume's exclusive host lock before its store opens and holds it until the store closes; a second is refused before it opens anything, whatever its `--durable-root`. | M4 (start) → Attaching, Refused | `core/frontend/durable/provider.go` `DurableProvider.lockVolumeOnHost` | `TestOneLiveProcessPerVolumePerHost`, `TestHostVolumeLockDirectoryCreatedOrRefused`, `TestHostVolumeLockRefusesNonDirectoryLockPath`, `TestHostVolumeLockTakesReadOnlyLockFile` (`core/frontend/durable/one_process_per_volume_test.go`); `TestHostVolumeLockCreatesParent0755AndLocks0700`, `TestHostVolumeLockKeepsExistingDirectoryModes` (`core/frontend/durable/volume_lock_parent_mode_test.go`); `TestVolumeLockDirTestOnlyRefusedUnderSystemd` (`cmd/blockvolume/volume_lock_flag_test.go`) | — | ACTIVE | | `INV-WS-SINGLE-FILER-001` | A chunk volume starts only when `--chunk-filer` is the only filer of its group: a master listing another filer or several refuses at once, whichever master answers first; a filer no master lists within 60 s is refused. A startup census, not a fence: a filer added to the group later is not detected. | M4 (startup) → Refused | `core/frontend/chunkstore/single_filer.go` `CheckSingleFiler`; `cmd/blockvolume/chunk_remote.go` `newChunkWiring`; `cmd/sw-block/chunk.go` `refuseUnlessSingleFiler` | `TestCheckSingleFilerRefusesAnotherOrSeveralFilers`, `TestCheckSingleFilerFailsClosed`, `TestCheckSingleFilerFavourableThenStalledRefuses`, `TestIsTargetComparesScopedAddresses`, `TestCheckSingleFilerPasses` (`core/frontend/chunkstore/single_filer_test.go`), `TestChunkWiringRefusesAMultiFilerGroup` (`cmd/blockvolume/single_filer_test.go`), `TestOpsChunk_WritingCommandsRunTheSingleFilerCheck` (`cmd/sw-block/chunk_start_check_test.go`), `TestOpsChunk_VerifyRunsTheSingleFilerCheck` (`cmd/sw-block/chunk_verify_test.go`) | — | ACTIVE | diff --git a/seaweed-block/docs/operator-guide.md b/seaweed-block/docs/operator-guide.md index 17efd02f20..8adf89485c 100644 --- a/seaweed-block/docs/operator-guide.md +++ b/seaweed-block/docs/operator-guide.md @@ -55,6 +55,11 @@ one live blockvolume per volume ([one process per volume](releases/one-process-p A first start whose `--durable-blocks` or `--durable-blocksize` disagrees with the volume record is refused before any local store is created: it exits 78 (the unit does not restart it) with a line `geometry_mismatch: --durable-blocks ... disagree with the volume record`; correct the flag and start it again. + If that first start cannot read the volume record because the filer failed the read, it exits 75 with `the volume + record of could not be read ... no local store was created; retrying` and the unit starts it again. During a long + outage the unit can reach its start limit; once the filer answers, run `systemctl reset-failed ` and start it. + If the record is there but corrupt, it exits 78 with `the volume record of is unreadable (corrupt: ...)`: restore + or recreate the record, then start it. A wrong-size local store left by an earlier release's first start is different: its log repeats `chunk attach check: chunkstore: geometry_mismatch` and it exits; waiting or restarting with the right flags does not help. In one sitting: stop the unit first; then check that the volume never served: `sw-block ops chunk show --volume --chunk-filer --chunk-path ` prints `"epoch":0` and @@ -205,6 +210,7 @@ Every command on the pages above, and the test that runs it. | A snapshot refused with `host_slot_busy` / `no background slot` while every host slot is held, retried with the same request id | `TestSnapshotLadderF1VolumesOneHost` (`cmd/blockvolume`, `F1_RUN=1`, `F1_HOST_LIMIT_DIR` set, 3 slots; `F1_SLOT_RETRY_SECONDS=0` is its negative control) | binary | | Full local disk; full `--host-limit-dir` | `TestProcedureLocalDiskFull` (`cmd/blockvolume`, root, `testdata/diskfull.sh`); what a Linux guest sees: `TestProcedureLocalDiskFullKernelInitiator` (kernel NVMe/TCP host) | binary | | A first start with the wrong `--durable-blocks`: refused before any local store is created (exit 78) | `TestWrongGeometryFlagIsRefusedBeforeTheStoreIsCreated` (`cmd/blockvolume`) | binary | +| A first start over a corrupt volume record: exit 78 before any local store is created; a start once the record is restored | `TestCorruptRecordIsRefusedBeforeTheStoreIsCreated` (`cmd/blockvolume`) | binary | | A wrong-size local store left by an earlier release (`geometry_mismatch` at attach): the guard (`sw-block ops chunk show`), removing the local files, a start with the right flags | `TestWrongGeometryCureAsWritten` (`cmd/blockvolume`; the store is planted from a capture of such a run) | binary | | SeaweedFS (filer or volume server) down during a cut | `TestProcedureStoreDownDuringACut` (`cmd/blockvolume`) | binary | | `blockmaster` refuses a `--workspace-max-clock-skew` whose half does not exceed its fence-exit budget (at or below 10.1 s) | `TestBlockmasterRefusesASkewBoundAtOrBelowTheFenceExit` (`cmd/blockvolume`, tag `subprocess`) | binary | From 880a8ba6f6e2f6179baefba3c17fe22c71928fcc Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 23 Nov 2026 16:44:38 -0800 Subject: [PATCH 03/35] test(blockvolume): the guide's reset-failed procedure after a filer outage, under real systemd Co-Authored-By: Claude Opus 5.5 --- ...tup_systemd_filer_down_integration_test.go | 107 ++++++++++++++++++ 1 file changed, 107 insertions(+) create mode 100644 seaweed-block/cmd/blockvolume/startup_systemd_filer_down_integration_test.go diff --git a/seaweed-block/cmd/blockvolume/startup_systemd_filer_down_integration_test.go b/seaweed-block/cmd/blockvolume/startup_systemd_filer_down_integration_test.go new file mode 100644 index 0000000000..a76996f919 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/startup_systemd_filer_down_integration_test.go @@ -0,0 +1,107 @@ +//go:build linux && subprocess && chunkstore_integration && systemd_integration + +package main_test + +import ( + "context" + "fmt" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + "time" +) + +// The operator guide's procedure for a first start during a long filer +// outage, run as written under real systemd (root): the blockvolume unit, +// with the shipped restart policy and a short start limit, starts while the +// filer is down; each start fails before any store exists until systemd +// stops retrying (start-limit-hit). The filer comes back; `systemctl +// reset-failed ` and `systemctl start ` then serve the volume. +// +// A runtime unit file (/run/systemd/system) stands for the installed unit: +// a transient systemd-run unit would be removed by reset-failed. +func TestSystemdFirstStartDuringAFilerOutageThenResetFailedServes(t *testing.T) { + if os.Getuid() != 0 { + t.Skip("real systemd units need root") + } + env := startSourceWithSnapshot(t, "v2") + env.h.command(t, "ops", "chunk", "restore", "--source", "v1", "--snapshot", "s1", "--target", "v2", + "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath) + b := env.hosts["n-v2"] + + shipped := gap1ShippedPolicy(t) + unit := fmt.Sprintf("swb-c04-filer-outage-%d.service", os.Getpid()) + unitPath := filepath.Join("/run/systemd/system", unit) + quoted := []string{fmt.Sprintf("%q", env.h.volume)} + for _, a := range env.volArgsFor(b) { + quoted = append(quoted, fmt.Sprintf("%q", a)) + } + spec := strings.Join([]string{ + "[Unit]", + "Description=sw-block test unit: first start during a filer outage", + "StartLimitIntervalSec=600", + "StartLimitBurst=2", + "[Service]", + "Type=exec", + "ExecStart=" + strings.Join(quoted, " "), + "Restart=on-failure", + "RestartSec=" + shipped["RestartSec"], + "RestartPreventExitStatus=" + shipped["RestartPreventExitStatus"], + "TimeoutStopSec=" + shipped["TimeoutStopSec"], + "", + }, "\n") + systemctl := func(args ...string) (string, error) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + out, err := exec.CommandContext(ctx, "systemctl", args...).CombinedOutput() + return string(out), err + } + t.Cleanup(func() { + gap1CleanupUnit(t, unit) + _ = os.Remove(unitPath) + _, _ = systemctl("daemon-reload") + }) + if err := os.WriteFile(unitPath, []byte(spec), 0o644); err != nil { + t.Fatal(err) + } + if out, err := systemctl("daemon-reload"); err != nil { + t.Fatalf("daemon-reload: %v %s", err, out) + } + + env.cluster.stopProc(t, "filer") + if out, err := systemctl("start", "--no-block", unit); err != nil { + t.Fatalf("start %s: %v %s", unit, err, out) + } + var state map[string]string + poll(t, 8*time.Minute, unit+" never reached start-limit-hit with the filer down", func() bool { + s, err := gap1ReadUnit(unit) + state = s + return err == nil && s["Result"] == "start-limit-hit" + }) + entries, _ := os.ReadDir(b.root) + t.Logf("filer down: %s gave up: Result %s, NRestarts %s, ExecMainStatus %s, ActiveState %s; files under --durable-root %d", + unit, state["Result"], state["NRestarts"], state["ExecMainStatus"], state["ActiveState"], len(entries)) + if len(entries) != 0 { + t.Fatalf("the failed starts created %d files under --durable-root", len(entries)) + } + + env.cluster.restartProc(t, "filer") + w4WaitTCP(t, env.cluster.filerGRPC, 30*time.Second) + // The guide, as written: reset-failed, then start. + if out, err := systemctl("reset-failed", unit); err != nil { + t.Fatalf("systemctl reset-failed %s: %v %s", unit, err, out) + } + if out, err := systemctl("start", unit); err != nil { + t.Fatalf("systemctl start %s: %v %s", unit, err, out) + } + poll(t, 2*time.Minute, "v2 never served after reset-failed and start", func() bool { + return volumeFrontendReady(b.status, "v2") + }) + head := env.headOf(t, "v2") + if strings.Contains(head, `"holder":""`) { + t.Fatalf("v2 serves but its HEAD is not claimed: %s", head) + } + t.Logf("after reset-failed + start: v2 serves; HEAD %s", head) +} From cf667f633c7a8e2b23c6de12d48d2ba3d4cfa3f6 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 23 Nov 2026 16:45:05 -0800 Subject: [PATCH 04/35] test(blockvolume): HEADSZ snapshot timeout and retried cuts TEST V1-SPEC r2.99: HEADSZ_SNAPSHOT_TIMEOUT passes the snapshot command's --timeout (the server caps it at its operation deadline); HEADSZ_ATTEMPTS retries a failed cut with the same request id. Every attempt is recorded with its error, wall time, the volume's last cut and its chunk-key count in the filer afterwards, so a retry shows whether an earlier attempt's uploads were kept. A cut that never completes is recorded as cut_not_completed. Co-Authored-By: Claude Fable 5.1 --- .../blockvolume/head_size_integration_test.go | 174 ++++++++++++++++-- 1 file changed, 155 insertions(+), 19 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/head_size_integration_test.go b/seaweed-block/cmd/blockvolume/head_size_integration_test.go index bfb8c84446..c7add5f4a3 100644 --- a/seaweed-block/cmd/blockvolume/head_size_integration_test.go +++ b/seaweed-block/cmd/blockvolume/head_size_integration_test.go @@ -7,6 +7,7 @@ import ( "fmt" "io" "net/http" + "net/url" "os" "path/filepath" "strconv" @@ -27,29 +28,51 @@ import ( // room for is recorded as refused by the blockvolume's headroom check, never // shrunk or bypassed. The JSON report goes to HEADSZ_REPORT. // +// HEADSZ_SNAPSHOT_TIMEOUT is the snapshot command's --timeout (default 60s; +// the server caps it at its own operation deadline). HEADSZ_ATTEMPTS (default +// 1) retries a failed cut with the same request id; every attempt is +// recorded with the volume's chunk-key count in the filer after it, so a +// retry shows whether an earlier attempt's uploads were kept. A cut that never +// completes is recorded as cut_not_completed, not failed. +// // The filer runs on its default store (leveldb2) under the test's directory; // a filer.toml anywhere weed would read one fails the test before any start, // so the store measured is the one named in the report. const headSegmentBytes = 1 << 30 +// headSzAttempt is one snapshot command for one cut: a failed attempt is +// resent with the same request id, as the command's refusal says. +type headSzAttempt struct { + Attempt int `json:"attempt"` + ExitCode int `json:"exit_code"` + Code string `json:"code,omitempty"` + Message string `json:"message,omitempty"` + WallMs float64 `json:"wall_ms"` + KeysAfter int `json:"chunk_keys_after"` + LastCutTotalMs float64 `json:"last_cut_total_ms"` + LastCutChunks int `json:"last_cut_uploaded_chunks"` +} + type headSzCut struct { - Cut int `json:"cut"` - ChangedBlocks int `json:"changed_blocks"` - HeadBytes int `json:"head_bytes"` - HeadSegments int `json:"head_segments"` - CutTotalMs float64 `json:"cut_total_ms"` - BarrierPauseMs float64 `json:"cut_barrier_pause_ms"` - UploadedChunks int `json:"uploaded_chunks"` - UploadedBytes int64 `json:"uploaded_bytes"` - SnapshotMs float64 `json:"snapshot_command_ms"` + Cut int `json:"cut"` + Completed bool `json:"completed"` + Attempts []headSzAttempt `json:"attempts"` + ChangedBlocks int `json:"changed_blocks"` + HeadBytes int `json:"head_bytes"` + HeadSegments int `json:"head_segments"` + CutTotalMs float64 `json:"cut_total_ms"` + BarrierPauseMs float64 `json:"cut_barrier_pause_ms"` + UploadedChunks int `json:"uploaded_chunks"` + UploadedBytes int64 `json:"uploaded_bytes"` + SnapshotMs float64 `json:"snapshot_command_ms"` } type headSzSize struct { Size string `json:"size"` Bytes uint64 `json:"bytes"` Segments int `json:"segments"` - Result string `json:"result"` // measured | refused_headroom + Result string `json:"result"` // measured | refused_headroom | cut_not_completed Refusal string `json:"refusal,omitempty"` WriteMs float64 `json:"write_ms,omitempty"` Cuts []headSzCut `json:"cuts,omitempty"` @@ -103,6 +126,20 @@ func TestHeadSizeAgainstVolumeSize(t *testing.T) { } changeCuts = n } + cfg := headSzConfig{snapshotTimeout: "60s", attempts: 1} + if v := os.Getenv("HEADSZ_SNAPSHOT_TIMEOUT"); v != "" { + if _, err := time.ParseDuration(v); err != nil { + t.Fatalf("HEADSZ_SNAPSHOT_TIMEOUT=%q: %v", v, err) + } + cfg.snapshotTimeout = v + } + if v := os.Getenv("HEADSZ_ATTEMPTS"); v != "" { + n, err := strconv.Atoi(v) + if err != nil || n < 1 { + t.Fatalf("HEADSZ_ATTEMPTS=%q", v) + } + cfg.attempts = n + } h := newPlannedHandoffHarness(t) clusterDir := filepath.Join(h.dir, "weed") if err := os.MkdirAll(clusterDir, 0o700); err != nil { @@ -142,12 +179,20 @@ func TestHeadSizeAgainstVolumeSize(t *testing.T) { master.waitLog(t, 30*time.Second, "blockmaster: lock acquired, reloaded=") for _, s := range sizes { - rep.Sizes = append(rep.Sizes, headSzOne(t, env, s, changeCuts)) + rep.Sizes = append(rep.Sizes, headSzOne(t, env, cfg, s, changeCuts)) } } +// headSzConfig: HEADSZ_SNAPSHOT_TIMEOUT is the snapshot command's --timeout +// (the server caps it at its own operation deadline); HEADSZ_ATTEMPTS is how +// many times one cut is tried before it is recorded as not completed. +type headSzConfig struct { + snapshotTimeout string + attempts int +} + // headSzOne measures one size; its blockvolume is stopped at the end. -func headSzOne(t *testing.T, env *handoffEnv, size string, changeCuts int) headSzSize { +func headSzOne(t *testing.T, env *handoffEnv, cfg headSzConfig, size string, changeCuts int) headSzSize { t.Helper() bytes := headSzParse(t, size) id := "h" + strings.ToLower(strings.TrimSpace(size)) @@ -194,7 +239,12 @@ func headSzOne(t *testing.T, env *handoffEnv, size string, changeCuts int) headS c.flush(t) changed = 1 } - row.Cuts = append(row.Cuts, headSzCutOnce(t, env, b, cut, changed)) + r := headSzCutOnce(t, env, cfg, b, cut, changed) + row.Cuts = append(row.Cuts, r) + if !r.Completed { + row.Result = "cut_not_completed" + return row + } } row.Result = "measured" if row.Segments > 0 && len(row.Cuts) > 0 { @@ -203,16 +253,39 @@ func headSzOne(t *testing.T, env *handoffEnv, size string, changeCuts int) headS return row } -// headSzCutOnce takes one snapshot and reads what it wrote: HEAD from the -// filer, the cut from the volume's durable status. -func headSzCutOnce(t *testing.T, env *handoffEnv, b bvHost, cut, changed int) headSzCut { +// headSzCutOnce takes one snapshot, retried with the same request id up to +// cfg.attempts times, and reads what it wrote: HEAD from the filer, the cut +// from the volume's durable status. After every attempt it counts the +// volume's chunk keys in the filer, so a retry shows whether the chunks an +// earlier attempt uploaded are still there. +func headSzCutOnce(t *testing.T, env *handoffEnv, cfg headSzConfig, b bvHost, cut, changed int) headSzCut { t.Helper() r := headSzCut{Cut: cut, ChangedBlocks: changed} start := time.Now() - out, errOut := env.h.command(t, "ops", "chunk", "snapshot", "--volume", b.volume, "--status-addr", b.status, - "--name", fmt.Sprintf("headsz-%d", cut), "--request-id", fmt.Sprintf("headsz-%s-%d", b.volume, cut)) + for a := 1; a <= cfg.attempts; a++ { + as := time.Now() + out, _, code := env.h.run(t, "ops", "chunk", "snapshot", "--volume", b.volume, "--status-addr", b.status, "--timeout", cfg.snapshotTimeout, + "--name", fmt.Sprintf("headsz-%d", cut), "--request-id", fmt.Sprintf("headsz-%s-%d", b.volume, cut)) + at := headSzAttempt{Attempt: a, ExitCode: code, WallMs: ms(time.Since(as)), KeysAfter: headSzCountDir(t, env, env.chunkPath+"/"+b.volume+"/keys")} + if code != 0 { + var e struct{ Code, Message string } + if json.Unmarshal([]byte(strings.TrimSpace(out)), &e) == nil { + at.Code, at.Message = e.Code, e.Message + } else { + at.Message = strings.TrimSpace(out) + } + } + at.LastCutTotalMs, at.LastCutChunks = headSzLastCut(t, b) + r.Attempts = append(r.Attempts, at) + if code == 0 { + r.Completed = true + break + } + } r.SnapshotMs = ms(time.Since(start)) - _, _ = out, errOut + if !r.Completed { + return r + } var st struct { Volumes []struct { VolumeID string @@ -249,6 +322,69 @@ func headSzCutOnce(t *testing.T, env *handoffEnv, b bvHost, cut, changed int) he return r } +// headSzLastCut reads the volume's last cut total (ms) and uploaded chunks +// from its durable status; zeros when there is no last cut yet. +func headSzLastCut(t *testing.T, b bvHost) (float64, int) { + t.Helper() + var st struct { + Volumes []struct { + VolumeID string + Chunk *struct { + Stats struct { + LastCut *struct { + TotalNs int64 + UploadedChunks int + } + } + } + } + } + if err := json.Unmarshal(headSzGet(t, "http://"+b.status+"/status/durable?volume="+b.volume, 4<<20), &st); err != nil { + t.Fatalf("durable status of %s: %v", b.volume, err) + } + for _, s := range st.Volumes { + if s.VolumeID == b.volume && s.Chunk != nil && s.Chunk.Stats.LastCut != nil { + return float64(s.Chunk.Stats.LastCut.TotalNs) / 1e6, s.Chunk.Stats.LastCut.UploadedChunks + } + } + return 0, 0 +} + +// headSzCountDir counts the entries of one filer directory by its JSON +// listing; a directory that does not exist yet counts 0. +func headSzCountDir(t *testing.T, env *handoffEnv, dir string) int { + t.Helper() + c := &http.Client{Timeout: 30 * time.Second} + n, last := 0, "" + for { + req, _ := http.NewRequest(http.MethodGet, "http://"+env.cluster.filerHTTP+dir+"/?limit=1000&lastFileName="+url.QueryEscape(last), nil) + req.Header.Set("Accept", "application/json") + resp, err := c.Do(req) + if err != nil { + t.Fatalf("filer list %s: %v", dir, err) + } + if resp.StatusCode == http.StatusNotFound { + resp.Body.Close() + return n + } + var page struct { + Entries []struct{ FullPath string } + ShouldDisplayLoadMore bool + LastFileName string + } + err = json.NewDecoder(resp.Body).Decode(&page) + resp.Body.Close() + if err != nil { + t.Fatalf("filer list %s: %v", dir, err) + } + n += len(page.Entries) + if !page.ShouldDisplayLoadMore || page.LastFileName == "" { + return n + } + last = page.LastFileName + } +} + func headSzGet(t *testing.T, u string, limit int64) []byte { t.Helper() c := &http.Client{Timeout: 30 * time.Second} From 6516a950ffa6ca1a212dd11c0ec3217e3af9ed1e Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 23 Nov 2026 16:51:21 -0800 Subject: [PATCH 05/35] review fold: the create-mode geometry check in M1 (diagram and row); the systemd test needs GAP1_SYSTEMD_AUTHORIZED=1 and root Co-Authored-By: Claude Opus 5.5 --- .../startup_systemd_filer_down_integration_test.go | 7 +++++-- seaweed-block/docs/design/invariants.md | 2 ++ 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/startup_systemd_filer_down_integration_test.go b/seaweed-block/cmd/blockvolume/startup_systemd_filer_down_integration_test.go index a76996f919..1753751b68 100644 --- a/seaweed-block/cmd/blockvolume/startup_systemd_filer_down_integration_test.go +++ b/seaweed-block/cmd/blockvolume/startup_systemd_filer_down_integration_test.go @@ -23,8 +23,11 @@ import ( // A runtime unit file (/run/systemd/system) stands for the installed unit: // a transient systemd-run unit would be removed by reset-failed. func TestSystemdFirstStartDuringAFilerOutageThenResetFailedServes(t *testing.T) { - if os.Getuid() != 0 { - t.Skip("real systemd units need root") + if os.Getenv("GAP1_SYSTEMD_AUTHORIZED") != "1" { + t.Fatal("explicit real-systemd qualification authorization required; no skip counts as proof") + } + if os.Geteuid() != 0 { + t.Fatal("systemd qualification needs root") } env := startSourceWithSnapshot(t, "v2") env.h.command(t, "ops", "chunk", "restore", "--source", "v1", "--snapshot", "s1", "--target", "v2", diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 1fdacbf315..73e2c3026c 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -46,6 +46,7 @@ The local storage engine and the durable backend in front of it. Diagrams in the stateDiagram-v2 [*] --> Opened: OpenWALStore / CreateWALStore [*] --> CreateRefused: CreateWALStore without local headroom (free < size + WAL) + [*] --> CreateRefused: chunk volume, create mode: geometry flags disagree with the volume record, or the record is not read Opened --> Recovering: RecoverVolume Recovering --> Serving: Recover ok, backend operational; workspace primary: lease held, then HEAD claim, then frontends listen, then ready Serving --> Closed: runtime HEAD fence, exit 78 head_fenced @@ -62,6 +63,7 @@ stateDiagram-v2 |---|---|---|---|---| | — | Opened | v3 A/B descriptors and owned-map dependencies valid, exclusive file ownership acquired; legacy formats refused; backend starts not operational | `core/storage/walstore.go` `OpenWALStoreWithOptions`; `core/frontend/durable/provider.go` `openOrCreate` | `INV-WAL-OPGATE-001`, `INV-WAL-V3-ACTIVATION-001`, `INV-WAL-V3-DESCRIPTOR-001`, `INV-WAL-V3-MAP-PUBLISH-001` | | — | CreateRefused | a new volume needs the durable root's free space >= its size + WAL, checked before the store, its WAL or its fresh marker is created (the replica floor, written when the assignment arrives, precedes the check and stays); the refusal ends the process with status 1; an existing volume opens and warns when its remaining data growth + WAL exceed the free space | `core/frontend/durable/headroom.go`; `core/frontend/durable/provider.go` `openOrCreate` | `INV-LOCAL-HEADROOM-001` | +| — | CreateRefused | a chunk volume in create mode (no local store yet): before the provider is built, the geometry flags are compared with the volume record; they disagree, or the record is there but does not decode: exit 78; the filer failed the read: exit 75; nothing is created; an absent record keeps the create path; an existing store is never rechecked against the flags | `cmd/blockvolume/main.go` (create-mode check); `cmd/blockvolume/chunk_remote.go` `geometryFlagsRefusal` | `INV-VOL-GEOMETRY-FLAGS-RECORD-001` | | Opened | Recovering | the volume is open in the provider | `core/frontend/durable/provider.go` `RecoverVolume` | `INV-WAL-OPGATE-001` | | Recovering | Serving | v3 nonce/cursor-bound physical prefix satisfies its W/BASE gate; rollback fence and rebuilt bounds publish before reuse; `Recover` aborts/drains an open COW window before lower locks, holds the capture barrier and invalidates proofs at start/end; the frontend targets start, and `FrontendPrimaryReady` is reported, only once the backend admits I/O (a chunk volume: after its storage claim; attach-pending or fenced reports not ready with the reason); a workspace primary claims HEAD, listens and reports ready only while its lease guard permits now (`WorkspaceLeaseGuard.Held`; without a grant: `NotReadyReason=lease_not_held`, exit 75 after the start-time wait) | `core/storage/walstore_v3.go` `recoverV3`; `core/storage/walstore.go` `WALStore.Recover`; `cmd/blockvolume/frontend_gate.go` `awaitFrontendStart`; `core/frontend/durable/storage_adapter.go` `FirstServing`; `core/host/volume/status_server.go` `statusProjection`; `core/host/volume/workspace_lease.go` `Held` | `INV-WAL-SYNCED-RECOVERED-001`, `INV-WAL-REPLAY-LWW-001`, `INV-WAL-FRONTIER-GAP-001`, `INV-CUT-RECOVER-BARRIER-001`, `INV-WAL-V3-W-RECOVERY-001`, `INV-WAL-V3-FENCE-001`, `INV-WAL-V3-MAP-PUBLISH-001`, `INV-FE-PRIMARY-READY-OPERATIONAL-001`, `INV-WS-SERVE-LEASE-HELD-001` | | Recovering | RecoveryFailed | a WAL integrity failure or an I/O error; the backend stays not operational and the host blocks local readiness with `wal_corrupt` or `io_error` | `cmd/blockvolume/durable_startup.go` `openAndRecoverDurable`; `core/host/volume/recovery_watchdog.go` `LocalRecoveryHealthReason` | `INV-WAL-TYPED-FAILCLOSED-001`, `INV-WAL-OPGATE-001`, `INV-WAL-V3-W-RECOVERY-001` | From 32fb4b78fed40d0f2b19372af7878700c0a8b7c3 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 23 Nov 2026 16:54:08 -0800 Subject: [PATCH 06/35] test(blockvolume): the systemd outage test uses the real lock directory and the unit's failed state after its burst Under systemd blockvolume refuses --volume-lock-dir-test-only (exit 2), so the first run never reached the filer check. systemd 249 reports the start limit as a failed unit with Result=exit-code and 'Start request repeated too quickly', not Result=start-limit-hit. Co-Authored-By: Claude Opus 5.5 --- ...tup_systemd_filer_down_integration_test.go | 36 +++++++++++++++---- 1 file changed, 30 insertions(+), 6 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/startup_systemd_filer_down_integration_test.go b/seaweed-block/cmd/blockvolume/startup_systemd_filer_down_integration_test.go index 1753751b68..5b0c0e86ad 100644 --- a/seaweed-block/cmd/blockvolume/startup_systemd_filer_down_integration_test.go +++ b/seaweed-block/cmd/blockvolume/startup_systemd_filer_down_integration_test.go @@ -16,8 +16,9 @@ import ( // The operator guide's procedure for a first start during a long filer // outage, run as written under real systemd (root): the blockvolume unit, // with the shipped restart policy and a short start limit, starts while the -// filer is down; each start fails before any store exists until systemd -// stops retrying (start-limit-hit). The filer comes back; `systemctl +// filer is down; each start fails at the startup filer check (exit 1, no +// store) until systemd stops retrying (its start limit). The filer comes +// back; `systemctl // reset-failed ` and `systemctl start ` then serve the volume. // // A runtime unit file (/run/systemd/system) stands for the installed unit: @@ -37,9 +38,23 @@ func TestSystemdFirstStartDuringAFilerOutageThenResetFailedServes(t *testing.T) shipped := gap1ShippedPolicy(t) unit := fmt.Sprintf("swb-c04-filer-outage-%d.service", os.Getpid()) unitPath := filepath.Join("/run/systemd/system", unit) + // Under systemd blockvolume refuses the test-only lock directory: the + // unit uses the real one, as an installed unit does. quoted := []string{fmt.Sprintf("%q", env.h.volume)} - for _, a := range env.volArgsFor(b) { - quoted = append(quoted, fmt.Sprintf("%q", a)) + args := env.volArgsFor(b) + for i := 0; i < len(args); i++ { + if args[i] == "--volume-lock-dir-test-only" { + i++ + continue + } + quoted = append(quoted, fmt.Sprintf("%q", args[i])) + } + const lockDir = "/run/sw-block/locks" + if _, err := os.Stat(lockDir); os.IsNotExist(err) { + if err := os.MkdirAll(lockDir, 0o755); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = os.Remove(lockDir); _ = os.Remove(filepath.Dir(lockDir)) }) } spec := strings.Join([]string{ "[Unit]", @@ -77,15 +92,24 @@ func TestSystemdFirstStartDuringAFilerOutageThenResetFailedServes(t *testing.T) if out, err := systemctl("start", "--no-block", unit); err != nil { t.Fatalf("start %s: %v %s", unit, err, out) } + // systemd gives up when the start limit is hit: the unit stays failed + // after StartLimitBurst restarts, and the journal says "Start request + // repeated too quickly" (systemd 249 keeps Result=exit-code). var state map[string]string - poll(t, 8*time.Minute, unit+" never reached start-limit-hit with the filer down", func() bool { + poll(t, 8*time.Minute, unit+" never stopped retrying with the filer down", func() bool { s, err := gap1ReadUnit(unit) state = s - return err == nil && s["Result"] == "start-limit-hit" + return err == nil && s["ActiveState"] == "failed" && s["NRestarts"] == "2" }) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + journal, _ := exec.CommandContext(ctx, "journalctl", "--unit="+unit, "--no-pager").CombinedOutput() + cancel() entries, _ := os.ReadDir(b.root) t.Logf("filer down: %s gave up: Result %s, NRestarts %s, ExecMainStatus %s, ActiveState %s; files under --durable-root %d", unit, state["Result"], state["NRestarts"], state["ExecMainStatus"], state["ActiveState"], len(entries)) + if !strings.Contains(string(journal), "Start request repeated too quickly") || state["ExecMainStatus"] != "1" { + t.Fatalf("the unit did not stop on its start limit after failing at the startup filer check (status %s):\n%s", state["ExecMainStatus"], journal) + } if len(entries) != 0 { t.Fatalf("the failed starts created %d files under --durable-root", len(entries)) } From 0c44cbc29aff778b57628629ec5344b6ddcdfb9a Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 23 Nov 2026 16:59:53 -0800 Subject: [PATCH 07/35] test(blockvolume): HEADSZ runs its snapshots past the shared 150 s bound TEST V1-SPEC r2.99/r2.100: the shared sw-block runner kills a command after 150 s, so a cut longer than that never reached the server's own operation deadline. HEADSZ now runs the snapshot command with its own bound, the command's --timeout plus a minute, and records a command it still has to kill as an attempt. It also records the volume's DirtyChunks (its capture candidates) before the first cut. Co-Authored-By: Claude Fable 5.1 --- .../blockvolume/head_size_integration_test.go | 81 ++++++++++++++++--- 1 file changed, 72 insertions(+), 9 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/head_size_integration_test.go b/seaweed-block/cmd/blockvolume/head_size_integration_test.go index c7add5f4a3..e49bf238c4 100644 --- a/seaweed-block/cmd/blockvolume/head_size_integration_test.go +++ b/seaweed-block/cmd/blockvolume/head_size_integration_test.go @@ -3,12 +3,15 @@ package main_test import ( + "context" "encoding/json" + "errors" "fmt" "io" "net/http" "net/url" "os" + "os/exec" "path/filepath" "strconv" "strings" @@ -69,14 +72,17 @@ type headSzCut struct { } type headSzSize struct { - Size string `json:"size"` - Bytes uint64 `json:"bytes"` - Segments int `json:"segments"` - Result string `json:"result"` // measured | refused_headroom | cut_not_completed - Refusal string `json:"refusal,omitempty"` - WriteMs float64 `json:"write_ms,omitempty"` - Cuts []headSzCut `json:"cuts,omitempty"` - HeadPerGiB float64 `json:"head_bytes_per_gib,omitempty"` + Size string `json:"size"` + Bytes uint64 `json:"bytes"` + Segments int `json:"segments"` + Result string `json:"result"` // measured | refused_headroom | cut_not_completed + Refusal string `json:"refusal,omitempty"` + WriteMs float64 `json:"write_ms,omitempty"` + // DirtyBeforeCut1 is the volume's DirtyChunks (its capture candidates) + // from the durable status right before the first cut. + DirtyBeforeCut1 int `json:"dirty_chunks_before_cut1"` + Cuts []headSzCut `json:"cuts,omitempty"` + HeadPerGiB float64 `json:"head_bytes_per_gib,omitempty"` } type headSzReport struct { @@ -231,6 +237,7 @@ func headSzOne(t *testing.T, env *handoffEnv, cfg headSzConfig, size string, cha _ = c.io.SetDeadline(time.Now().Add(60 * time.Second)) c.flush(t) row.WriteMs = ms(time.Since(start)) + row.DirtyBeforeCut1 = headSzDirty(t, b) for cut := 1; cut <= 1+changeCuts; cut++ { changed := 0 if cut > 1 { @@ -264,7 +271,7 @@ func headSzCutOnce(t *testing.T, env *handoffEnv, cfg headSzConfig, b bvHost, cu start := time.Now() for a := 1; a <= cfg.attempts; a++ { as := time.Now() - out, _, code := env.h.run(t, "ops", "chunk", "snapshot", "--volume", b.volume, "--status-addr", b.status, "--timeout", cfg.snapshotTimeout, + out, code := headSzRun(t, env, cfg.snapshotTimeout, "ops", "chunk", "snapshot", "--volume", b.volume, "--status-addr", b.status, "--timeout", cfg.snapshotTimeout, "--name", fmt.Sprintf("headsz-%d", cut), "--request-id", fmt.Sprintf("headsz-%s-%d", b.volume, cut)) at := headSzAttempt{Attempt: a, ExitCode: code, WallMs: ms(time.Since(as)), KeysAfter: headSzCountDir(t, env, env.chunkPath+"/"+b.volume+"/keys")} if code != 0 { @@ -385,6 +392,62 @@ func headSzCountDir(t *testing.T, env *handoffEnv, dir string) int { } } +// headSzRun runs sw-block with its own bound, the snapshot command's +// --timeout plus a minute, so the server's operation deadline answers first +// (the shared runner's fixed 150 s would kill a longer cut). A command that +// still has to be killed returns exit code -1 and its output, a recorded +// attempt, never a test failure. +func headSzRun(t *testing.T, env *handoffEnv, timeout string, args ...string) (string, int) { + t.Helper() + d, err := time.ParseDuration(timeout) + if err != nil { + t.Fatalf("timeout %q: %v", timeout, err) + } + ctx, cancel := context.WithTimeout(context.Background(), d+time.Minute) + defer cancel() + cmd := exec.CommandContext(ctx, env.h.cli, args...) + cmd.Dir = env.h.dir + cmd.WaitDelay = 5 * time.Second + var stdout, stderr strings.Builder + cmd.Stdout, cmd.Stderr = &stdout, &stderr + err = cmd.Run() + env.h.logCommand(args, stdout.String(), stderr.String(), err) + var exit *exec.ExitError + switch { + case err == nil: + return stdout.String(), 0 + case errors.As(err, &exit) && ctx.Err() == nil: + return stdout.String(), exit.ExitCode() + case ctx.Err() != nil: + return "killed after " + (d + time.Minute).String() + ": " + strings.TrimSpace(stdout.String()+" "+stderr.String()), -1 + } + t.Fatalf("sw-block %q: %v\nstdout: %s\nstderr: %s", args, err, stdout.String(), stderr.String()) + return "", -1 +} + +// headSzDirty reads the volume's DirtyChunks (its capture candidates) from +// its durable status; -1 when the status has no chunk section. +func headSzDirty(t *testing.T, b bvHost) int { + t.Helper() + var st struct { + Volumes []struct { + VolumeID string + Chunk *struct { + Stats struct{ DirtyChunks int } + } + } + } + if err := json.Unmarshal(headSzGet(t, "http://"+b.status+"/status/durable?volume="+b.volume, 4<<20), &st); err != nil { + t.Fatalf("durable status of %s: %v", b.volume, err) + } + for _, s := range st.Volumes { + if s.VolumeID == b.volume && s.Chunk != nil { + return s.Chunk.Stats.DirtyChunks + } + } + return -1 +} + func headSzGet(t *testing.T, u string, limit int64) []byte { t.Helper() c := &http.Client{Timeout: 30 * time.Second} From c0fce8dc111a566553c8972dcc998352b850de45 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 23 Nov 2026 17:01:53 -0800 Subject: [PATCH 08/35] test(blockvolume): HEADSZ records each attempt's candidates and payload TEST V1-SPEC r2.100: after every cut attempt HEADSZ records the volume's DirtyChunks (capture candidates) and its last successful cut's CandidateChunks, UnchangedChunks and PayloadNs, as the durable status reports them, so the candidate count and its cost are measured per size. Co-Authored-By: Claude Fable 5.1 --- .../blockvolume/head_size_integration_test.go | 35 +++++++++++++------ 1 file changed, 25 insertions(+), 10 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/head_size_integration_test.go b/seaweed-block/cmd/blockvolume/head_size_integration_test.go index e49bf238c4..ce866aef3f 100644 --- a/seaweed-block/cmd/blockvolume/head_size_integration_test.go +++ b/seaweed-block/cmd/blockvolume/head_size_integration_test.go @@ -55,6 +55,15 @@ type headSzAttempt struct { KeysAfter int `json:"chunk_keys_after"` LastCutTotalMs float64 `json:"last_cut_total_ms"` LastCutChunks int `json:"last_cut_uploaded_chunks"` + // DirtyAfter is the volume's DirtyChunks (capture candidates) after the + // attempt: on a failed attempt it shows whether the work done was kept. + DirtyAfter int `json:"dirty_chunks_after"` + // the volume's last SUCCESSFUL cut's candidates, unchanged chunks and + // payload (streaming, copy, upload) wall time, as its durable status + // reports them (a failed attempt does not change them) + LastCutCandidates int `json:"last_cut_candidate_chunks"` + LastCutUnchanged int `json:"last_cut_unchanged_chunks"` + LastCutPayloadMs float64 `json:"last_cut_payload_ms"` } type headSzCut struct { @@ -282,7 +291,10 @@ func headSzCutOnce(t *testing.T, env *handoffEnv, cfg headSzConfig, b bvHost, cu at.Message = strings.TrimSpace(out) } } - at.LastCutTotalMs, at.LastCutChunks = headSzLastCut(t, b) + at.DirtyAfter = headSzDirty(t, b) + lc := headSzLastCut(t, b) + at.LastCutTotalMs, at.LastCutChunks = float64(lc.TotalNs)/1e6, lc.UploadedChunks + at.LastCutCandidates, at.LastCutUnchanged, at.LastCutPayloadMs = lc.CandidateChunks, lc.UnchangedChunks, float64(lc.PayloadNs)/1e6 r.Attempts = append(r.Attempts, at) if code == 0 { r.Completed = true @@ -329,19 +341,22 @@ func headSzCutOnce(t *testing.T, env *handoffEnv, cfg headSzConfig, b bvHost, cu return r } -// headSzLastCut reads the volume's last cut total (ms) and uploaded chunks -// from its durable status; zeros when there is no last cut yet. -func headSzLastCut(t *testing.T, b bvHost) (float64, int) { +// headSzLastCutStats is the part of the volume's last cut an attempt records. +type headSzLastCutStats struct { + TotalNs, PayloadNs int64 + UploadedChunks, CandidateChunks, UnchangedChunks int +} + +// headSzLastCut reads the volume's last cut from its durable status; zeros +// when there is no last cut yet. +func headSzLastCut(t *testing.T, b bvHost) headSzLastCutStats { t.Helper() var st struct { Volumes []struct { VolumeID string Chunk *struct { Stats struct { - LastCut *struct { - TotalNs int64 - UploadedChunks int - } + LastCut *headSzLastCutStats } } } @@ -351,10 +366,10 @@ func headSzLastCut(t *testing.T, b bvHost) (float64, int) { } for _, s := range st.Volumes { if s.VolumeID == b.volume && s.Chunk != nil && s.Chunk.Stats.LastCut != nil { - return float64(s.Chunk.Stats.LastCut.TotalNs) / 1e6, s.Chunk.Stats.LastCut.UploadedChunks + return *s.Chunk.Stats.LastCut } } - return 0, 0 + return headSzLastCutStats{} } // headSzCountDir counts the entries of one filer directory by its JSON From 162f914a3110adcd4c30252662db9b02dd26d0c2 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 23 Nov 2026 17:03:03 -0800 Subject: [PATCH 09/35] test(blockvolume): the systemd test removes only the lock directories it created Co-Authored-By: Claude Opus 5.5 --- ...tup_systemd_filer_down_integration_test.go | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/startup_systemd_filer_down_integration_test.go b/seaweed-block/cmd/blockvolume/startup_systemd_filer_down_integration_test.go index 5b0c0e86ad..28570b441d 100644 --- a/seaweed-block/cmd/blockvolume/startup_systemd_filer_down_integration_test.go +++ b/seaweed-block/cmd/blockvolume/startup_systemd_filer_down_integration_test.go @@ -49,13 +49,24 @@ func TestSystemdFirstStartDuringAFilerOutageThenResetFailedServes(t *testing.T) } quoted = append(quoted, fmt.Sprintf("%q", args[i])) } + // Create the lock directory and its parent only if missing, and remove + // only what this test created (child first); nothing pre-existing is + // touched. const lockDir = "/run/sw-block/locks" - if _, err := os.Stat(lockDir); os.IsNotExist(err) { - if err := os.MkdirAll(lockDir, 0o755); err != nil { - t.Fatal(err) + var created []string + for _, dir := range []string{filepath.Dir(lockDir), lockDir} { + if _, err := os.Stat(dir); os.IsNotExist(err) { + if err := os.Mkdir(dir, 0o755); err != nil { + t.Fatal(err) + } + created = append(created, dir) } - t.Cleanup(func() { _ = os.Remove(lockDir); _ = os.Remove(filepath.Dir(lockDir)) }) } + t.Cleanup(func() { + for i := len(created) - 1; i >= 0; i-- { + _ = os.Remove(created[i]) + } + }) spec := strings.Join([]string{ "[Unit]", "Description=sw-block test unit: first start during a filer outage", From e9f01cbaf2b1ee7cd5099262231217aeefb705c1 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 23 Nov 2026 17:05:36 -0800 Subject: [PATCH 10/35] test(blockvolume): phase 0 baseline: what losing blockmaster costs the guests today Co-Authored-By: Claude Opus 5.5 --- ...phase0_master_baseline_integration_test.go | 232 ++++++++++++++++++ .../snapshot_ladder_f1_integration_test.go | 6 +- 2 files changed, 236 insertions(+), 2 deletions(-) create mode 100644 seaweed-block/cmd/blockvolume/phase0_master_baseline_integration_test.go diff --git a/seaweed-block/cmd/blockvolume/phase0_master_baseline_integration_test.go b/seaweed-block/cmd/blockvolume/phase0_master_baseline_integration_test.go new file mode 100644 index 0000000000..bc5bebc54e --- /dev/null +++ b/seaweed-block/cmd/blockvolume/phase0_master_baseline_integration_test.go @@ -0,0 +1,232 @@ +//go:build linux && subprocess && chunkstore_integration + +package main_test + +import ( + "fmt" + "sync" + "testing" + "time" +) + +// Phase 0 baseline: what blockmaster's loss costs the guests today, measured +// with real binaries and an in-test NVMe/TCP initiator, so that phase 0 +// (mTLS on the master/holder link) can be gated against it. One write of 4 +// KiB every 10 ms per volume, each with a 30 s command deadline. +// +// (a) blockmaster SIGKILLed and restarted 5 s later under guest writes: +// guest write errors (expected 0) and the write latency; +// (b) blockmaster down 60 s: the time until each volume fences, then, +// with the master back, until it serves again. The harness restarts +// an exited blockvolume after the shipped RestartSec (5 s), as the unit +// does, and counts the starts against the shipped start limit (10 in +// 600 s); +// (c) as (b) with 3 volumes. +// +// The numbers are logged as PHASE0 lines; only (a)'s zero write errors and +// (b)/(c)'s serving again are asserted. + +const ( + baselineEvery = 10 * time.Millisecond + baselineDeadline = 30 * time.Second + unitRestartSec = 5 * time.Second + unitStartLimit = 10 + unitStartLimitSpan = 600 * time.Second +) + +type baselineWriter struct { + mu sync.Mutex + samples []f1Sample + errAt time.Time + err error + stopped chan struct{} + stopOnce sync.Once + done chan struct{} +} + +// startBaselineWriter writes to vol's frontend until stopped or until the +// first failed write (the fence, when the master is gone). +func startBaselineWriter(t *testing.T, env *handoffEnv, key string) *baselineWriter { + t.Helper() + b := env.hosts[key] + c := dialNVMe(t, b.nvme, plannedHandoffNQN) + w := &baselineWriter{stopped: make(chan struct{}), done: make(chan struct{})} + go func() { + defer close(w.done) + defer c.close() + for n := uint64(0); ; n++ { + select { + case <-w.stopped: + return + case <-time.After(baselineEvery): + } + lba := n % 1024 + s := time.Now() + _ = c.io.SetDeadline(s.Add(baselineDeadline)) + err := c.tryWrite(lba, f1Block(b.volume, 0, "phase0", lba)) + w.mu.Lock() + w.samples = append(w.samples, f1Sample{start: s, d: time.Since(s)}) + if err != nil { + w.err, w.errAt = err, time.Now() + } + w.mu.Unlock() + if err != nil { + return + } + } + }() + return w +} + +func (w *baselineWriter) stop() { + w.stopOnce.Do(func() { close(w.stopped) }) + <-w.done +} + +// maxLatency is the longest write that started in [from, to]. +func (w *baselineWriter) maxLatency(from, to time.Time) (time.Duration, int) { + w.mu.Lock() + defer w.mu.Unlock() + var max time.Duration + n := 0 + for _, s := range w.samples { + if !s.start.Before(from) && !s.start.After(to) { + n++ + if s.d > max { + max = s.d + } + } + } + return max, n +} + +func TestPhase0BaselineMasterKilledAndRestartedUnderWrites(t *testing.T) { + env, _ := f1StartEnv(t, f1Config{Volumes: 1}) + vols := f1StartSources(t, env, 1) + w := startBaselineWriter(t, env, vols[0].id) + time.Sleep(10 * time.Second) + killAt := time.Now() + env.masterProcess.kill(t) + time.Sleep(5 * time.Second) + env.masterProcess = env.h.start(t, "blockmaster-restarted", env.h.master, env.masterArgs...) + env.masterProcess.waitLog(t, 30*time.Second, "blockmaster: lock acquired, reloaded=") + backAt := time.Now() + time.Sleep(30 * time.Second) + w.stop() + all, n := w.maxLatency(time.Time{}, time.Now()) + around, m := w.maxLatency(killAt, backAt.Add(5*time.Second)) + t.Logf("PHASE0 (a) master SIGKILL + restart after 5 s: writes %d, write errors %d (%v), max write latency %v, max in the kill window (%d writes) %v, master back after %v", + n, map[bool]int{true: 1, false: 0}[w.err != nil], w.err, all.Round(time.Microsecond), m, around.Round(time.Microsecond), backAt.Sub(killAt).Round(time.Millisecond)) + if w.err != nil { + t.Fatalf("phase 0 baseline (a): a guest write failed while the master was down 5 s: %v", w.err) + } +} + +// unitEmulator restarts an exited blockvolume after unitRestartSec, as the +// shipped unit does, and records every exit. +type unitEmulator struct { + mu sync.Mutex + d *daemon + starts []time.Time + exits []string + stop chan struct{} + done chan struct{} +} + +func emulateUnit(t *testing.T, env *handoffEnv, key string, d *daemon) *unitEmulator { + u := &unitEmulator{d: d, starts: []time.Time{time.Now()}, stop: make(chan struct{}), done: make(chan struct{})} + go func() { + defer close(u.done) + for { + u.mu.Lock() + cur := u.d + u.mu.Unlock() + select { + case <-u.stop: + return + case <-cur.done: + } + u.mu.Lock() + u.exits = append(u.exits, fmt.Sprintf("%s exit %d", time.Now().Format("15:04:05.000"), exitCode(cur.err))) + u.mu.Unlock() + select { + case <-u.stop: + return + case <-time.After(unitRestartSec): + } + next := env.h.start(t, fmt.Sprintf("blockvolume-%s-unit-%d", key, len(u.starts)), env.h.volume, env.volArgsFor(env.hosts[key])...) + u.mu.Lock() + u.d, u.starts = next, append(u.starts, time.Now()) + u.mu.Unlock() + } + }() + return u +} + +// startLimitHit reports whether the unit's starts would have exceeded the +// shipped limit (more than unitStartLimit starts within unitStartLimitSpan). +func (u *unitEmulator) startLimitHit() bool { + u.mu.Lock() + defer u.mu.Unlock() + for i := range u.starts { + n := 0 + for _, s := range u.starts[i:] { + if s.Sub(u.starts[i]) <= unitStartLimitSpan { + n++ + } + } + if n > unitStartLimit { + return true + } + } + return false +} + +func phase0MasterDown60s(t *testing.T, n int) { + env, _ := f1StartEnv(t, f1Config{Volumes: n}) + vols := f1StartSources(t, env, n) + writers := make([]*baselineWriter, n) + units := make([]*unitEmulator, n) + for i, v := range vols { + writers[i] = startBaselineWriter(t, env, v.id) + units[i] = emulateUnit(t, env, v.id, v.d) + } + time.Sleep(10 * time.Second) + killAt := time.Now() + env.masterProcess.kill(t) + time.Sleep(60 * time.Second) + env.masterProcess = env.h.start(t, "blockmaster-back", env.h.master, env.masterArgs...) + env.masterProcess.waitLog(t, 30*time.Second, "blockmaster: lock acquired, reloaded=") + backAt := time.Now() + for i, v := range vols { + b := env.hosts[v.id] + poll(t, 5*time.Minute, v.id+" never served again after the master came back", func() bool { return volumeFrontendReady(b.status, b.volume) }) + servedAt := time.Now() + probe := startBaselineWriter(t, env, v.id) + time.Sleep(time.Second) + probe.stop() + if probe.err != nil { + t.Fatalf("%s serves again but a write failed: %v", v.id, probe.err) + } + writers[i].stop() + close(units[i].stop) + <-units[i].done + w, u := writers[i], units[i] + u.mu.Lock() + starts, exits := len(u.starts), append([]string(nil), u.exits...) + u.mu.Unlock() + fence := "none" + if w.err != nil { + fence = w.errAt.Sub(killAt).Round(time.Millisecond).String() + } + firstExit := "none" + if len(exits) > 0 { + firstExit = exits[0] + } + t.Logf("PHASE0 (%s) master down 60 s, volume %s: first failed write after %s (%v); exits %v (first %s); starts %d, start limit (%d in %v) hit %v; serving again %v after the master came back", + map[int]string{1: "b", 3: "c"}[n], v.id, fence, w.err, exits, firstExit, starts, unitStartLimit, unitStartLimitSpan, u.startLimitHit(), servedAt.Sub(backAt).Round(time.Millisecond)) + } +} + +func TestPhase0BaselineMasterDown60sOneVolume(t *testing.T) { phase0MasterDown60s(t, 1) } +func TestPhase0BaselineMasterDown60sThreeVolumes(t *testing.T) { phase0MasterDown60s(t, 3) } diff --git a/seaweed-block/cmd/blockvolume/snapshot_ladder_f1_integration_test.go b/seaweed-block/cmd/blockvolume/snapshot_ladder_f1_integration_test.go index b4d2a8b560..fc4bdc68e0 100644 --- a/seaweed-block/cmd/blockvolume/snapshot_ladder_f1_integration_test.go +++ b/seaweed-block/cmd/blockvolume/snapshot_ladder_f1_integration_test.go @@ -235,10 +235,12 @@ func f1StartEnv(t *testing.T, cfg f1Config) (*handoffEnv, *daemon) { spec := filepath.Join(h.dir, "cluster-spec.yaml") must(os.WriteFile(spec, []byte(fmt.Sprintf("nodes:\n - server_id: s1\n data_addr: %s\n ctrl_addr: %s\nvolumes:\n%s", h.dataAddr, h.ctrlAddr, vols.String())), 0o644)) mstate := filepath.Join(h.dir, "master") - master := h.start(t, "blockmaster", h.master, "--authority-store", filepath.Join(mstate, "authority"), "--lifecycle-store", filepath.Join(mstate, "lifecycle"), + env.masterArgs = []string{"--authority-store", filepath.Join(mstate, "authority"), "--lifecycle-store", filepath.Join(mstate, "lifecycle"), "--cluster-spec", spec, "--expected-slots-per-volume", "1", "--listen", h.masterAddr, - "--workspace-rpc", "--workspace-head-base-url", "http://"+env.cluster.filerHTTP+env.chunkPath) + "--workspace-rpc", "--workspace-head-base-url", "http://" + env.cluster.filerHTTP + env.chunkPath} + master := h.start(t, "blockmaster", h.master, env.masterArgs...) master.waitLog(t, 30*time.Second, "blockmaster: lock acquired, reloaded=") + env.masterProcess = master return env, master } From e04a353af6b5ce84320500089a5fc019f4e39a45 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 23 Nov 2026 17:18:50 -0800 Subject: [PATCH 11/35] test(blockvolume): a long blockmaster outage under real systemd with the shipped start limit Co-Authored-By: Claude Opus 5.5 --- ..._systemd_master_outage_integration_test.go | 178 ++++++++++++++++++ 1 file changed, 178 insertions(+) create mode 100644 seaweed-block/cmd/blockvolume/startup_systemd_master_outage_integration_test.go diff --git a/seaweed-block/cmd/blockvolume/startup_systemd_master_outage_integration_test.go b/seaweed-block/cmd/blockvolume/startup_systemd_master_outage_integration_test.go new file mode 100644 index 0000000000..084c77787d --- /dev/null +++ b/seaweed-block/cmd/blockvolume/startup_systemd_master_outage_integration_test.go @@ -0,0 +1,178 @@ +//go:build linux && subprocess && chunkstore_integration && systemd_integration + +package main_test + +import ( + "bufio" + "context" + "fmt" + "os" + "os/exec" + "path/filepath" + "strconv" + "strings" + "testing" + "time" +) + +// A long blockmaster outage under real systemd (root), with the shipped +// unit's restart policy AND its shipped start limit: a serving volume's +// blockvolume fences, exits 75 and is restarted by the unit; each start +// waits for a grant and exits 75 again. The test keeps the master down until +// systemd stops retrying (the start limit) or 12 minutes pass, records when +// and after how many restarts, then brings the master back and records +// whether the volume serves by itself, and, if the unit failed, how long +// `systemctl reset-failed` + `systemctl start` take to serve it. +// +// A runtime unit file (/run/systemd/system) stands for the installed unit. +func TestSystemdMasterOutagePastTheStartLimit(t *testing.T) { + if os.Getenv("GAP1_SYSTEMD_AUTHORIZED") != "1" { + t.Fatal("explicit real-systemd qualification authorization required; no skip counts as proof") + } + if os.Geteuid() != 0 { + t.Fatal("systemd qualification needs root") + } + shipped := gap1ShippedPolicy(t) + interval, burst := shippedStartLimit(t) + + env := startHandoffEnv(t, 1) + b := env.hosts["s1"] + unit := fmt.Sprintf("swb-c04-master-outage-%d.service", os.Getpid()) + writeRuntimeUnit(t, unit, env.h.volume, env.volArgsFor(b), []string{ + "StartLimitIntervalSec=" + interval, + "StartLimitBurst=" + burst, + }, []string{ + "Restart=on-failure", + "RestartSec=" + shipped["RestartSec"], + "RestartPreventExitStatus=" + shipped["RestartPreventExitStatus"], + "TimeoutStopSec=" + shipped["TimeoutStopSec"], + }) + if out, err := runSystemctl("start", unit); err != nil { + t.Fatalf("start %s: %v %s", unit, err, out) + } + poll(t, 2*time.Minute, "v1 never served under the unit", func() bool { return volumeFrontendReady(b.status, "v1") }) + + killAt := time.Now() + env.masterProcess.kill(t) + var state map[string]string + gaveUp := false + for deadline := killAt.Add(12 * time.Minute); time.Now().Before(deadline); time.Sleep(2 * time.Second) { + s, err := gap1ReadUnit(unit) + if err == nil { + state = s + if s["ActiveState"] == "failed" { + gaveUp = true + break + } + } + } + downFor := time.Since(killAt) + journal := unitJournal(unit) + t.Logf("PHASE0-SYSTEMD master down %v: unit gave up (start limit %s in %s) %v; NRestarts %s; ActiveState %s; Result %s; 'Start request repeated too quickly' %v", + downFor.Round(time.Second), burst, interval, gaveUp, state["NRestarts"], state["ActiveState"], state["Result"], strings.Contains(journal, "Start request repeated too quickly")) + + env.masterProcess = env.h.start(t, "blockmaster-back", env.h.master, env.masterArgs...) + env.masterProcess.waitLog(t, 30*time.Second, "blockmaster: lock acquired, reloaded=") + backAt := time.Now() + served := false + for deadline := backAt.Add(90 * time.Second); time.Now().Before(deadline) && !served; time.Sleep(time.Second) { + served = volumeFrontendReady(b.status, "v1") + } + if served { + t.Logf("PHASE0-SYSTEMD with the master back, v1 served by itself after %v", time.Since(backAt).Round(time.Millisecond)) + return + } + t.Logf("PHASE0-SYSTEMD with the master back, v1 did not serve by itself within 90 s (unit %s)", state["ActiveState"]) + if out, err := runSystemctl("reset-failed", unit); err != nil { + t.Fatalf("systemctl reset-failed %s: %v %s", unit, err, out) + } + resetAt := time.Now() + if out, err := runSystemctl("start", unit); err != nil { + t.Fatalf("systemctl start %s: %v %s", unit, err, out) + } + poll(t, 3*time.Minute, "v1 never served after reset-failed and start", func() bool { return volumeFrontendReady(b.status, "v1") }) + t.Logf("PHASE0-SYSTEMD after reset-failed + start, v1 served after %v", time.Since(resetAt).Round(time.Millisecond)) +} + +// shippedStartLimit reads StartLimitIntervalSec and StartLimitBurst from the +// shipped sw-blockvolume.service. +func shippedStartLimit(t *testing.T) (interval, burst string) { + t.Helper() + f, err := os.Open(filepath.Join("..", "..", "deploy", "systemd", "sw-blockvolume.service")) + if err != nil { + t.Fatal(err) + } + defer f.Close() + sc := bufio.NewScanner(f) + for sc.Scan() { + line := strings.TrimSpace(sc.Text()) + if v, ok := strings.CutPrefix(line, "StartLimitIntervalSec="); ok { + interval = v + } + if v, ok := strings.CutPrefix(line, "StartLimitBurst="); ok { + burst = v + } + } + if _, err := strconv.Atoi(burst); err != nil || interval == "" { + t.Fatalf("shipped unit start limit unreadable: interval %q burst %q", interval, burst) + } + return interval, burst +} + +// writeRuntimeUnit installs a runtime unit (removed, with daemon-reload, +// when the test ends) that runs exe with args, minus the test-only lock +// directory: under systemd blockvolume uses the real one, which is created +// for the test when missing and removed only if this test created it. +func writeRuntimeUnit(t *testing.T, unit, exe string, args, unitSection, serviceSection []string) { + t.Helper() + quoted := []string{fmt.Sprintf("%q", exe)} + for i := 0; i < len(args); i++ { + if args[i] == "--volume-lock-dir-test-only" { + i++ + continue + } + quoted = append(quoted, fmt.Sprintf("%q", args[i])) + } + const lockDir = "/run/sw-block/locks" + var created []string + for _, dir := range []string{filepath.Dir(lockDir), lockDir} { + if _, err := os.Stat(dir); os.IsNotExist(err) { + if err := os.Mkdir(dir, 0o755); err != nil { + t.Fatal(err) + } + created = append(created, dir) + } + } + path := filepath.Join("/run/systemd/system", unit) + t.Cleanup(func() { + gap1CleanupUnit(t, unit) + _ = os.Remove(path) + _, _ = runSystemctl("daemon-reload") + for i := len(created) - 1; i >= 0; i-- { + _ = os.Remove(created[i]) + } + }) + lines := append([]string{"[Unit]", "Description=sw-block test unit"}, unitSection...) + lines = append(lines, "[Service]", "Type=exec", "ExecStart="+strings.Join(quoted, " ")) + lines = append(lines, serviceSection...) + if err := os.WriteFile(path, []byte(strings.Join(lines, "\n")+"\n"), 0o644); err != nil { + t.Fatal(err) + } + if out, err := runSystemctl("daemon-reload"); err != nil { + t.Fatalf("daemon-reload: %v %s", err, out) + } +} + +func runSystemctl(args ...string) (string, error) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + out, err := exec.CommandContext(ctx, "systemctl", args...).CombinedOutput() + return string(out), err +} + +func unitJournal(unit string) string { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + out, _ := exec.CommandContext(ctx, "journalctl", "--unit="+unit, "--no-pager").CombinedOutput() + return string(out) +} From 640f5823890628b4ca20130c61c27429a8f91999 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 23 Nov 2026 17:30:41 -0800 Subject: [PATCH 12/35] test(blockvolume): HEADSZ keeps each attempt's whole chunk status TEST V1-SPEC r2.104: after every cut attempt HEADSZ stores the volume's whole chunk section of its durable status as served (every counter and the full LastCut), so a term the named fields do not cover can still be read. Co-Authored-By: Claude Fable 5.1 --- .../blockvolume/head_size_integration_test.go | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/seaweed-block/cmd/blockvolume/head_size_integration_test.go b/seaweed-block/cmd/blockvolume/head_size_integration_test.go index ce866aef3f..374db5c335 100644 --- a/seaweed-block/cmd/blockvolume/head_size_integration_test.go +++ b/seaweed-block/cmd/blockvolume/head_size_integration_test.go @@ -58,6 +58,10 @@ type headSzAttempt struct { // DirtyAfter is the volume's DirtyChunks (capture candidates) after the // attempt: on a failed attempt it shows whether the work done was kept. DirtyAfter int `json:"dirty_chunks_after"` + // ChunkStatusAfter is the volume's whole chunk section of its durable + // status after the attempt, as served (every counter and the full + // LastCut), so a term no named field covers can still be read. + ChunkStatusAfter json.RawMessage `json:"chunk_status_after,omitempty"` // the volume's last SUCCESSFUL cut's candidates, unchanged chunks and // payload (streaming, copy, upload) wall time, as its durable status // reports them (a failed attempt does not change them) @@ -292,6 +296,7 @@ func headSzCutOnce(t *testing.T, env *handoffEnv, cfg headSzConfig, b bvHost, cu } } at.DirtyAfter = headSzDirty(t, b) + at.ChunkStatusAfter = headSzChunkStatus(t, b) lc := headSzLastCut(t, b) at.LastCutTotalMs, at.LastCutChunks = float64(lc.TotalNs)/1e6, lc.UploadedChunks at.LastCutCandidates, at.LastCutUnchanged, at.LastCutPayloadMs = lc.CandidateChunks, lc.UnchangedChunks, float64(lc.PayloadNs)/1e6 @@ -440,6 +445,27 @@ func headSzRun(t *testing.T, env *handoffEnv, timeout string, args ...string) (s return "", -1 } +// headSzChunkStatus returns the volume's chunk section of its durable status +// as served, unparsed; nil when there is none. +func headSzChunkStatus(t *testing.T, b bvHost) json.RawMessage { + t.Helper() + var st struct { + Volumes []struct { + VolumeID string + Chunk json.RawMessage + } + } + if err := json.Unmarshal(headSzGet(t, "http://"+b.status+"/status/durable?volume="+b.volume, 4<<20), &st); err != nil { + t.Fatalf("durable status of %s: %v", b.volume, err) + } + for _, s := range st.Volumes { + if s.VolumeID == b.volume && len(s.Chunk) > 0 && string(s.Chunk) != "null" { + return s.Chunk + } + } + return nil +} + // headSzDirty reads the volume's DirtyChunks (its capture candidates) from // its durable status; -1 when the status has no chunk section. func headSzDirty(t *testing.T, b bvHost) int { From 6d00eb63b414fe39ba1c2181d25e05f3cabfd110 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 23 Nov 2026 18:05:55 -0800 Subject: [PATCH 13/35] fix: a cut's payload time counts staging; the layer counts staged chunks A cut's PayloadNs now counts its staging rounds even when they uploaded nothing (every staged chunk was zero), so a first cut that spent its time reading and hashing shows it. The layer status gains StagedChunks: the chunks staged by every cut attempt, failed ones included, so a cut retried after its deadline shows the progress its earlier attempts made. DirtyChunks is documented as the next cut's candidates, not its progress. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/storage/chunk_layer.go | 7 +- seaweed-block/core/storage/chunk_seam.go | 12 +++- .../storage/chunk_stage_accounting_test.go | 65 +++++++++++++++++++ seaweed-block/docs/status-schema.md | 3 +- 4 files changed, 80 insertions(+), 7 deletions(-) create mode 100644 seaweed-block/core/storage/chunk_stage_accounting_test.go diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index 5e5c917556..dd74cd178c 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -778,9 +778,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch if !guestFrozen { staged, intents, err = l.stage(ctx, &st, spill.bytes) } - if st.UploadedBytes > 0 { - st.PayloadNs += time.Since(stageStart).Nanoseconds() - } + st.PayloadNs += time.Since(stageStart).Nanoseconds() if err != nil { dropCapturedIntents(ctx, intents) return chunkCutResult{}, err @@ -1631,6 +1629,9 @@ func (l *chunkLayerImpl) stage(ctx context.Context, st *chunkCutStats, spillCap staged[idx] = sc } st.StagedChunks += len(batch) + l.stMu.Lock() + l.stats.StagedChunks += uint64(len(batch)) + l.stMu.Unlock() if hook := l.testAfterStageHook; hook != nil { hook(round) } diff --git a/seaweed-block/core/storage/chunk_seam.go b/seaweed-block/core/storage/chunk_seam.go index bbd219d4fb..e72a00a958 100644 --- a/seaweed-block/core/storage/chunk_seam.go +++ b/seaweed-block/core/storage/chunk_seam.go @@ -489,8 +489,13 @@ type chunkCutStats struct { // results whose outcome stayed unresolved after the HEAD re-read. // - PendingUnresolved: an unresolved proposal is held now. // - DirtyChunks is the number of chunks dirty since the last HEAD now -// (the C11 bitmap popcount); the cut scheduler's threshold reads it. -// Chunks still awaiting reconciliation are not counted. +// (the C11 bitmap popcount): the next cut's candidates, not its +// progress (it does not fall while a cut runs or across failed +// attempts); the cut scheduler's threshold reads it. Chunks still +// awaiting reconciliation are not counted. +// - StagedChunks counts the chunks every cut attempt of this layer +// staged, failed attempts included (in-process): the progress a cut +// retried after its deadline has made. // - Reconciling: the dirty set is being reconciled against HEAD; no cut // publishes until it is done. ReconcileDone of ReconcileTotal chunks // are compared. @@ -508,7 +513,8 @@ type chunkLayerStats struct { CASConflicts uint64 // HEAD CAS precondition failures CASUnknown uint64 // HEAD CAS results still unresolved after the re-read PendingUnresolved bool // an unresolved HEAD proposal is held now - DirtyChunks int // chunks dirty since the last HEAD (not counting those awaiting reconciliation) + 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) 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/core/storage/chunk_stage_accounting_test.go b/seaweed-block/core/storage/chunk_stage_accounting_test.go new file mode 100644 index 0000000000..1416056a42 --- /dev/null +++ b/seaweed-block/core/storage/chunk_stage_accounting_test.go @@ -0,0 +1,65 @@ +package storage + +import ( + "context" + "errors" + "testing" + "time" +) + +// zeroStagedLayer is a layer past its zero baseline cut with n chunks +// rewritten with zeros: candidates that staging reads and hashes but never +// uploads. The spill cap of two chunks makes the cut stage them. +func zeroStagedLayer(t *testing.T, n int) (*fakeChunkRemote, *chunkLayerImpl) { + t.Helper() + s, f, l, w := precopyLayer(t, 1, 0) + l.cfg.COWSpillLimit = 2 * ctChunkBytes + for c := 0; c < n; c++ { + w.write(t, s, uint32(c*ctChunkBlocks+2), 0) + } + return f, l +} + +// The payload time of a cut counts its staging rounds even when they +// upload nothing (every staged chunk was zero), so a first cut that spent +// its time reading and hashing shows it. +func TestChunkStage_PayloadTimeCountsStagingWithoutUploads(t *testing.T) { + _, l := zeroStagedLayer(t, 6) + // Staging takes measurable time on any clock resolution. + l.testAfterStageHook = func(int) { time.Sleep(20 * time.Millisecond) } + r, err := l.Cut(ctTimeout(t)) + if err != nil { + t.Fatal(err) + } + st := r.Stats + if st.StageRounds == 0 || st.StagedChunks == 0 { + t.Fatalf("cut stats %+v; want staging rounds", st) + } + if st.UploadedBytes != 0 { + t.Fatalf("uploaded %d bytes; want none (every staged chunk is zero)", st.UploadedBytes) + } + if st.PayloadNs < int64(20*time.Millisecond) { + t.Fatalf("payload time %d ns with %d chunks staged; want the staging time", st.PayloadNs, st.StagedChunks) + } +} + +// The layer counts every chunk staged by any cut attempt, a failed one +// included, so a first cut retried after its deadline shows the progress +// its earlier attempts made; the last successful cut's stats do not move. +func TestChunkStage_StagedChunksCountsFailedAttempts(t *testing.T) { + _, l := zeroStagedLayer(t, 6) + before := l.Stats() + ctx, cancel := context.WithCancel(context.Background()) + l.testBeforeBarrierLockHook = cancel + if _, err := l.Cut(ctx); !errors.Is(err, context.Canceled) { + t.Fatalf("cut: %v; want it cancelled before the barrier", err) + } + l.testBeforeBarrierLockHook = nil + after := l.Stats() + if after.StagedChunks <= before.StagedChunks { + t.Fatalf("staged chunks %d before, %d after a failed attempt that staged; want more", before.StagedChunks, after.StagedChunks) + } + if after.CutSeq != before.CutSeq || after.LastCut.StagedChunks != before.LastCut.StagedChunks { + t.Fatal("a failed attempt changed the last successful cut") + } +} diff --git a/seaweed-block/docs/status-schema.md b/seaweed-block/docs/status-schema.md index 93db9c50d6..8e38ecfade 100644 --- a/seaweed-block/docs/status-schema.md +++ b/seaweed-block/docs/status-schema.md @@ -227,7 +227,8 @@ Durable store state of the served volume. Go type `volume.durableStatusBody`. | `Volumes[].Chunk.Stats.CASConflicts` | uint64 | HEAD CAS precondition failures | | `Volumes[].Chunk.Stats.CASUnknown` | uint64 | HEAD CAS results still unresolved after the re-read | | `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) | +| `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.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 f437a52ef7df9511208bf9c37c22e25ee66346c1 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 23 Nov 2026 18:24:14 -0800 Subject: [PATCH 14/35] fix: count each staged chunk as it finishes; ledger row for the stage counters StagedChunks is counted when staging remembers a chunk for reuse, so a round interrupted partway counts what it finished instead of nothing; the copy window, which shares the upload stream, does not count. The counter's contract (only grows, a re-staged chunk counts again, in-process) is stated in the status and in a new invariant row with its tests: an exact count of 6 for a failed attempt, 0 for its reusing retry, and 5 of 6 for a round whose upload fails at the sixth chunk. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/storage/chunk_cut_cow.go | 2 +- .../core/storage/chunk_cut_payload.go | 16 +++++-- seaweed-block/core/storage/chunk_layer.go | 3 -- .../core/storage/chunk_review271_test.go | 4 +- seaweed-block/core/storage/chunk_seam.go | 10 +++-- .../storage/chunk_stage_accounting_test.go | 43 ++++++++++++++++++- seaweed-block/docs/design/invariants.md | 3 +- 7 files changed, 65 insertions(+), 16 deletions(-) diff --git a/seaweed-block/core/storage/chunk_cut_cow.go b/seaweed-block/core/storage/chunk_cut_cow.go index 35144e34ff..ca7291c56c 100644 --- a/seaweed-block/core/storage/chunk_cut_cow.go +++ b/seaweed-block/core/storage/chunk_cut_cow.go @@ -621,7 +621,7 @@ func (l *chunkLayerImpl) copyCOWWindow(ctx context.Context, w *cutCOWWindow, rec } } order := hotChunkKeys(indices, recent) - out, intents, err := l.streamCutPayloads(ctx, order, head, func(ctx context.Context, idx uint64) (capturedChunk, error) { + out, intents, err := l.streamCutPayloads(ctx, order, head, false, func(ctx context.Context, idx uint64) (capturedChunk, error) { c, ok, err := l.copyCOWEntry(w, idx) if err != nil { return capturedChunk{}, err diff --git a/seaweed-block/core/storage/chunk_cut_payload.go b/seaweed-block/core/storage/chunk_cut_payload.go index 6e66f07433..c166290edd 100644 --- a/seaweed-block/core/storage/chunk_cut_payload.go +++ b/seaweed-block/core/storage/chunk_cut_payload.go @@ -41,7 +41,10 @@ func hotChunkKeys(indices map[uint64]bool, recent map[uint64]uint64) []uint64 { // image through PUT/retry, then reads its next candidate independently of slow // workers. One durable intent covers all candidate keys before the first PUT; // unused keys are harmless and retain no payload memory. -func (l *chunkLayerImpl) streamCutPayloads(ctx context.Context, batch []uint64, head chunkHead, read func(context.Context, uint64) (capturedChunk, error)) ([]capturedChunk, []string, error) { +// +// staging says the batch is a staging round (before the barrier): each chunk +// it finishes is counted in Stats.StagedChunks as it finishes. +func (l *chunkLayerImpl) streamCutPayloads(ctx context.Context, batch []uint64, head chunkHead, staging bool, read func(context.Context, uint64) (capturedChunk, error)) ([]capturedChunk, []string, error) { out := make([]capturedChunk, len(batch)) keys := make([]string, len(batch)) for i, idx := range batch { @@ -74,7 +77,7 @@ func (l *chunkLayerImpl) streamCutPayloads(ctx context.Context, batch []uint64, return fmt.Errorf("storage: capture upload: %w", errors.Join(errChunkRemoteUnavailable, errCutUpload, err)) } } - l.rememberPayload(c, head.Gen) + l.rememberPayload(c, head.Gen, staging) c.data = nil out[i] = c return nil @@ -86,7 +89,7 @@ func (l *chunkLayerImpl) streamCutPayloads(ctx context.Context, batch []uint64, } func (l *chunkLayerImpl) stagePayloadRound(ctx context.Context, batch []uint64, versions map[uint64]uint64, head chunkHead, st *chunkCutStats) (map[uint64]stagedChunk, []string, error) { - out, intents, err := l.streamCutPayloads(ctx, batch, head, func(ctx context.Context, idx uint64) (capturedChunk, error) { + out, intents, err := l.streamCutPayloads(ctx, batch, head, true, func(ctx context.Context, idx uint64) (capturedChunk, error) { data, err := l.readChunk(idx) if err != nil { return capturedChunk{}, err @@ -114,11 +117,16 @@ func (l *chunkLayerImpl) stagePayloadRound(ctx context.Context, batch []uint64, // until this version is superseded or a confirmed HEAD makes it reachable. // This cache belongs to one layer/owner lifetime. Generation equality is not // a reuse proof across reopen or takeover; those require content-hash matching. -func (l *chunkLayerImpl) rememberPayload(c capturedChunk, gen uint64) { +// A staged chunk is counted in Stats.StagedChunks here, when it is +// remembered, so an interrupted round counts what it finished. +func (l *chunkLayerImpl) rememberPayload(c capturedChunk, gen uint64, staged bool) { c.data = nil l.stMu.Lock() defer l.stMu.Unlock() + if staged { + l.stats.StagedChunks++ + } if l.reusable == nil { l.reusable = make(map[uint64]stagedChunk) } diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index dd74cd178c..02954e75e2 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -1629,9 +1629,6 @@ func (l *chunkLayerImpl) stage(ctx context.Context, st *chunkCutStats, spillCap staged[idx] = sc } st.StagedChunks += len(batch) - l.stMu.Lock() - l.stats.StagedChunks += uint64(len(batch)) - l.stMu.Unlock() if hook := l.testAfterStageHook; hook != nil { hook(round) } diff --git a/seaweed-block/core/storage/chunk_review271_test.go b/seaweed-block/core/storage/chunk_review271_test.go index c0b6b2515f..9ddeafd667 100644 --- a/seaweed-block/core/storage/chunk_review271_test.go +++ b/seaweed-block/core/storage/chunk_review271_test.go @@ -202,7 +202,7 @@ func TestCutPayloadReadsOverlapEarlierUploadsWithinBudget(t *testing.T) { t.Cleanup(func() { cancel(); free(); cowWaitSignal(t, done, "overlap cleanup") }) go func() { defer close(done) - _, _, err := l.streamCutPayloads(ctx, []uint64{0, 1, 2}, chunkHead{}, func(_ context.Context, idx uint64) (capturedChunk, error) { + _, _, err := l.streamCutPayloads(ctx, []uint64{0, 1, 2}, chunkHead{}, false, func(_ context.Context, idx uint64) (capturedChunk, error) { if idx == 2 { close(readThird) } @@ -233,7 +233,7 @@ func TestCutPayloadIntentCountLargeCandidateSets(t *testing.T) { for i := range batch { batch[i] = uint64(i) } - _, ids, err := l.streamCutPayloads(ctTimeout(t), batch, chunkHead{}, func(_ context.Context, idx uint64) (capturedChunk, error) { + _, ids, err := l.streamCutPayloads(ctTimeout(t), batch, chunkHead{}, false, func(_ context.Context, idx uint64) (capturedChunk, error) { data := makeBlock(ctBlockSize, byte(idx%255+1)) return capturedChunk{idx: idx, data: data, sum: sha256.Sum256(data)}, nil }) diff --git a/seaweed-block/core/storage/chunk_seam.go b/seaweed-block/core/storage/chunk_seam.go index e72a00a958..ae9344d73b 100644 --- a/seaweed-block/core/storage/chunk_seam.go +++ b/seaweed-block/core/storage/chunk_seam.go @@ -493,9 +493,13 @@ type chunkCutStats struct { // progress (it does not fall while a cut runs or across failed // attempts); the cut scheduler's threshold reads it. Chunks still // awaiting reconciliation are not counted. -// - StagedChunks counts the chunks every cut attempt of this layer -// staged, failed attempts included (in-process): the progress a cut -// retried after its deadline has made. +// - StagedChunks counts the chunks staging finished (read, hashed, +// uploaded when not zero, and remembered for reuse) in every cut +// attempt of this layer: a failed attempt and an interrupted round +// count what they finished. It only grows: a chunk staged again (after +// a guest write re-dirtied it, or in a later cut) counts again; it is +// in-process (a restart starts at 0). The progress a cut retried after +// its deadline has made. // - Reconciling: the dirty set is being reconciled against HEAD; no cut // publishes until it is done. ReconcileDone of ReconcileTotal chunks // are compared. diff --git a/seaweed-block/core/storage/chunk_stage_accounting_test.go b/seaweed-block/core/storage/chunk_stage_accounting_test.go index 1416056a42..dc8a284789 100644 --- a/seaweed-block/core/storage/chunk_stage_accounting_test.go +++ b/seaweed-block/core/storage/chunk_stage_accounting_test.go @@ -46,6 +46,7 @@ func TestChunkStage_PayloadTimeCountsStagingWithoutUploads(t *testing.T) { // The layer counts every chunk staged by any cut attempt, a failed one // included, so a first cut retried after its deadline shows the progress // its earlier attempts made; the last successful cut's stats do not move. +// An attempt that staged all 6 candidates counts exactly 6. func TestChunkStage_StagedChunksCountsFailedAttempts(t *testing.T) { _, l := zeroStagedLayer(t, 6) before := l.Stats() @@ -56,10 +57,48 @@ func TestChunkStage_StagedChunksCountsFailedAttempts(t *testing.T) { } l.testBeforeBarrierLockHook = nil after := l.Stats() - if after.StagedChunks <= before.StagedChunks { - t.Fatalf("staged chunks %d before, %d after a failed attempt that staged; want more", before.StagedChunks, after.StagedChunks) + if got := after.StagedChunks - before.StagedChunks; got != 6 { + t.Fatalf("a failed attempt that staged all 6 candidates counted %d", got) } if after.CutSeq != before.CutSeq || after.LastCut.StagedChunks != before.LastCut.StagedChunks { t.Fatal("a failed attempt changed the last successful cut") } + // A retry stages nothing again (the chunks are reused) and counts nothing. + if _, err := l.Cut(ctTimeout(t)); err != nil { + t.Fatal(err) + } + if got := l.Stats().StagedChunks - after.StagedChunks; got != 0 { + t.Fatalf("the retry counted %d staged chunks; want 0 (every chunk reused)", got) + } +} + +// A round that fails partway counts the chunks it finished, each remembered +// for reuse, and not the ones it did not: one upload worker stages the five +// zero chunks (the most recent writes go first), then the non-zero chunk's +// upload fails at its intent. +func TestChunkStage_StagedChunksCountsAnInterruptedRound(t *testing.T) { + s, f, l, w := precopyLayer(t, 1, 0) + l.cfg.COWSpillLimit = 2 * ctChunkBytes + l.cfg.UploadConcurrency = 1 + w.write(t, s, uint32(0*ctChunkBlocks+2), 0x5a) // oldest write: staged last + for c := 1; c <= 5; c++ { + w.write(t, s, uint32(c*ctChunkBlocks+2), 0) + } + f.mu.Lock() + f.failPutIntent = errors.New("intent refused") + f.mu.Unlock() + before := l.Stats().StagedChunks + l.stMu.Lock() + reusedBefore := len(l.reusable) + l.stMu.Unlock() + if _, err := l.Cut(ctTimeout(t)); err == nil { + t.Fatal("cut succeeded; want the staging round to fail at the intent") + } + l.stMu.Lock() + remembered := len(l.reusable) - reusedBefore + l.stMu.Unlock() + got := l.Stats().StagedChunks - before + if got != 5 || uint64(remembered) != got { + t.Fatalf("interrupted round counted %d staged chunks, remembered %d; want 5 and 5", got, remembered) + } } diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 73e2c3026c..e6252c26ab 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 -319 rows: 248 ACTIVE, 68 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 303 new. +320 rows: 249 ACTIVE, 68 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 303 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. @@ -820,6 +820,7 @@ Notes: | `INV-CUT-BIRTH-001` | A captured chunk birth is bounded by the same-barrier cut frontier: native capture uses min(conservative owned-map maximum, H), retaining lower inherited births. A dropped unacked suffix and reused LSN cannot emit BirthLSN > HEAD.RemoteLSN; the manifest validator still refuses future births. | M5 Quiesce -> Copy -> Manifest | `core/storage/chunk_birth.go` `captureBirths`; `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `TestChunkBirthDroppedSuffixPublishesWithRealManifest` (`core/storage/chunk_birth_manifest_test.go`), `TestChunkBirthCOWDoesNotObservePostBarrierWrite`, `TestChunkBirthBASEUsesInheritedFrontierIncludingZero` | Cut image at H; real recovery/manifest regression, not a new model claim | ACTIVE | | `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-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 | From dfe64e1658a36becc0581f6de79834b8b5da4a6f Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 23 Nov 2026 19:52:57 -0800 Subject: [PATCH 15/35] docs: state flat image references and shared-space retention Co-Authored-By: Codex --- seaweed-block/docs/design/agent-workspace-design.md | 2 +- seaweed-block/docs/design/invariants.md | 3 ++- seaweed-block/docs/operator-guide.md | 4 ++-- seaweed-block/docs/standalone-deployment.md | 12 +++++++++++- 4 files changed, 16 insertions(+), 5 deletions(-) diff --git a/seaweed-block/docs/design/agent-workspace-design.md b/seaweed-block/docs/design/agent-workspace-design.md index 6efab16f51..d6b38299c2 100644 --- a/seaweed-block/docs/design/agent-workspace-design.md +++ b/seaweed-block/docs/design/agent-workspace-design.md @@ -103,7 +103,7 @@ Per volume, under the chunk base directory in the filer (`core/frontend/chunksto - Each HEAD is logically full: restore never chains deltas. - A flat (format 1) HEAD is upgraded at its next cut ([chunk manifests](../chunk-manifests.md)). In a host-side proxy, the root of a 10 GiB volume shrank from 261,531 bytes (flat) to 2,172 bytes (two-level) (§13). -**How versions share data.** A HEAD, a snapshot and a fork root are each a complete map from chunk index to chunk key. There is no backing chain and no per-layer bitmap that falls through to a parent, as qcow2 backing files or overlay layers have. +**How versions share data.** A HEAD, a snapshot and a fork root are each a complete map from chunk index to chunk key. There is no backing chain and no per-layer bitmap that falls through to a parent, as qcow2 backing files or overlay layers have. This is `INV-HEAD-FLAT-001`: immutable segment indirection is part of one image map, not a parent-image chain. - A cut uploads a new key only for a chunk whose content changed (§5, step 6) and rewrites only the segments that list such chunks. Every other index keeps its key, and every other segment its object, from the previous HEAD. A snapshot copies the root; a fork writes a new root with the same references (§6). Neither copies a chunk or a segment. - So a chunk that was not rewritten after a snapshot is the same object in that snapshot, in every later snapshot and in HEAD. A chunk rewritten after the snapshot has an old key that only the snapshot (and any earlier version that shares it) still references. - A read looks up one map: the root, one segment, one chunk. It never walks a chain, and deleting a version never requires merging another one. diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index e6252c26ab..7134d244ac 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 -320 rows: 249 ACTIVE, 68 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 303 new. +321 rows: 250 ACTIVE, 68 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 306 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. @@ -887,6 +887,7 @@ Notes: | ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | |---|---|---|---|---|---|---| +| `INV-HEAD-FLAT-001` | Every HEAD and snapshot root is a complete image map, directly or through immutable segments. Forks preserve original object owners; reads never fall through to a parent HEAD or snapshot, so successive forks add no backing-chain depth. | M6 snapshot: published → fork | `core/frontend/chunkstore/catalog.go` `Fork`; `core/frontend/chunkstore/manifest.go` `qualifyManifestKey`, `resolveManifest` | `TestFork_ForkOfForkKeepsOriginalOwner` (`core/frontend/chunkstore/catalog_test.go`); `TestManifest_ForkAfterParentSnapshotDelete` (`core/frontend/chunkstore/manifest_test.go`) | —; existing representation, no new transition | ACTIVE | | `INV-CHUNK-WRITE-ONCE-001` | Chunk and segment keys are write-once: a key that exists or once existed is refused, and a volume writes only its own keys. | M6 key: Bound | `core/frontend/chunkstore/chunk_remote.go` `putObject` | `TestChunkRemote_KeysAreWriteOnce` (`core/frontend/chunkstore/chunk_remote_test.go`); `TestChunkLayer_C5_ChunksAreImmutable` (`core/storage/chunk_layer_contract_test.go`) | — | ACTIVE | | `INV-MAINT-ONE-OWNER` | Only the current attached handle with matching replica/epoch/endpoint admits maintenance; one attached volume admits at most one pass; elapsed ticks coalesce and never enqueue catch-up work. | M8 Armed → Running | `provider_chunk.go` `chunkMaintenanceLoop` | `TestMaintenanceCoalescesWhileOnePassIsHeld`, `TestMaintenancePassHasOneDeadline`, `TestMaintenanceRejectsForeignLineageBeforeAdmission`, `TestMaintenanceSameHandleRearmsAfterJoinedStop` | `MaintenanceOwner` `OneOwner`, `CurrentHandleAtAdmission` | ACTIVE | | `INV-MAINT-SCOPE` | Per-volume GC traces foreign roots while restricting candidate reclamation, intent expiry and copy settlement to its volume; namespace coverage is not imported. | M8 scoped GC | `gc.go` `Collector.run`; `gc_copy.go` `SweepCopies`; `gc_execution.go` `ExecuteVolumeGC` | `TestVolumeGC_ForeignIntentRootsAndLocalCandidates`, `TestVolumeGC_DoesNotImportGlobalMark`, `TestVolumeGC_ForeignEligibleCaptureIntentStaysProtected`, `TestVolumeGC_ForeignEligibleCopyIsNotSettled` | `ScopedMaintenanceGC` `ForeignRootSurvives`, `ForeignCandidatesUntouched`, `OwnCoverageOnly` | ACTIVE | diff --git a/seaweed-block/docs/operator-guide.md b/seaweed-block/docs/operator-guide.md index 8adf89485c..98e32a3f93 100644 --- a/seaweed-block/docs/operator-guide.md +++ b/seaweed-block/docs/operator-guide.md @@ -135,10 +135,10 @@ default) can expire the host's slots; keep host clocks synchronized. - scheduled and manual snapshots; - deleting snapshots, and getting space back: - GC deletes the chunks after the grace (`--grace`, 1 hour by default), so a deleted snapshot's space is - reclaimed about 2 hours after the delete; + reclaimed about 2 hours after the delete unless still referenced by a snapshot, fork or restore; - then the asynchronous SeaweedFS vacuum compacts the volume files; - `ops chunk verify`; -- restoring a snapshot into a new, independent volume. +- forking a snapshot into a new volume that shares immutable objects, or restoring it into a new, independent volume. A snapshot can be refused with `host_slot_busy` / `no background slot` (retryable) while every host slot is held by other volumes' cuts; retry with the same request id. With many volumes on a host, a snapshot may wait for a slot: diff --git a/seaweed-block/docs/standalone-deployment.md b/seaweed-block/docs/standalone-deployment.md index a1a08f1e57..b7a0112f80 100644 --- a/seaweed-block/docs/standalone-deployment.md +++ b/seaweed-block/docs/standalone-deployment.md @@ -506,7 +506,7 @@ Space comes back in two steps. Neither is immediate. 1. **GC deletes the chunks**, after the grace. The grace is `sw-block ops chunk gc --grace`, **1 hour by default**. - A deleted snapshot keeps its chunks rooted for the grace after the delete. - A chunk is then reclaimed only once two complete GC marks, at least the grace apart, have both seen it unreferenced. - - With the default grace, a deleted snapshot's chunks are reclaimed about **2 hours** after the delete. That needs a GC pass at least 1 hour after the delete and another at least 1 hour after that. + - With the default grace, a deleted snapshot's unreferenced chunks are reclaimed about **2 hours** after the delete. Chunks still referenced by another snapshot, fork or restore remain live. That needs a GC pass at least 1 hour after the delete and another at least 1 hour after that. - Automatic GC is off by default (`--chunk-maintenance-gc`), so run the passes yourself: ```bash @@ -564,6 +564,16 @@ therefore see every chunk of every volume and snapshot as unreferenced. - Space is returned only by the two steps above (`sw-block ops chunk gc`, then a SeaweedFS vacuum). `volume.vacuum` is safe: it compacts needles that were already deleted. +### Forking a snapshot into a new volume + +A fork creates a new volume sharing the snapshot's immutable chunks and segments: + +```bash +sw-block ops chunk fork --source v1 --snapshot before-upgrade --target v2 --chunk-filer FILER --request-id fork-v2 +``` + +Keep the request id to retry an uncertain result. The new HEAD contains a complete image map; reads do not walk back through parent volumes or snapshots. A fork of a fork preserves the original object owners without adding a backing chain. Deleting the source snapshot does not delete objects still referenced by the fork. Use restore when the target must eventually own its data independently. + ### Restoring a snapshot into a new volume A restore makes a new, independent volume from a snapshot. The source volume and its snapshot can be deleted afterwards. From 6a4420983c8b8208815fa403c0ca3792e91e62f5 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 23 Nov 2026 19:59:06 -0800 Subject: [PATCH 16/35] test: prove flat grandchild reads and template source retirement Co-Authored-By: Codex --- .../template_retirement_integration_test.go | 61 +++++++++++++++ .../frontend/chunkstore/flat_head_test.go | 78 +++++++++++++++++++ seaweed-block/docs/design/invariants.md | 2 +- seaweed-block/docs/standalone-deployment.md | 38 +++++++++ 4 files changed, 178 insertions(+), 1 deletion(-) create mode 100644 seaweed-block/cmd/blockvolume/template_retirement_integration_test.go create mode 100644 seaweed-block/core/frontend/chunkstore/flat_head_test.go diff --git a/seaweed-block/cmd/blockvolume/template_retirement_integration_test.go b/seaweed-block/cmd/blockvolume/template_retirement_integration_test.go new file mode 100644 index 0000000000..5c86ba1be0 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/template_retirement_integration_test.go @@ -0,0 +1,61 @@ +//go:build subprocess && chunkstore_integration + +package main_test + +import ( + "testing" + "time" +) + +// TestProcedureRetireTemplateSource runs the template-holder procedure: +// fork the seed, publish the template on the holder, fork a consumer, then +// seal/revoke/ACK and delete the original source. No GC grace is advanced; +// the final ordinary pass proves its command and reads, not reclamation. +func TestProcedureRetireTemplateSource(t *testing.T) { + env := startHandoffEnvWith(t, 1, []string{"template-holder", "consumer"}) + env.volExtra = []string{"--chunk-capture-interval", "0", "--chunk-snapshot-schedule", "off"} + source := env.start(t, "blockvolume-source", "s1") + e := env.adopt(t, source, "s1") + const template = "template-holder" + want := map[uint64][]byte{5: pattern("template-seed!!")} + env.writeBlock(t, "s1", 5, want[5]) + env.snapshot(t, "s1", "v1", "seed") + for _, step := range []struct{ source, snapshot, target string }{ + {"v1", "seed", template}, {template, "template-v1", "consumer"}, + } { + env.h.command(t, "ops", "chunk", "fork", "--source", step.source, "--snapshot", step.snapshot, + "--target", step.target, "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath, + "--request-id", "fork-"+step.target) + env.startTarget(t, step.target, "blockvolume-"+step.target) + env.requireBlocks(t, "n-"+step.target, 0, 16, want) + env.requireEdges(t, "n-"+step.target) + if step.target == template { + env.snapshot(t, "n-"+template, template, "template-v1") + } + } + g := env.seal(t, "s1", e) + env.revoke(t, e, g) + // The process must ACK and exit naturally; a signal would skip the ACK. + if err := source.wait(30 * time.Second); err != nil { + t.Fatalf("source did not exit naturally after revocation: %v", err) + } + env.waitAck(t, e, g) + env.deleteSnapshot(t, "v1", "seed") + out, stderr, code := env.volumeDelete(t, "delete-template-source") + requireDeleteCompleted(t, out, stderr, code, false) + env.requireDeletedForGood(t, "delete-template-source") + check := func() { + for _, vol := range []string{template, "consumer"} { + env.h.command(t, "ops", "chunk", "verify", "--volume", vol, "--all-snapshots", "--depth", "data", + "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath) + env.requireBlocks(t, "n-"+vol, 0, 16, want) + env.requireEdges(t, "n-"+vol) + } + env.requireSnapshotNames(t, template, "template-v1") + } + check() + env.h.command(t, "ops", "chunk", "gc", "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath, + "--master", env.h.masterAddr, "--apply") + check() + t.Logf("template source retired; %s/template-v1 and consumer read unchanged after a default-grace GC pass", template) +} diff --git a/seaweed-block/core/frontend/chunkstore/flat_head_test.go b/seaweed-block/core/frontend/chunkstore/flat_head_test.go new file mode 100644 index 0000000000..b83d032c70 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/flat_head_test.go @@ -0,0 +1,78 @@ +package chunkstore + +import ( + "bytes" + "context" + "path" + "testing" +) + +func TestForkGrandchildReadsEveryBlockWithoutAncestorImages(t *testing.T) { + f, b, c, source := catalogFixture(t) + ctx := context.Background() + if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "seed", RequestID: "seed"}, source); err != nil { + t.Fatal(err) + } + if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "seed", Target: "v2", RequestID: "parent"}); err != nil { + t.Fatal(err) + } + parent, err := NewChunkRemote(f, b, catBase+"/v2") + if err != nil { + t.Fatal(err) + } + ph, err := parent.GetHead(ctx) + if err != nil { + t.Fatal(err) + } + if _, err := c.CreateSnapshot(ctx, "v2", SnapshotRequest{Name: "template", RequestID: "template"}, ph); err != nil { + t.Fatal(err) + } + if _, err := c.Fork(ctx, ForkRequest{Source: "v2", Snapshot: "template", Target: "v3", RequestID: "grandchild"}); err != nil { + t.Fatal(err) + } + // Remove only ancestor image metadata, preserving immutable object bindings. + for vol, name := range map[string]string{"v1": "seed", "v2": "template"} { + attempt := snapPath(t, f, vol, name) + for _, entry := range []string{attempt, path.Join(catBase, vol, snapNamesDir, name), path.Join(catBase, vol, headName)} { + if err := f.DeleteEntry(ctx, path.Dir(entry), path.Base(entry), nil); err != nil { + t.Fatal(err) + } + if _, err := f.LookupEntry(ctx, path.Dir(entry), path.Base(entry)); err == nil { + t.Fatalf("ancestor image metadata remains: %s", entry) + } + } + } + // Open a fresh reader: no cached parent HEAD or snapshot can supply data. + grandchild, err := NewChunkRemote(f, b, catBase+"/v3") + if err != nil { + t.Fatal(err) + } + h, err := grandchild.GetHead(ctx) + if err != nil { + t.Fatal(err) + } + if len(h.Chunks) != 2 { + t.Fatalf("grandchild lost its complete image: %d chunks", len(h.Chunks)) + } + for block := uint64(0); block < uint64(catGeo.NumBlocks); block++ { + got := make([]byte, catGeo.BlockSize) + if ref, ok := h.Chunks[block/uint64(catGeo.ChunkBlocks)]; ok { + data, err := grandchild.Get(ctx, ref.Key) + if err != nil { + t.Fatalf("block %d: %v", block, err) + } + off := (block % uint64(catGeo.ChunkBlocks)) * uint64(catGeo.BlockSize) + copy(got, data[off:off+uint64(catGeo.BlockSize)]) + } + var fill byte + switch block / uint64(catGeo.ChunkBlocks) { + case 0: + fill = 0x10 + case 3: + fill = 0x13 + } + if !bytes.Equal(got, bytes.Repeat([]byte{fill}, int(catGeo.BlockSize))) { + t.Fatalf("block %d differs after ancestor images were removed", block) + } + } +} diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 7134d244ac..b0d3c0580f 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -887,7 +887,7 @@ Notes: | ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | |---|---|---|---|---|---|---| -| `INV-HEAD-FLAT-001` | Every HEAD and snapshot root is a complete image map, directly or through immutable segments. Forks preserve original object owners; reads never fall through to a parent HEAD or snapshot, so successive forks add no backing-chain depth. | M6 snapshot: published → fork | `core/frontend/chunkstore/catalog.go` `Fork`; `core/frontend/chunkstore/manifest.go` `qualifyManifestKey`, `resolveManifest` | `TestFork_ForkOfForkKeepsOriginalOwner` (`core/frontend/chunkstore/catalog_test.go`); `TestManifest_ForkAfterParentSnapshotDelete` (`core/frontend/chunkstore/manifest_test.go`) | —; existing representation, no new transition | ACTIVE | +| `INV-HEAD-FLAT-001` | Every HEAD and snapshot root is a complete image map, directly or through immutable segments. Forks preserve original object owners; reads never fall through to a parent HEAD or snapshot, so successive forks add no backing-chain depth. | M6 snapshot: published → fork | `core/frontend/chunkstore/catalog.go` `Fork`; `core/frontend/chunkstore/manifest.go` `qualifyManifestKey`, `resolveManifest` | `TestForkGrandchildReadsEveryBlockWithoutAncestorImages` (`core/frontend/chunkstore/flat_head_test.go`); `TestFork_ForkOfForkKeepsOriginalOwner` (`core/frontend/chunkstore/catalog_test.go`); `TestManifest_ForkAfterParentSnapshotDelete` (`core/frontend/chunkstore/manifest_test.go`) | —; existing representation, no new transition | ACTIVE | | `INV-CHUNK-WRITE-ONCE-001` | Chunk and segment keys are write-once: a key that exists or once existed is refused, and a volume writes only its own keys. | M6 key: Bound | `core/frontend/chunkstore/chunk_remote.go` `putObject` | `TestChunkRemote_KeysAreWriteOnce` (`core/frontend/chunkstore/chunk_remote_test.go`); `TestChunkLayer_C5_ChunksAreImmutable` (`core/storage/chunk_layer_contract_test.go`) | — | ACTIVE | | `INV-MAINT-ONE-OWNER` | Only the current attached handle with matching replica/epoch/endpoint admits maintenance; one attached volume admits at most one pass; elapsed ticks coalesce and never enqueue catch-up work. | M8 Armed → Running | `provider_chunk.go` `chunkMaintenanceLoop` | `TestMaintenanceCoalescesWhileOnePassIsHeld`, `TestMaintenancePassHasOneDeadline`, `TestMaintenanceRejectsForeignLineageBeforeAdmission`, `TestMaintenanceSameHandleRearmsAfterJoinedStop` | `MaintenanceOwner` `OneOwner`, `CurrentHandleAtAdmission` | ACTIVE | | `INV-MAINT-SCOPE` | Per-volume GC traces foreign roots while restricting candidate reclamation, intent expiry and copy settlement to its volume; namespace coverage is not imported. | M8 scoped GC | `gc.go` `Collector.run`; `gc_copy.go` `SweepCopies`; `gc_execution.go` `ExecuteVolumeGC` | `TestVolumeGC_ForeignIntentRootsAndLocalCandidates`, `TestVolumeGC_DoesNotImportGlobalMark`, `TestVolumeGC_ForeignEligibleCaptureIntentStaysProtected`, `TestVolumeGC_ForeignEligibleCopyIsNotSettled` | `ScopedMaintenanceGC` `ForeignRootSurvives`, `ForeignCandidatesUntouched`, `OwnCoverageOnly` | ACTIVE | diff --git a/seaweed-block/docs/standalone-deployment.md b/seaweed-block/docs/standalone-deployment.md index b7a0112f80..06e0c37ef5 100644 --- a/seaweed-block/docs/standalone-deployment.md +++ b/seaweed-block/docs/standalone-deployment.md @@ -574,6 +574,44 @@ sw-block ops chunk fork --source v1 --snapshot before-upgrade --target v2 --chun Keep the request id to retry an uncertain result. The new HEAD contains a complete image map; reads do not walk back through parent volumes or snapshots. A fork of a fork preserves the original object owners without adding a backing chain. Deleting the source snapshot does not delete objects still referenced by the fork. Use restore when the target must eventually own its data independently. +### Retiring the source of a template + +A template is an ordinary immutable snapshot, not a separate volume kind. Keep the volume holding an offered template snapshot: volume deletion refuses while any snapshot name exists. To retire the original source instead, first move the template image into a dedicated holder using existing fork and snapshot operations. + +Prerequisites: `v1` is serving, its only snapshot is `seed`, and the standalone cluster spec has new volume placements for `template-holder` and `consumer`. Neither target blockvolume has started yet. Use the same filer and chunk namespace throughout. + +1. Create the holder: + + ```bash + sw-block ops chunk fork --source v1 --snapshot seed --target template-holder --chunk-filer FILER --request-id fork-template-holder + ``` + +2. Start `template-holder` with the normal standalone blockvolume command and its own volume id, endpoints and local root. Wait for its frontend readiness; read back the seed's known data before proceeding. Take the template snapshot: + + ```bash + sw-block ops chunk snapshot --volume template-holder --status-addr HOLDER_STATUS --name template-v1 + ``` + +3. Create a consumer, start its blockvolume on its own placement and root, and verify its known data: + + ```bash + sw-block ops chunk fork --source template-holder --snapshot template-v1 --target consumer --chunk-filer FILER --request-id fork-consumer + ``` + +4. Stop the source writer. Follow [Delete a volume](volume-lifecycle.md#delete-a-volume) for `v1`: plain detach, revoke its exact replica/epoch/sealed generation, wait for its recorded ACK and natural exit, delete `seed`, then delete `v1`. Do not signal the process in place of waiting for its ACK. Require the completed delete answer and `show` state `deleted` before continuing. + +5. Verify both surviving images, including the holder's template snapshot: + + ```bash + sw-block ops chunk verify --volume template-holder --all-snapshots --depth data --chunk-filer FILER + sw-block ops chunk verify --volume consumer --all-snapshots --depth data --chunk-filer FILER + sw-block ops chunk gc --chunk-filer FILER --master MASTER --apply + ``` + + Read back the known data again and repeat both verify commands after the pass. This immediate pass is not a reclamation measurement: its default grace has not elapsed. Continue namespace-wide GC as described above for unused objects; attached-volume maintenance alone does not collect a deleted source's namespace. + +Keep `template-holder/template-v1` while it is offered for new consumers. Retiring that snapshot later does not delete objects still referenced by existing consumers. Deleting the holder volume itself still requires the ordinary seal/revoke/ACK and snapshot-deletion procedure; do not remove its backing filer directory or object bindings by hand. + ### Restoring a snapshot into a new volume A restore makes a new, independent volume from a snapshot. The source volume and its snapshot can be deleted afterwards. From a7bac0b2ae2a1c7eb3ac1ddec6b72d0b0c8c9c06 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 23 Nov 2026 19:59:19 -0800 Subject: [PATCH 17/35] test: use an exact block pattern in the retirement procedure Co-Authored-By: Codex --- .../cmd/blockvolume/template_retirement_integration_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/seaweed-block/cmd/blockvolume/template_retirement_integration_test.go b/seaweed-block/cmd/blockvolume/template_retirement_integration_test.go index 5c86ba1be0..9d19893679 100644 --- a/seaweed-block/cmd/blockvolume/template_retirement_integration_test.go +++ b/seaweed-block/cmd/blockvolume/template_retirement_integration_test.go @@ -17,7 +17,7 @@ func TestProcedureRetireTemplateSource(t *testing.T) { source := env.start(t, "blockvolume-source", "s1") e := env.adopt(t, source, "s1") const template = "template-holder" - want := map[uint64][]byte{5: pattern("template-seed!!")} + want := map[uint64][]byte{5: pattern("template-seed!!!")} env.writeBlock(t, "s1", 5, want[5]) env.snapshot(t, "s1", "v1", "seed") for _, step := range []struct{ source, snapshot, target string }{ From 7ea9b7ab02289b00186ca96ca20a6d9ebfad4edf Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 23 Nov 2026 20:01:10 -0800 Subject: [PATCH 18/35] test: bound template verification in the procedure and guide Co-Authored-By: Codex --- .../cmd/blockvolume/template_retirement_integration_test.go | 2 +- seaweed-block/docs/standalone-deployment.md | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/template_retirement_integration_test.go b/seaweed-block/cmd/blockvolume/template_retirement_integration_test.go index 9d19893679..c4da02ffb6 100644 --- a/seaweed-block/cmd/blockvolume/template_retirement_integration_test.go +++ b/seaweed-block/cmd/blockvolume/template_retirement_integration_test.go @@ -46,7 +46,7 @@ func TestProcedureRetireTemplateSource(t *testing.T) { env.requireDeletedForGood(t, "delete-template-source") check := func() { for _, vol := range []string{template, "consumer"} { - env.h.command(t, "ops", "chunk", "verify", "--volume", vol, "--all-snapshots", "--depth", "data", + env.h.command(t, "ops", "chunk", "verify", "--volume", vol, "--all-snapshots", "--depth", "data", "--timeout", "2m", "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath) env.requireBlocks(t, "n-"+vol, 0, 16, want) env.requireEdges(t, "n-"+vol) diff --git a/seaweed-block/docs/standalone-deployment.md b/seaweed-block/docs/standalone-deployment.md index 06e0c37ef5..c04d06e2e4 100644 --- a/seaweed-block/docs/standalone-deployment.md +++ b/seaweed-block/docs/standalone-deployment.md @@ -603,8 +603,8 @@ Prerequisites: `v1` is serving, its only snapshot is `seed`, and the standalone 5. Verify both surviving images, including the holder's template snapshot: ```bash - sw-block ops chunk verify --volume template-holder --all-snapshots --depth data --chunk-filer FILER - sw-block ops chunk verify --volume consumer --all-snapshots --depth data --chunk-filer FILER + sw-block ops chunk verify --volume template-holder --all-snapshots --depth data --timeout 2m --chunk-filer FILER + sw-block ops chunk verify --volume consumer --all-snapshots --depth data --timeout 2m --chunk-filer FILER sw-block ops chunk gc --chunk-filer FILER --master MASTER --apply ``` From ca7819fab23d89219bf8896d6f7dc59ca637ab12 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 23 Nov 2026 20:04:58 -0800 Subject: [PATCH 19/35] docs: separate the template retirement procedure for review Co-Authored-By: Codex --- .../template_retirement_integration_test.go | 61 ------------------- seaweed-block/docs/standalone-deployment.md | 38 ------------ 2 files changed, 99 deletions(-) delete mode 100644 seaweed-block/cmd/blockvolume/template_retirement_integration_test.go diff --git a/seaweed-block/cmd/blockvolume/template_retirement_integration_test.go b/seaweed-block/cmd/blockvolume/template_retirement_integration_test.go deleted file mode 100644 index c4da02ffb6..0000000000 --- a/seaweed-block/cmd/blockvolume/template_retirement_integration_test.go +++ /dev/null @@ -1,61 +0,0 @@ -//go:build subprocess && chunkstore_integration - -package main_test - -import ( - "testing" - "time" -) - -// TestProcedureRetireTemplateSource runs the template-holder procedure: -// fork the seed, publish the template on the holder, fork a consumer, then -// seal/revoke/ACK and delete the original source. No GC grace is advanced; -// the final ordinary pass proves its command and reads, not reclamation. -func TestProcedureRetireTemplateSource(t *testing.T) { - env := startHandoffEnvWith(t, 1, []string{"template-holder", "consumer"}) - env.volExtra = []string{"--chunk-capture-interval", "0", "--chunk-snapshot-schedule", "off"} - source := env.start(t, "blockvolume-source", "s1") - e := env.adopt(t, source, "s1") - const template = "template-holder" - want := map[uint64][]byte{5: pattern("template-seed!!!")} - env.writeBlock(t, "s1", 5, want[5]) - env.snapshot(t, "s1", "v1", "seed") - for _, step := range []struct{ source, snapshot, target string }{ - {"v1", "seed", template}, {template, "template-v1", "consumer"}, - } { - env.h.command(t, "ops", "chunk", "fork", "--source", step.source, "--snapshot", step.snapshot, - "--target", step.target, "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath, - "--request-id", "fork-"+step.target) - env.startTarget(t, step.target, "blockvolume-"+step.target) - env.requireBlocks(t, "n-"+step.target, 0, 16, want) - env.requireEdges(t, "n-"+step.target) - if step.target == template { - env.snapshot(t, "n-"+template, template, "template-v1") - } - } - g := env.seal(t, "s1", e) - env.revoke(t, e, g) - // The process must ACK and exit naturally; a signal would skip the ACK. - if err := source.wait(30 * time.Second); err != nil { - t.Fatalf("source did not exit naturally after revocation: %v", err) - } - env.waitAck(t, e, g) - env.deleteSnapshot(t, "v1", "seed") - out, stderr, code := env.volumeDelete(t, "delete-template-source") - requireDeleteCompleted(t, out, stderr, code, false) - env.requireDeletedForGood(t, "delete-template-source") - check := func() { - for _, vol := range []string{template, "consumer"} { - env.h.command(t, "ops", "chunk", "verify", "--volume", vol, "--all-snapshots", "--depth", "data", "--timeout", "2m", - "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath) - env.requireBlocks(t, "n-"+vol, 0, 16, want) - env.requireEdges(t, "n-"+vol) - } - env.requireSnapshotNames(t, template, "template-v1") - } - check() - env.h.command(t, "ops", "chunk", "gc", "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath, - "--master", env.h.masterAddr, "--apply") - check() - t.Logf("template source retired; %s/template-v1 and consumer read unchanged after a default-grace GC pass", template) -} diff --git a/seaweed-block/docs/standalone-deployment.md b/seaweed-block/docs/standalone-deployment.md index c04d06e2e4..b7a0112f80 100644 --- a/seaweed-block/docs/standalone-deployment.md +++ b/seaweed-block/docs/standalone-deployment.md @@ -574,44 +574,6 @@ sw-block ops chunk fork --source v1 --snapshot before-upgrade --target v2 --chun Keep the request id to retry an uncertain result. The new HEAD contains a complete image map; reads do not walk back through parent volumes or snapshots. A fork of a fork preserves the original object owners without adding a backing chain. Deleting the source snapshot does not delete objects still referenced by the fork. Use restore when the target must eventually own its data independently. -### Retiring the source of a template - -A template is an ordinary immutable snapshot, not a separate volume kind. Keep the volume holding an offered template snapshot: volume deletion refuses while any snapshot name exists. To retire the original source instead, first move the template image into a dedicated holder using existing fork and snapshot operations. - -Prerequisites: `v1` is serving, its only snapshot is `seed`, and the standalone cluster spec has new volume placements for `template-holder` and `consumer`. Neither target blockvolume has started yet. Use the same filer and chunk namespace throughout. - -1. Create the holder: - - ```bash - sw-block ops chunk fork --source v1 --snapshot seed --target template-holder --chunk-filer FILER --request-id fork-template-holder - ``` - -2. Start `template-holder` with the normal standalone blockvolume command and its own volume id, endpoints and local root. Wait for its frontend readiness; read back the seed's known data before proceeding. Take the template snapshot: - - ```bash - sw-block ops chunk snapshot --volume template-holder --status-addr HOLDER_STATUS --name template-v1 - ``` - -3. Create a consumer, start its blockvolume on its own placement and root, and verify its known data: - - ```bash - sw-block ops chunk fork --source template-holder --snapshot template-v1 --target consumer --chunk-filer FILER --request-id fork-consumer - ``` - -4. Stop the source writer. Follow [Delete a volume](volume-lifecycle.md#delete-a-volume) for `v1`: plain detach, revoke its exact replica/epoch/sealed generation, wait for its recorded ACK and natural exit, delete `seed`, then delete `v1`. Do not signal the process in place of waiting for its ACK. Require the completed delete answer and `show` state `deleted` before continuing. - -5. Verify both surviving images, including the holder's template snapshot: - - ```bash - sw-block ops chunk verify --volume template-holder --all-snapshots --depth data --timeout 2m --chunk-filer FILER - sw-block ops chunk verify --volume consumer --all-snapshots --depth data --timeout 2m --chunk-filer FILER - sw-block ops chunk gc --chunk-filer FILER --master MASTER --apply - ``` - - Read back the known data again and repeat both verify commands after the pass. This immediate pass is not a reclamation measurement: its default grace has not elapsed. Continue namespace-wide GC as described above for unused objects; attached-volume maintenance alone does not collect a deleted source's namespace. - -Keep `template-holder/template-v1` while it is offered for new consumers. Retiring that snapshot later does not delete objects still referenced by existing consumers. Deleting the holder volume itself still requires the ordinary seal/revoke/ACK and snapshot-deletion procedure; do not remove its backing filer directory or object bindings by hand. - ### Restoring a snapshot into a new volume A restore makes a new, independent volume from a snapshot. The source volume and its snapshot can be deleted afterwards. From b10708fa8eabf9642b5375d9db74a8d3f37e4461 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 23 Nov 2026 20:05:32 -0800 Subject: [PATCH 20/35] docs: qualify the template source retirement procedure Co-Authored-By: Codex --- .../template_retirement_integration_test.go | 61 +++++++++++++++++++ seaweed-block/docs/standalone-deployment.md | 38 ++++++++++++ 2 files changed, 99 insertions(+) create mode 100644 seaweed-block/cmd/blockvolume/template_retirement_integration_test.go diff --git a/seaweed-block/cmd/blockvolume/template_retirement_integration_test.go b/seaweed-block/cmd/blockvolume/template_retirement_integration_test.go new file mode 100644 index 0000000000..c4da02ffb6 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/template_retirement_integration_test.go @@ -0,0 +1,61 @@ +//go:build subprocess && chunkstore_integration + +package main_test + +import ( + "testing" + "time" +) + +// TestProcedureRetireTemplateSource runs the template-holder procedure: +// fork the seed, publish the template on the holder, fork a consumer, then +// seal/revoke/ACK and delete the original source. No GC grace is advanced; +// the final ordinary pass proves its command and reads, not reclamation. +func TestProcedureRetireTemplateSource(t *testing.T) { + env := startHandoffEnvWith(t, 1, []string{"template-holder", "consumer"}) + env.volExtra = []string{"--chunk-capture-interval", "0", "--chunk-snapshot-schedule", "off"} + source := env.start(t, "blockvolume-source", "s1") + e := env.adopt(t, source, "s1") + const template = "template-holder" + want := map[uint64][]byte{5: pattern("template-seed!!!")} + env.writeBlock(t, "s1", 5, want[5]) + env.snapshot(t, "s1", "v1", "seed") + for _, step := range []struct{ source, snapshot, target string }{ + {"v1", "seed", template}, {template, "template-v1", "consumer"}, + } { + env.h.command(t, "ops", "chunk", "fork", "--source", step.source, "--snapshot", step.snapshot, + "--target", step.target, "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath, + "--request-id", "fork-"+step.target) + env.startTarget(t, step.target, "blockvolume-"+step.target) + env.requireBlocks(t, "n-"+step.target, 0, 16, want) + env.requireEdges(t, "n-"+step.target) + if step.target == template { + env.snapshot(t, "n-"+template, template, "template-v1") + } + } + g := env.seal(t, "s1", e) + env.revoke(t, e, g) + // The process must ACK and exit naturally; a signal would skip the ACK. + if err := source.wait(30 * time.Second); err != nil { + t.Fatalf("source did not exit naturally after revocation: %v", err) + } + env.waitAck(t, e, g) + env.deleteSnapshot(t, "v1", "seed") + out, stderr, code := env.volumeDelete(t, "delete-template-source") + requireDeleteCompleted(t, out, stderr, code, false) + env.requireDeletedForGood(t, "delete-template-source") + check := func() { + for _, vol := range []string{template, "consumer"} { + env.h.command(t, "ops", "chunk", "verify", "--volume", vol, "--all-snapshots", "--depth", "data", "--timeout", "2m", + "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath) + env.requireBlocks(t, "n-"+vol, 0, 16, want) + env.requireEdges(t, "n-"+vol) + } + env.requireSnapshotNames(t, template, "template-v1") + } + check() + env.h.command(t, "ops", "chunk", "gc", "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath, + "--master", env.h.masterAddr, "--apply") + check() + t.Logf("template source retired; %s/template-v1 and consumer read unchanged after a default-grace GC pass", template) +} diff --git a/seaweed-block/docs/standalone-deployment.md b/seaweed-block/docs/standalone-deployment.md index b7a0112f80..c04d06e2e4 100644 --- a/seaweed-block/docs/standalone-deployment.md +++ b/seaweed-block/docs/standalone-deployment.md @@ -574,6 +574,44 @@ sw-block ops chunk fork --source v1 --snapshot before-upgrade --target v2 --chun Keep the request id to retry an uncertain result. The new HEAD contains a complete image map; reads do not walk back through parent volumes or snapshots. A fork of a fork preserves the original object owners without adding a backing chain. Deleting the source snapshot does not delete objects still referenced by the fork. Use restore when the target must eventually own its data independently. +### Retiring the source of a template + +A template is an ordinary immutable snapshot, not a separate volume kind. Keep the volume holding an offered template snapshot: volume deletion refuses while any snapshot name exists. To retire the original source instead, first move the template image into a dedicated holder using existing fork and snapshot operations. + +Prerequisites: `v1` is serving, its only snapshot is `seed`, and the standalone cluster spec has new volume placements for `template-holder` and `consumer`. Neither target blockvolume has started yet. Use the same filer and chunk namespace throughout. + +1. Create the holder: + + ```bash + sw-block ops chunk fork --source v1 --snapshot seed --target template-holder --chunk-filer FILER --request-id fork-template-holder + ``` + +2. Start `template-holder` with the normal standalone blockvolume command and its own volume id, endpoints and local root. Wait for its frontend readiness; read back the seed's known data before proceeding. Take the template snapshot: + + ```bash + sw-block ops chunk snapshot --volume template-holder --status-addr HOLDER_STATUS --name template-v1 + ``` + +3. Create a consumer, start its blockvolume on its own placement and root, and verify its known data: + + ```bash + sw-block ops chunk fork --source template-holder --snapshot template-v1 --target consumer --chunk-filer FILER --request-id fork-consumer + ``` + +4. Stop the source writer. Follow [Delete a volume](volume-lifecycle.md#delete-a-volume) for `v1`: plain detach, revoke its exact replica/epoch/sealed generation, wait for its recorded ACK and natural exit, delete `seed`, then delete `v1`. Do not signal the process in place of waiting for its ACK. Require the completed delete answer and `show` state `deleted` before continuing. + +5. Verify both surviving images, including the holder's template snapshot: + + ```bash + sw-block ops chunk verify --volume template-holder --all-snapshots --depth data --timeout 2m --chunk-filer FILER + sw-block ops chunk verify --volume consumer --all-snapshots --depth data --timeout 2m --chunk-filer FILER + sw-block ops chunk gc --chunk-filer FILER --master MASTER --apply + ``` + + Read back the known data again and repeat both verify commands after the pass. This immediate pass is not a reclamation measurement: its default grace has not elapsed. Continue namespace-wide GC as described above for unused objects; attached-volume maintenance alone does not collect a deleted source's namespace. + +Keep `template-holder/template-v1` while it is offered for new consumers. Retiring that snapshot later does not delete objects still referenced by existing consumers. Deleting the holder volume itself still requires the ordinary seal/revoke/ACK and snapshot-deletion procedure; do not remove its backing filer directory or object bindings by hand. + ### Restoring a snapshot into a new volume A restore makes a new, independent volume from a snapshot. The source volume and its snapshot can be deleted afterwards. From de0dfd057523a6cd62bd75ade5608c92504d8884 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 23 Nov 2026 18:39:31 -0800 Subject: [PATCH 21/35] test: red test for a crash keeping an extent write whose WAL record was not synced The flusher writes a dirty block's extent before its WAL record is synced (below the WAL pressure threshold it does not sync first). The test runs the real flusher, cuts the power at its fsync (the extent page it wrote kept, the unsynced WAL record lost, no checkpoint), recovers and re-attaches: the block reads the lost write's bytes locally while HEAD holds the chunk without them, and the chunk is not a cut candidate, so nothing reconciles local and published. Fails on main. Co-Authored-By: Claude Opus 5.5 --- .../core/storage/chunk_u1_reorder_test.go | 113 ++++++++++++++++++ 1 file changed, 113 insertions(+) create mode 100644 seaweed-block/core/storage/chunk_u1_reorder_test.go diff --git a/seaweed-block/core/storage/chunk_u1_reorder_test.go b/seaweed-block/core/storage/chunk_u1_reorder_test.go new file mode 100644 index 0000000000..c7ecc20027 --- /dev/null +++ b/seaweed-block/core/storage/chunk_u1_reorder_test.go @@ -0,0 +1,113 @@ +package storage + +import ( + "bytes" + "context" + "errors" + "os" + "testing" +) + +// The flusher writes a dirty block's extent before the WAL record behind it +// is synced (below the WAL pressure threshold it does not sync first), and +// page writeback has no order across offsets of one file. A crash can then +// keep the extent bytes of a write whose WAL record is lost (an unacked +// write). After recovery the chunk's map entry has not moved, so the chunk +// is not a cut candidate: local reads return the lost write's bytes while +// the published HEAD holds the chunk without them, and no cut compares the +// two. Local and published must agree for every block of a chunk that is +// not a candidate. +// +// The crash is injected, not raced: the real flusher runs and is stopped at +// its fsync; the store file after the crash is the file as it was before the +// unacked write, plus that block's extent page as the flusher left it, as if +// only that page had reached the disk. A flusher that writes extents only +// from synced records leaves the page unchanged and passes. +func TestRedCrashKeepingAnUnsyncedExtentWriteLeavesLocalAndHEADApart(t *testing.T) { + ctx := context.Background() + s, path, crash := crashableStore(t) + remote := NewMemChunkRemote() + cfg := chunkLayerConfig{ChunkBlocks: ctChunkBlocks, Epoch: 1, Holder: "h"} + layer := mustAttach(t, s, remote, cfg) + + acked := bytes.Repeat([]byte{0xA1}, ctBlockSize) + if _, err := s.Write(1, acked); err != nil { // chunk 0 + t.Fatal(err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + if _, err := layer.Capture(ctx); err != nil { + t.Fatal(err) + } + // Time passes: the flusher checkpoints, so the cut's clear of chunk 0 + // is in the persisted map (chunk 0 is not a candidate any more). + mustSyncFlush(t, s) + if n := layer.Stats().DirtyChunks; n != 0 { + t.Fatalf("after the cut and a checkpoint: %d candidate chunks; want 0", n) + } + // Read through the store's own handle (another open of the file is + // refused on some platforms while the store holds its lock). + fi, err := s.fd.Stat() + if err != nil { + t.Fatal(err) + } + before := make([]byte, fi.Size()) + if _, err := s.fd.ReadAt(before, 0); err != nil { + t.Fatal(err) + } + + // An unacked write to another block of chunk 0. The flusher runs (below + // the WAL pressure threshold, as in normal use); the power is cut at its + // fsync: the extent pages it wrote may be on the disk, the WAL record + // (never synced) is not, and no checkpoint follows. + lost := bytes.Repeat([]byte{0xB2}, ctBlockSize) + const lostLBA = 2 + if _, err := s.Write(lostLBA, lost); err != nil { + t.Fatal(err) + } + off := int64(s.extentBase) + int64(lostLBA)*int64(ctBlockSize) + page := make([]byte, ctBlockSize) + s.testBeforeFileSync = func() { + if _, err := s.fd.ReadAt(page, off); err != nil { + t.Error(err) + } + s.noteFsyncFailure(errors.New("power cut")) + } + _ = s.flusher.flushOnce() // fails at its fsync: no checkpoint + s.testBeforeFileSync = nil + crash() + + // The disk after the crash: the earlier file, plus only that extent page + // as the flusher left it. + img := append([]byte(nil), before...) + copy(img[off:off+int64(ctBlockSize)], page) + if err := os.WriteFile(path, img, 0o644); err != nil { + t.Fatal(err) + } + s2, _ := reopen(t, path) + layer2 := mustAttach(t, s2, remote, cfg) + + local, err := s2.Read(lostLBA) + if err != nil { + t.Fatal(err) + } + head, err := remote.GetHead(ctx) + if err != nil { + t.Fatal(err) + } + published := make([]byte, ctBlockSize) + if ref, ok := head.Chunks[0]; ok { + chunk, err := remote.Get(ctx, ref.Key) + if err != nil { + t.Fatal(err) + } + inChunk := (lostLBA % ctChunkBlocks) * ctBlockSize + copy(published, chunk[inChunk:inChunk+ctBlockSize]) + } + candidate := layer2.Stats().DirtyChunks > 0 + t.Logf("after the crash: local block %d = %#x..., published = %#x..., chunk 0 a cut candidate: %v", lostLBA, local[0], published[0], candidate) + if !bytes.Equal(local, published) && !candidate { + t.Fatalf("block %d reads the lost write's bytes locally (%#x) while HEAD holds %#x, and chunk 0 is not a cut candidate: local and published disagree with nothing to reconcile them", lostLBA, local[0], published[0]) + } +} From c921de54e02f765018d7c5b18c6ebfadc460bf4e Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 23 Nov 2026 18:57:52 -0800 Subject: [PATCH 22/35] fix: the flusher writes an extent only from a synced WAL record Page writeback has no order across offsets of one file, so an extent written from a WAL record that is not yet durable could survive a power loss that loses the record: extent bytes no recovered record or map entry accounts for, under a chunk certified equal to HEAD. The flusher now skips dirty entries above the synced (acknowledged) WAL frontier; they stay dirty until a Sync or the pressure sync makes them durable, and the checkpoint is computed from the written entries only (it was already clamped to that frontier). Recover and the install log already fsync their records before raising the frontier. Co-Authored-By: Claude Opus 5.5 --- .../storage/checkpoint_diagnostics_test.go | 12 ++++++------ .../core/storage/chunk_u1_reorder_test.go | 18 +++++++++--------- seaweed-block/core/storage/flusher.go | 9 +++++++++ seaweed-block/docs/design/invariants.md | 3 ++- 4 files changed, 26 insertions(+), 16 deletions(-) diff --git a/seaweed-block/core/storage/checkpoint_diagnostics_test.go b/seaweed-block/core/storage/checkpoint_diagnostics_test.go index 4620636189..9bd7a10bd7 100644 --- a/seaweed-block/core/storage/checkpoint_diagnostics_test.go +++ b/seaweed-block/core/storage/checkpoint_diagnostics_test.go @@ -126,10 +126,10 @@ func TestCheckpointDiagnostics_LogRateLimit(t *testing.T) { } } -// A starved checkpoint: flush cycles keep succeeding (clamped to the -// acknowledged frontier, nothing persisted moves) while the persisted -// CheckpointLSN and the last advance stay frozen. Only a real move of the -// persisted checkpoint counts as an advance. +// A starved checkpoint: writes that are never synced are never flushed +// (INV-WAL-V3-WRITE-AHEAD-001), so flush cycles move nothing: the persisted +// CheckpointLSN, the success count and the last advance stay frozen. Only a +// real move of the persisted checkpoint counts as an advance. func TestCheckpointDiagnostics_StarvedCheckpointIsVisible(t *testing.T) { s, _ := newMappedCheckpointStoreV3(t) mustAttach(t, s, newFakeChunkRemote(), ctConfig(1)) @@ -150,8 +150,8 @@ func TestCheckpointDiagnostics_StarvedCheckpointIsVisible(t *testing.T) { } } starved := s.CheckpointPersistence() - if starved.Successes <= first.Successes { - t.Fatalf("flush cycles did not keep succeeding: %+v", starved) + if starved.Successes != first.Successes { + t.Fatalf("flush cycles over unsynced writes made a checkpoint call: first %+v starved %+v", first, starved) } if starved.CheckpointLSN != 1 || starved.Advances != 1 || !starved.LastAdvance.Equal(first.LastAdvance) { t.Fatalf("a clamped success counted as an advance: first %+v starved %+v", first, starved) diff --git a/seaweed-block/core/storage/chunk_u1_reorder_test.go b/seaweed-block/core/storage/chunk_u1_reorder_test.go index c7ecc20027..7323608e06 100644 --- a/seaweed-block/core/storage/chunk_u1_reorder_test.go +++ b/seaweed-block/core/storage/chunk_u1_reorder_test.go @@ -8,15 +8,14 @@ import ( "testing" ) -// The flusher writes a dirty block's extent before the WAL record behind it -// is synced (below the WAL pressure threshold it does not sync first), and -// page writeback has no order across offsets of one file. A crash can then -// keep the extent bytes of a write whose WAL record is lost (an unacked -// write). After recovery the chunk's map entry has not moved, so the chunk -// is not a cut candidate: local reads return the lost write's bytes while -// the published HEAD holds the chunk without them, and no cut compares the -// two. Local and published must agree for every block of a chunk that is -// not a candidate. +// Page writeback has no order across offsets of one file, so an extent +// written from a WAL record that is not yet durable could survive a power +// loss that loses the record (an unacked write). After recovery the chunk's +// map entry would not have moved, the chunk would not be a cut candidate, +// and local reads would return the lost write's bytes while the published +// HEAD holds the chunk without them. The flusher therefore writes extents +// only from synced records (INV-WAL-V3-WRITE-AHEAD-001). Local and published +// must agree for every block of a chunk that is not a candidate. // // The crash is injected, not raced: the real flusher runs and is stopped at // its fsync; the store file after the crash is the file as it was before the @@ -24,6 +23,7 @@ import ( // only that page had reached the disk. A flusher that writes extents only // from synced records leaves the page unchanged and passes. func TestRedCrashKeepingAnUnsyncedExtentWriteLeavesLocalAndHEADApart(t *testing.T) { + // The name keeps its red-first form so the history and the row match. ctx := context.Background() s, path, crash := crashableStore(t) remote := NewMemChunkRemote() diff --git a/seaweed-block/core/storage/flusher.go b/seaweed-block/core/storage/flusher.go index cdfa1368f0..470182c493 100644 --- a/seaweed-block/core/storage/flusher.go +++ b/seaweed-block/core/storage/flusher.go @@ -183,6 +183,12 @@ func (f *flusher) flushOnceInternal(allowClosed bool) (err error) { recoveryGen = store.v3.recoverGen.Load() entries := store.dm.snapshot() + // Write-ahead (INV-WAL-V3-WRITE-AHEAD-001): only entries whose WAL + // record is durable reach the extent. An entry above the synced WAL + // frontier stays dirty for a later cycle: written now, a power loss + // could keep its extent page and lose its record, leaving extent bytes + // that no recovered record or map entry accounts for. + synced := store.v3.wack.Load() store.mu.RUnlock() if len(entries) == 0 { @@ -218,6 +224,9 @@ func (f *flusher) flushOnceInternal(allowClosed bool) (err error) { recordCache := &flushRecordCacheV3{recoveryGen: recoveryGen} for _, e := range entries { + if e.LSN > synced { + continue + } data, _, err := f.readDirtyRecordV3Cached(e, recordCache) if err != nil { return err diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index b0d3c0580f..2850aaf270 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 -321 rows: 250 ACTIVE, 68 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 306 new. +322 rows: 251 ACTIVE, 68 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 307 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. @@ -529,6 +529,7 @@ The "Machine / transition" column refers to Part A. Notes under a table record w | `INV-WAL-V3-ACTIVATION-PROVIDER-001` | The durable provider's capture, HEAD restore and status paths probe, open and create volumes through the public v3 selectors (`ProbeWALStoreV3`, `OpenWALStore`, `CreateWALStoreWithOptions`). | M1 open/create/readonly | `core/frontend/durable/provider.go` `openOrCreate` | `TestDurableProviderV3_HEADRestorePreservesRemoteImageAndNextLSN`, `TestDurableProviderV3_StatusTracksRecoverSyncAndCapture` (`core/frontend/durable/provider_format_v3_test.go`) | — | ACTIVE | | `INV-WAL-V3-LEGACY-FIXTURE-ISOLATION-001` | No default-build production code calls a legacy fixture constructor, and no legacy fixture is in the transitive import closure of the production storage packages. | M1 open/create/readonly | build layout: legacy fixtures outside the default production import closure | `TestLegacyFixtureIsolation` (`core/storage/legacy_fixture_isolation_test.go`) | — | ACTIVE | | `INV-WAL-V3-FLUSH-PROFILE-001` | Native flusher header/full-record/decode counters describe actual reads and validation; I/O failure is distinct from validation failure and only successfully materialized blocks count validated. | M1 checkpoint instrumentation | `walstore_v3.go` `readWholeRecordProfiledV3`, `readDirtyRecordV3` | `TestFlusherV3ProfileCountsRealRecordStages` | Observability; no durability transition change | ACTIVE | +| `INV-WAL-V3-WRITE-AHEAD-001` | No extent byte reaches the disk before its WAL record is durable: the flusher writes an extent only from dirty entries at or below the synced (acknowledged) WAL frontier; Recover and the install log fsync their records before raising it. | M1 Serving (flusher extent write) | `core/storage/flusher.go` `flushOnceInternal`; `walstore_v3.go` `recoverV3` (descriptor publish fsync before `wack`); `install_log_v3.go` | `TestRedCrashKeepingAnUnsyncedExtentWriteLeavesLocalAndHEADApart` (`core/storage/chunk_u1_reorder_test.go`) | — | ACTIVE | | `INV-WAL-V3-CAPTURE-CANDIDATES-001` | A retained WAL entry already covered by HEAD is not dirt since HEAD. New post-HEAD WAL entries, UNKNOWN map chunks and map max-LSN above HEAD remain capture candidates. | M5 candidate selection | `chunk_layer.go` `captureCandidates` | `TestChunkLayerV3CapturedUncheckpointedWALIsCleanUntilRewritten`, `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, `TestBaseInstallV3CompletePersistsTheMapUnknownOfBaseWrites` | Conservative reachability unchanged; narrower redundant work | ACTIVE | | `INV-WAL-V3-DESCRIPTOR-001` | A v3 descriptor slot is used only if it is valid: a matching CRC32C (Castagnoli), every reserved byte zero, an accepted impl, a nonzero slotGen at most 2^64-2, a nonzero nonce, and geometry consistent under checked arithmetic. | M1 Opened (v3 descriptor selection) | `core/storage/superblock_v3.go` `decodeSlotV3`, `descriptorV3.validate`, `checkedAddV3` | `TestSlotV3VectorsDecodeAsExpected`, `TestSlotV3CounterExhaustion` (`core/storage/superblock_v3_test.go`) | — | STUB | | `INV-WAL-V3-DESCRIPTOR-BASE-001` | A valid v3 descriptor slot has CheckpointLSN ≤ mapCoveredCheckpoint ≤ W, and BASE fields that follow the rules of its BASE state. | M1 Opened (v3 descriptor selection) | `core/storage/superblock_v3.go` `descriptorV3.validate` | `TestSlotV3VectorsDecodeAsExpected`, `TestSlotV3InstalledMayHaveCursorBelowTail` (`core/storage/superblock_v3_test.go`) | — | STUB | From 9ffae70bf9bfaa9edd26e2d72316fdf1b334bbcb Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 23 Nov 2026 19:02:12 -0800 Subject: [PATCH 23/35] fix: a flusher cycle with no synced entry is idle; test the pressure path The flusher keeps only the snapshot's synced entries before its empty check, so a cycle over unsynced writes alone writes no extent and makes no fsync (it fsynced an empty batch before). A new test drives a guest that never flushes: below the WAL pressure threshold nothing reaches the extent; past it, the flusher's pressure sync makes the writes durable and the same cycle writes every block's newest bytes and advances the checkpoint. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/storage/flusher.go | 13 ++-- .../core/storage/flusher_write_ahead_test.go | 66 +++++++++++++++++++ seaweed-block/docs/design/invariants.md | 2 +- 3 files changed, 76 insertions(+), 5 deletions(-) create mode 100644 seaweed-block/core/storage/flusher_write_ahead_test.go diff --git a/seaweed-block/core/storage/flusher.go b/seaweed-block/core/storage/flusher.go index 470182c493..9ea96f526c 100644 --- a/seaweed-block/core/storage/flusher.go +++ b/seaweed-block/core/storage/flusher.go @@ -187,9 +187,17 @@ func (f *flusher) flushOnceInternal(allowClosed bool) (err error) { // record is durable reach the extent. An entry above the synced WAL // frontier stays dirty for a later cycle: written now, a power loss // could keep its extent page and lose its record, leaving extent bytes - // that no recovered record or map entry accounts for. + // that no recovered record or map entry accounts for. A cycle with no + // synced entry is idle: no extent write and no fsync. synced := store.v3.wack.Load() store.mu.RUnlock() + kept := entries[:0] + for _, e := range entries { + if e.LSN <= synced { + kept = append(kept, e) + } + } + entries = kept if len(entries) == 0 { return store.refreshW() // the mode-C idle refresh (DESIGN 6.2) @@ -224,9 +232,6 @@ func (f *flusher) flushOnceInternal(allowClosed bool) (err error) { recordCache := &flushRecordCacheV3{recoveryGen: recoveryGen} for _, e := range entries { - if e.LSN > synced { - continue - } data, _, err := f.readDirtyRecordV3Cached(e, recordCache) if err != nil { return err diff --git a/seaweed-block/core/storage/flusher_write_ahead_test.go b/seaweed-block/core/storage/flusher_write_ahead_test.go new file mode 100644 index 0000000000..14864a3570 --- /dev/null +++ b/seaweed-block/core/storage/flusher_write_ahead_test.go @@ -0,0 +1,66 @@ +package storage + +import ( + "bytes" + "path/filepath" + "testing" +) + +// A guest that never flushes: below the WAL pressure threshold its writes +// are not synced, so the flusher writes none of their extents +// (INV-WAL-V3-WRITE-AHEAD-001) and the checkpoint stays; once the WAL is +// past the threshold, the flusher's pressure sync makes them durable and the +// same cycle writes every block's newest bytes to the extent and advances +// the checkpoint. The data never waits for a guest flush that does not come. +func TestFlusherWriteAheadNeverFlushingGuestReachesExtentAtPressure(t *testing.T) { + for _, mode := range []WMode{WModeStrict, WModeLagged} { + t.Run(map[WMode]string{WModeStrict: "A", WModeLagged: "C"}[mode], func(t *testing.T) { + s, err := createMappedWALStoreV3ForTest(filepath.Join(t.TempDir(), "pressure"), 64, 4096, 64*1024, mode, 4) + if err != nil { + t.Fatal(err) + } + s.DisableAutoFlushForRecoveryTest() + t.Cleanup(func() { _ = s.Close() }) + expected := map[uint32][]byte{} + write := func(lba uint32) { + t.Helper() + data := bytes.Repeat([]byte{byte(s.NextLSN())}, 4096) + if _, err := s.Write(lba, data); err != nil { + t.Fatal(err) + } + expected[lba] = data + } + extent := func(lba uint32) []byte { + t.Helper() + b, err := s.readFromExtent(lba) + if err != nil { + t.Fatal(err) + } + return b + } + + write(0) + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + if bytes.Equal(extent(0), expected[0]) || s.CheckpointLSN() != 0 { + t.Fatalf("below pressure: an unsynced write reached the extent (checkpoint %d)", s.CheckpointLSN()) + } + + for lba := uint32(1); s.walUsedFraction() < 0.72; lba = (lba + 1) % 64 { + write(lba) + } + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + for lba, want := range expected { + if !bytes.Equal(extent(lba), want) { + t.Fatalf("after the pressure sync: block %d's extent does not hold its newest write", lba) + } + } + if s.CheckpointLSN() == 0 { + t.Fatal("after the pressure sync: the checkpoint did not advance") + } + }) + } +} diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 2850aaf270..72135fb4cf 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -529,7 +529,7 @@ The "Machine / transition" column refers to Part A. Notes under a table record w | `INV-WAL-V3-ACTIVATION-PROVIDER-001` | The durable provider's capture, HEAD restore and status paths probe, open and create volumes through the public v3 selectors (`ProbeWALStoreV3`, `OpenWALStore`, `CreateWALStoreWithOptions`). | M1 open/create/readonly | `core/frontend/durable/provider.go` `openOrCreate` | `TestDurableProviderV3_HEADRestorePreservesRemoteImageAndNextLSN`, `TestDurableProviderV3_StatusTracksRecoverSyncAndCapture` (`core/frontend/durable/provider_format_v3_test.go`) | — | ACTIVE | | `INV-WAL-V3-LEGACY-FIXTURE-ISOLATION-001` | No default-build production code calls a legacy fixture constructor, and no legacy fixture is in the transitive import closure of the production storage packages. | M1 open/create/readonly | build layout: legacy fixtures outside the default production import closure | `TestLegacyFixtureIsolation` (`core/storage/legacy_fixture_isolation_test.go`) | — | ACTIVE | | `INV-WAL-V3-FLUSH-PROFILE-001` | Native flusher header/full-record/decode counters describe actual reads and validation; I/O failure is distinct from validation failure and only successfully materialized blocks count validated. | M1 checkpoint instrumentation | `walstore_v3.go` `readWholeRecordProfiledV3`, `readDirtyRecordV3` | `TestFlusherV3ProfileCountsRealRecordStages` | Observability; no durability transition change | ACTIVE | -| `INV-WAL-V3-WRITE-AHEAD-001` | No extent byte reaches the disk before its WAL record is durable: the flusher writes an extent only from dirty entries at or below the synced (acknowledged) WAL frontier; Recover and the install log fsync their records before raising it. | M1 Serving (flusher extent write) | `core/storage/flusher.go` `flushOnceInternal`; `walstore_v3.go` `recoverV3` (descriptor publish fsync before `wack`); `install_log_v3.go` | `TestRedCrashKeepingAnUnsyncedExtentWriteLeavesLocalAndHEADApart` (`core/storage/chunk_u1_reorder_test.go`) | — | ACTIVE | +| `INV-WAL-V3-WRITE-AHEAD-001` | No extent byte reaches the disk before its WAL record is durable: the flusher writes an extent only from dirty entries at or below the synced (acknowledged) WAL frontier; Recover and the install log fsync their records before raising it. | M1 Serving (flusher extent write) | `core/storage/flusher.go` `flushOnceInternal`; `walstore_v3.go` `recoverV3` (descriptor publish fsync before `wack`); `install_log_v3.go` | `TestRedCrashKeepingAnUnsyncedExtentWriteLeavesLocalAndHEADApart` (`core/storage/chunk_u1_reorder_test.go`); `TestFlusherWriteAheadNeverFlushingGuestReachesExtentAtPressure` (`core/storage/flusher_write_ahead_test.go`) | — | ACTIVE | | `INV-WAL-V3-CAPTURE-CANDIDATES-001` | A retained WAL entry already covered by HEAD is not dirt since HEAD. New post-HEAD WAL entries, UNKNOWN map chunks and map max-LSN above HEAD remain capture candidates. | M5 candidate selection | `chunk_layer.go` `captureCandidates` | `TestChunkLayerV3CapturedUncheckpointedWALIsCleanUntilRewritten`, `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, `TestBaseInstallV3CompletePersistsTheMapUnknownOfBaseWrites` | Conservative reachability unchanged; narrower redundant work | ACTIVE | | `INV-WAL-V3-DESCRIPTOR-001` | A v3 descriptor slot is used only if it is valid: a matching CRC32C (Castagnoli), every reserved byte zero, an accepted impl, a nonzero slotGen at most 2^64-2, a nonzero nonce, and geometry consistent under checked arithmetic. | M1 Opened (v3 descriptor selection) | `core/storage/superblock_v3.go` `decodeSlotV3`, `descriptorV3.validate`, `checkedAddV3` | `TestSlotV3VectorsDecodeAsExpected`, `TestSlotV3CounterExhaustion` (`core/storage/superblock_v3_test.go`) | — | STUB | | `INV-WAL-V3-DESCRIPTOR-BASE-001` | A valid v3 descriptor slot has CheckpointLSN ≤ mapCoveredCheckpoint ≤ W, and BASE fields that follow the rules of its BASE state. | M1 Opened (v3 descriptor selection) | `core/storage/superblock_v3.go` `descriptorV3.validate` | `TestSlotV3VectorsDecodeAsExpected`, `TestSlotV3InstalledMayHaveCursorBelowTail` (`core/storage/superblock_v3_test.go`) | — | STUB | From 11f817d6d8cfb15916c30f703575fc0e3e1c192a Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 23 Nov 2026 19:41:21 -0800 Subject: [PATCH 24/35] test: a checkpoint over a superseded synced record needs the flusher's sync to cover the WAL b=X and c=Y synced, then b=Z unsynced: the flusher skips b (its newest entry is unsynced) and its checkpoint passes X's record, which never reached the extent. Crash after the checkpoint, with the WAL region as of the last sync that covered it: b reads Z, because the flusher's sync is the whole-file fsync of the one descriptor. The control models an extent-only flusher sync and loses X (b reads the bytes from before X), showing the checkpoint bound rests on that. INV-WAL-FLUSH-SYNC-COVERS-WAL-001 moves from STUB to ACTIVE with this test; INV-WAL-V3-WRITE-AHEAD-001 states the dependency. Co-Authored-By: Claude Opus 5.5 --- .../storage/flusher_superseded_record_test.go | 111 ++++++++++++++++++ seaweed-block/docs/design/invariants.md | 8 +- 2 files changed, 115 insertions(+), 4 deletions(-) create mode 100644 seaweed-block/core/storage/flusher_superseded_record_test.go diff --git a/seaweed-block/core/storage/flusher_superseded_record_test.go b/seaweed-block/core/storage/flusher_superseded_record_test.go new file mode 100644 index 0000000000..30788378b1 --- /dev/null +++ b/seaweed-block/core/storage/flusher_superseded_record_test.go @@ -0,0 +1,111 @@ +package storage + +import ( + "bytes" + "os" + "testing" +) + +// The flusher skips an LBA whose newest entry is not yet synced, so a +// cycle's checkpoint can pass an OLDER synced record of that LBA that never +// reached the extent (it was superseded in the dirty map by the unsynced +// one). That is safe only because the cycle's sync is the whole-file fsync +// of the one descriptor holding WAL and extent: it makes the newer record +// durable before the checkpoint is published, so recovery replays it +// (INV-WAL-FLUSH-SYNC-COVERS-WAL-001). b=X, c=Y, Sync, b=Z unsynced, one +// flusher cycle, crash after its checkpoint: b must read X or Z, never the +// bytes from before X. +// +// The crash image keeps the WAL region as of the last sync that covered it +// and everything else as of the crash. The product's syncs (the WAL sync and +// the flusher's) both cover the WAL. The control models a flusher sync that +// covers only the extent (a range sync, or WAL and extent in separate files) +// and shows the checkpoint bound would then lose X: the premise is +// load-bearing. +func TestFlusherCheckpointOverASupersededSyncedRecord(t *testing.T) { + for _, c := range []struct { + name string + flushCoversWAL bool + wantBeforeXRead bool + }{ + {"whole-file flusher sync (product)", true, false}, + {"control: extent-only flusher sync", false, true}, + } { + t.Run(c.name, func(t *testing.T) { + s, path, crash := crashableStore(t) + d := s.v3.pub.current() + walOff, walLen := int64(d.WALOffset), int64(d.WALSize) + readWAL := func() []byte { + b := make([]byte, walLen) + if _, err := s.fd.ReadAt(b, walOff); err != nil { + t.Fatal(err) + } + return b + } + durableWAL := readWAL() + realWALSync, realFlushSync := s.syncWALFile, s.syncExtentFile + s.syncWALFile = func() error { + err := realWALSync() + if err == nil { + durableWAL = readWAL() + } + return err + } + s.syncExtentFile = func() error { + err := realFlushSync() + if err == nil && c.flushCoversWAL { + durableWAL = readWAL() + } + return err + } + + const b, cLBA = 3, 9 + X, Y, Z := bytes.Repeat([]byte{0x58}, ctBlockSize), bytes.Repeat([]byte{0x59}, ctBlockSize), bytes.Repeat([]byte{0x5a}, ctBlockSize) + before, err := s.Read(b) + if err != nil { + t.Fatal(err) + } + if _, err := s.Write(b, X); err != nil { + t.Fatal(err) + } + if _, err := s.Write(cLBA, Y); err != nil { + t.Fatal(err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + if _, err := s.Write(b, Z); err != nil { // unsynced: supersedes X in the dirty map + t.Fatal(err) + } + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + if cp := s.CheckpointLSN(); cp < 2 { + t.Fatalf("checkpoint %d after the cycle; want it past X's record (it covers Y)", cp) + } + crash() + + img, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + copy(img[walOff:walOff+walLen], durableWAL) + if err := os.WriteFile(path, img, 0o644); err != nil { + t.Fatal(err) + } + s2, _ := reopen(t, path) + got, err := s2.Read(b) + if err != nil { + t.Fatal(err) + } + isBefore := bytes.Equal(got, before) && !bytes.Equal(got, X) + switch { + case c.wantBeforeXRead && !isBefore: + t.Fatalf("control: block %d reads %#x after the crash; the model should lose X here (premise not shown load-bearing)", b, got[0]) + case !c.wantBeforeXRead && !bytes.Equal(got, X) && !bytes.Equal(got, Z): + t.Fatalf("block %d reads %#x after the crash; want X (%#x) or Z (%#x), never the bytes from before X", b, got[0], X[0], Z[0]) + } + t.Logf("block %d after the crash: %#x", b, got[0]) + }) + } +} diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 72135fb4cf..2878cca9bb 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: 251 ACTIVE, 68 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 307 new. +322 rows: 252 ACTIVE, 67 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 307 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. @@ -529,7 +529,7 @@ The "Machine / transition" column refers to Part A. Notes under a table record w | `INV-WAL-V3-ACTIVATION-PROVIDER-001` | The durable provider's capture, HEAD restore and status paths probe, open and create volumes through the public v3 selectors (`ProbeWALStoreV3`, `OpenWALStore`, `CreateWALStoreWithOptions`). | M1 open/create/readonly | `core/frontend/durable/provider.go` `openOrCreate` | `TestDurableProviderV3_HEADRestorePreservesRemoteImageAndNextLSN`, `TestDurableProviderV3_StatusTracksRecoverSyncAndCapture` (`core/frontend/durable/provider_format_v3_test.go`) | — | ACTIVE | | `INV-WAL-V3-LEGACY-FIXTURE-ISOLATION-001` | No default-build production code calls a legacy fixture constructor, and no legacy fixture is in the transitive import closure of the production storage packages. | M1 open/create/readonly | build layout: legacy fixtures outside the default production import closure | `TestLegacyFixtureIsolation` (`core/storage/legacy_fixture_isolation_test.go`) | — | ACTIVE | | `INV-WAL-V3-FLUSH-PROFILE-001` | Native flusher header/full-record/decode counters describe actual reads and validation; I/O failure is distinct from validation failure and only successfully materialized blocks count validated. | M1 checkpoint instrumentation | `walstore_v3.go` `readWholeRecordProfiledV3`, `readDirtyRecordV3` | `TestFlusherV3ProfileCountsRealRecordStages` | Observability; no durability transition change | ACTIVE | -| `INV-WAL-V3-WRITE-AHEAD-001` | No extent byte reaches the disk before its WAL record is durable: the flusher writes an extent only from dirty entries at or below the synced (acknowledged) WAL frontier; Recover and the install log fsync their records before raising it. | M1 Serving (flusher extent write) | `core/storage/flusher.go` `flushOnceInternal`; `walstore_v3.go` `recoverV3` (descriptor publish fsync before `wack`); `install_log_v3.go` | `TestRedCrashKeepingAnUnsyncedExtentWriteLeavesLocalAndHEADApart` (`core/storage/chunk_u1_reorder_test.go`); `TestFlusherWriteAheadNeverFlushingGuestReachesExtentAtPressure` (`core/storage/flusher_write_ahead_test.go`) | — | ACTIVE | +| `INV-WAL-V3-WRITE-AHEAD-001` | No extent byte reaches the disk before its WAL record is durable: the flusher writes an extent only from dirty entries at or below the synced (acknowledged) WAL frontier; Recover and the install log fsync their records before raising it. | M1 Serving (flusher extent write) | `core/storage/flusher.go` `flushOnceInternal`; `walstore_v3.go` `recoverV3` (descriptor publish fsync before `wack`); `install_log_v3.go` | `TestRedCrashKeepingAnUnsyncedExtentWriteLeavesLocalAndHEADApart` (`core/storage/chunk_u1_reorder_test.go`); `TestFlusherWriteAheadNeverFlushingGuestReachesExtentAtPressure` (`core/storage/flusher_write_ahead_test.go`) | A checkpoint may pass a synced record superseded by an unsynced newer one only because the cycle's sync covers the whole file, WAL included (one file, one descriptor: `INV-WAL-FLUSH-SYNC-COVERS-WAL-001`); separating WAL and extent, or a range sync, must first change the checkpoint bound | ACTIVE | | `INV-WAL-V3-CAPTURE-CANDIDATES-001` | A retained WAL entry already covered by HEAD is not dirt since HEAD. New post-HEAD WAL entries, UNKNOWN map chunks and map max-LSN above HEAD remain capture candidates. | M5 candidate selection | `chunk_layer.go` `captureCandidates` | `TestChunkLayerV3CapturedUncheckpointedWALIsCleanUntilRewritten`, `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, `TestBaseInstallV3CompletePersistsTheMapUnknownOfBaseWrites` | Conservative reachability unchanged; narrower redundant work | ACTIVE | | `INV-WAL-V3-DESCRIPTOR-001` | A v3 descriptor slot is used only if it is valid: a matching CRC32C (Castagnoli), every reserved byte zero, an accepted impl, a nonzero slotGen at most 2^64-2, a nonzero nonce, and geometry consistent under checked arithmetic. | M1 Opened (v3 descriptor selection) | `core/storage/superblock_v3.go` `decodeSlotV3`, `descriptorV3.validate`, `checkedAddV3` | `TestSlotV3VectorsDecodeAsExpected`, `TestSlotV3CounterExhaustion` (`core/storage/superblock_v3_test.go`) | — | STUB | | `INV-WAL-V3-DESCRIPTOR-BASE-001` | A valid v3 descriptor slot has CheckpointLSN ≤ mapCoveredCheckpoint ≤ W, and BASE fields that follow the rules of its BASE state. | M1 Opened (v3 descriptor selection) | `core/storage/superblock_v3.go` `descriptorV3.validate` | `TestSlotV3VectorsDecodeAsExpected`, `TestSlotV3InstalledMayHaveCursorBelowTail` (`core/storage/superblock_v3_test.go`) | — | STUB | @@ -1018,12 +1018,12 @@ Notes: | `INV-WAL-DATA-SYNC-STATUS-001` | The data sync mode chosen at open and its reason are logged and exposed in durable status. | M1 Create / Sync / Checkpoint | `data_sync.go` `bindDataFileSync`, `DataSyncPolicy`; `core/frontend/durable/storage_adapter.go` status | `TestDurableProvider_DataSyncStatus` (`core/frontend/durable/data_sync_status_test.go`) | — | ACTIVE | | `INV-WAL-ALLOCATION-001` | `SWBLOCK_ALLOCATION` selects allocation at create: sparse, the default, or prezero; fallocate is refused. `SWBLOCK_PREZERO=1` is an alias of prezero. | M1 Create / Sync / Checkpoint | `walstore_v3.go` Create | `TestDefaultCreatedVolumeStaysSparse`, `TestFallocateAllocationIsRefused` (`core/storage/data_sync_linux_test.go`) | — | ACTIVE | | `INV-WAL-PREZERO-001` | Prezero writes every byte at create and fsyncs; a file opened as initialized is refused when it has holes or unwritten extent mappings. | M1 Create / Sync / Checkpoint | `walstore_v3.go` Create | `TestPrezeroCreatesInitializedVolume`, `TestInitializedFileRejectsSparseAndUnwritten` (`core/storage/data_sync_linux_test.go`) | — | ACTIVE | -| `INV-WAL-FLUSH-SYNC-COVERS-WAL-001` | WAL and extent data live in one store file, and the WAL sync and the flusher's extent sync are the same whole-file fsync or fdatasync of that one descriptor, never a range sync, so every flusher sync also makes the WAL durable. | M1 Serving → Serving (checkpoint) | `core/storage/walstore.go` `openInitializedV3`; `core/storage/data_sync.go` `bindDataFileSync`; `core/storage/flusher.go` `flushOnceInternal` | — | — | STUB | +| `INV-WAL-FLUSH-SYNC-COVERS-WAL-001` | WAL and extent data live in one store file, and the WAL sync and the flusher's extent sync are the same whole-file fsync or fdatasync of that one descriptor, never a range sync, so every flusher sync also makes the WAL durable. | M1 Serving → Serving (checkpoint) | `core/storage/walstore.go` `openInitializedV3`; `core/storage/data_sync.go` `bindDataFileSync`; `core/storage/flusher.go` `flushOnceInternal` | `TestFlusherCheckpointOverASupersededSyncedRecord` (`core/storage/flusher_superseded_record_test.go`; its control models an extent-only flusher sync and loses X) | — | ACTIVE | - `INV-WAL-DATA-SYNC-001` and the rows split from it: enforced by reading, with no test of their own: the mode is not reselected during the life of an open volume; descriptor, map, create and directory durability always use fsync, whatever the data sync mode; an existing file is never prezeroed. Notes: -- `INV-WAL-FLUSH-SYNC-COVERS-WAL-001`: the one-file, one-descriptor, no-range-sync clause is enforced by reading; no test asserts it yet. Fault-injection tests replace the WAL sync and the extent sync separately and do not check that they are the same call. +- `INV-WAL-FLUSH-SYNC-COVERS-WAL-001`: the one-file, one-descriptor, no-range-sync clause is enforced by reading; `TestFlusherCheckpointOverASupersededSyncedRecord` shows why it is load-bearing (a checkpoint over a superseded synced record is safe only if the flusher's sync made the newer record durable; its control, an extent-only sync, loses the older record). No test checks that the WAL sync and the extent sync are the same call. ## Part C. Change rules From a2441488eb1e04b4fc9b506afef8580c840e63e8 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 23 Nov 2026 17:01:17 -0800 Subject: [PATCH 25/35] 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 26/35] 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 27/35] 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 28/35] 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 29/35] 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 76692a5ef7bec78b95ec7da5510a46ed672a8eb7 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 23 Nov 2026 22:02:21 -0800 Subject: [PATCH 30/35] test: guard that the flusher sync and the WAL sync are one whole-file sync A source-level test checks that the store opener binds exactly one data sync for its file and that both the flusher's extent sync and the WAL sync use it (a range sync, a second descriptor, or a WAL sync that no longer calls the shared sync fails it). The checkpoint bound over a superseded synced record rests on this. The crash test helpers also close the owned-map file of a crashed store, so the crash tests' directory cleanup no longer fails where an open file cannot be deleted. Co-Authored-By: Claude Opus 5.5 --- .../core/storage/chunk_fake_remote_test.go | 12 ++ .../storage/sync_covers_wal_guard_test.go | 128 ++++++++++++++++++ seaweed-block/docs/design/invariants.md | 4 +- 3 files changed, 142 insertions(+), 2 deletions(-) create mode 100644 seaweed-block/core/storage/sync_covers_wal_guard_test.go diff --git a/seaweed-block/core/storage/chunk_fake_remote_test.go b/seaweed-block/core/storage/chunk_fake_remote_test.go index 417724798a..9151a70438 100644 --- a/seaweed-block/core/storage/chunk_fake_remote_test.go +++ b/seaweed-block/core/storage/chunk_fake_remote_test.go @@ -727,6 +727,7 @@ func crashableStore(t *testing.T) (*WALStore, string, func()) { if err := s.fd.Close(); err != nil { t.Fatal(err) } + crashOwnedMap(s) } } @@ -753,6 +754,7 @@ func reopen(t *testing.T, path string) (*WALStore, func()) { if err := s.fd.Close(); err != nil { t.Fatal(err) } + crashOwnedMap(s) } } @@ -1133,3 +1135,13 @@ func waitReconciledForTest(t *testing.T, layer chunkLayer) { time.Sleep(time.Millisecond) } } + +// crashOwnedMap closes the owned-map file of a crashed store without +// persisting anything, as the process's exit would; otherwise its handle +// stays open and a platform that refuses to delete an open file fails the +// test's directory cleanup. +func crashOwnedMap(s *WALStore) { + if s.v3 != nil && s.v3.ownedMap != nil && s.v3.ownedMap.fd != nil { + _ = s.v3.ownedMap.fd.Close() + } +} diff --git a/seaweed-block/core/storage/sync_covers_wal_guard_test.go b/seaweed-block/core/storage/sync_covers_wal_guard_test.go new file mode 100644 index 0000000000..d299b8ca14 --- /dev/null +++ b/seaweed-block/core/storage/sync_covers_wal_guard_test.go @@ -0,0 +1,128 @@ +package storage + +import ( + "go/ast" + "go/parser" + "go/token" + "os" + "path/filepath" + "strings" + "testing" +) + +// INV-WAL-FLUSH-SYNC-COVERS-WAL-001, checked in the source: the flusher's +// extent sync and the WAL sync are the same whole-file sync of the store's +// one descriptor. The checkpoint bound rests on it (a checkpoint may pass a +// synced record superseded by an unsynced newer one only because the +// flusher's sync makes the newer record durable too). In the package's +// non-test Go files: +// - the function that sets syncExtentFile binds exactly one data sync +// (bindDataFileSync of the store file) and no other function sets it; +// - every assignment to syncExtentFile assigns exactly that result; +// - every assignment to syncWALFile is a function that calls that result. +// +// A range sync, a second descriptor for the WAL or the extent, or a WAL sync +// that no longer calls the shared sync fails here first. +func TestSyncCoversWALGuard(t *testing.T) { + files, err := filepath.Glob("*.go") + if err != nil { + t.Fatal(err) + } + fset := token.NewFileSet() + binds, extentOK, extentBad, walOK, walBad := 0, 0, []string{}, 0, []string{} + shared := "" // the variable bindDataFileSync's sync result is bound to + type asg struct { + field string + rhs ast.Expr + pos token.Position + } + var asgs []asg + for _, f := range files { + if strings.HasSuffix(f, "_test.go") { + continue + } + src, err := os.ReadFile(f) + if err != nil { + t.Fatal(err) + } + file, err := parser.ParseFile(fset, f, src, 0) + if err != nil { + t.Fatal(err) + } + for _, decl := range file.Decls { + fn, ok := decl.(*ast.FuncDecl) + if !ok || fn.Body == nil { + continue + } + var fnBinds []string + setsExtent := false + ast.Inspect(fn.Body, func(n ast.Node) bool { + a, ok := n.(*ast.AssignStmt) + if !ok { + return true + } + for i, rhs := range a.Rhs { + if call, ok := rhs.(*ast.CallExpr); ok { + if id, ok := call.Fun.(*ast.Ident); ok && id.Name == "bindDataFileSync" && len(a.Lhs) > 0 { + if lhs, ok := a.Lhs[0].(*ast.Ident); ok { + fnBinds = append(fnBinds, lhs.Name) + } + } + } + if i < len(a.Lhs) { + if sel, ok := a.Lhs[i].(*ast.SelectorExpr); ok && (sel.Sel.Name == "syncExtentFile" || sel.Sel.Name == "syncWALFile") { + asgs = append(asgs, asg{sel.Sel.Name, rhs, fset.Position(a.Pos())}) + if sel.Sel.Name == "syncExtentFile" { + setsExtent = true + } + } + } + } + return true + }) + if setsExtent { + binds += len(fnBinds) + if len(fnBinds) > 0 { + shared = fnBinds[0] + } + } + } + } + if binds != 1 || shared == "" { + t.Fatalf("the function setting syncExtentFile binds %d data syncs (first bound to %q); want exactly one: one descriptor, one sync", binds, shared) + } + callsShared := func(e ast.Expr) bool { + found := false + ast.Inspect(e, func(n ast.Node) bool { + if c, ok := n.(*ast.CallExpr); ok { + if id, ok := c.Fun.(*ast.Ident); ok && id.Name == shared { + found = true + } + } + return !found + }) + return found + } + for _, a := range asgs { + switch a.field { + case "syncExtentFile": + if id, ok := a.rhs.(*ast.Ident); ok && id.Name == shared { + extentOK++ + } else { + extentBad = append(extentBad, a.pos.String()) + } + case "syncWALFile": + if fl, ok := a.rhs.(*ast.FuncLit); ok && callsShared(fl) { + walOK++ + } else { + walBad = append(walBad, a.pos.String()) + } + } + } + if extentOK == 0 || len(extentBad) > 0 { + t.Fatalf("syncExtentFile assigned the shared sync %q %d times; other assignments at %v: the flusher's sync must be the WAL's whole-file sync", shared, extentOK, extentBad) + } + if walOK == 0 || len(walBad) > 0 { + t.Fatalf("syncWALFile assigned a function calling %q %d times; other assignments at %v", shared, walOK, walBad) + } +} diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 2878cca9bb..750081d60b 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -1018,12 +1018,12 @@ Notes: | `INV-WAL-DATA-SYNC-STATUS-001` | The data sync mode chosen at open and its reason are logged and exposed in durable status. | M1 Create / Sync / Checkpoint | `data_sync.go` `bindDataFileSync`, `DataSyncPolicy`; `core/frontend/durable/storage_adapter.go` status | `TestDurableProvider_DataSyncStatus` (`core/frontend/durable/data_sync_status_test.go`) | — | ACTIVE | | `INV-WAL-ALLOCATION-001` | `SWBLOCK_ALLOCATION` selects allocation at create: sparse, the default, or prezero; fallocate is refused. `SWBLOCK_PREZERO=1` is an alias of prezero. | M1 Create / Sync / Checkpoint | `walstore_v3.go` Create | `TestDefaultCreatedVolumeStaysSparse`, `TestFallocateAllocationIsRefused` (`core/storage/data_sync_linux_test.go`) | — | ACTIVE | | `INV-WAL-PREZERO-001` | Prezero writes every byte at create and fsyncs; a file opened as initialized is refused when it has holes or unwritten extent mappings. | M1 Create / Sync / Checkpoint | `walstore_v3.go` Create | `TestPrezeroCreatesInitializedVolume`, `TestInitializedFileRejectsSparseAndUnwritten` (`core/storage/data_sync_linux_test.go`) | — | ACTIVE | -| `INV-WAL-FLUSH-SYNC-COVERS-WAL-001` | WAL and extent data live in one store file, and the WAL sync and the flusher's extent sync are the same whole-file fsync or fdatasync of that one descriptor, never a range sync, so every flusher sync also makes the WAL durable. | M1 Serving → Serving (checkpoint) | `core/storage/walstore.go` `openInitializedV3`; `core/storage/data_sync.go` `bindDataFileSync`; `core/storage/flusher.go` `flushOnceInternal` | `TestFlusherCheckpointOverASupersededSyncedRecord` (`core/storage/flusher_superseded_record_test.go`; its control models an extent-only flusher sync and loses X) | — | ACTIVE | +| `INV-WAL-FLUSH-SYNC-COVERS-WAL-001` | WAL and extent data live in one store file, and the WAL sync and the flusher's extent sync are the same whole-file fsync or fdatasync of that one descriptor, never a range sync, so every flusher sync also makes the WAL durable. | M1 Serving → Serving (checkpoint) | `core/storage/walstore.go` `openInitializedV3`; `core/storage/data_sync.go` `bindDataFileSync`; `core/storage/flusher.go` `flushOnceInternal` | `TestFlusherCheckpointOverASupersededSyncedRecord` (`core/storage/flusher_superseded_record_test.go`; its control models an extent-only flusher sync and loses X); `TestSyncCoversWALGuard` (`core/storage/sync_covers_wal_guard_test.go`: the store opener binds one data sync, and the flusher sync and the WAL sync both use it) | — | ACTIVE | - `INV-WAL-DATA-SYNC-001` and the rows split from it: enforced by reading, with no test of their own: the mode is not reselected during the life of an open volume; descriptor, map, create and directory durability always use fsync, whatever the data sync mode; an existing file is never prezeroed. Notes: -- `INV-WAL-FLUSH-SYNC-COVERS-WAL-001`: the one-file, one-descriptor, no-range-sync clause is enforced by reading; `TestFlusherCheckpointOverASupersededSyncedRecord` shows why it is load-bearing (a checkpoint over a superseded synced record is safe only if the flusher's sync made the newer record durable; its control, an extent-only sync, loses the older record). No test checks that the WAL sync and the extent sync are the same call. +- `INV-WAL-FLUSH-SYNC-COVERS-WAL-001`: the one-file, one-descriptor, no-range-sync clause is enforced by reading; `TestFlusherCheckpointOverASupersededSyncedRecord` shows why it is load-bearing (a checkpoint over a superseded synced record is safe only if the flusher's sync made the newer record durable; its control, an extent-only sync, loses the older record). `TestSyncCoversWALGuard` checks in the source that the WAL sync and the flusher's extent sync are the one data sync the store opener binds for its file. ## Part C. Change rules From 45134d4581332b4198ba8f760dd4a5e7ad529f69 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 23 Nov 2026 22:07:05 -0800 Subject: [PATCH 31/35] 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 | From 3819309942b5c3f8b3508b69bc8a1c481b2b63c0 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 23 Nov 2026 22:54:21 -0800 Subject: [PATCH 32/35] test: the status's hydration counters follow first reads A row and a test for the two per-volume counters the status already reports: the HEAD-named chunks still to hydrate (AbsentChunks) and the chunks hydrated so far (Hydration.Completed, cumulative). On a restore target whose HEAD names two chunks they start at 2 and 0; a read of an un-hydrated chunk moves both by one and a repeat read moves neither, so a caller can prove a read happened before its chunk was hydrated. Co-Authored-By: Claude Opus 5.5 --- .../durable/hydration_progress_test.go | 79 +++++++++++++++++++ seaweed-block/docs/design/invariants.md | 3 +- 2 files changed, 81 insertions(+), 1 deletion(-) create mode 100644 seaweed-block/core/frontend/durable/hydration_progress_test.go diff --git a/seaweed-block/core/frontend/durable/hydration_progress_test.go b/seaweed-block/core/frontend/durable/hydration_progress_test.go new file mode 100644 index 0000000000..3841d2b410 --- /dev/null +++ b/seaweed-block/core/frontend/durable/hydration_progress_test.go @@ -0,0 +1,79 @@ +package durable + +import ( + "bytes" + "context" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/storage" +) + +func hydrationProgress(t *testing.T, p *DurableProvider) (absent int, hydrated uint64) { + t.Helper() + for _, st := range p.DurableStatuses() { + if st.VolumeID == "v1" && st.Chunk != nil && st.Chunk.Attached { + return st.Chunk.Stats.AbsentChunks, st.Chunk.Stats.Hydration.Completed + } + } + t.Fatal("v1 has no attached chunk layer") + return 0, 0 +} + +// INV-CUT-HYDRATION-PROGRESS-001: the status reports, per volume, the +// chunks still to hydrate (AbsentChunks: HEAD-named, not yet local) and the +// chunks hydrated so far (Hydration.Completed, cumulative). A read of an +// un-hydrated chunk moves both by one; a second read of it moves neither. A +// caller can therefore prove that a read happened before its chunk was +// hydrated by reading the two before and after it. +func TestHydrationProgressCountersFollowFirstReads(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) + } + data := map[int64][]byte{3: bytes.Repeat([]byte{0x33}, 4096), 7: bytes.Repeat([]byte{0x77}, 4096)} + for chunk, b := range data { + if _, err := src.Backend("v1").Write(ctx, chunk*16*4096, b); 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) + } + + p := kzProvider(t, t.TempDir(), mem) + if _, err := p.EnsureStorage("v1"); err != nil { + t.Fatal(err) + } + if _, err := p.RecoverVolume(ctx, "v1"); err != nil { + t.Fatal(err) + } + want := []struct { + read int64 // chunk read before the check (-1: none) + absent int + hydrated uint64 + }{{-1, 2, 0}, {3, 1, 1}, {3, 1, 1}, {7, 0, 2}} + got := make([]byte, 4096) + for _, w := range want { + if w.read >= 0 { + if n, err := p.Backend("v1").Read(ctx, w.read*16*4096, got); err != nil || n != len(got) || !bytes.Equal(got, data[w.read]) { + t.Fatalf("read of chunk %d: %d %v, data equal %v", w.read, n, err, bytes.Equal(got, data[w.read])) + } + } + if absent, hydrated := hydrationProgress(t, p); absent != w.absent || hydrated != w.hydrated { + t.Fatalf("after reading chunk %d: %d still to hydrate, %d hydrated; want %d, %d", w.read, absent, hydrated, w.absent, w.hydrated) + } + } +} diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index f5e1ae5477..ace443cffe 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 -323 rows: 253 ACTIVE, 67 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 308 new. +324 rows: 254 ACTIVE, 67 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 309 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. @@ -858,6 +858,7 @@ Notes: | `INV-CUT-INTENT-CLOSE-001` | Close deletes the intents of reusable uploads and leftover intents, but never an intent of a proposal whose CAS outcome is still unresolved. | M5 Close | `core/storage/chunk_layer.go` `Close`, `captureLocked`, `dropIntents` | `TestChunkCloseDropsReusableButKeepsUnknownCASRoots` (`core/storage/chunk_review271_test.go`); `TestHeadBeltOldCASUnconfirmedKeepsIntentsAndFrontier`, `TestHeadBeltLowerEpochConflictFencesWithoutCleanup`, `TestHeadBeltEmptyBaseForeignPublicationFences` (`core/storage/chunk_head_belt_test.go`) | — | ACTIVE | | `INV-CUT-SEGMENT-REUSE-001` | A cut rewrites only manifest segments whose chunk references changed, and an uploaded but unpublished segment leaves the published root unchanged. | M5 Manifest | `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `TestManifest_ReusesUnchangedRangeAndCrashKeepsOldRoot` (`core/frontend/chunkstore/manifest_test.go`) | `CutPipeline` `SegConsistent` | ACTIVE | | `INV-CUT-HYDRATION-WAIT-001` | A read command shares its arrival deadline across chunks. A timed-out waiter returns typed pending without cancelling a shared fill. Per-layer worker and distinct-flight limits bound remote work; Close wakes waiters and joins issued fills before storage release. Physical/hash errors remain terminal. | M4 Holder (hydration wait) | `core/storage/chunk_hydration.go`; `core/storage/walstore.go` `ReadContext`; `core/frontend/durable/storage_adapter.go` `readStorageBlock`; `core/frontend/nvme/session.go` `handleRead` | `TestDurableHydration_MultipleChunksShareOneDeadline`, `TestDurableHydration_NVMePreservesPhysicalAndHashErrors`, `TestSessionReadBudgetIncludesQueueResidence`, `TestChunkHydration_QueueAndWorkerLimitsAreBounded`, `TestChunkHydration_CloseWakesCallerAndJoinsUninterruptibleGet`, `TestChunkHydration_ContextlessReadAllowsSlowFill`, `TestChunkHydration_NewGenerationDoesNotJoinStaleGet`, `TestChunkHydration_StaleCompletionKeepsReplacement`, `TestDurableHydration_RMWFenceWinsCallerExpiry` | — | ACTIVE | +| `INV-CUT-HYDRATION-PROGRESS-001` | The status reports per volume the HEAD-named chunks still to hydrate (`AbsentChunks`) and the chunks hydrated so far (`Hydration.Completed`, cumulative); a read of an un-hydrated chunk moves both by one, a repeat read neither. Observation only. | M5 hydration (reader; no transition) | `core/storage/chunk_layer.go` `Stats` (`absentHydratable`); `core/storage/chunk_hydration.go` `hydrationWorker` | `TestHydrationProgressCountersFollowFirstReads` (`core/frontend/durable/hydration_progress_test.go`) | — | ACTIVE | | `INV-CUT-READMISS-001` | A block fetched from HEAD after a move is installed only if it does not overwrite a newer local extent version; a newer WAL-only write still wins on reads, and HEAD's value may be installed beneath it as the backing value, which is correct if a crash loses that unsynced write. | M4 Holder (lazy restore) | `core/storage/chunk_layer.go` `OnReadMiss`, `installFetchedBlock`; `core/storage/walstore.go` `readFromExtent` | `TestChunkLayer_WALOnlyOverlapReadNeverReturnsUntouchedZero` (`core/storage/chunk_layer_races_test.go`); `TestWALStore_PostReadMissRechecksWALFormat` (`core/storage/walstore_read_miss_v3_test.go`; real-store v2/v3 dispatch) | — | ACTIVE | | `INV-CUT-TIMER-RESTART-001` | A successful cut of any kind restarts the periodic timer, which runs on in-process monotonic time (a restart starts a fresh schedule; wall-clock steps move nothing). | M5 periodic trigger (before Admit) | `core/frontend/durable/provider_chunk.go` `chunkLoop` | `TestWALStoreChunk_ExplicitCutRestartsTheTimer`, `TestWALStoreChunk_ExplicitCutOverlappingTheTimerRestartsIt` (`core/frontend/durable/provider_chunk_sched_test.go`); `TestCutPolicy_TimerRunsOnObservationTime`, `TestCutPolicy_StaggerPreservesExplicitTimerReset` (`core/frontend/durable/cut_policy_test.go`) | — | ACTIVE | | `INV-CUT-TIMER-SKIP-001` | A periodic cut decided from an older last cut is skipped under the capture lock: no automatic cut follows another within the interval. | M5 periodic trigger (before Admit) | `core/storage/chunk_periodic_cut.go` `CutUnlessCutSince`; `core/frontend/durable/provider_chunk.go` `chunkLoop` | `TestChunkPeriodicCut_SkipsAfterANewerCut`, `TestChunkPeriodicCut_SkipsANewerCutWithAnOlderStamp` (`core/storage/chunk_periodic_cut_test.go`); `TestWALStoreChunk_ExplicitCutOverlappingTheTimerRestartsIt` (`core/frontend/durable/provider_chunk_sched_test.go`) | — | ACTIVE | From 1378b4b2a97f57fb03aa93f147a6663b63d67a17 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 24 Nov 2026 00:21:17 -0800 Subject: [PATCH 33/35] test(durable): allow loaded-host setup in plain detach test --- .../core/frontend/durable/provider_plain_detach_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/seaweed-block/core/frontend/durable/provider_plain_detach_test.go b/seaweed-block/core/frontend/durable/provider_plain_detach_test.go index 37edd575bc..3d7986a308 100644 --- a/seaweed-block/core/frontend/durable/provider_plain_detach_test.go +++ b/seaweed-block/core/frontend/durable/provider_plain_detach_test.go @@ -113,7 +113,7 @@ func TestPlainDetachAfterPrecopyRefusalRequiresIdleFrontend(t *testing.T) { } func TestPlainDetachSkipsPrecopyCostAdmission(t *testing.T) { - ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() remote := storage.NewMemChunkRemote() p := precopyProvider(t, remote, &parkView{stubView: v1View()}) From 6411ce74e95e850badeb4885c01ef84f9d824705 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 24 Nov 2026 00:54:30 -0800 Subject: [PATCH 34/35] test: give CSI volume subprocesses private lock directories --- seaweed-block/cmd/blockcsi/main_test.go | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/seaweed-block/cmd/blockcsi/main_test.go b/seaweed-block/cmd/blockcsi/main_test.go index 5a8286d420..93269d719d 100644 --- a/seaweed-block/cmd/blockcsi/main_test.go +++ b/seaweed-block/cmd/blockcsi/main_test.go @@ -8,6 +8,7 @@ import ( "os" "os/exec" "path/filepath" + "strings" "syscall" "testing" "time" @@ -342,6 +343,7 @@ func startG15aVolume(t *testing.T, bin, art string, o g15aVolumeOpts) *g15aProc "--replica-id", o.replicaID, "--data-addr", o.dataAddr, "--ctrl-addr", o.ctrlAddr, + "--volume-lock-dir-test-only", t.TempDir(), "--durable-root", filepath.Join(art, "store-"+o.logTag), "--durable-impl", "walstore", "--durable-blocks", "256", @@ -349,6 +351,12 @@ func startG15aVolume(t *testing.T, bin, art string, o g15aVolumeOpts) *g15aProc "--heartbeat-interval", "200ms", "--t1-readiness", ) + // The test override is refused under systemd; do not inherit the test runner's invocation. + for _, kv := range os.Environ() { + if !strings.HasPrefix(kv, "INVOCATION_ID=") { + cmd.Env = append(cmd.Env, kv) + } + } if o.iscsiAddr != "" { cmd.Args = append(cmd.Args, "--iscsi-listen", o.iscsiAddr, From aba6f601f3bd3259f3efbb18f1f56f099036b3bc Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 24 Nov 2026 00:56:58 -0800 Subject: [PATCH 35/35] test: allow upload overlap startup on loaded hosts --- seaweed-block/core/storage/chunk_upload_parallel_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/seaweed-block/core/storage/chunk_upload_parallel_test.go b/seaweed-block/core/storage/chunk_upload_parallel_test.go index 99e289f0e9..3536384d51 100644 --- a/seaweed-block/core/storage/chunk_upload_parallel_test.go +++ b/seaweed-block/core/storage/chunk_upload_parallel_test.go @@ -167,7 +167,7 @@ func TestChunkUploads_FailureJoinsBeforeIntentCleanup(t *testing.T) { select { case <-r.failed: cancel() // retries are now allowed; terminate this cut explicitly - case <-time.After(time.Second): + case <-time.After(30 * time.Second): t.Fatal("uploads did not overlap") } select {