From 81e0ea739215ea282cca139862811d424fa17f14 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 15 Nov 2026 15:07:38 -0800 Subject: [PATCH 01/10] chunkstore, volume, sw-block: snapshot retention and space accounting surfaces (RED) claude05's rulings (2026-11-15 22:53Z): the surfaces and the controls, with the behavior stubbed (the planner keeps everything, the policy is not stored, usage reports nothing, no fork needs a parent, the class is neither validated nor stored). - chunkstore: snapshot class (semantic / pinned) on the snapshot; RetentionPolicy stored on the VOLUME entry (extended attributes, CAS on a revision); planRetention / Retain [dry run]; Usage (live, per-snapshot exclusive, stored bytes). - volume: GET /status/chunk?volume= (usage and policy); the snapshot route carries "class". - sw-block: ops chunk usage, ops chunk retain [--dry-run | --set-policy --keep-*], snapshot --class / --pin / --expires. - controls: policy edges (newest N with name tie-break; pinned never expired by count or age but unpinned past its expiry; semantic and labeled snapshots not exempt; younger than T and clock skew; hourly buckets; fork parent), an agent checkpointing every step stays bounded, dry run writes nothing, retain keeps N + pinned and frees names, the policy CAS, class validation, an incomplete fork's parent kept, usage from manifests; CLI usage/retain; and a real-service test against SeaweedFS (chunkstore_integration, CHUNKSTORE_WEED): N+5 snapshots plus pinned ones -> retain leaves N + pinned, accounting follows. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/cmd/sw-block/chunk.go | 38 +- seaweed-block/cmd/sw-block/chunk_retain.go | 90 ++++ .../cmd/sw-block/chunk_retain_test.go | 90 ++++ .../core/frontend/chunkstore/catalog.go | 14 +- .../core/frontend/chunkstore/retention.go | 367 ++++++++++++++++ .../chunkstore/retention_integration_test.go | 137 ++++++ .../frontend/chunkstore/retention_test.go | 406 ++++++++++++++++++ .../core/frontend/chunkstore/usage.go | 179 ++++++++ .../core/host/volume/chunk_control.go | 35 +- .../core/host/volume/chunk_control_test.go | 7 + .../core/host/volume/status_chunk_test.go | 59 +++ .../core/host/volume/status_server.go | 1 + 12 files changed, 1412 insertions(+), 11 deletions(-) create mode 100644 seaweed-block/cmd/sw-block/chunk_retain.go create mode 100644 seaweed-block/cmd/sw-block/chunk_retain_test.go create mode 100644 seaweed-block/core/frontend/chunkstore/retention.go create mode 100644 seaweed-block/core/frontend/chunkstore/retention_integration_test.go create mode 100644 seaweed-block/core/frontend/chunkstore/retention_test.go create mode 100644 seaweed-block/core/frontend/chunkstore/usage.go create mode 100644 seaweed-block/core/host/volume/status_chunk_test.go diff --git a/seaweed-block/cmd/sw-block/chunk.go b/seaweed-block/cmd/sw-block/chunk.go index 57e12fa49b..5c73ee364f 100644 --- a/seaweed-block/cmd/sw-block/chunk.go +++ b/seaweed-block/cmd/sw-block/chunk.go @@ -44,7 +44,7 @@ var dialChunkFiler = func(addr string) (chunkstore.Filer, func() error, error) { func runOpsChunk(args []string, stdout, stderr io.Writer) int { if len(args) == 0 { - return chunkFail("", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "expected cut|snapshot|snapshots|snapshot-delete|fork|detach|show", false) + return chunkFail("", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "expected cut|snapshot|snapshots|snapshot-delete|fork|detach|show|usage|retain", false) } switch args[0] { case "cut": @@ -61,6 +61,10 @@ func runOpsChunk(args []string, stdout, stderr io.Writer) int { return chunkFork(args[1:], stdout, stderr) case "show": return chunkShow(args[1:], stdout, stderr) + case "usage": + return chunkUsage(args[1:], stdout, stderr) + case "retain": + return chunkRetain(args[1:], stdout, stderr) default: return chunkFail("", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, fmt.Sprintf("unknown subcommand %q", args[0]), false) } @@ -168,9 +172,10 @@ func chunkCut(args []string, stdout, stderr io.Writer) int { func chunkSnapshot(args []string, stdout, stderr io.Writer) int { fs := chunkFlagSet("snapshot", stderr) var ( - volumeID, statusAddr, name, requestID, consistency string - expiresAtNs int64 - timeout time.Duration + volumeID, statusAddr, name, requestID, consistency, class string + expiresAtNs int64 + timeout, expires time.Duration + pin bool ) labels := labelFlags{} fs.StringVar(&volumeID, "volume", "", "volume id") @@ -178,7 +183,10 @@ func chunkSnapshot(args []string, stdout, stderr io.Writer) int { fs.StringVar(&name, "name", "", "snapshot name") fs.StringVar(&requestID, "request-id", "", "idempotency id; generated and printed when empty (reuse it to retry)") fs.StringVar(&consistency, "consistency", "crash", "crash, or app when the guest was frozen by the caller") - fs.Int64Var(&expiresAtNs, "expires-at-ns", 0, "stored for the retention policy; not enforced here") + fs.Int64Var(&expiresAtNs, "expires-at-ns", 0, "pins the snapshot until this time (unix ns); retention expires it afterwards") + fs.DurationVar(&expires, "expires", 0, "pins the snapshot for this long from now (sets --expires-at-ns)") + fs.StringVar(&class, "class", "", "retention class: semantic (an automatic checkpoint, expired by the policy) or pinned (kept until deleted)") + fs.BoolVar(&pin, "pin", false, "shorthand for --class pinned") fs.Var(labels, "label", "key=value label (repeatable)") fs.DurationVar(&timeout, "timeout", 60*time.Second, "operation bound (capped at the server's OpDeadline)") if err := fs.Parse(args); err != nil { @@ -187,12 +195,28 @@ func chunkSnapshot(args []string, stdout, stderr io.Writer) int { if volumeID == "" || statusAddr == "" || name == "" { return chunkFail("snapshot", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--volume, --status-addr and --name are required", false) } + if pin { + if class != "" && class != chunkstore.SnapshotClassPinned { + return chunkFail("snapshot", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--pin conflicts with --class "+class, false) + } + class = chunkstore.SnapshotClassPinned + } + if expires < 0 || expires > 0 && expiresAtNs != 0 { + return chunkFail("snapshot", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--expires must be positive and does not combine with --expires-at-ns", false) + } + if expires > 0 { + expiresAtNs = time.Now().Add(expires).UnixNano() + } if requestID == "" { requestID = newRequestID() fmt.Fprintf(stderr, "sw-block ops chunk snapshot: request id %s (reuse it to retry)\n", requestID) } - return chunkPost("snapshot", statusAddr, "/chunk/snapshot", timeout, map[string]any{"volumeID": volumeID, "name": name, - "requestID": requestID, "labels": map[string]string(labels), "consistency": consistency, "expiresAtNs": expiresAtNs}, stdout, stderr) + body := map[string]any{"volumeID": volumeID, "name": name, + "requestID": requestID, "labels": map[string]string(labels), "consistency": consistency, "expiresAtNs": expiresAtNs} + if class != "" { + body["class"] = class // only when set: the request otherwise keeps its spec fields + } + return chunkPost("snapshot", statusAddr, "/chunk/snapshot", timeout, body, stdout, stderr) } func chunkDetach(args []string, stdout, stderr io.Writer) int { diff --git a/seaweed-block/cmd/sw-block/chunk_retain.go b/seaweed-block/cmd/sw-block/chunk_retain.go new file mode 100644 index 0000000000..a742b6253f --- /dev/null +++ b/seaweed-block/cmd/sw-block/chunk_retain.go @@ -0,0 +1,90 @@ +package main + +import ( + "context" + "io" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/ops" +) + +// chunkUsage: sw-block ops chunk usage --volume v --chunk-filer host:port +// prints the volume's space accounting and retention policy (from +// manifests and filer listings; no chunk data reads). +func chunkUsage(args []string, stdout, stderr io.Writer) int { + fs := chunkFlagSet("usage", stderr) + var ( + volumeID, filer, base string + timeout time.Duration + ) + fs.StringVar(&volumeID, "volume", "", "volume id") + fs.StringVar(&filer, "chunk-filer", "", "SeaweedFS filer gRPC address host:port") + fs.StringVar(&base, "chunk-path", defaultChunkPathCLI, "filer directory holding one directory per volume") + fs.DurationVar(&timeout, "timeout", 60*time.Second, "filer timeout") + if err := fs.Parse(args); err != nil { + return chunkFail(chunkName(fs), stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, err.Error(), false) + } + if volumeID == "" { + return chunkFail("usage", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--volume is required", false) + } + cat, closeFn, exit := chunkCatalog("usage", filer, base, stdout, stderr) + if exit >= 0 { + return exit + } + defer closeFn() + ctx, cancel := context.WithTimeout(context.Background(), timeout) + defer cancel() + u, err := cat.Usage(ctx, volumeID) + return chunkResult("usage", u, err, stdout, stderr) +} + +// chunkRetain: sw-block ops chunk retain --volume v --chunk-filer host:port +// [--dry-run] applies the volume's retention policy (deletes the expired +// snapshots; GC reclaims their chunks). With --set-policy it stores the +// policy given by the --keep-* flags on the VOLUME entry instead. +func chunkRetain(args []string, stdout, stderr io.Writer) int { + fs := chunkFlagSet("retain", stderr) + var ( + volumeID, filer, base string + timeout, keepYounger time.Duration + dryRun, setPolicy bool + keepNewest, keepHourly, keepDaily, keepWeekly int + ) + fs.StringVar(&volumeID, "volume", "", "volume id") + fs.StringVar(&filer, "chunk-filer", "", "SeaweedFS filer gRPC address host:port") + fs.StringVar(&base, "chunk-path", defaultChunkPathCLI, "filer directory holding one directory per volume") + fs.DurationVar(&timeout, "timeout", 5*time.Minute, "bound for this pass") + fs.BoolVar(&dryRun, "dry-run", false, "list what would be deleted; write nothing") + fs.BoolVar(&setPolicy, "set-policy", false, "store the --keep-* policy on the volume instead of applying it") + fs.IntVar(&keepNewest, "keep-newest", chunkstore.DefaultKeepNewest, "with --set-policy: keep the newest N unpinned snapshots") + fs.DurationVar(&keepYounger, "keep-younger", chunkstore.DefaultKeepYounger, "with --set-policy: keep every snapshot younger than this") + fs.IntVar(&keepHourly, "keep-hourly", 0, "with --set-policy: keep the newest snapshot of each of the last N hours") + fs.IntVar(&keepDaily, "keep-daily", 0, "with --set-policy: keep the newest snapshot of each of the last N days") + fs.IntVar(&keepWeekly, "keep-weekly", 0, "with --set-policy: keep the newest snapshot of each of the last N weeks") + if err := fs.Parse(args); err != nil { + return chunkFail(chunkName(fs), stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, err.Error(), false) + } + if volumeID == "" || timeout <= 0 { + return chunkFail("retain", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--volume is required and --timeout must be positive", false) + } + if setPolicy && dryRun { + return chunkFail("retain", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--set-policy and --dry-run do not combine", false) + } + cat, closeFn, exit := chunkCatalog("retain", filer, base, stdout, stderr) + if exit >= 0 { + return exit + } + defer closeFn() + ctx, cancel := context.WithTimeout(context.Background(), timeout) + defer cancel() + if setPolicy { + p := chunkstore.RetentionPolicy{KeepNewest: keepNewest, KeepYoungerNs: int64(keepYounger), KeepHourly: keepHourly, KeepDaily: keepDaily, KeepWeekly: keepWeekly} + if err := cat.SetRetentionPolicy(ctx, volumeID, p); err != nil { + return chunkResult("retain", nil, err, stdout, stderr) + } + return chunkResult("retain", map[string]any{"volumeID": volumeID, "policy": p, "policySet": true}, nil, stdout, stderr) + } + res, err := cat.Retain(ctx, volumeID, dryRun) + return chunkResult("retain", res, err, stdout, stderr) +} diff --git a/seaweed-block/cmd/sw-block/chunk_retain_test.go b/seaweed-block/cmd/sw-block/chunk_retain_test.go new file mode 100644 index 0000000000..3623088e6c --- /dev/null +++ b/seaweed-block/cmd/sw-block/chunk_retain_test.go @@ -0,0 +1,90 @@ +package main + +import ( + "context" + "encoding/json" + "fmt" + "strings" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// snapshot --pin / --class / --expires send the retention class and the +// expiry; conflicting flags are refused before any request. +func TestOpsChunk_SnapshotPinAndExpires(t *testing.T) { + srv, got := chunkServer(t, 200, `{"volumeID":"v1","name":"s1"}`) + before := time.Now() + if code, _, errs := runChunk("snapshot", "--volume", "v1", "--status-addr", srv.URL, "--name", "s1", "--request-id", "r", "--pin", "--expires", "1h"); code != 0 { + t.Fatalf("snapshot --pin --expires: %d %q", code, errs) + } + body := (*got)[0].body + exp, _ := body["expiresAtNs"].(float64) + if body["class"] != chunkstore.SnapshotClassPinned || exp < float64(before.Add(time.Hour).UnixNano())-1e9 { + t.Fatalf("pinned request: %+v", body) + } + for _, args := range [][]string{ + {"--pin", "--class", "semantic"}, + {"--expires", "1h", "--expires-at-ns", "5"}, + {"--expires", "-1s"}, + } { + a := append([]string{"snapshot", "--volume", "v1", "--status-addr", srv.URL, "--name", "s2"}, args...) + if code, out, _ := runChunk(a...); code == 0 || !strings.Contains(out, codeBadRequestCLI) { + t.Fatalf("snapshot %v: exit %d %q; want a bad request", args, code, out) + } + } + if len(*got) != 1 { + t.Fatalf("refused flags still sent requests: %d", len(*got)) + } +} + +// usage and retain run catalog-direct against the filer: set a policy, +// dry-run, apply, and see the accounting follow. +func TestOpsChunk_UsageAndRetain(t *testing.T) { + ctx := context.Background() + mem := chunkstore.NewMemFiler() + prev := dialChunkFiler + dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { return mem, func() error { return nil }, nil } + t.Cleanup(func() { dialChunkFiler = prev }) + cat, err := chunkstore.NewCatalog(mem, defaultChunkPathCLI) + if err != nil { + t.Fatal(err) + } + if _, err := cat.EnsureVolume(ctx, "v1", chunkstore.Geometry{NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 8}); err != nil { + t.Fatal(err) + } + old := time.Now().Add(-48 * time.Hour) + cat.SetClock(func() time.Time { return old }) + head := storage.ChunkHead{Gen: 2, Epoch: 1, Holder: "s1/r1", RemoteLSN: 42, State: storage.ChunkHeadActive, + Chunks: map[uint64]storage.ChunkRef{0: {Key: "chunks/e1/c0/k"}}} + for i := 0; i < 5; i++ { + if _, err := cat.CreateSnapshot(ctx, "v1", chunkstore.SnapshotRequest{Name: fmt.Sprintf("s%d", i), RequestID: fmt.Sprintf("r%d", i), Class: chunkstore.SnapshotClassSemantic}, head); err != nil { + t.Fatal(err) + } + } + + filer := []string{"--volume", "v1", "--chunk-filer", "filer:18888"} + if code, out, errs := runChunk(append([]string{"retain", "--set-policy", "--keep-newest", "2", "--keep-younger", "1m"}, filer...)...); code != 0 || !strings.Contains(out, `"policySet":true`) { + t.Fatalf("set policy: %d %q %q", code, out, errs) + } + code, out, errs := runChunk(append([]string{"retain", "--dry-run"}, filer...)...) + var dry chunkstore.RetentionResult + if code != 0 || json.Unmarshal([]byte(out), &dry) != nil || !dry.DryRun || dry.Expired != 3 || len(dry.Deleted) != 0 { + t.Fatalf("dry run: %d %q %q", code, out, errs) + } + code, out, errs = runChunk(append([]string{"retain"}, filer...)...) + var applied chunkstore.RetentionResult + if code != 0 || json.Unmarshal([]byte(out), &applied) != nil || len(applied.Deleted) != 3 || applied.Kept != 2 { + t.Fatalf("retain: %d %q %q", code, out, errs) + } + code, out, errs = runChunk(append([]string{"usage"}, filer...)...) + var u chunkstore.VolumeUsage + if code != 0 || json.Unmarshal([]byte(out), &u) != nil || len(u.Snapshots) != 2 || u.Policy.KeepNewest != 2 || !u.PolicySet { + t.Fatalf("usage: %d %q %q", code, out, errs) + } + if code, out, _ := runChunk("retain", "--volume", "v1", "--chunk-filer", "f:1", "--set-policy", "--dry-run"); code == 0 || !strings.Contains(out, codeBadRequestCLI) { + t.Fatalf("--set-policy --dry-run: %d %q; want a bad request", code, out) + } +} diff --git a/seaweed-block/core/frontend/chunkstore/catalog.go b/seaweed-block/core/frontend/chunkstore/catalog.go index b70e17d002..6f643676ea 100644 --- a/seaweed-block/core/frontend/chunkstore/catalog.go +++ b/seaweed-block/core/frontend/chunkstore/catalog.go @@ -196,6 +196,9 @@ type snapDoc struct { Parent *Parent `json:"parent"` Labels map[string]string `json:"labels"` ExpiresAtNs int64 `json:"expires_at_ns"` + // Class is the retention class: "semantic", "pinned", or "" for a + // snapshot made before classes existed (see retention.go). + Class string `json:"class,omitempty"` } // SnapshotInfo describes one snapshot, with the field names of the HTTP API @@ -215,6 +218,7 @@ type SnapshotInfo struct { Parent *Parent `json:"parent"` ExpiresAtNs int64 `json:"expiresAtNs"` Replayed bool `json:"replayed"` + Class string `json:"class"` head storage.ChunkHead geo Geometry @@ -231,6 +235,9 @@ type SnapshotRequest struct { Consistency string // "crash" (default) or "app" ExpiresAtNs int64 CreatedBy string + // Class is the retention class: "semantic" or "pinned" ("" leaves it + // unset, which retention treats as unpinned). + Class string // SourceReadAt is when the caller obtained the HEAD it snapshots (the // cut's return); OpDeadline counts from it. Zero means now. SourceReadAt time.Time @@ -651,7 +658,7 @@ func decodeSnap(p string, e *filerpb.Entry) (SnapshotInfo, string, error) { VolumeID: doc.VolumeID, Name: doc.Name, HeadGen: head.Gen, HeadEpoch: head.Epoch, CutLSN: head.RemoteLSN, CreatedNs: doc.CreatedNs, State: state, ChunkCount: len(head.Chunks), ManifestBytes: len(e.GetContent()), Consistency: doc.Consistency, Labels: doc.Labels, Parent: doc.Parent, ExpiresAtNs: doc.ExpiresAtNs, - head: head, geo: doc.Geometry, + Class: doc.Class, head: head, geo: doc.Geometry, }, doc.RequestID, nil } @@ -801,6 +808,9 @@ func (c *Catalog) CreateSnapshot(ctx context.Context, vol string, req SnapshotRe if consistency == "" { consistency = "crash" } + if err := validSnapshotClass(req.Class); err != nil { + return SnapshotInfo{}, err + } if head.Gen == 0 { return SnapshotInfo{}, catErr(CodeNotChunkVolume, false, nil, "volume %s has no published HEAD to snapshot", vol) } @@ -824,7 +834,7 @@ func (c *Catalog) CreateSnapshot(ctx context.Context, vol string, req SnapshotRe } doc := snapDoc{Format: snapFormat, VolumeID: vol, Name: req.Name, RequestID: req.RequestID, CreatedNs: c.now().UnixNano(), CreatedBy: req.CreatedBy, Consistency: consistency, Head: headEnt.Content, Geometry: v.Geometry, Parent: v.Parent, - Labels: req.Labels, ExpiresAtNs: req.ExpiresAtNs} + Labels: req.Labels, ExpiresAtNs: req.ExpiresAtNs, Class: ""} // RED: class not stored body, err := json.Marshal(doc) if err != nil { return SnapshotInfo{}, err diff --git a/seaweed-block/core/frontend/chunkstore/retention.go b/seaweed-block/core/frontend/chunkstore/retention.go new file mode 100644 index 0000000000..a02b920712 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/retention.go @@ -0,0 +1,367 @@ +package chunkstore + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "sort" + "strconv" + "time" + + "google.golang.org/protobuf/proto" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// Snapshot retention (claude05's rulings, 2026-11-15 22:53Z). +// +// A snapshot has a class, stored with it: +// - "semantic": an automatic checkpoint (e.g. an agent's per-step +// checkpoint). Governed by count, age and the log-spaced keeps. +// - "pinned": an explicit keep. It is never expired by count or age, +// only by its own ExpiresAtNs or an explicit delete. A snapshot with +// ExpiresAtNs set is pinned whatever its class. +// - "" (snapshots made before classes existed): treated as unpinned. +// +// The policy is stored on the VOLUME entry. Retain keeps +// +// newest KeepNewest unpinned +// + every pinned snapshot not yet past its ExpiresAtNs +// + every snapshot younger than KeepYounger (a creation time in the +// future, from clock skew, counts as young) +// + the log-spaced keeps: the newest snapshot of each of the last +// KeepHourly hours, KeepDaily days and KeepWeekly weeks +// + every snapshot a fork still needs (named by a volume's fork record +// while that volume has no real published HEAD yet) +// +// and deletes every other snapshot through DeleteSnapshot (attempt-scoped +// tombstone rules: HEAD is never touched, the name is freed, the attempt +// path stays). A pinned snapshot past its ExpiresAtNs is treated as +// unpinned. GC reclaims the chunks. + +const ( + SnapshotClassSemantic = "semantic" + SnapshotClassPinned = "pinned" + + CodeInvalidClass = "invalid_class" + CodeInvalidPolicy = "invalid_policy" + + DefaultKeepNewest = 10 + DefaultKeepYounger = time.Hour + + extRetention = "retention" + extRetentionRev = "retention_rev" +) + +func validSnapshotClass(class string) error { + if red := true; red { // RED: no validation + return nil + } + switch class { + case "", SnapshotClassSemantic, SnapshotClassPinned: + return nil + } + return catErr(CodeInvalidClass, false, nil, "snapshot class %q: want %q or %q", class, SnapshotClassSemantic, SnapshotClassPinned) +} + +// Pinned reports whether the snapshot is an explicit keep. +func (s SnapshotInfo) Pinned() bool { + return s.Class == SnapshotClassPinned || s.ExpiresAtNs > 0 +} + +// RetentionPolicy is a volume's snapshot retention policy. +type RetentionPolicy struct { + KeepNewest int `json:"keepNewest"` + KeepYoungerNs int64 `json:"keepYoungerNs"` + KeepHourly int `json:"keepHourly"` + KeepDaily int `json:"keepDaily"` + KeepWeekly int `json:"keepWeekly"` +} + +// DefaultRetentionPolicy is the policy of a volume that never set one. +func DefaultRetentionPolicy() RetentionPolicy { + return RetentionPolicy{KeepNewest: DefaultKeepNewest, KeepYoungerNs: int64(DefaultKeepYounger)} +} + +func (p RetentionPolicy) validate() error { + if p.KeepNewest < 0 || p.KeepYoungerNs < 0 || p.KeepHourly < 0 || p.KeepDaily < 0 || p.KeepWeekly < 0 { + return catErr(CodeInvalidPolicy, false, nil, "retention policy %+v: counts and durations must not be negative", p) + } + return nil +} + +// ReadRetentionPolicy returns vol's policy; set is false (and the policy +// is DefaultRetentionPolicy) when none was ever set. +func (c *Catalog) ReadRetentionPolicy(ctx context.Context, vol string) (RetentionPolicy, bool, error) { + e, _, err := c.volumeEntry(ctx, vol) + if err != nil { + return RetentionPolicy{}, false, err + } + return decodeRetention(e) +} + +func decodeRetention(e *filerpb.Entry) (RetentionPolicy, bool, error) { + raw := e.Extended[extRetention] + if len(raw) == 0 { + return DefaultRetentionPolicy(), false, nil + } + var p RetentionPolicy + if err := json.Unmarshal(raw, &p); err != nil { + return RetentionPolicy{}, false, catErr(CodeInvalidPolicy, false, err, "stored retention policy is unreadable") + } + return p, true, nil +} + +// volumeEntry reads vol's VOLUME entry; a volume without one is +// not_chunk_volume. +func (c *Catalog) volumeEntry(ctx context.Context, vol string) (*filerpb.Entry, string, error) { + root, err := c.volRoot(vol) + if err != nil { + return nil, "", err + } + e, err := c.f.LookupEntry(ctx, root, volumeName) + if errors.Is(err, ErrNotFound) { + return nil, "", catErr(CodeNotChunkVolume, false, nil, "volume %s has no VOLUME entry", vol) + } + if err != nil { + return nil, "", remoteErr(err, "read VOLUME of %s", vol) + } + return e, root, nil +} + +// SetRetentionPolicy stores p on vol's VOLUME entry. Only the policy's +// extended attributes change; the volume document is untouched. The update +// is conditional on the policy revision read, so of two concurrent setters +// one wins and the other gets a retryable remote error. +func (c *Catalog) SetRetentionPolicy(ctx context.Context, vol string, p RetentionPolicy) error { + if red := true; red { // RED: stores nothing + return nil + } + if err := p.validate(); err != nil { + return err + } + e, root, err := c.volumeEntry(ctx, vol) + if err != nil { + return err + } + rev := string(e.Extended[extRetentionRev]) + n, _ := strconv.ParseUint(rev, 10, 64) + body, err := json.Marshal(p) + if err != nil { + return err + } + next := proto.Clone(e).(*filerpb.Entry) + if next.Extended == nil { + next.Extended = map[string][]byte{} + } + next.Extended[extRetention] = body + next.Extended[extRetentionRev] = []byte(strconv.FormatUint(n+1, 10)) + if err := c.f.UpdateEntry(ctx, root, next, map[string][]byte{extRetentionRev: []byte(rev)}); err != nil { + return remoteErr(err, "set the retention policy of %s", vol) + } + return nil +} + +// RetentionDecision is one snapshot's fate under a policy. +type RetentionDecision struct { + Name string `json:"name"` + CreatedNs int64 `json:"createdNs"` + Class string `json:"class"` + Pinned bool `json:"pinned"` + Keep bool `json:"keep"` + Reasons []string `json:"reasons"` // why it is kept; "expired" when it goes +} + +// The reasons a snapshot is kept. +const ( + keepNewest = "newest" + keepPinned = "pinned" + keepYoung = "younger_than_policy" + keepHourly = "hourly" + keepDaily = "daily" + keepWeekly = "weekly" + keepForkParent = "fork_parent" + reasonExpired = "expired" +) + +// planRetention decides, from one listing, which snapshots policy keeps at +// now. needed names the snapshots a fork still needs. Unpinned snapshots +// are ranked newest first; equal creation times rank by name, so the plan +// is deterministic. +func planRetention(p RetentionPolicy, snaps []SnapshotInfo, needed map[string]bool, now time.Time) []RetentionDecision { + if red := true; red { // RED: keeps everything + out := make([]RetentionDecision, len(snaps)) + for i, s := range snaps { + out[i] = RetentionDecision{Name: s.Name, Keep: true, Reasons: []string{"red"}} + } + return out + } + ordered := append([]SnapshotInfo(nil), snaps...) + sort.SliceStable(ordered, func(i, j int) bool { + if ordered[i].CreatedNs != ordered[j].CreatedNs { + return ordered[i].CreatedNs > ordered[j].CreatedNs + } + return ordered[i].Name < ordered[j].Name + }) + nowNs := now.UnixNano() + out := make([]RetentionDecision, len(ordered)) + unpinned := 0 + buckets := map[string]bool{} + for i, s := range ordered { + pinned := s.Pinned() && (s.ExpiresAtNs == 0 || nowNs < s.ExpiresAtNs) + d := RetentionDecision{Name: s.Name, CreatedNs: s.CreatedNs, Class: s.Class, Pinned: pinned} + if pinned { + d.Reasons = append(d.Reasons, keepPinned) + } else { + if unpinned < p.KeepNewest { + d.Reasons = append(d.Reasons, keepNewest) + } + unpinned++ + } + age := time.Duration(nowNs - s.CreatedNs) + if age < time.Duration(p.KeepYoungerNs) { + d.Reasons = append(d.Reasons, keepYoung) + } + for _, lk := range []struct { + reason string + period time.Duration + count int + }{ + {keepHourly, time.Hour, p.KeepHourly}, + {keepDaily, 24 * time.Hour, p.KeepDaily}, + {keepWeekly, 7 * 24 * time.Hour, p.KeepWeekly}, + } { + if lk.count <= 0 || age < 0 { + continue + } + ago := int64(age / lk.period) // 0 = the current period + if ago >= int64(lk.count) { + continue + } + key := fmt.Sprintf("%s/%d", lk.reason, s.CreatedNs/int64(lk.period)) + if !buckets[key] { // ordered newest first: the first seen is the bucket's newest + buckets[key] = true + d.Reasons = append(d.Reasons, lk.reason) + } + } + if needed[s.Name] { + d.Reasons = append(d.Reasons, keepForkParent) + } + d.Keep = len(d.Reasons) > 0 + if !d.Keep { + d.Reasons = []string{reasonExpired} + } + out[i] = d + } + return out +} + +// RetentionResult is the outcome of one Retain pass. +type RetentionResult struct { + VolumeID string `json:"volumeID"` + Policy RetentionPolicy `json:"policy"` + PolicySet bool `json:"policySet"` + DryRun bool `json:"dryRun"` + Decisions []RetentionDecision `json:"decisions"` + Deleted []string `json:"deleted"` // names deleted (empty on a dry run) + Kept int `json:"kept"` + Expired int `json:"expired"` +} + +// Retain applies vol's retention policy at the catalog clock's now. A dry +// run plans and writes nothing. Otherwise every expired snapshot is +// deleted through DeleteSnapshot; a snapshot that is already gone counts +// as deleted, and the first other failure stops the pass and is returned +// with what was deleted so far. +func (c *Catalog) Retain(ctx context.Context, vol string, dryRun bool) (RetentionResult, error) { + e, _, err := c.volumeEntry(ctx, vol) + if err != nil { + return RetentionResult{}, err + } + p, set, err := decodeRetention(e) + if err != nil { + return RetentionResult{}, err + } + snaps, err := c.allSnapshots(ctx, vol) + if err != nil { + return RetentionResult{}, err + } + needed, err := c.forkParentsNeeded(ctx, vol) + if err != nil { + return RetentionResult{}, err + } + res := RetentionResult{VolumeID: vol, Policy: p, PolicySet: set, DryRun: dryRun, Deleted: []string{}} + res.Decisions = planRetention(p, snaps, needed, c.now()) + for _, d := range res.Decisions { + if d.Keep { + res.Kept++ + continue + } + res.Expired++ + if dryRun { + continue + } + if _, err := c.DeleteSnapshot(ctx, vol, d.Name); err != nil && CodeOf(err) != CodeSnapshotNotFound { + return res, err + } + res.Deleted = append(res.Deleted, d.Name) + } + return res, nil +} + +// allSnapshots lists every published, not-deleting snapshot of vol. +func (c *Catalog) allSnapshots(ctx context.Context, vol string) ([]SnapshotInfo, error) { + var out []SnapshotInfo + after := "" + for { + page, next, err := c.ListSnapshots(ctx, vol, ListOptions{StartAfter: after, Limit: maxListLimit}) + if err != nil { + return nil, err + } + out = append(out, page...) + if next == "" { + return out, nil + } + if next <= after { + return nil, errors.New("chunkstore: non-advancing snapshot listing") + } + after = next + } +} + +// forkParentsNeeded names the snapshots of vol a fork still needs: a +// volume whose fork record names vol and the snapshot, and which has no +// real published HEAD yet (absent or aborted). A published fork HEAD pins +// its chunks for GC itself, so it no longer needs the snapshot. +func (c *Catalog) forkParentsNeeded(ctx context.Context, vol string) (map[string]bool, error) { + if red := true; red { // RED: no fork needs a parent + return map[string]bool{}, nil + } + vols, err := c.ListVolumes(ctx) + if err != nil { + return nil, err + } + needed := map[string]bool{} + for _, other := range vols { + if other == vol { + continue + } + v, ok, err := c.ReadVolume(ctx, other) + if err != nil { + return nil, err + } + if !ok || v.Fork == nil || v.Fork.Source != vol { + continue + } + h, has, err := c.ReadHead(ctx, other) + if err != nil { + return nil, err + } + if !has || h.State == storage.ChunkHeadAborted { + needed[v.Fork.Snapshot] = true + } + } + return needed, nil +} diff --git a/seaweed-block/core/frontend/chunkstore/retention_integration_test.go b/seaweed-block/core/frontend/chunkstore/retention_integration_test.go new file mode 100644 index 0000000000..54c01cae93 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/retention_integration_test.go @@ -0,0 +1,137 @@ +//go:build chunkstore_integration + +package chunkstore + +import ( + "bytes" + "context" + "fmt" + "path" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// Retention and accounting against a real SeaweedFS (CHUNKSTORE_WEED): +// N+5 semantic snapshots plus pinned ones; a dry run writes nothing; retain +// leaves N plus the pinned; accounting follows (GC not run: the deleted +// snapshots' chunks are still stored, now unreferenced). +func TestIntegration_RetainAndUsage(t *testing.T) { + c := startWeed(t) + ctx := context.Background() + const base = "/swblock/chunks" + geo := Geometry{NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 8} + full := uint64(geo.ChunkBlocks) * uint64(geo.BlockSize) + cat, err := NewCatalog(c.client(t, base), base) + if err != nil { + t.Fatal(err) + } + if _, err := cat.EnsureVolume(ctx, "v1", geo); err != nil { + t.Fatal(err) + } + r := c.remote(t, path.Join(base, "v1")) + clock := time.Now().Add(-72 * time.Hour) + cat.SetClock(func() time.Time { return clock }) + + // One snapshot per step; each step rewrites chunk 0 under a new key, + // so every snapshot but the newest owns one chunk exclusively. + cur, err := r.GetHead(ctx) + if err != nil { + t.Fatal(err) + } + step := 0 + snapshot := func(name, class string) { + t.Helper() + data := bytes.Repeat([]byte{byte(step + 1)}, int(full)) + key := fmt.Sprintf("chunks/e1/c0/step-%02d", step) + step++ + if err := r.Put(ctx, key, data); err != nil { + t.Fatal(err) + } + next := storage.ChunkHead{Epoch: 1, Holder: "h1", RemoteLSN: uint64(step), Chunks: map[uint64]storage.ChunkRef{0: ref(key, data)}} + gen, err := r.CASHead(ctx, storage.ChunkHeadVersion{Gen: cur.Gen, Epoch: cur.Epoch}, next) + if err != nil { + t.Fatal(err) + } + next.Gen = gen + cur = next + clock = clock.Add(time.Minute) + if _, err := cat.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: name, RequestID: "r-" + name, Class: class}, next); err != nil { + t.Fatal(err) + } + } + snapshot("golden-a", SnapshotClassPinned) // the oldest, but pinned + snapshot("golden-b", SnapshotClassPinned) + const n = DefaultKeepNewest + for i := 0; i < n+5; i++ { + snapshot(fmt.Sprintf("s%02d", i), SnapshotClassSemantic) + } + clock = time.Now() + + before, err := cat.Usage(ctx, "v1") + if err != nil { + t.Fatal(err) + } + if len(before.Snapshots) != n+7 || before.StoredBindings != n+7 || before.StoredUpperBound || before.LiveBytes != full { + t.Fatalf("before: %d snapshots, %d bindings, upper=%t, live=%d", len(before.Snapshots), before.StoredBindings, before.StoredUpperBound, before.LiveBytes) + } + exclusive := func(u VolumeUsage) uint64 { + var sum uint64 + for _, s := range u.Snapshots { + sum += s.ExclusiveBytes + } + return sum + } + if got := exclusive(before); got != uint64(n+6)*full { + t.Fatalf("before: exclusive %d, want %d (all but the newest snapshot)", got, uint64(n+6)*full) + } + + // Dry run: exactly the 5 oldest semantic snapshots, nothing written. + namesBefore, err := c.client(t, base).ListEntries(ctx, path.Join(base, "v1", snapNamesDir), "", "", 0) + if err != nil { + t.Fatal(err) + } + dry, err := cat.Retain(ctx, "v1", true) + if err != nil { + t.Fatal(err) + } + var wouldGo []string + for _, d := range dry.Decisions { + if !d.Keep { + wouldGo = append(wouldGo, d.Name) + } + } + if fmt.Sprint(wouldGo) != "[s04 s03 s02 s01 s00]" || len(dry.Deleted) != 0 { + t.Fatalf("dry run: would delete %v, deleted %v", wouldGo, dry.Deleted) + } + namesAfter, err := c.client(t, base).ListEntries(ctx, path.Join(base, "v1", snapNamesDir), "", "", 0) + if err != nil || len(namesAfter) != len(namesBefore) { + t.Fatalf("dry run changed the name records: %d -> %d (%v)", len(namesBefore), len(namesAfter), err) + } + + res, err := cat.Retain(ctx, "v1", false) + if err != nil { + t.Fatal(err) + } + if len(res.Deleted) != 5 || res.Kept != n+2 { + t.Fatalf("retain: deleted %v, kept %d", res.Deleted, res.Kept) + } + after, err := cat.Usage(ctx, "v1") + if err != nil { + t.Fatal(err) + } + left := map[string]bool{} + for _, s := range after.Snapshots { + left[s.Name] = true + } + if len(after.Snapshots) != n+2 || !left["golden-a"] || !left["golden-b"] || left["s04"] || !left["s05"] { + t.Fatalf("after: snapshots %v", left) + } + if got := exclusive(after); got != uint64(n+1)*full { + t.Fatalf("after: exclusive %d, want %d", got, uint64(n+1)*full) + } + if after.StoredBindings != n+7 || !after.StoredUpperBound { + t.Fatalf("after: %d bindings, upper=%t; want all still stored (no GC yet), flagged as an upper bound", after.StoredBindings, after.StoredUpperBound) + } +} diff --git a/seaweed-block/core/frontend/chunkstore/retention_test.go b/seaweed-block/core/frontend/chunkstore/retention_test.go new file mode 100644 index 0000000000..1ade148d81 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/retention_test.go @@ -0,0 +1,406 @@ +package chunkstore + +import ( + "context" + "crypto/sha256" + "fmt" + "path" + "strings" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// Snapshot retention and space accounting (claude05's rulings +// 2026-11-15 22:53Z): policy edges, dry run, forks, accounting. + +var retBase = time.Unix(1_000_000, 0) + +func snapAt(name string, at time.Time, class string, expiresAt time.Time, labels map[string]string) SnapshotInfo { + s := SnapshotInfo{Name: name, CreatedNs: at.UnixNano(), Class: class, Labels: labels} + if !expiresAt.IsZero() { + s.ExpiresAtNs = expiresAt.UnixNano() + } + return s +} + +func kept(ds []RetentionDecision) map[string][]string { + out := map[string][]string{} + for _, d := range ds { + if d.Keep { + out[d.Name] = d.Reasons + } + } + return out +} + +func noYoung() RetentionPolicy { return RetentionPolicy{KeepNewest: 10} } + +// Newest N unpinned are kept; equal creation times rank by name. +func TestPlanRetention_NewestNWithNameTieBreak(t *testing.T) { + now := retBase.Add(48 * time.Hour) + var snaps []SnapshotInfo + for i := 0; i < 15; i++ { + snaps = append(snaps, snapAt(fmt.Sprintf("s%02d", i), retBase.Add(time.Duration(i)*time.Minute), SnapshotClassSemantic, time.Time{}, nil)) + } + k := kept(planRetention(noYoung(), snaps, nil, now)) + if len(k) != 10 { + t.Fatalf("kept %d, want 10: %v", len(k), k) + } + for i := 5; i < 15; i++ { + if _, ok := k[fmt.Sprintf("s%02d", i)]; !ok { + t.Fatalf("newest s%02d not kept: %v", i, k) + } + } + tie := []SnapshotInfo{snapAt("b", retBase, "", time.Time{}, nil), snapAt("a", retBase, "", time.Time{}, nil)} + if k := kept(planRetention(RetentionPolicy{KeepNewest: 1}, tie, nil, now)); len(k) != 1 || k["a"] == nil { + t.Fatalf("tie: kept %v, want only a (name order)", k) + } +} + +// Pinned: never expired by count or age; past its ExpiresAtNs it is +// unpinned again. Semantic and labeled snapshots are not exempt. +func TestPlanRetention_PinnedSemanticAndLabels(t *testing.T) { + now := retBase.Add(48 * time.Hour) + snaps := []SnapshotInfo{ + snapAt("pinned-old", retBase, SnapshotClassPinned, time.Time{}, nil), + snapAt("pinned-by-expiry", retBase, "", now.Add(time.Hour), nil), + snapAt("pinned-expired", retBase, SnapshotClassPinned, now.Add(-time.Second), nil), + snapAt("semantic-old", retBase, SnapshotClassSemantic, time.Time{}, nil), + snapAt("labeled-old", retBase, "", time.Time{}, map[string]string{"agent.step": "npm-ci"}), + } + k := kept(planRetention(RetentionPolicy{}, snaps, nil, now)) + if len(k) != 2 || k["pinned-old"] == nil || k["pinned-by-expiry"] == nil { + t.Fatalf("kept %v; want exactly pinned-old and pinned-by-expiry", k) + } +} + +// Younger than T is kept beyond N; a creation time in the future (clock +// skew) counts as young. +func TestPlanRetention_YoungAndClockSkew(t *testing.T) { + now := retBase.Add(48 * time.Hour) + p := RetentionPolicy{KeepNewest: 0, KeepYoungerNs: int64(time.Hour)} + snaps := []SnapshotInfo{ + snapAt("young", now.Add(-30*time.Minute), SnapshotClassSemantic, time.Time{}, nil), + snapAt("future", now.Add(10*time.Minute), SnapshotClassSemantic, time.Time{}, nil), + snapAt("old", now.Add(-2*time.Hour), SnapshotClassSemantic, time.Time{}, nil), + } + k := kept(planRetention(p, snaps, nil, now)) + if len(k) != 2 || k["young"] == nil || k["future"] == nil { + t.Fatalf("kept %v; want young and future", k) + } +} + +// Log-spaced keeps: the newest snapshot of each of the last H hours. +func TestPlanRetention_HourlyBuckets(t *testing.T) { + now := retBase.Add(48*time.Hour + 59*time.Minute) // late in an hour + var snaps []SnapshotInfo + for i := 0; i < 12; i++ { // every 30 min over the last 6 hours + snaps = append(snaps, snapAt(fmt.Sprintf("s%02d", i), now.Add(-time.Duration(i)*30*time.Minute), SnapshotClassSemantic, time.Time{}, nil)) + } + k := kept(planRetention(RetentionPolicy{KeepHourly: 3}, snaps, nil, now)) + if len(k) != 3 { + t.Fatalf("kept %d, want 3 (one per hour for the last 3 hours): %v", len(k), k) + } + for _, reasons := range k { + if len(reasons) != 1 || reasons[0] != keepHourly { + t.Fatalf("reasons %v; want hourly", reasons) + } + } +} + +// A snapshot a fork still needs is kept whatever the policy says. +func TestPlanRetention_ForkParentKept(t *testing.T) { + now := retBase.Add(48 * time.Hour) + snaps := []SnapshotInfo{snapAt("parent", retBase, SnapshotClassSemantic, time.Time{}, nil)} + k := kept(planRetention(RetentionPolicy{}, snaps, map[string]bool{"parent": true}, now)) + if len(k) != 1 || k["parent"][0] != keepForkParent { + t.Fatalf("kept %v; want parent (fork_parent)", k) + } +} + +// An agent that checkpoints every step stays bounded: one semantic +// snapshot a minute for a day keeps at most N + T/step + hourly buckets. +func TestPlanRetention_AgentCheckpointingEveryStepStaysBounded(t *testing.T) { + p := RetentionPolicy{KeepNewest: DefaultKeepNewest, KeepYoungerNs: int64(DefaultKeepYounger), KeepHourly: 24} + start := retBase + var snaps []SnapshotInfo + for i := 0; i < 24*60; i++ { + snaps = append(snaps, snapAt(fmt.Sprintf("step-%05d", i), start.Add(time.Duration(i)*time.Minute), SnapshotClassSemantic, time.Time{}, map[string]string{"agent.step": fmt.Sprint(i)})) + } + now := start.Add(24 * time.Hour) + bound := p.KeepNewest + int(DefaultKeepYounger/time.Minute) + p.KeepHourly + if k := kept(planRetention(p, snaps, nil, now)); len(k) > bound { + t.Fatalf("kept %d of %d step checkpoints; want at most %d", len(k), len(snaps), bound) + } + // The bound holds however long the agent runs. + for i := 24 * 60; i < 7*24*60; i++ { + snaps = append(snaps, snapAt(fmt.Sprintf("step-%05d", i), start.Add(time.Duration(i)*time.Minute), SnapshotClassSemantic, time.Time{}, nil)) + } + if k := kept(planRetention(p, snaps, nil, start.Add(7*24*time.Hour))); len(k) > bound { + t.Fatalf("after a week: kept %d; want at most %d", len(k), bound) + } +} + +// retentionFixture makes n semantic snapshots of v1, one a minute, two +// days before the catalog clock's now. +func retentionFixture(t *testing.T, n int) (*fakeFiler, *Catalog, storage.ChunkHead, *time.Time) { + t.Helper() + f, _, c, h := catalogFixture(t) + clock := retBase + c.SetClock(func() time.Time { return clock }) + for i := 0; i < n; i++ { + clock = retBase.Add(time.Duration(i) * time.Minute) + if _, err := c.CreateSnapshot(context.Background(), "v1", SnapshotRequest{Name: fmt.Sprintf("s%02d", i), RequestID: fmt.Sprintf("r%02d", i), Class: SnapshotClassSemantic}, h); err != nil { + t.Fatal(err) + } + } + clock = retBase.Add(48 * time.Hour) + return f, c, h, &clock +} + +func snapNames(t *testing.T, c *Catalog) map[string]bool { + t.Helper() + snaps, err := c.allSnapshots(context.Background(), "v1") + if err != nil { + t.Fatal(err) + } + out := map[string]bool{} + for _, s := range snaps { + out[s.Name] = true + } + return out +} + +// A dry run lists exactly what would go and writes nothing. +func TestCatalog_RetainDryRunWritesNothing(t *testing.T) { + f, c, _, _ := retentionFixture(t, 15) + before := len(f.allWritten()) + res, err := c.Retain(context.Background(), "v1", true) + if err != nil { + t.Fatal(err) + } + if got := len(f.allWritten()); got != before { + t.Fatalf("dry run wrote %d entries", got-before) + } + var expired []string + for _, d := range res.Decisions { + if !d.Keep { + expired = append(expired, d.Name) + } + } + if res.Expired != 5 || res.Kept != 10 || len(res.Deleted) != 0 || strings.Join(expired, ",") != "s04,s03,s02,s01,s00" { + t.Fatalf("dry run: expired=%d kept=%d deleted=%v names=%v; want the 5 oldest listed, none deleted", res.Expired, res.Kept, res.Deleted, expired) + } + if len(snapNames(t, c)) != 15 { + t.Fatal("dry run removed snapshots") + } +} + +// Retain deletes the expired snapshots, keeps N plus the pinned one, and +// frees the expired names. +func TestCatalog_RetainKeepsNewestNAndPinned(t *testing.T) { + _, c, h, clock := retentionFixture(t, 15) + ctx := context.Background() + saved := *clock + *clock = retBase.Add(-time.Hour) // the oldest snapshot of all, but pinned + if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "golden", RequestID: "rg", Class: SnapshotClassPinned}, h); err != nil { + t.Fatal(err) + } + *clock = saved + res, err := c.Retain(ctx, "v1", false) + if err != nil { + t.Fatal(err) + } + names := snapNames(t, c) + if len(res.Deleted) != 5 || len(names) != 11 || !names["golden"] || names["s00"] || !names["s14"] { + t.Fatalf("after retain: deleted=%v remaining=%v; want 5 deleted, s05..s14 and golden left", res.Deleted, names) + } + if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s00", RequestID: "reuse"}, h); err != nil { + t.Fatalf("expired name not freed: %v", err) + } +} + +// The policy lives on the VOLUME entry: default until set; set stores it +// without touching the volume document; negatives are refused. +func TestCatalog_RetentionPolicyStoredOnVolume(t *testing.T) { + _, _, c, _ := catalogFixture(t) + ctx := context.Background() + p, set, err := c.ReadRetentionPolicy(ctx, "v1") + if err != nil || set || p != DefaultRetentionPolicy() { + t.Fatalf("unset policy: %+v set=%t err=%v; want the default", p, set, err) + } + want := RetentionPolicy{KeepNewest: 3, KeepYoungerNs: int64(time.Minute), KeepDaily: 7} + if err := c.SetRetentionPolicy(ctx, "v1", want); err != nil { + t.Fatal(err) + } + if p, set, err := c.ReadRetentionPolicy(ctx, "v1"); err != nil || !set || p != want { + t.Fatalf("stored policy: %+v set=%t err=%v", p, set, err) + } + if v, ok, err := c.ReadVolume(ctx, "v1"); err != nil || !ok || v.Geometry != catGeo { + t.Fatalf("volume after setting a policy: %+v %t %v", v, ok, err) + } + if err := c.SetRetentionPolicy(ctx, "v1", RetentionPolicy{KeepNewest: -1}); CodeOf(err) != CodeInvalidPolicy { + t.Fatalf("negative policy: %v; want invalid_policy", err) + } +} + +// Two setters racing on one revision: the second update's precondition +// fails. +func TestCatalog_RetentionPolicyConcurrentSetIsConditional(t *testing.T) { + f, _, c, _ := catalogFixture(t) + ctx := context.Background() + f.failUpdate = func(p string) error { + if p == path.Join(catBase, "v1", volumeName) { + f.failUpdate = nil + // another setter lands first + e := f.entries[p] + e.Extended[extRetentionRev] = []byte("7") + } + return nil + } + if err := c.SetRetentionPolicy(ctx, "v1", RetentionPolicy{KeepNewest: 1}); err == nil { + t.Fatal("a set that lost the race succeeded") + } +} + +// The class is validated and stored with the snapshot. +func TestCatalog_SnapshotClass(t *testing.T) { + _, _, c, h := catalogFixture(t) + ctx := context.Background() + if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "x", RequestID: "rx", Class: "forever"}, h); CodeOf(err) != CodeInvalidClass { + t.Fatalf("unknown class: %v; want invalid_class", err) + } + s, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "p", RequestID: "rp", Class: SnapshotClassPinned}, h) + if err != nil || s.Class != SnapshotClassPinned || !s.Pinned() { + t.Fatalf("pinned snapshot: %+v %v", s, err) + } + snaps, err := c.allSnapshots(ctx, "v1") + if err != nil || len(snaps) != 1 || snaps[0].Class != SnapshotClassPinned { + t.Fatalf("listed class: %+v %v", snaps, err) + } +} + +// A fork whose HEAD is not yet written still needs its parent snapshot: +// retain keeps it; once the fork's HEAD is published it no longer does. +func TestCatalog_RetainKeepsParentOfAnIncompleteFork(t *testing.T) { + f, c, _, clock := retentionFixture(t, 3) + ctx := context.Background() + if err := c.SetRetentionPolicy(ctx, "v1", RetentionPolicy{}); err != nil { // keep nothing by policy + t.Fatal(err) + } + // The fake filer lists only directory entries it holds; a real filer + // has them for every volume directory. + for _, vol := range []string{"v1", "v2"} { + if err := f.CreateEntry(ctx, catBase, &filerpb.Entry{Name: vol, IsDirectory: true}, true); err != nil { + t.Fatal(err) + } + } + holdFirst(f, catBase+"/v2/HEAD") + if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s01", Target: "v2", RequestID: "f"}); CodeOf(err) != CodeOutcomeUnknown { + t.Fatalf("fork with a held HEAD create: %v", err) + } + res, err := c.Retain(ctx, "v1", true) + if err != nil { + t.Fatal(err) + } + if k := kept(res.Decisions); len(k) != 1 || k["s01"] == nil || k["s01"][0] != keepForkParent { + t.Fatalf("incomplete fork: kept %v; want only s01 (fork_parent)", k) + } + if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s01", Target: "v2", RequestID: "f"}); err != nil { + t.Fatalf("fork retry: %v", err) + } + _ = clock + if res, err := c.Retain(ctx, "v1", true); err != nil || res.Kept != 0 { + t.Fatalf("published fork: kept %d (%v); want 0", res.Kept, err) + } +} + +// publishTagged installs a HEAD for vol with chunks under keys tagged tag. +func publishTagged(t *testing.T, f *fakeFiler, b *fakeBlobs, vol, tag string, chunks map[uint64][]byte) storage.ChunkHead { + t.Helper() + ctx := context.Background() + r, err := NewChunkRemote(f, b, path.Join(catBase, vol)) + if err != nil { + t.Fatal(err) + } + h := storage.ChunkHead{Epoch: 1, Holder: "h1", RemoteLSN: 43, Chunks: map[uint64]storage.ChunkRef{}} + for idx, data := range chunks { + key := fmt.Sprintf("chunks/%s/c%d/k", tag, idx) + if err := r.Put(ctx, key, data); err != nil { + t.Fatal(err) + } + h.Chunks[idx] = storage.ChunkRef{Key: key, SHA256: sha256.Sum256(data)} + } + cur, err := r.GetHead(ctx) + if err != nil { + t.Fatal(err) + } + gen, err := r.CASHead(ctx, storage.ChunkHeadVersion{Gen: cur.Gen, Epoch: cur.Epoch}, h) + if err != nil { + t.Fatal(err) + } + h.Gen = gen + return h +} + +// Accounting from manifests and listings: live bytes from HEAD; a +// snapshot's exclusive bytes are what only it references; stored bytes +// count every binding, exact for referenced keys. +func TestCatalog_UsageFromManifests(t *testing.T) { + f, b, c, h := catalogFixture(t) // HEAD: chunks 0 and 3 + ctx := context.Background() + full := uint64(catGeo.ChunkBlocks) * uint64(catGeo.BlockSize) + if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r1"}, h); err != nil { + t.Fatal(err) + } + u, err := c.Usage(ctx, "v1") + if err != nil { + t.Fatal(err) + } + if u.LiveChunks != 2 || u.LiveBytes != 2*full || len(u.Snapshots) != 1 || u.Snapshots[0].ExclusiveBytes != 0 { + t.Fatalf("shared chunks: %+v", u) + } + if u.StoredBindings != 2 || u.StoredBytes != 2*full || u.StoredUpperBound { + t.Fatalf("stored: %+v; want 2 bindings, exact", u) + } + + // HEAD moves on: chunk 0 is rewritten, so s1 alone holds the old one. + publishTagged(t, f, b, "v1", "e2", map[uint64][]byte{0: chunkBytes(0x20), 3: chunkBytes(0x13)}) + u, err = c.Usage(ctx, "v1") + if err != nil { + t.Fatal(err) + } + if u.Snapshots[0].ExclusiveBytes != 2*full { + // both of s1's chunks are now exclusive: the new HEAD uses e2 keys + t.Fatalf("after HEAD moved: s1 exclusive %d, want %d", u.Snapshots[0].ExclusiveBytes, 2*full) + } + if u.StoredBindings != 4 || u.StoredBytes != 4*full || u.StoredUpperBound { + t.Fatalf("stored after HEAD moved: %+v; want 4 bindings, exact", u) + } + + // s1 deleted: its keys are unreferenced but still stored (until GC), + // counted at the full chunk size as an upper bound. + if _, err := c.DeleteSnapshot(ctx, "v1", "s1"); err != nil { + t.Fatal(err) + } + u, err = c.Usage(ctx, "v1") + if err != nil { + t.Fatal(err) + } + if len(u.Snapshots) != 0 || u.StoredBindings != 4 || !u.StoredUpperBound { + t.Fatalf("after delete: %+v; want no snapshots, 4 bindings, upper bound", u) + } +} + +// chunkSize clips the last chunk to NumBlocks. +func TestChunkSizeClipsLastChunk(t *testing.T) { + g := Geometry{NumBlocks: 20, BlockSize: 4096, ChunkBlocks: 8} + for idx, want := range map[uint64]uint64{0: 8 * 4096, 1: 8 * 4096, 2: 4 * 4096, 3: 0} { + if got := chunkSize(g, idx); got != want { + t.Errorf("chunk %d: %d, want %d", idx, got, want) + } + } +} diff --git a/seaweed-block/core/frontend/chunkstore/usage.go b/seaweed-block/core/frontend/chunkstore/usage.go new file mode 100644 index 0000000000..b4120fb473 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/usage.go @@ -0,0 +1,179 @@ +package chunkstore + +import ( + "context" + "errors" + "net/url" + "path" + "sort" + "strings" + + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// Space accounting (claude05's rulings, 2026-11-15 22:53Z). Everything is +// computed from manifests and filer listings; no chunk data is read. +// +// A chunk's bytes are ChunkBlocks x BlockSize, the last chunk clipped to +// NumBlocks (ChunkRef carries no size). +// +// - LiveBytes: the chunks HEAD references. +// - per snapshot, ExclusiveBytes: the chunks that snapshot references and +// neither HEAD nor any other live snapshot does, i.e. what deleting it +// would let GC reclaim. +// - StoredBytes: the volume's chunk-key bindings in the filer (what is +// stored now, referenced or not). A binding a manifest references is +// counted at its exact (clipped) size; any other binding at the full +// chunk size, so StoredBytes is an upper bound whenever +// StoredUpperBound is set. +// +// "Bytes uploaded since creation" needs a counter nothing records today (a +// follow-up). The unreferenced-not-yet-collected bytes come from GC's +// preview once that lands (#140). + +// SnapshotUsage is one snapshot's share of a volume's space. +type SnapshotUsage struct { + Name string `json:"name"` + CreatedNs int64 `json:"createdNs"` + Class string `json:"class"` + Pinned bool `json:"pinned"` + Chunks int `json:"chunks"` + ExclusiveBytes uint64 `json:"exclusiveBytes"` +} + +// VolumeUsage is a volume's space accounting. +type VolumeUsage struct { + VolumeID string `json:"volumeID"` + ChunkBytes uint64 `json:"chunkBytes"` // one full chunk + LiveChunks int `json:"liveChunks"` + LiveBytes uint64 `json:"liveBytes"` + Snapshots []SnapshotUsage `json:"snapshots"` + StoredBindings int `json:"storedBindings"` + StoredBytes uint64 `json:"storedBytes"` + StoredUpperBound bool `json:"storedUpperBound"` + Policy RetentionPolicy `json:"policy"` + PolicySet bool `json:"policySet"` +} + +// chunkSize is the byte size of chunk index idx under g. +func chunkSize(g Geometry, idx uint64) uint64 { + full := uint64(g.ChunkBlocks) * uint64(g.BlockSize) + if g.ChunkBlocks == 0 { + return 0 + } + first := idx * uint64(g.ChunkBlocks) + if first >= g.NumBlocks { + return 0 + } + if rest := g.NumBlocks - first; rest < uint64(g.ChunkBlocks) { + return rest * uint64(g.BlockSize) + } + return full +} + +// Usage computes vol's space accounting. +func (c *Catalog) Usage(ctx context.Context, vol string) (VolumeUsage, error) { + if red := true; red { // RED: no accounting + return VolumeUsage{VolumeID: vol, Snapshots: []SnapshotUsage{}}, nil + } + v, ok, err := c.ReadVolume(ctx, vol) + if err != nil { + return VolumeUsage{}, err + } + if !ok { + return VolumeUsage{}, catErr(CodeNotChunkVolume, false, nil, "volume %s has no VOLUME entry", vol) + } + g := v.Geometry + u := VolumeUsage{VolumeID: vol, ChunkBytes: uint64(g.ChunkBlocks) * uint64(g.BlockSize), Snapshots: []SnapshotUsage{}} + if u.Policy, u.PolicySet, err = c.ReadRetentionPolicy(ctx, vol); err != nil { + return VolumeUsage{}, err + } + + head, _, err := c.ReadHead(ctx, vol) + if err != nil { + return VolumeUsage{}, err + } + snaps, err := c.allSnapshots(ctx, vol) + if err != nil { + return VolumeUsage{}, err + } + + // holders counts, per chunk key, how many of HEAD and the live + // snapshots reference it; size is each referenced key's byte size. + holders := map[string]int{} + size := map[string]uint64{} + addHolder := func(h storage.ChunkHead) { + seen := map[string]bool{} + for idx, ref := range h.Chunks { + size[ref.Key] = chunkSize(g, idx) + if !seen[ref.Key] { + seen[ref.Key] = true + holders[ref.Key]++ + } + } + } + addHolder(head) + for idx := range head.Chunks { + u.LiveChunks++ + u.LiveBytes += chunkSize(g, idx) + } + for _, s := range snaps { + addHolder(s.Head()) + } + for _, s := range snaps { + su := SnapshotUsage{Name: s.Name, CreatedNs: s.CreatedNs, Class: s.Class, Pinned: s.Pinned(), Chunks: len(s.Head().Chunks)} + seen := map[string]bool{} + for _, ref := range s.Head().Chunks { + if seen[ref.Key] { + continue + } + seen[ref.Key] = true + if holders[ref.Key] == 1 { + su.ExclusiveBytes += size[ref.Key] + } + } + u.Snapshots = append(u.Snapshots, su) + } + sort.Slice(u.Snapshots, func(i, j int) bool { + if u.Snapshots[i].CreatedNs != u.Snapshots[j].CreatedNs { + return u.Snapshots[i].CreatedNs > u.Snapshots[j].CreatedNs + } + return u.Snapshots[i].Name < u.Snapshots[j].Name + }) + + // Stored: this volume's own chunk-key bindings. + r, err := NewChunkRemote(c.f, nilBlobs{}, path.Join(c.base, vol)) + if err != nil { + return VolumeUsage{}, err + } + after := "" + for { + page, err := c.f.ListEntries(ctx, r.keyDir(), "", after, listPage) + if err != nil { + return VolumeUsage{}, remoteErr(err, "list the chunk keys of %s", vol) + } + for _, e := range page { + if e.GetName() <= after { + return VolumeUsage{}, errors.New("chunkstore: non-advancing chunk key listing") + } + after = e.GetName() + if e.GetIsDirectory() || string(e.Extended[extKind]) != kindChunkKey { + continue + } + key, err := url.PathUnescape(e.GetName()) + if err != nil || strings.HasPrefix(key, "@") { + continue + } + u.StoredBindings++ + if n, ok := size[key]; ok { + u.StoredBytes += n + } else { + u.StoredBytes += u.ChunkBytes + u.StoredUpperBound = true + } + } + if len(page) < listPage { + return u, nil + } + } +} diff --git a/seaweed-block/core/host/volume/chunk_control.go b/seaweed-block/core/host/volume/chunk_control.go index f1fdfa77af..5fdbe5792a 100644 --- a/seaweed-block/core/host/volume/chunk_control.go +++ b/seaweed-block/core/host/volume/chunk_control.go @@ -31,6 +31,9 @@ type ChunkControl interface { ListSnapshots(ctx context.Context, volumeID string, opts chunkstore.ListOptions) ([]chunkstore.SnapshotInfo, string, error) DeleteSnapshot(ctx context.Context, volumeID, name string) (string, error) Detach(ctx context.Context, volumeID string) (ChunkDetachResponse, error) + // Usage is the volume's space accounting and retention policy + // (GET /status/chunk). + Usage(ctx context.Context, volumeID string) (chunkstore.VolumeUsage, error) } // ChunkCutResponse is the body of a successful POST /chunk/cut (§3.1). @@ -54,6 +57,7 @@ type ChunkSnapshotRequest struct { Labels map[string]string Consistency string ExpiresAtNs int64 + Class string // retention class: "semantic" or "pinned" } // ChunkDetachResponse is the body of a successful POST /chunk/detach (§3.6). @@ -315,6 +319,7 @@ func (s *StatusServer) handleChunkSnapshot(w http.ResponseWriter, r *http.Reques Labels map[string]string `json:"labels"` Consistency string `json:"consistency"` ExpiresAtNs int64 `json:"expiresAtNs"` + Class string `json:"class"` TimeoutMs int64 `json:"timeoutMs"` } if !decodeChunkBody(w, r, &req) { @@ -327,7 +332,7 @@ func (s *StatusServer) handleChunkSnapshot(w http.ResponseWriter, r *http.Reques ctx, cancel := chunkContext(r, req.TimeoutMs) defer cancel() info, err := ctl.Snapshot(ctx, req.VolumeID, ChunkSnapshotRequest{Name: req.Name, RequestID: req.RequestID, - Labels: req.Labels, Consistency: req.Consistency, ExpiresAtNs: req.ExpiresAtNs}) + Labels: req.Labels, Consistency: req.Consistency, ExpiresAtNs: req.ExpiresAtNs, Class: req.Class}) if err != nil { writeChunkFailure(w, err) return @@ -459,7 +464,7 @@ func (c *chunkControl) Cut(ctx context.Context, volumeID string, minLSN uint64) // is cut, and the HEAD that cut installed is stored. func (c *chunkControl) Snapshot(ctx context.Context, volumeID string, req ChunkSnapshotRequest) (chunkstore.SnapshotInfo, error) { sreq := chunkstore.SnapshotRequest{Name: req.Name, RequestID: req.RequestID, Labels: req.Labels, - Consistency: req.Consistency, ExpiresAtNs: req.ExpiresAtNs, CreatedBy: "blockvolume"} + Consistency: req.Consistency, ExpiresAtNs: req.ExpiresAtNs, CreatedBy: "blockvolume", Class: req.Class} if info, replayed, err := c.cat.SnapshotReplay(ctx, volumeID, sreq); err != nil || replayed { return info, err } @@ -479,6 +484,32 @@ func (c *chunkControl) DeleteSnapshot(ctx context.Context, volumeID, name string return c.cat.DeleteSnapshot(ctx, volumeID, name) } +func (c *chunkControl) Usage(ctx context.Context, volumeID string) (chunkstore.VolumeUsage, error) { + return c.cat.Usage(ctx, volumeID) +} + +// handleStatusChunk answers GET /status/chunk?volume=: the served +// volume's space accounting and retention policy, computed from manifests +// and filer listings (no chunk data reads). +func (s *StatusServer) handleStatusChunk(w http.ResponseWriter, r *http.Request) { + if !s.chunkAdmit(w, r, http.MethodGet) { + return + } + volumeID := r.URL.Query().Get("volume") + ctl := s.chunkTarget(w, volumeID) + if ctl == nil { + return + } + ctx, cancel := chunkContext(r, 0) + defer cancel() + u, err := ctl.Usage(ctx, volumeID) + if err != nil { + writeChunkFailure(w, err) + return + } + writeChunkJSON(w, http.StatusOK, u) +} + func (c *chunkControl) Detach(ctx context.Context, volumeID string) (ChunkDetachResponse, error) { r, last, err := c.p.DetachVolume(ctx, volumeID) if err != nil { diff --git a/seaweed-block/core/host/volume/chunk_control_test.go b/seaweed-block/core/host/volume/chunk_control_test.go index 5a0499b880..53a752bd7d 100644 --- a/seaweed-block/core/host/volume/chunk_control_test.go +++ b/seaweed-block/core/host/volume/chunk_control_test.go @@ -27,6 +27,7 @@ type fakeChunkControl struct { next string state string detach ChunkDetachResponse + usage chunkstore.VolumeUsage lastOpts chunkstore.ListOptions lastSnap ChunkSnapshotRequest lastMin uint64 @@ -61,6 +62,12 @@ func (f *fakeChunkControl) DeleteSnapshot(ctx context.Context, vol, name string) f.calls++ return f.state, f.err } +func (f *fakeChunkControl) Usage(ctx context.Context, vol string) (chunkstore.VolumeUsage, error) { + f.calls++ + f.remember(ctx) + return f.usage, f.err +} + func (f *fakeChunkControl) Detach(ctx context.Context, vol string) (ChunkDetachResponse, error) { f.calls++ f.remember(ctx) diff --git a/seaweed-block/core/host/volume/status_chunk_test.go b/seaweed-block/core/host/volume/status_chunk_test.go new file mode 100644 index 0000000000..469b129eea --- /dev/null +++ b/seaweed-block/core/host/volume/status_chunk_test.go @@ -0,0 +1,59 @@ +package volume + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "testing" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" +) + +// GET /status/chunk?volume= answers the served volume's space accounting +// and retention policy; the usual chunk-route guards apply. +func TestStatusServer_StatusChunkUsage(t *testing.T) { + fake := &fakeChunkControl{usage: chunkstore.VolumeUsage{ + VolumeID: "v1", ChunkBytes: 32768, LiveChunks: 2, LiveBytes: 65536, StoredBindings: 3, StoredBytes: 98304, StoredUpperBound: true, + Snapshots: []chunkstore.SnapshotUsage{{Name: "s1", Class: chunkstore.SnapshotClassSemantic, Chunks: 2, ExclusiveBytes: 32768}}, + Policy: chunkstore.DefaultRetentionPolicy(), + }} + s := chunkServer(t, fake, true) + w := serveStatusChunk(t, s, http.MethodGet, "/status/chunk?volume=v1") + if w.Code != http.StatusOK { + t.Fatalf("status %d: %s", w.Code, w.Body) + } + var got chunkstore.VolumeUsage + if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil { + t.Fatal(err) + } + if got.LiveBytes != 65536 || got.StoredBytes != 98304 || !got.StoredUpperBound || len(got.Snapshots) != 1 || got.Snapshots[0].ExclusiveBytes != 32768 || got.Policy.KeepNewest != chunkstore.DefaultKeepNewest { + t.Fatalf("usage body %+v", got) + } + if w := serveStatusChunk(t, s, http.MethodGet, "/status/chunk?volume=v9"); w.Code != http.StatusNotFound { + t.Fatalf("other volume: %d", w.Code) + } + if w := serveStatusChunk(t, s, http.MethodPost, "/status/chunk?volume=v1"); w.Code != http.StatusMethodNotAllowed { + t.Fatalf("POST: %d", w.Code) + } +} + +// The snapshot route carries the retention class through. +func TestStatusServer_ChunkSnapshotCarriesClass(t *testing.T) { + fake := &fakeChunkControl{snap: chunkstore.SnapshotInfo{VolumeID: "v1", Name: "s1"}} + s := chunkServer(t, fake, true) + if w := serve(t, s, http.MethodPost, "/chunk/snapshot", `{"volumeID":"v1","name":"s1","requestID":"r","class":"pinned"}`, ""); w.Code != http.StatusOK { + t.Fatalf("snapshot: %d %s", w.Code, w.Body) + } + if fake.lastSnap.Class != chunkstore.SnapshotClassPinned { + t.Fatalf("class not passed through: %+v", fake.lastSnap) + } +} + +func serveStatusChunk(t *testing.T, s *StatusServer, method, target string) *httptest.ResponseRecorder { + t.Helper() + req := httptest.NewRequest(method, target, nil) + req.RemoteAddr = "127.0.0.1:5555" + w := httptest.NewRecorder() + s.handleStatusChunk(w, req) + return w +} diff --git a/seaweed-block/core/host/volume/status_server.go b/seaweed-block/core/host/volume/status_server.go index 95c30eea26..e021fcb301 100644 --- a/seaweed-block/core/host/volume/status_server.go +++ b/seaweed-block/core/host/volume/status_server.go @@ -316,6 +316,7 @@ func (s *StatusServer) Start(addr string) (string, error) { } if s.chunkEnabled { mux.Handle("/chunk/", s.chunkMux()) + mux.HandleFunc("/status/chunk", s.handleStatusChunk) } s.srv = &http.Server{Handler: mux, ReadHeaderTimeout: 5 * time.Second} From 4e5ff2cc95ab72a3a4ac84951a11ddc555297c79 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 15 Nov 2026 15:08:17 -0800 Subject: [PATCH 02/10] chunkstore: snapshot retention and space accounting claude05's rulings (2026-11-15 22:53Z). Retention, policy on the VOLUME entry: keep the newest KeepNewest unpinned snapshots, every pinned snapshot not yet past its ExpiresAtNs, every snapshot younger than KeepYounger (a future creation time from clock skew counts as young), the newest snapshot of each of the last KeepHourly / KeepDaily / KeepWeekly periods, and every snapshot a fork still needs (named by a fork whose HEAD is absent or aborted). Everything else is deleted through DeleteSnapshot (attempt-scoped tombstones; HEAD untouched; names freed); GC reclaims the chunks. Equal creation times rank by name. Semantic and labeled snapshots are not exempt; a pinned snapshot past its expiry is unpinned. Defaults: 10 newest, 1h. A dry run plans and writes nothing. The policy is stored as extended attributes on the VOLUME entry, conditional on a revision. Accounting, from manifests and filer listings (no data reads; a chunk is ChunkBlocks x BlockSize, the last clipped): live bytes from HEAD; per-snapshot exclusive bytes (referenced by no other holder); stored bytes from the volume's chunk-key bindings, exact for referenced keys and a full chunk (an upper bound, flagged) for the rest. The unreferenced-not-yet-collected bytes come from GC's preview once #140 merges; bytes uploaded since creation need a counter (follow-up). Co-Authored-By: Claude Opus 5.5 --- .../core/frontend/chunkstore/catalog.go | 2 +- .../core/frontend/chunkstore/retention.go | 16 ---------------- seaweed-block/core/frontend/chunkstore/usage.go | 3 --- 3 files changed, 1 insertion(+), 20 deletions(-) diff --git a/seaweed-block/core/frontend/chunkstore/catalog.go b/seaweed-block/core/frontend/chunkstore/catalog.go index 6f643676ea..c3fbf1653e 100644 --- a/seaweed-block/core/frontend/chunkstore/catalog.go +++ b/seaweed-block/core/frontend/chunkstore/catalog.go @@ -834,7 +834,7 @@ func (c *Catalog) CreateSnapshot(ctx context.Context, vol string, req SnapshotRe } doc := snapDoc{Format: snapFormat, VolumeID: vol, Name: req.Name, RequestID: req.RequestID, CreatedNs: c.now().UnixNano(), CreatedBy: req.CreatedBy, Consistency: consistency, Head: headEnt.Content, Geometry: v.Geometry, Parent: v.Parent, - Labels: req.Labels, ExpiresAtNs: req.ExpiresAtNs, Class: ""} // RED: class not stored + Labels: req.Labels, ExpiresAtNs: req.ExpiresAtNs, Class: req.Class} body, err := json.Marshal(doc) if err != nil { return SnapshotInfo{}, err diff --git a/seaweed-block/core/frontend/chunkstore/retention.go b/seaweed-block/core/frontend/chunkstore/retention.go index a02b920712..27283b9d44 100644 --- a/seaweed-block/core/frontend/chunkstore/retention.go +++ b/seaweed-block/core/frontend/chunkstore/retention.go @@ -56,9 +56,6 @@ const ( ) func validSnapshotClass(class string) error { - if red := true; red { // RED: no validation - return nil - } switch class { case "", SnapshotClassSemantic, SnapshotClassPinned: return nil @@ -136,9 +133,6 @@ func (c *Catalog) volumeEntry(ctx context.Context, vol string) (*filerpb.Entry, // is conditional on the policy revision read, so of two concurrent setters // one wins and the other gets a retryable remote error. func (c *Catalog) SetRetentionPolicy(ctx context.Context, vol string, p RetentionPolicy) error { - if red := true; red { // RED: stores nothing - return nil - } if err := p.validate(); err != nil { return err } @@ -191,13 +185,6 @@ const ( // are ranked newest first; equal creation times rank by name, so the plan // is deterministic. func planRetention(p RetentionPolicy, snaps []SnapshotInfo, needed map[string]bool, now time.Time) []RetentionDecision { - if red := true; red { // RED: keeps everything - out := make([]RetentionDecision, len(snaps)) - for i, s := range snaps { - out[i] = RetentionDecision{Name: s.Name, Keep: true, Reasons: []string{"red"}} - } - return out - } ordered := append([]SnapshotInfo(nil), snaps...) sort.SliceStable(ordered, func(i, j int) bool { if ordered[i].CreatedNs != ordered[j].CreatedNs { @@ -336,9 +323,6 @@ func (c *Catalog) allSnapshots(ctx context.Context, vol string) ([]SnapshotInfo, // real published HEAD yet (absent or aborted). A published fork HEAD pins // its chunks for GC itself, so it no longer needs the snapshot. func (c *Catalog) forkParentsNeeded(ctx context.Context, vol string) (map[string]bool, error) { - if red := true; red { // RED: no fork needs a parent - return map[string]bool{}, nil - } vols, err := c.ListVolumes(ctx) if err != nil { return nil, err diff --git a/seaweed-block/core/frontend/chunkstore/usage.go b/seaweed-block/core/frontend/chunkstore/usage.go index b4120fb473..52b7fdf9d0 100644 --- a/seaweed-block/core/frontend/chunkstore/usage.go +++ b/seaweed-block/core/frontend/chunkstore/usage.go @@ -73,9 +73,6 @@ func chunkSize(g Geometry, idx uint64) uint64 { // Usage computes vol's space accounting. func (c *Catalog) Usage(ctx context.Context, vol string) (VolumeUsage, error) { - if red := true; red { // RED: no accounting - return VolumeUsage{VolumeID: vol, Snapshots: []SnapshotUsage{}}, nil - } v, ok, err := c.ReadVolume(ctx, vol) if err != nil { return VolumeUsage{}, err From 23d125daa7ab31cedad70c1039fe005ec5dfff23 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 15 Nov 2026 15:36:46 -0800 Subject: [PATCH 03/10] chunkstore: RED controls for the retention review Controls for the six review findings on retention, failing against stubs that restore each old behaviour: - a same-name pinned replacement made after planning is deleted (retain deletes by name); - a fork that starts after the scan loses its parent; a stale hold; a fork after the hold check; - log-spaced keeps use calendar periods (10:20 and 09:50 both kept at 10:30 with keep-hourly 1); - exclusive bytes ignore a fork's "@owner/key" holders; - a failing pass discards its partial result (catalog and CLI); - an invalid class cuts before it is refused, and maps to 409. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/cmd/sw-block/chunk_retain.go | 40 +++ .../cmd/sw-block/chunk_retain_partial_test.go | 97 ++++++ .../core/frontend/chunkstore/catalog.go | 60 +++- .../core/frontend/chunkstore/retention.go | 327 ++++++++++++++++-- .../chunkstore/retention_integration_test.go | 95 +++++ .../chunkstore/retention_review_test.go | 269 ++++++++++++++ .../core/frontend/chunkstore/usage.go | 81 ++++- .../core/host/volume/chunk_control.go | 7 +- .../host/volume/chunk_control_class_test.go | 41 +++ 9 files changed, 960 insertions(+), 57 deletions(-) create mode 100644 seaweed-block/cmd/sw-block/chunk_retain_partial_test.go create mode 100644 seaweed-block/core/frontend/chunkstore/retention_review_test.go create mode 100644 seaweed-block/core/host/volume/chunk_control_class_test.go diff --git a/seaweed-block/cmd/sw-block/chunk_retain.go b/seaweed-block/cmd/sw-block/chunk_retain.go index a742b6253f..fc3664e471 100644 --- a/seaweed-block/cmd/sw-block/chunk_retain.go +++ b/seaweed-block/cmd/sw-block/chunk_retain.go @@ -2,6 +2,9 @@ package main import ( "context" + "encoding/json" + "errors" + "fmt" "io" "time" @@ -86,5 +89,42 @@ func chunkRetain(args []string, stdout, stderr io.Writer) int { return chunkResult("retain", map[string]any{"volumeID": volumeID, "policy": p, "policySet": true}, nil, stdout, stderr) } res, err := cat.Retain(ctx, volumeID, dryRun) + if err != nil && res.VolumeID != "" { + // The pass stopped part way: report what it did (confirmed + // deletions, the failing snapshot with whether its outcome is + // uncertain, what it never reached) with the error, and fail. + return retainPartial(res, err, stdout, stderr) + } return chunkResult("retain", res, err, stdout, stderr) } + +// retainOutput is a retention result together with the error that +// stopped it. +type retainOutput struct { + chunkstore.RetentionResult + Error *chunkErrBody `json:"error,omitempty"` +} + +func retainPartial(res chunkstore.RetentionResult, err error, stdout, stderr io.Writer) int { + if red := true; red { // RED: the partial result is discarded + return chunkResult("retain", nil, err, stdout, stderr) + } + body := chunkErrBody{Code: chunkstore.CodeOf(err), Message: err.Error(), Retryable: true} + var ce *chunkstore.CatalogError + if errors.As(err, &ce) { + body = chunkErrBody{Code: ce.Code, Message: ce.Detail(), Retryable: ce.Retryable} + } + if body.Code == "" { + body.Code = codeInternalCLI + } + fmt.Fprintf(stderr, "sw-block ops chunk retain: %s: %s (deleted %d, not attempted %d)\n", body.Code, body.Message, len(res.Deleted), len(res.NotAttempted)) + out, mErr := json.Marshal(retainOutput{RetentionResult: res, Error: &body}) + if mErr != nil { + fmt.Fprintf(stderr, "sw-block ops chunk retain: %v\n", mErr) + return chunkExitFailed + } + if wErr := writeAll(stdout, append(out, '\n')); wErr != nil { + fmt.Fprintf(stderr, "sw-block ops chunk retain: write the result: %v\n", wErr) + } + return chunkExitFailed +} diff --git a/seaweed-block/cmd/sw-block/chunk_retain_partial_test.go b/seaweed-block/cmd/sw-block/chunk_retain_partial_test.go new file mode 100644 index 0000000000..705e2ca9d5 --- /dev/null +++ b/seaweed-block/cmd/sw-block/chunk_retain_partial_test.go @@ -0,0 +1,97 @@ +package main + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "strings" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// failingFiler fails the UpdateEntry calls fail picks, after or before +// applying them. +type failingFiler struct { + *chunkstore.MemFiler + fail func(dir, name string) bool + afterApply bool +} + +func (f *failingFiler) UpdateEntry(ctx context.Context, dir string, e *filerpb.Entry, expected map[string][]byte) error { + if f.fail != nil && f.fail(dir, e.GetName()) { + if f.afterApply { + if err := f.MemFiler.UpdateEntry(ctx, dir, e, expected); err != nil { + return err + } + return errors.New("response lost") + } + return errors.New("filer unavailable") + } + return f.MemFiler.UpdateEntry(ctx, dir, e, expected) +} + +// retain that fails part way prints what it confirmed, the failing +// snapshot (uncertain) and what it never reached, with the error, and +// exits nonzero; a lost response is finished by the next run. +func TestOpsChunk_RetainReportsPartialProgress(t *testing.T) { + ctx := context.Background() + ff := &failingFiler{MemFiler: chunkstore.NewMemFiler()} + prev := dialChunkFiler + dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { return ff, func() error { return nil }, nil } + t.Cleanup(func() { dialChunkFiler = prev }) + cat, err := chunkstore.NewCatalog(ff, defaultChunkPathCLI) + if err != nil { + t.Fatal(err) + } + if _, err := cat.EnsureVolume(ctx, "v1", chunkstore.Geometry{NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 8}); err != nil { + t.Fatal(err) + } + base := time.Now().Add(-48 * time.Hour) + head := storage.ChunkHead{Gen: 2, Epoch: 1, Holder: "s1/r1", RemoteLSN: 42, State: storage.ChunkHeadActive, + Chunks: map[uint64]storage.ChunkRef{0: {Key: "chunks/e1/c0/k"}}} + for i := 0; i < 4; i++ { + at := base.Add(time.Duration(i) * time.Minute) + cat.SetClock(func() time.Time { return at }) + if _, err := cat.CreateSnapshot(ctx, "v1", chunkstore.SnapshotRequest{Name: fmt.Sprintf("s%d", i), RequestID: fmt.Sprintf("r%d", i)}, head); err != nil { + t.Fatal(err) + } + } + filer := []string{"--volume", "v1", "--chunk-filer", "filer:18888"} + if code, out, errs := runChunk(append([]string{"retain", "--set-policy", "--keep-newest", "0", "--keep-younger", "0s"}, filer...)...); code != 0 { + t.Fatalf("set policy: %d %q %q", code, out, errs) + } + // Expired newest first: s3, s2, s1, s0. The mark of s2 fails. + ff.fail = func(dir, _ string) bool { return strings.HasSuffix(dir, "/snaps/s2") } + type partial struct { + chunkstore.RetentionResult + Error *chunkErrBody `json:"error"` + } + code, out, errs := runChunk(append([]string{"retain"}, filer...)...) + var p partial + if code == 0 || json.Unmarshal([]byte(out), &p) != nil || p.Error == nil || p.Failed == nil { + t.Fatalf("failing retain: exit %d %q %q; want nonzero with the partial result", code, out, errs) + } + if strings.Join(p.Deleted, ",") != "s3" || p.Failed.Name != "s2" || !p.Failed.Uncertain || strings.Join(p.NotAttempted, ",") != "s1,s0" { + t.Fatalf("partial result: %+v", p) + } + if !strings.Contains(errs, "deleted 1, not attempted 2") { + t.Fatalf("stderr %q; want the counts", errs) + } + + ff.afterApply = true // the mark lands, its response is lost + code, out, _ = runChunk(append([]string{"retain"}, filer...)...) + if code == 0 || json.Unmarshal([]byte(out), &p) != nil || p.Failed == nil || p.Failed.Name != "s2" || !p.Failed.Uncertain { + t.Fatalf("lost response: exit %d %q", code, out) + } + ff.fail = nil + code, out, errs = runChunk(append([]string{"retain"}, filer...)...) + var done chunkstore.RetentionResult + if code != 0 || json.Unmarshal([]byte(out), &done) != nil || strings.Join(done.Deleted, ",") != "s1,s0,s2" { + t.Fatalf("rerun: %d %q %q; want s1, s0 and the half-deleted s2", code, out, errs) + } +} diff --git a/seaweed-block/core/frontend/chunkstore/catalog.go b/seaweed-block/core/frontend/chunkstore/catalog.go index c3fbf1653e..eeca29c9c8 100644 --- a/seaweed-block/core/frontend/chunkstore/catalog.go +++ b/seaweed-block/core/frontend/chunkstore/catalog.go @@ -220,6 +220,8 @@ type SnapshotInfo struct { Replayed bool `json:"replayed"` Class string `json:"class"` + attempt string // the attempt the name resolved to, when read by name + head storage.ChunkHead geo Geometry } @@ -282,6 +284,9 @@ type Catalog struct { // OpDeadline bounds a snapshot or fork (DefaultOpDeadline when zero). OpDeadline time.Duration now func() time.Time + // retainHook, when set, runs at the named stages of a Retain pass (a + // test seam for interleavings; see hookPlanned). + retainHook func(stage, name string) } // NewCatalog returns the catalog for the chunk base directory base (the @@ -606,6 +611,7 @@ func (c *Catalog) resolveSnap(ctx context.Context, vol, name string) (snapRef, b if err != nil { return snapRef{}, false, err } + info.attempt = rec.Attempt ref.entry, ref.info = e, info return ref, true, nil } @@ -808,7 +814,7 @@ func (c *Catalog) CreateSnapshot(ctx context.Context, vol string, req SnapshotRe if consistency == "" { consistency = "crash" } - if err := validSnapshotClass(req.Class); err != nil { + if err := ValidateSnapshotClass(req.Class); err != nil { return SnapshotInfo{}, err } if head.Gen == 0 { @@ -1160,12 +1166,31 @@ func (c *Catalog) Fork(ctx context.Context, req ForkRequest) (ForkResult, error) } } - readAt := c.now() - snap, err := c.readSnap(ctx, req.Source, req.Snapshot) + // Hold the parent attempt before reading it (review of #142): a + // retention pass that marks it deleting reads the holds after its + // mark, so either it sees this hold and keeps the snapshot, or this + // read sees the attempt deleting and the fork refuses before anything + // is installed. + srcRoot, err := c.volRoot(req.Source) if err != nil { return ForkResult{}, err } + held, err := c.holdForkParent(ctx, srcRoot, req) + if err != nil { + return ForkResult{}, err + } + readAt := c.now() + snap, err := c.readSnap(ctx, req.Source, req.Snapshot) + if err != nil { + c.dropForkHold(ctx, srcRoot, req, held) + return ForkResult{}, err + } + if snap.attempt != held { + c.dropForkHold(ctx, srcRoot, req, held) + return ForkResult{}, catErr(CodeOutcomeUnknown, true, nil, "fork %s: snapshot %s/%s changed while it was being held; retry", req.Target, req.Source, req.Snapshot) + } if snap.State == SnapDeleting { + c.dropForkHold(ctx, srcRoot, req, held) return ForkResult{}, catErr(CodeSnapshotDeleting, false, nil, "snapshot %s/%s is being deleted", req.Source, req.Snapshot) } if snap.geo == (Geometry{}) { @@ -1261,9 +1286,38 @@ func (c *Catalog) Fork(ctx context.Context, req ForkRequest) (ForkResult, error) if outcome != createUnsettled { c.dropIntent(ctx, dstRoot, id) // confirmed, or refused for good } + c.dropForkHold(ctx, srcRoot, req, held) // the fork has its HEAD: the parent is no longer needed for it return forkResult(existing, outcome != createdNow), nil } +// holdForkParent records that fork req needs the attempt its snapshot name +// resolves to now, and returns that attempt ("" when the name resolves to +// nothing; the read that follows then refuses). +func (c *Catalog) holdForkParent(ctx context.Context, srcRoot string, req ForkRequest) (string, error) { + ref, ok, err := c.resolveSnap(ctx, req.Source, req.Snapshot) + if err != nil || !ok { + return "", err + } + if red := true; red { // RED: no hold recorded + return ref.rec.Attempt, nil + } + now := c.now().Unix() + e := &filerpb.Entry{Name: req.Target, Attributes: &filerpb.FuseAttributes{Mtime: now, Crtime: now, FileMode: 0o644}} + if err := c.f.CreateEntry(ctx, forkHoldDir(srcRoot, req.Snapshot, ref.rec.Attempt), e, true); err != nil && !errors.Is(err, ErrExists) { + return "", remoteErr(err, "hold snapshot %s/%s for fork %s", req.Source, req.Snapshot, req.Target) + } + return ref.rec.Attempt, nil +} + +// dropForkHold removes a completed fork's hold (best effort: a stale hold +// is ignored once the target has a HEAD). +func (c *Catalog) dropForkHold(ctx context.Context, srcRoot string, req ForkRequest, attempt string) { + if attempt == "" { + return + } + _ = c.f.DeleteEntry(ctx, forkHoldDir(srcRoot, req.Snapshot, attempt), req.Target, nil) +} + // AbortFork settles a dead fork for a GC sweep (W5 ruling, 2026-11-15 // 17:30Z): it claims the target's HEAD, the fork's publishing entry, with // an exclusive create of an aborted HEAD tombstone. claimed is true when diff --git a/seaweed-block/core/frontend/chunkstore/retention.go b/seaweed-block/core/frontend/chunkstore/retention.go index 27283b9d44..c291809a77 100644 --- a/seaweed-block/core/frontend/chunkstore/retention.go +++ b/seaweed-block/core/frontend/chunkstore/retention.go @@ -5,6 +5,7 @@ import ( "encoding/json" "errors" "fmt" + "path" "sort" "strconv" "time" @@ -31,15 +32,39 @@ import ( // + every pinned snapshot not yet past its ExpiresAtNs // + every snapshot younger than KeepYounger (a creation time in the // future, from clock skew, counts as young) -// + the log-spaced keeps: the newest snapshot of each of the last -// KeepHourly hours, KeepDaily days and KeepWeekly weeks -// + every snapshot a fork still needs (named by a volume's fork record -// while that volume has no real published HEAD yet) +// + the log-spaced keeps (below) +// + every snapshot a fork still needs // -// and deletes every other snapshot through DeleteSnapshot (attempt-scoped -// tombstone rules: HEAD is never touched, the name is freed, the attempt -// path stays). A pinned snapshot past its ExpiresAtNs is treated as -// unpinned. GC reclaims the chunks. +// and deletes every other snapshot. A pinned snapshot past its ExpiresAtNs +// is treated as unpinned. GC reclaims the chunks. +// +// Log-spaced keeps use rolling windows anchored at now: window k of a +// period P holds the snapshots whose age is in [k*P, (k+1)*P). For +// KeepHourly = H, the newest snapshot of each of windows 0..H-1 is kept +// (likewise daily and weekly). So at 10:30 with KeepHourly = 1 only the +// newest snapshot of 09:30..10:30 is kept, not one per clock hour. +// +// Deletion is bound to the exact attempt planned (review of #142): the +// attempt's own entry is marked deleting conditionally, and the name +// record is removed only while it still names that attempt, so a +// same-name replacement made after planning is never touched. +// +// Fork parents. A fork records a hold on the parent attempt before it +// reads it (forkholds///, see Fork). Retain marks +// the attempt deleting first and then reads its holds: a hold whose fork +// target has no HEAD yet reverts the mark and keeps the snapshot. A fork +// that creates its hold after that read finds the attempt deleting and +// refuses before installing anything. Either way no incomplete fork loses +// its parent. A hold counts while its target has no HEAD and either the +// target's VOLUME records this fork, or the hold is younger than the +// operation deadline (the fork may still be about to publish its VOLUME); +// a hold left by a fork that died before its VOLUME is stale after that. +// A fork published before holds existed is still found by the fork-record +// scan (forkParentsNeeded). +// +// A pass interrupted after marking a snapshot deleting (e.g. a lost +// response) leaves it deleting with its name still held; the next pass +// finishes it the same way (holds checked again, then the name freed). const ( SnapshotClassSemantic = "semantic" @@ -53,9 +78,13 @@ const ( extRetention = "retention" extRetentionRev = "retention_rev" + + forkHoldsDir = "forkholds" ) -func validSnapshotClass(class string) error { +// ValidateSnapshotClass refuses a class other than "", "semantic" and +// "pinned" (invalid_class). +func ValidateSnapshotClass(class string) error { switch class { case "", SnapshotClassSemantic, SnapshotClassPinned: return nil @@ -161,6 +190,7 @@ func (c *Catalog) SetRetentionPolicy(ctx context.Context, vol string, p Retentio // RetentionDecision is one snapshot's fate under a policy. type RetentionDecision struct { Name string `json:"name"` + Attempt string `json:"attempt"` CreatedNs int64 `json:"createdNs"` Class string `json:"class"` Pinned bool `json:"pinned"` @@ -195,10 +225,10 @@ func planRetention(p RetentionPolicy, snaps []SnapshotInfo, needed map[string]bo nowNs := now.UnixNano() out := make([]RetentionDecision, len(ordered)) unpinned := 0 - buckets := map[string]bool{} + windows := map[string]bool{} for i, s := range ordered { pinned := s.Pinned() && (s.ExpiresAtNs == 0 || nowNs < s.ExpiresAtNs) - d := RetentionDecision{Name: s.Name, CreatedNs: s.CreatedNs, Class: s.Class, Pinned: pinned} + d := RetentionDecision{Name: s.Name, Attempt: s.attempt, CreatedNs: s.CreatedNs, Class: s.Class, Pinned: pinned} if pinned { d.Reasons = append(d.Reasons, keepPinned) } else { @@ -223,13 +253,20 @@ func planRetention(p RetentionPolicy, snaps []SnapshotInfo, needed map[string]bo if lk.count <= 0 || age < 0 { continue } - ago := int64(age / lk.period) // 0 = the current period - if ago >= int64(lk.count) { + k := int64(age / lk.period) // the rolling window holding this age + // RED: calendar periods, as before the review + if red := true; red { + if age >= time.Duration(lk.count)*lk.period { + continue + } + k = -1 - s.CreatedNs/int64(lk.period) + } + if k >= int64(lk.count) { continue } - key := fmt.Sprintf("%s/%d", lk.reason, s.CreatedNs/int64(lk.period)) - if !buckets[key] { // ordered newest first: the first seen is the bucket's newest - buckets[key] = true + key := fmt.Sprintf("%s/%d", lk.reason, k) + if !windows[key] { // ordered newest first: the first seen is the window's newest + windows[key] = true d.Reasons = append(d.Reasons, lk.reason) } } @@ -245,6 +282,19 @@ func planRetention(p RetentionPolicy, snaps []SnapshotInfo, needed map[string]bo return out } +// RetentionFailure is the deletion that stopped a Retain pass. +type RetentionFailure struct { + Name string `json:"name"` + Attempt string `json:"attempt"` + Code string `json:"code"` + Message string `json:"message"` + // Uncertain is set when the failing call was a mutation whose outcome + // is unknown (e.g. the response was lost): the snapshot may or may + // not be marked deleting. It is false when the pass failed before + // changing anything for this snapshot. + Uncertain bool `json:"uncertain"` +} + // RetentionResult is the outcome of one Retain pass. type RetentionResult struct { VolumeID string `json:"volumeID"` @@ -252,16 +302,23 @@ type RetentionResult struct { PolicySet bool `json:"policySet"` DryRun bool `json:"dryRun"` Decisions []RetentionDecision `json:"decisions"` - Deleted []string `json:"deleted"` // names deleted (empty on a dry run) - Kept int `json:"kept"` - Expired int `json:"expired"` + Deleted []string `json:"deleted"` // confirmed deleted (empty on a dry run) + Replaced []string `json:"replaced"` // planned, but the name now holds another attempt: left alone + ForkHeld []string `json:"forkHeld"` // planned, but a fork took a hold meanwhile: kept + Failed *RetentionFailure `json:"failed,omitempty"` + // NotAttempted lists the expired snapshots not reached because the + // pass stopped at Failed. + NotAttempted []string `json:"notAttempted"` + Kept int `json:"kept"` + Expired int `json:"expired"` } // Retain applies vol's retention policy at the catalog clock's now. A dry -// run plans and writes nothing. Otherwise every expired snapshot is -// deleted through DeleteSnapshot; a snapshot that is already gone counts -// as deleted, and the first other failure stops the pass and is returned -// with what was deleted so far. +// run plans and writes nothing. Otherwise each expired snapshot's planned +// attempt is deleted (deleteRetainedAttempt). The first failure stops the +// pass; the result then still reports every confirmed deletion, the +// failure (with whether its outcome is uncertain), and what was not +// attempted, together with the error. func (c *Catalog) Retain(ctx context.Context, vol string, dryRun bool) (RetentionResult, error) { e, _, err := c.volumeEntry(ctx, vol) if err != nil { @@ -271,39 +328,236 @@ func (c *Catalog) Retain(ctx context.Context, vol string, dryRun bool) (Retentio if err != nil { return RetentionResult{}, err } - snaps, err := c.allSnapshots(ctx, vol) + listed, err := c.listSnapshots(ctx, vol, true) if err != nil { return RetentionResult{}, err } + var snaps, unfinished []SnapshotInfo + for _, s := range listed { + if s.State == SnapDeleting { + unfinished = append(unfinished, s) // a pass stopped after its mark + } else { + snaps = append(snaps, s) + } + } needed, err := c.forkParentsNeeded(ctx, vol) if err != nil { return RetentionResult{}, err } - res := RetentionResult{VolumeID: vol, Policy: p, PolicySet: set, DryRun: dryRun, Deleted: []string{}} + res := RetentionResult{VolumeID: vol, Policy: p, PolicySet: set, DryRun: dryRun, + Deleted: []string{}, Replaced: []string{}, ForkHeld: []string{}, NotAttempted: []string{}} res.Decisions = planRetention(p, snaps, needed, c.now()) + var expired []RetentionDecision for _, d := range res.Decisions { if d.Keep { res.Kept++ continue } res.Expired++ - if dryRun { - continue - } - if _, err := c.DeleteSnapshot(ctx, vol, d.Name); err != nil && CodeOf(err) != CodeSnapshotNotFound { + expired = append(expired, d) + } + for _, s := range unfinished { + expired = append(expired, RetentionDecision{Name: s.Name, Attempt: s.attempt, CreatedNs: s.CreatedNs, Class: s.Class, Reasons: []string{SnapDeleting}}) + } + if dryRun { + return res, nil + } + c.hook(hookPlanned, "") + for i, d := range expired { + outcome, uncertain, err := c.deleteRetainedAttempt(ctx, vol, d.Name, d.Attempt) + if err != nil { + res.Failed = &RetentionFailure{Name: d.Name, Attempt: d.Attempt, Code: codeOrRemote(err), Message: err.Error(), Uncertain: uncertain} + for _, rest := range expired[i+1:] { + res.NotAttempted = append(res.NotAttempted, rest.Name) + } return res, err } - res.Deleted = append(res.Deleted, d.Name) + switch outcome { + case retainDeleted: + res.Deleted = append(res.Deleted, d.Name) + case retainReplaced: + res.Replaced = append(res.Replaced, d.Name) + case retainForkHeld: + res.ForkHeld = append(res.ForkHeld, d.Name) + } } return res, nil } -// allSnapshots lists every published, not-deleting snapshot of vol. +func codeOrRemote(err error) string { + if code := CodeOf(err); code != "" { + return code + } + return CodeRemoteUnavailable +} + +type retainOutcome int + +const ( + retainDeleted retainOutcome = iota // marked deleting (or already gone) and the name freed + retainReplaced // the planned attempt is gone; another attempt holds the name + retainForkHeld // a fork holds the attempt: the mark was reverted, kept +) + +// deleteRetainedAttempt deletes the planned attempt of vol/name and only +// that attempt. uncertain reports, with an error, that the failing call +// was a mutation whose outcome is unknown. +func (c *Catalog) deleteRetainedAttempt(ctx context.Context, vol, name, attempt string) (retainOutcome, bool, error) { + if red := true; red { // RED: delete by name, as before the review + c.hook(hookUnheld, name) + if _, err := c.DeleteSnapshot(ctx, vol, name); err != nil && CodeOf(err) != CodeSnapshotNotFound { + return 0, false, err + } + return retainDeleted, false, nil + } + root, err := c.volRoot(vol) + if err != nil { + return 0, false, err + } + dir := path.Join(root, snapsDir, name) + e, err := c.f.LookupEntry(ctx, dir, attempt) + if errors.Is(err, ErrNotFound) { + return c.freeName(ctx, root, name, attempt) + } + if err != nil { + return 0, false, remoteErr(err, "read snapshot %s/%s attempt %s", vol, name, attempt) + } + if string(e.Extended[extSnapState]) == SnapDeleting { + // A pass stopped after its mark: decide the holds again. + held, err := c.forkHeld(ctx, vol, root, name, attempt) + if err != nil { + return 0, false, err + } + if held { + return c.revertMark(ctx, dir, e, name, attempt) + } + return c.freeName(ctx, root, name, attempt) + } + if string(e.Extended[extSnapState]) == SnapActive { + marked := proto.Clone(e).(*filerpb.Entry) + marked.Extended[extSnapState] = []byte(SnapDeleting) + marked.Extended[extSnapDeletedNs] = []byte(strconv.FormatInt(c.now().UnixNano(), 10)) + err := c.f.UpdateEntry(ctx, dir, marked, map[string][]byte{ + extSnapState: []byte(SnapActive), + extSnapGen: e.Extended[extSnapGen], + }) + switch { + case errors.Is(err, ErrPrecondition) || errors.Is(err, ErrNotFound): + // changed under us: decided again from a fresh read below + case err != nil: + return 0, true, remoteErr(err, "mark snapshot %s/%s attempt %s deleting", vol, name, attempt) + default: + held, err := c.forkHeld(ctx, vol, root, name, attempt) + if err != nil { + return 0, false, err // marked deleting; a rerun keeps or completes it + } + if held { + return c.revertMark(ctx, dir, marked, name, attempt) + } + c.hook(hookUnheld, name) + } + e, err = c.f.LookupEntry(ctx, dir, attempt) + if errors.Is(err, ErrNotFound) { + return c.freeName(ctx, root, name, attempt) + } + if err != nil { + return 0, false, remoteErr(err, "re-read snapshot %s/%s attempt %s", vol, name, attempt) + } + if string(e.Extended[extSnapState]) == SnapActive { + return 0, false, remoteErr(nil, "snapshot %s/%s attempt %s is still active after the delete mark", vol, name, attempt) + } + } + return c.freeName(ctx, root, name, attempt) +} + +// revertMark returns a deleting attempt to active: a fork holds it. +func (c *Catalog) revertMark(ctx context.Context, dir string, e *filerpb.Entry, name, attempt string) (retainOutcome, bool, error) { + back := proto.Clone(e).(*filerpb.Entry) + back.Extended[extSnapState] = []byte(SnapActive) + delete(back.Extended, extSnapDeletedNs) + if err := c.f.UpdateEntry(ctx, dir, back, map[string][]byte{extSnapState: []byte(SnapDeleting)}); err != nil { + return 0, true, remoteErr(err, "revert snapshot %s attempt %s: a fork holds it", name, attempt) + } + return retainForkHeld, false, nil +} + +// Test seams: hook stages in a Retain pass. +const ( + hookPlanned = "planned" // after planning, before any deletion + hookUnheld = "unheld" // a snapshot is marked and no hold was found, before its name is freed +) + +func (c *Catalog) hook(stage, name string) { + if c.retainHook != nil { + c.retainHook(stage, name) + } +} + +// freeName removes the name record of name only while it names attempt. +func (c *Catalog) freeName(ctx context.Context, root, name, attempt string) (retainOutcome, bool, error) { + err := c.f.DeleteEntry(ctx, path.Join(root, snapNamesDir), name, map[string][]byte{extAttempt: []byte(attempt)}) + switch { + case err == nil || errors.Is(err, ErrNotFound): + return retainDeleted, false, nil + case errors.Is(err, ErrPrecondition): + return retainReplaced, false, nil + } + return 0, true, remoteErr(err, "remove the name record %s", name) +} + +// forkHoldDir is where forks record their holds on a parent attempt. +func forkHoldDir(root, name, attempt string) string { + return path.Join(root, forkHoldsDir, name, attempt) +} + +// forkHeld reports whether a fork still needs attempt of vol/name: one of +// its holds names a target with no HEAD yet whose VOLUME records this +// fork, or whose hold is younger than the operation deadline (its VOLUME +// may be about to land). A hold whose target has a real or aborted HEAD +// is stale (that fork completed or lost), as is an old hold with no +// matching VOLUME (that fork died before publishing). +func (c *Catalog) forkHeld(ctx context.Context, vol, root, name, attempt string) (bool, error) { + holds, err := c.f.ListEntries(ctx, forkHoldDir(root, name, attempt), "", "", 0) + if err != nil { + return false, remoteErr(err, "list the fork holds of %s/%s", name, attempt) + } + for _, h := range holds { + if h.GetIsDirectory() { + continue + } + target := h.GetName() + _, has, err := c.ReadHead(ctx, target) + if err != nil { + return false, err + } + if has { + continue + } + v, ok, err := c.ReadVolume(ctx, target) + if err != nil { + return false, err + } + if ok && v.Fork != nil && v.Fork.Source == vol && v.Fork.Snapshot == name { + return true, nil + } + if c.now().Sub(time.Unix(h.GetAttributes().GetCrtime(), 0)) < c.deadline() { + return true, nil + } + } + return false, nil +} + +// allSnapshots lists every published, not-deleting snapshot of vol, with +// the attempt each name resolved to. func (c *Catalog) allSnapshots(ctx context.Context, vol string) ([]SnapshotInfo, error) { + return c.listSnapshots(ctx, vol, false) +} + +func (c *Catalog) listSnapshots(ctx context.Context, vol string, deleting bool) ([]SnapshotInfo, error) { var out []SnapshotInfo after := "" for { - page, next, err := c.ListSnapshots(ctx, vol, ListOptions{StartAfter: after, Limit: maxListLimit}) + page, next, err := c.ListSnapshots(ctx, vol, ListOptions{StartAfter: after, Limit: maxListLimit, IncludeDeleting: deleting}) if err != nil { return nil, err } @@ -318,10 +572,11 @@ func (c *Catalog) allSnapshots(ctx context.Context, vol string) ([]SnapshotInfo, } } -// forkParentsNeeded names the snapshots of vol a fork still needs: a -// volume whose fork record names vol and the snapshot, and which has no -// real published HEAD yet (absent or aborted). A published fork HEAD pins -// its chunks for GC itself, so it no longer needs the snapshot. +// forkParentsNeeded names the snapshots of vol a fork still needs by its +// published fork record: a volume whose fork record names vol and the +// snapshot, and which has no real published HEAD yet (absent or aborted). +// It covers forks published before fork holds existed; a newer fork is +// also covered, atomically, by its hold (deleteRetainedAttempt). func (c *Catalog) forkParentsNeeded(ctx context.Context, vol string) (map[string]bool, error) { vols, err := c.ListVolumes(ctx) if err != nil { diff --git a/seaweed-block/core/frontend/chunkstore/retention_integration_test.go b/seaweed-block/core/frontend/chunkstore/retention_integration_test.go index 54c01cae93..d5353c70a2 100644 --- a/seaweed-block/core/frontend/chunkstore/retention_integration_test.go +++ b/seaweed-block/core/frontend/chunkstore/retention_integration_test.go @@ -135,3 +135,98 @@ func TestIntegration_RetainAndUsage(t *testing.T) { t.Fatalf("after: %d bindings, upper=%t; want all still stored (no GC yet), flagged as an upper bound", after.StoredBindings, after.StoredUpperBound) } } + +// The two held schedules of the review of #142 against a real filer: +// (1) a same-name pinned replacement made after planning survives (the +// filer's conditional name delete refuses the stale attempt); (2) a fork +// that starts after the scan and stops before its HEAD (VOLUME published, +// deadline exceeded) keeps its parent, and completes on retry. +func TestIntegration_RetainHeldSchedules(t *testing.T) { + c := startWeed(t) + ctx := context.Background() + const base = "/swblock/chunks" + geo := Geometry{NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 8} + full := int(geo.ChunkBlocks) * int(geo.BlockSize) + cat, err := NewCatalog(c.client(t, base), base) + if err != nil { + t.Fatal(err) + } + if _, err := cat.EnsureVolume(ctx, "v1", geo); err != nil { + t.Fatal(err) + } + r := c.remote(t, path.Join(base, "v1")) + data := bytes.Repeat([]byte{7}, full) + if err := r.Put(ctx, "chunks/e1/c0/k", data); err != nil { + t.Fatal(err) + } + cur, err := r.GetHead(ctx) + if err != nil { + t.Fatal(err) + } + head := storage.ChunkHead{Epoch: 1, Holder: "h1", RemoteLSN: 1, Chunks: map[uint64]storage.ChunkRef{0: ref("chunks/e1/c0/k", data)}} + if head.Gen, err = r.CASHead(ctx, storage.ChunkHeadVersion{Gen: cur.Gen, Epoch: cur.Epoch}, head); err != nil { + t.Fatal(err) + } + clock := time.Now().Add(-72 * time.Hour) + cat.SetClock(func() time.Time { clock = clock.Add(time.Second); return clock }) // every read advances + for i := 0; i < 3; i++ { + if _, err := cat.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: fmt.Sprintf("s%02d", i), RequestID: fmt.Sprintf("r%02d", i), Class: SnapshotClassSemantic}, head); err != nil { + t.Fatal(err) + } + } + if err := cat.SetRetentionPolicy(ctx, "v1", RetentionPolicy{}); err != nil { // keep nothing by policy + t.Fatal(err) + } + clock = time.Now() + + var pinnedAttempt string + cat.retainHook = func(stage, _ string) { + if stage != hookPlanned { + return + } + // (1) s00 is replaced by a pinned snapshot of the same name. + if _, err := cat.DeleteSnapshot(ctx, "v1", "s00"); err != nil { + t.Fatal(err) + } + if _, err := cat.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s00", RequestID: "pinned-b", Class: SnapshotClassPinned}, head); err != nil { + t.Fatal(err) + } + b, err := cat.readSnap(ctx, "v1", "s00") + if err != nil { + t.Fatal(err) + } + pinnedAttempt = b.attempt + // (2) a fork of s01 publishes its VOLUME and stops before HEAD. + cat.OpDeadline = time.Nanosecond + _, err = cat.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s01", Target: "v2", RequestID: "f"}) + cat.OpDeadline = 0 + if CodeOf(err) != CodeDeadlineExceeded { + t.Fatalf("fork past its deadline: %v; want deadline_exceeded", err) + } + if _, ok, err := cat.ReadVolume(ctx, "v2"); !ok || err != nil { + t.Fatalf("the stopped fork's VOLUME: ok=%t %v", ok, err) + } + } + res, err := cat.Retain(ctx, "v1", false) + if err != nil { + t.Fatal(err) + } + cat.retainHook = nil + if fmt.Sprint(res.Deleted) != "[s02]" || fmt.Sprint(res.Replaced) != "[s00]" || fmt.Sprint(res.ForkHeld) != "[s01]" { + t.Fatalf("retain: deleted=%v replaced=%v forkHeld=%v; want s02 / s00 / s01", res.Deleted, res.Replaced, res.ForkHeld) + } + b, err := cat.readSnap(ctx, "v1", "s00") + if err != nil || b.attempt != pinnedAttempt || b.State != SnapActive || b.Class != SnapshotClassPinned { + t.Fatalf("pinned replacement: %+v %v (attempt %s, want %s)", b, err, b.attempt, pinnedAttempt) + } + if s, err := cat.readSnap(ctx, "v1", "s01"); err != nil || s.State != SnapActive { + t.Fatalf("fork parent: %+v %v; want active", s, err) + } + if _, err := cat.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s01", Target: "v2", RequestID: "f"}); err != nil { + t.Fatalf("fork retry: %v", err) + } + res, err = cat.Retain(ctx, "v1", false) + if err != nil || fmt.Sprint(res.Deleted) != "[s01]" { + t.Fatalf("after the fork completed: deleted=%v %v; want s01 (s00 is pinned)", res.Deleted, err) + } +} diff --git a/seaweed-block/core/frontend/chunkstore/retention_review_test.go b/seaweed-block/core/frontend/chunkstore/retention_review_test.go new file mode 100644 index 0000000000..1af7fc7308 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/retention_review_test.go @@ -0,0 +1,269 @@ +package chunkstore + +import ( + "context" + "errors" + "strings" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" +) + +// Controls for the review of #142: attempt-bound deletion, fork holds, +// rolling windows, cross-volume holders and partial results. + +// Log-spaced keeps use rolling windows anchored at now, not calendar +// periods: at 10:30 with KeepHourly=1, 10:20 is kept and 09:50 (another +// clock hour, but inside the same rolling hour) is not. +func TestPlanRetention_RollingWindows(t *testing.T) { + day0 := time.Unix(86400*1000, 0) // midnight, so clock hours and days are visible + at := func(d time.Duration) time.Time { return day0.Add(d) } + nm := func(a time.Time) string { return a.UTC().Format("01-02T15:04") } + plan := func(p RetentionPolicy, now time.Time, ages ...time.Time) map[string][]string { + var snaps []SnapshotInfo + for _, a := range ages { + snaps = append(snaps, snapAt(nm(a), a, SnapshotClassSemantic, time.Time{}, nil)) + } + return kept(planRetention(p, snaps, nil, now)) + } + now := at(10*time.Hour + 30*time.Minute) + if k := plan(RetentionPolicy{KeepHourly: 1}, now, at(10*time.Hour+20*time.Minute), at(9*time.Hour+50*time.Minute)); len(k) != 1 || k[nm(at(10*time.Hour+20*time.Minute))] == nil { + t.Fatalf("hourly at 10:30: kept %v; want only 10:20", k) + } + // Windows k=0,1: [09:30,10:30) and [08:30,09:30). 09:00 is the newest of window 1. + if k := plan(RetentionPolicy{KeepHourly: 2}, now, at(10*time.Hour+20*time.Minute), at(9*time.Hour+50*time.Minute), at(9*time.Hour), at(8*time.Hour+40*time.Minute)); len(k) != 2 || k[nm(at(10*time.Hour+20*time.Minute))] == nil || k[nm(at(9*time.Hour))] == nil { + t.Fatalf("hourly=2 at 10:30: kept %v; want 10:20 and 09:00", k) + } + // Daily across a non-aligned midnight: at 01:00, 00:30 and 23:00 the + // day before are both in the last rolling day; only the newest stays. + now = at(24*time.Hour + time.Hour) + if k := plan(RetentionPolicy{KeepDaily: 1}, now, at(24*time.Hour+30*time.Minute), at(23*time.Hour)); len(k) != 1 || k[nm(at(24*time.Hour+30*time.Minute))] == nil { + t.Fatalf("daily at 01:00: kept %v; want only 00:30", k) + } + // Weekly: 8 days back is week window 1, 6 days back window 0. + if k := plan(RetentionPolicy{KeepWeekly: 1}, now, now.Add(-6*24*time.Hour), now.Add(-8*24*time.Hour)); len(k) != 1 { + t.Fatalf("weekly=1: kept %v; want only the 6-day-old one", k) + } + if k := plan(RetentionPolicy{KeepWeekly: 2}, now, now.Add(-6*24*time.Hour), now.Add(-8*24*time.Hour), now.Add(-13*24*time.Hour)); len(k) != 2 { + t.Fatalf("weekly=2: kept %v; want 6 and 8 days old", k) + } +} + +// Deletion is bound to the planned attempt: a same-name pinned replacement +// made between planning and deletion survives, attempt and name intact. +func TestCatalog_RetainSkipsASameNameReplacement(t *testing.T) { + _, c, h, _ := retentionFixture(t, 15) // s00..s04 expire + ctx := context.Background() + var newAttempt string + c.retainHook = func(stage, _ string) { + if stage != hookPlanned { + return + } + if _, err := c.DeleteSnapshot(ctx, "v1", "s02"); err != nil { + t.Fatal(err) + } + if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s02", RequestID: "pinned-b", Class: SnapshotClassPinned}, h); err != nil { + t.Fatal(err) + } + b, err := c.readSnap(ctx, "v1", "s02") + if err != nil { + t.Fatal(err) + } + newAttempt = b.attempt + } + res, err := c.Retain(ctx, "v1", false) + if err != nil { + t.Fatal(err) + } + b, err := c.readSnap(ctx, "v1", "s02") + if err != nil { + t.Fatalf("the pinned replacement is gone: %v", err) + } + if b.attempt != newAttempt || b.State != SnapActive || b.Class != SnapshotClassPinned { + t.Fatalf("replacement changed: %+v (attempt %s, want %s)", b, b.attempt, newAttempt) + } + if strings.Join(res.Replaced, ",") != "s02" || strings.Join(res.Deleted, ",") != "s04,s03,s01,s00" { + t.Fatalf("deleted=%v replaced=%v; want s02 replaced, the other four deleted", res.Deleted, res.Replaced) + } +} + +func forkFixture(t *testing.T) (*fakeFiler, *Catalog) { + t.Helper() + f, c, _, _ := retentionFixture(t, 3) + ctx := context.Background() + if err := c.SetRetentionPolicy(ctx, "v1", RetentionPolicy{}); err != nil { // keep nothing by policy + t.Fatal(err) + } + for _, vol := range []string{"v1", "v2"} { + if err := f.CreateEntry(ctx, catBase, &filerpb.Entry{Name: vol, IsDirectory: true}, true); err != nil { + t.Fatal(err) + } + } + return f, c +} + +// A fork that starts after the retention scan (its VOLUME published, its +// HEAD not yet) holds the parent: the mark is reverted, the parent kept, +// and the fork completes on retry. +func TestCatalog_RetainKeepsAParentForkedAfterTheScan(t *testing.T) { + f, c := forkFixture(t) + ctx := context.Background() + c.retainHook = func(stage, _ string) { + if stage != hookPlanned { + return + } + holdFirst(f, catBase+"/v2/HEAD") + if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s01", Target: "v2", RequestID: "f"}); CodeOf(err) != CodeOutcomeUnknown { + t.Fatalf("fork with a held HEAD create: %v", err) + } + } + res, err := c.Retain(ctx, "v1", false) + if err != nil { + t.Fatal(err) + } + if strings.Join(res.ForkHeld, ",") != "s01" || strings.Join(res.Deleted, ",") != "s02,s00" { + t.Fatalf("deleted=%v forkHeld=%v; want s01 kept for the fork", res.Deleted, res.ForkHeld) + } + if s, err := c.readSnap(ctx, "v1", "s01"); err != nil || s.State != SnapActive { + t.Fatalf("parent after retain: %+v %v; want active", s, err) + } + c.retainHook = nil + if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s01", Target: "v2", RequestID: "f"}); err != nil { + t.Fatalf("fork retry: %v", err) + } + // Completed: the hold is gone and the parent is no longer needed. + res, err = c.Retain(ctx, "v1", false) + if err != nil || strings.Join(res.Deleted, ",") != "s01" { + t.Fatalf("after the fork completed: deleted=%v %v; want s01", res.Deleted, err) + } +} + +// A fork that takes its hold after retention checked the holds finds the +// attempt deleting and refuses before installing anything. +func TestCatalog_ForkAfterTheHoldCheckRefuses(t *testing.T) { + f, c := forkFixture(t) + ctx := context.Background() + ran := false + c.retainHook = func(stage, name string) { + if stage != hookUnheld || name != "s01" { + return + } + ran = true + if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s01", Target: "v2", RequestID: "f"}); CodeOf(err) != CodeSnapshotDeleting { + t.Fatalf("fork of a marked parent: %v; want snapshot_deleting", err) + } + } + res, err := c.Retain(ctx, "v1", false) + if err != nil { + t.Fatal(err) + } + if !ran || strings.Join(res.Deleted, ",") != "s02,s01,s00" { + t.Fatalf("ran=%v deleted=%v; want all three", ran, res.Deleted) + } + if _, ok, err := c.ReadVolume(ctx, "v2"); ok || err != nil { + t.Fatalf("a refused fork published its VOLUME (%v)", err) + } + if holds, _ := f.ListEntries(ctx, forkHoldDir(catBase+"/v1", "s01", res.Decisions[1].Attempt), "", "", 0); len(holds) != 0 { + t.Fatalf("a refused fork left %d holds", len(holds)) + } +} + +// A hold whose fork died before publishing its VOLUME counts only within +// the operation deadline. +func TestCatalog_StaleForkHoldExpires(t *testing.T) { + f, c := forkFixture(t) + ctx := context.Background() + s, err := c.readSnap(ctx, "v1", "s01") + if err != nil { + t.Fatal(err) + } + now := c.now() + hold := func(target string, at time.Time) { + e := &filerpb.Entry{Name: target, Attributes: &filerpb.FuseAttributes{Crtime: at.Unix(), Mtime: at.Unix()}} + if err := f.CreateEntry(ctx, forkHoldDir(catBase+"/v1", "s01", s.attempt), e, true); err != nil { + t.Fatal(err) + } + } + hold("v8", now.Add(-time.Second)) // young: the fork may still publish + res, err := c.Retain(ctx, "v1", false) + if err != nil || strings.Join(res.ForkHeld, ",") != "s01" { + t.Fatalf("young hold: forkHeld=%v %v; want s01", res.ForkHeld, err) + } + if err := f.DeleteEntry(ctx, forkHoldDir(catBase+"/v1", "s01", s.attempt), "v8", nil); err != nil { + t.Fatal(err) + } + hold("v9", now.Add(-2*c.deadline())) // old, no VOLUME: the fork died + res, err = c.Retain(ctx, "v1", false) + if err != nil || strings.Join(res.Deleted, ",") != "s01" { + t.Fatalf("stale hold: deleted=%v %v; want s01", res.Deleted, err) + } +} + +// A failure part way reports the confirmed deletions, the failing +// snapshot (uncertain: the mark's outcome is unknown) and what was not +// attempted; a lost response leaves the snapshot deleting and the next +// pass finishes it. +func TestCatalog_RetainReportsPartialProgress(t *testing.T) { + f, c, _, _ := retentionFixture(t, 15) // s04,s03,s02,s01,s00 expire, in that order + ctx := context.Background() + f.failUpdate = func(p string) error { + if strings.Contains(p, "/snaps/s03/") { + return errors.New("filer unavailable") + } + return nil + } + res, err := c.Retain(ctx, "v1", false) + if err == nil || res.Failed == nil { + t.Fatalf("retain with a failing mark: %+v %v; want an error with the partial result", res, err) + } + if strings.Join(res.Deleted, ",") != "s04" || res.Failed.Name != "s03" || !res.Failed.Uncertain || strings.Join(res.NotAttempted, ",") != "s02,s01,s00" { + t.Fatalf("partial: deleted=%v failed=%+v notAttempted=%v", res.Deleted, res.Failed, res.NotAttempted) + } + + f.failUpdate = nil + f.failUpdateAfterApply = func(p string) error { + if strings.Contains(p, "/snaps/s03/") { + return errors.New("response lost") + } + return nil + } + res, err = c.Retain(ctx, "v1", false) + if err == nil || res.Failed == nil || res.Failed.Name != "s03" || !res.Failed.Uncertain || len(res.Deleted) != 0 { + t.Fatalf("lost response: %+v %v", res, err) + } + f.failUpdateAfterApply = nil + res, err = c.Retain(ctx, "v1", false) + if err != nil || strings.Join(res.Deleted, ",") != "s02,s01,s00,s03" { + t.Fatalf("rerun: deleted=%v %v; want the rest and the half-deleted s03", res.Deleted, err) + } + if _, ok, err := c.resolveSnap(ctx, "v1", "s03"); ok || err != nil { + t.Fatalf("s03's name still held after the rerun (%v)", err) + } +} + +// Exclusive bytes count other volumes' holders: after a completed fork, a +// snapshot whose chunks the fork's HEAD references ("@v1/key") owns none. +func TestCatalog_UsageCountsForkHolders(t *testing.T) { + f, b, c, h := catalogFixture(t) + ctx := context.Background() + for _, vol := range []string{"v1", "v2"} { + if err := f.CreateEntry(ctx, catBase, &filerpb.Entry{Name: vol, IsDirectory: true}, true); err != nil { + t.Fatal(err) + } + } + if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r1"}, h); err != nil { + t.Fatal(err) + } + if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "f"}); err != nil { + t.Fatal(err) + } + publishTagged(t, f, b, "v1", "e2", map[uint64][]byte{0: chunkBytes(0x20), 3: chunkBytes(0x13)}) + u, err := c.Usage(ctx, "v1") + if err != nil { + t.Fatal(err) + } + if len(u.Snapshots) != 1 || u.Snapshots[0].ExclusiveBytes != 0 { + t.Fatalf("s1 after v1's HEAD moved, v2 forked from it: %+v; want 0 exclusive (v2 holds both chunks)", u.Snapshots) + } +} diff --git a/seaweed-block/core/frontend/chunkstore/usage.go b/seaweed-block/core/frontend/chunkstore/usage.go index 52b7fdf9d0..0faac9fbcc 100644 --- a/seaweed-block/core/frontend/chunkstore/usage.go +++ b/seaweed-block/core/frontend/chunkstore/usage.go @@ -18,9 +18,13 @@ import ( // NumBlocks (ChunkRef carries no size). // // - LiveBytes: the chunks HEAD references. -// - per snapshot, ExclusiveBytes: the chunks that snapshot references and -// neither HEAD nor any other live snapshot does, i.e. what deleting it -// would let GC reclaim. +// - per snapshot, ExclusiveBytes: the chunks that snapshot references +// and no other holder does, where the holders are this volume's HEAD +// and live snapshots AND every other volume's HEAD and live snapshots +// (a fork's "@owner/key" references are resolved to the owner's +// chunk). These are the bytes deleting that snapshot makes eligible +// for GC; GC still keeps them through its grace period and while any +// in-flight intent names them, so they are not reclaimed at once. // - StoredBytes: the volume's chunk-key bindings in the filer (what is // stored now, referenced or not). A binding a manifest references is // counted at its exact (clipped) size; any other binding at the full @@ -95,38 +99,66 @@ func (c *Catalog) Usage(ctx context.Context, vol string) (VolumeUsage, error) { return VolumeUsage{}, err } - // holders counts, per chunk key, how many of HEAD and the live - // snapshots reference it; size is each referenced key's byte size. + // holders counts, per chunk identity (owner volume + key), how many + // HEADs and live snapshots of any volume reference it; size is each + // identity's byte size as this volume's geometry indexes it. holders := map[string]int{} size := map[string]uint64{} - addHolder := func(h storage.ChunkHead) { + addHolder := func(owner string, h storage.ChunkHead, sized bool) { seen := map[string]bool{} for idx, ref := range h.Chunks { - size[ref.Key] = chunkSize(g, idx) - if !seen[ref.Key] { - seen[ref.Key] = true - holders[ref.Key]++ + id := chunkIdentity(owner, ref.Key) + if sized { + size[id] = chunkSize(g, idx) + } + if !seen[id] { + seen[id] = true + holders[id]++ } } } - addHolder(head) + addHolder(vol, head, true) for idx := range head.Chunks { u.LiveChunks++ u.LiveBytes += chunkSize(g, idx) } for _, s := range snaps { - addHolder(s.Head()) + addHolder(vol, s.Head(), true) + } + others, err := c.ListVolumes(ctx) + if err != nil { + return VolumeUsage{}, err + } + for _, other := range others { + if other == vol { + continue + } + oh, has, err := c.ReadHead(ctx, other) + if err != nil { + return VolumeUsage{}, err + } + if has { + addHolder(other, oh, false) + } + osnaps, err := c.allSnapshots(ctx, other) + if err != nil { + return VolumeUsage{}, err + } + for _, s := range osnaps { + addHolder(other, s.Head(), false) + } } for _, s := range snaps { su := SnapshotUsage{Name: s.Name, CreatedNs: s.CreatedNs, Class: s.Class, Pinned: s.Pinned(), Chunks: len(s.Head().Chunks)} seen := map[string]bool{} for _, ref := range s.Head().Chunks { - if seen[ref.Key] { + id := chunkIdentity(vol, ref.Key) + if seen[id] { continue } - seen[ref.Key] = true - if holders[ref.Key] == 1 { - su.ExclusiveBytes += size[ref.Key] + seen[id] = true + if holders[id] == 1 { + su.ExclusiveBytes += size[id] } } u.Snapshots = append(u.Snapshots, su) @@ -162,7 +194,7 @@ func (c *Catalog) Usage(ctx context.Context, vol string) (VolumeUsage, error) { continue } u.StoredBindings++ - if n, ok := size[key]; ok { + if n, ok := size[chunkIdentity(vol, key)]; ok { u.StoredBytes += n } else { u.StoredBytes += u.ChunkBytes @@ -174,3 +206,18 @@ func (c *Catalog) Usage(ctx context.Context, vol string) (VolumeUsage, error) { } } } + +// chunkIdentity names the chunk a ref in volume vol points at: an +// owner-qualified "@owner/key" (a fork's reference) is owner's key, +// anything else is vol's. +func chunkIdentity(vol, key string) string { + if red := true; red { // RED: owner-qualified refs not resolved + return vol + "\x00" + key + } + if strings.HasPrefix(key, "@") { + if owner, rest, ok := strings.Cut(key[1:], "/"); ok { + return owner + "\x00" + rest + } + } + return vol + "\x00" + key +} diff --git a/seaweed-block/core/host/volume/chunk_control.go b/seaweed-block/core/host/volume/chunk_control.go index 5fdbe5792a..adba62b03c 100644 --- a/seaweed-block/core/host/volume/chunk_control.go +++ b/seaweed-block/core/host/volume/chunk_control.go @@ -214,7 +214,7 @@ func chunkErrorCode(err error) (int, string, bool) { func catalogStatus(code string) int { switch code { - case chunkstore.CodeInvalidName, chunkstore.CodeInvalidLabel: + case chunkstore.CodeInvalidName, chunkstore.CodeInvalidLabel: // RED: class and policy errors fall to 409 return http.StatusBadRequest case chunkstore.CodeSnapshotNotFound: return http.StatusNotFound @@ -463,6 +463,11 @@ func (c *chunkControl) Cut(ctx context.Context, volumeID string, minLSN uint64) // for the name gets snapshot_exists, both without cutting. Only a free name // is cut, and the HEAD that cut installed is stored. func (c *chunkControl) Snapshot(ctx context.Context, volumeID string, req ChunkSnapshotRequest) (chunkstore.SnapshotInfo, error) { + // Admit the request before anything can cut: an invalid class must + // not advance HEAD (review of #142). + if red := true; !red { // RED: the class is checked only after the cut + return chunkstore.SnapshotInfo{}, chunkstore.ValidateSnapshotClass(req.Class) + } sreq := chunkstore.SnapshotRequest{Name: req.Name, RequestID: req.RequestID, Labels: req.Labels, Consistency: req.Consistency, ExpiresAtNs: req.ExpiresAtNs, CreatedBy: "blockvolume", Class: req.Class} if info, replayed, err := c.cat.SnapshotReplay(ctx, volumeID, sreq); err != nil || replayed { diff --git a/seaweed-block/core/host/volume/chunk_control_class_test.go b/seaweed-block/core/host/volume/chunk_control_class_test.go new file mode 100644 index 0000000000..89d333a9bc --- /dev/null +++ b/seaweed-block/core/host/volume/chunk_control_class_test.go @@ -0,0 +1,41 @@ +package volume + +import ( + "context" + "net/http" + "testing" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" +) + +// An invalid class is refused before anything cuts or writes, and as a +// client error (400); a valid class cuts once, and its replay cuts none +// (review of #142). +func TestChunkControl_InvalidClassRefusedBeforeCut(t *testing.T) { + ctx := context.Background() + fp, ctl := adapterFixture(t) + _, err := ctl.Snapshot(ctx, "v1", ChunkSnapshotRequest{Name: "s1", RequestID: "r1", Class: "golden"}) + if chunkstore.CodeOf(err) != chunkstore.CodeInvalidClass { + t.Fatalf("invalid class: %v; want invalid_class", err) + } + if fp.cuts != 0 { + t.Fatalf("an invalid class cut %d times", fp.cuts) + } + if got, _, err := ctl.ListSnapshots(ctx, "v1", chunkstore.ListOptions{}); err != nil || len(got) != 0 { + t.Fatalf("an invalid class left snapshots %v (%v)", got, err) + } + for _, code := range []string{chunkstore.CodeInvalidClass, chunkstore.CodeInvalidPolicy} { + if s := catalogStatus(code); s != http.StatusBadRequest { + t.Fatalf("%s maps to %d, want 400", code, s) + } + } + + info, err := ctl.Snapshot(ctx, "v1", ChunkSnapshotRequest{Name: "s1", RequestID: "r1", Class: chunkstore.SnapshotClassPinned}) + if err != nil || info.Class != chunkstore.SnapshotClassPinned || fp.cuts != 1 { + t.Fatalf("valid class: %+v %v cuts=%d", info, err, fp.cuts) + } + info, err = ctl.Snapshot(ctx, "v1", ChunkSnapshotRequest{Name: "s1", RequestID: "r1", Class: chunkstore.SnapshotClassPinned}) + if err != nil || !info.Replayed || fp.cuts != 1 { + t.Fatalf("replay: %+v %v cuts=%d; want a replay with no new cut", info, err, fp.cuts) + } +} From 56300cc6c19a9dba68c084a5a463d7ee10ccb11b Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 15 Nov 2026 15:36:46 -0800 Subject: [PATCH 04/10] chunkstore: attempt-bound retention, fork holds, rolling windows - Retain deletes the exact attempt it planned: the attempt's entry is marked deleting conditionally and the name record is removed only while it names that attempt; a replacement is reported as replaced. - Fork records a hold (forkholds///) before it reads the parent. Retain marks first, then reads the holds: a live hold reverts the mark (fork_held); a fork holding after that read finds the attempt deleting and refuses before installing anything. A hold counts while its target has no HEAD and its VOLUME records the fork, or while it is younger than the operation deadline. - A pass stopped after a mark finishes (or reverts) it on the next run. - Log-spaced keeps use rolling windows anchored at now. - Exclusive bytes resolve "@owner/key" refs and count every volume's HEAD and live snapshots as holders; documented as eligible for GC subject to its grace period and intents. - Retain reports confirmed deletions, the failing snapshot (uncertain or not) and what it never reached; the CLI prints them with the error and exits nonzero. - chunkControl.Snapshot validates the class before any cut; invalid_class and invalid_policy map to 400. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/cmd/sw-block/chunk_retain.go | 3 --- seaweed-block/core/frontend/chunkstore/catalog.go | 3 --- .../core/frontend/chunkstore/retention.go | 14 -------------- seaweed-block/core/frontend/chunkstore/usage.go | 3 --- seaweed-block/core/host/volume/chunk_control.go | 6 +++--- 5 files changed, 3 insertions(+), 26 deletions(-) diff --git a/seaweed-block/cmd/sw-block/chunk_retain.go b/seaweed-block/cmd/sw-block/chunk_retain.go index fc3664e471..7b9702672c 100644 --- a/seaweed-block/cmd/sw-block/chunk_retain.go +++ b/seaweed-block/cmd/sw-block/chunk_retain.go @@ -106,9 +106,6 @@ type retainOutput struct { } func retainPartial(res chunkstore.RetentionResult, err error, stdout, stderr io.Writer) int { - if red := true; red { // RED: the partial result is discarded - return chunkResult("retain", nil, err, stdout, stderr) - } body := chunkErrBody{Code: chunkstore.CodeOf(err), Message: err.Error(), Retryable: true} var ce *chunkstore.CatalogError if errors.As(err, &ce) { diff --git a/seaweed-block/core/frontend/chunkstore/catalog.go b/seaweed-block/core/frontend/chunkstore/catalog.go index eeca29c9c8..5590fea2b0 100644 --- a/seaweed-block/core/frontend/chunkstore/catalog.go +++ b/seaweed-block/core/frontend/chunkstore/catalog.go @@ -1298,9 +1298,6 @@ func (c *Catalog) holdForkParent(ctx context.Context, srcRoot string, req ForkRe if err != nil || !ok { return "", err } - if red := true; red { // RED: no hold recorded - return ref.rec.Attempt, nil - } now := c.now().Unix() e := &filerpb.Entry{Name: req.Target, Attributes: &filerpb.FuseAttributes{Mtime: now, Crtime: now, FileMode: 0o644}} if err := c.f.CreateEntry(ctx, forkHoldDir(srcRoot, req.Snapshot, ref.rec.Attempt), e, true); err != nil && !errors.Is(err, ErrExists) { diff --git a/seaweed-block/core/frontend/chunkstore/retention.go b/seaweed-block/core/frontend/chunkstore/retention.go index c291809a77..bbec3c3793 100644 --- a/seaweed-block/core/frontend/chunkstore/retention.go +++ b/seaweed-block/core/frontend/chunkstore/retention.go @@ -254,13 +254,6 @@ func planRetention(p RetentionPolicy, snaps []SnapshotInfo, needed map[string]bo continue } k := int64(age / lk.period) // the rolling window holding this age - // RED: calendar periods, as before the review - if red := true; red { - if age >= time.Duration(lk.count)*lk.period { - continue - } - k = -1 - s.CreatedNs/int64(lk.period) - } if k >= int64(lk.count) { continue } @@ -403,13 +396,6 @@ const ( // that attempt. uncertain reports, with an error, that the failing call // was a mutation whose outcome is unknown. func (c *Catalog) deleteRetainedAttempt(ctx context.Context, vol, name, attempt string) (retainOutcome, bool, error) { - if red := true; red { // RED: delete by name, as before the review - c.hook(hookUnheld, name) - if _, err := c.DeleteSnapshot(ctx, vol, name); err != nil && CodeOf(err) != CodeSnapshotNotFound { - return 0, false, err - } - return retainDeleted, false, nil - } root, err := c.volRoot(vol) if err != nil { return 0, false, err diff --git a/seaweed-block/core/frontend/chunkstore/usage.go b/seaweed-block/core/frontend/chunkstore/usage.go index 0faac9fbcc..05ec785f61 100644 --- a/seaweed-block/core/frontend/chunkstore/usage.go +++ b/seaweed-block/core/frontend/chunkstore/usage.go @@ -211,9 +211,6 @@ func (c *Catalog) Usage(ctx context.Context, vol string) (VolumeUsage, error) { // owner-qualified "@owner/key" (a fork's reference) is owner's key, // anything else is vol's. func chunkIdentity(vol, key string) string { - if red := true; red { // RED: owner-qualified refs not resolved - return vol + "\x00" + key - } if strings.HasPrefix(key, "@") { if owner, rest, ok := strings.Cut(key[1:], "/"); ok { return owner + "\x00" + rest diff --git a/seaweed-block/core/host/volume/chunk_control.go b/seaweed-block/core/host/volume/chunk_control.go index adba62b03c..46e3f1135b 100644 --- a/seaweed-block/core/host/volume/chunk_control.go +++ b/seaweed-block/core/host/volume/chunk_control.go @@ -214,7 +214,7 @@ func chunkErrorCode(err error) (int, string, bool) { func catalogStatus(code string) int { switch code { - case chunkstore.CodeInvalidName, chunkstore.CodeInvalidLabel: // RED: class and policy errors fall to 409 + case chunkstore.CodeInvalidName, chunkstore.CodeInvalidLabel, chunkstore.CodeInvalidClass, chunkstore.CodeInvalidPolicy: return http.StatusBadRequest case chunkstore.CodeSnapshotNotFound: return http.StatusNotFound @@ -465,8 +465,8 @@ func (c *chunkControl) Cut(ctx context.Context, volumeID string, minLSN uint64) func (c *chunkControl) Snapshot(ctx context.Context, volumeID string, req ChunkSnapshotRequest) (chunkstore.SnapshotInfo, error) { // Admit the request before anything can cut: an invalid class must // not advance HEAD (review of #142). - if red := true; !red { // RED: the class is checked only after the cut - return chunkstore.SnapshotInfo{}, chunkstore.ValidateSnapshotClass(req.Class) + if err := chunkstore.ValidateSnapshotClass(req.Class); err != nil { + return chunkstore.SnapshotInfo{}, err } sreq := chunkstore.SnapshotRequest{Name: req.Name, RequestID: req.RequestID, Labels: req.Labels, Consistency: req.Consistency, ExpiresAtNs: req.ExpiresAtNs, CreatedBy: "blockvolume", Class: req.Class} From 6a41bc40bbc4210e2ae3da3c9399b08ba80bafd2 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 15 Nov 2026 15:53:04 -0800 Subject: [PATCH 05/10] chunkstore: RED controls for fork claims on the parent entry Controls for the four fork schedules of the second review, failing against stubs where Fork writes no claim, the delete mark is not conditioned on claims, and a dry run omits unfinished deleting attempts: - a fork claiming between retention's check and its mark (unit and real filer); - a fork that died before its VOLUME keeps the parent 30 days later; - a refused same-target request leaves the first request's claim; - a dry run lists the attempt a lost response left deleting. Co-Authored-By: Claude Opus 5.5 --- .../core/frontend/chunkstore/catalog.go | 124 ++++++---- .../core/frontend/chunkstore/retention.go | 216 ++++++++++-------- .../chunkstore/retention_integration_test.go | 52 +++-- .../chunkstore/retention_review_test.go | 141 +++++++++--- 4 files changed, 344 insertions(+), 189 deletions(-) diff --git a/seaweed-block/core/frontend/chunkstore/catalog.go b/seaweed-block/core/frontend/chunkstore/catalog.go index 5590fea2b0..e20a4b62f3 100644 --- a/seaweed-block/core/frontend/chunkstore/catalog.go +++ b/seaweed-block/core/frontend/chunkstore/catalog.go @@ -35,6 +35,8 @@ import ( "strings" "time" + "google.golang.org/protobuf/proto" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" "github.com/seaweedfs/seaweed-block/core/storage" ) @@ -1166,33 +1168,14 @@ func (c *Catalog) Fork(ctx context.Context, req ForkRequest) (ForkResult, error) } } - // Hold the parent attempt before reading it (review of #142): a - // retention pass that marks it deleting reads the holds after its - // mark, so either it sees this hold and keeps the snapshot, or this - // read sees the attempt deleting and the fork refuses before anything - // is installed. - srcRoot, err := c.volRoot(req.Source) - if err != nil { - return ForkResult{}, err - } - held, err := c.holdForkParent(ctx, srcRoot, req) - if err != nil { - return ForkResult{}, err - } + // Claim the parent before using it (review of #142): one conditional + // write on the parent attempt's entry, which retention's delete mark + // is conditioned against (see retention.go). readAt := c.now() - snap, err := c.readSnap(ctx, req.Source, req.Snapshot) + snap, err := c.claimForkParent(ctx, req) if err != nil { - c.dropForkHold(ctx, srcRoot, req, held) return ForkResult{}, err } - if snap.attempt != held { - c.dropForkHold(ctx, srcRoot, req, held) - return ForkResult{}, catErr(CodeOutcomeUnknown, true, nil, "fork %s: snapshot %s/%s changed while it was being held; retry", req.Target, req.Source, req.Snapshot) - } - if snap.State == SnapDeleting { - c.dropForkHold(ctx, srcRoot, req, held) - return ForkResult{}, catErr(CodeSnapshotDeleting, false, nil, "snapshot %s/%s is being deleted", req.Source, req.Snapshot) - } if snap.geo == (Geometry{}) { return ForkResult{}, fmt.Errorf("chunkstore: snapshot %s/%s has no geometry", req.Source, req.Snapshot) } @@ -1280,39 +1263,96 @@ func (c *Catalog) Fork(ctx context.Context, req ForkRequest) (ForkResult, error) return ForkResult{}, err } if h.State == storage.ChunkHeadAborted { - c.dropIntent(ctx, dstRoot, id) // the tombstone is permanent: this create never lands + c.dropIntent(ctx, dstRoot, id) // the tombstone is permanent: this create never lands + c.dropForkClaim(ctx, req, snap.attempt) // and this fork never needs the parent again return ForkResult{}, catErr(CodeTargetExists, false, nil, "fork %s lost to a sweep: its HEAD is an aborted tombstone; fork to a new volume id", req.Target) } if outcome != createUnsettled { c.dropIntent(ctx, dstRoot, id) // confirmed, or refused for good } - c.dropForkHold(ctx, srcRoot, req, held) // the fork has its HEAD: the parent is no longer needed for it + c.dropForkClaim(ctx, req, snap.attempt) // the fork has its HEAD: the parent is no longer needed for it return forkResult(existing, outcome != createdNow), nil } -// holdForkParent records that fork req needs the attempt its snapshot name -// resolves to now, and returns that attempt ("" when the name resolves to -// nothing; the read that follows then refuses). -func (c *Catalog) holdForkParent(ctx context.Context, srcRoot string, req ForkRequest) (string, error) { - ref, ok, err := c.resolveSnap(ctx, req.Source, req.Snapshot) - if err != nil || !ok { - return "", err +// claimForkParent adds fork req's claim to the parent attempt its +// snapshot name resolves to, conditioned on the entry being active with +// the claims read, and returns that snapshot. A parent deleting is +// refused (snapshot_deleting); a claim already there is reused. +func (c *Catalog) claimForkParent(ctx context.Context, req ForkRequest) (SnapshotInfo, error) { + root, err := c.volRoot(req.Source) + if err != nil { + return SnapshotInfo{}, err } - now := c.now().Unix() - e := &filerpb.Entry{Name: req.Target, Attributes: &filerpb.FuseAttributes{Mtime: now, Crtime: now, FileMode: 0o644}} - if err := c.f.CreateEntry(ctx, forkHoldDir(srcRoot, req.Snapshot, ref.rec.Attempt), e, true); err != nil && !errors.Is(err, ErrExists) { - return "", remoteErr(err, "hold snapshot %s/%s for fork %s", req.Source, req.Snapshot, req.Target) + token := forkClaim(req.Target, req.RequestID) + dir := path.Join(root, snapsDir, req.Snapshot) + for try := 0; try < 5; try++ { + ref, ok, err := c.resolveSnap(ctx, req.Source, req.Snapshot) + if err != nil { + return SnapshotInfo{}, err + } + if !ok || ref.entry == nil || ref.info.State == SnapAborted { + return SnapshotInfo{}, catErr(CodeSnapshotNotFound, false, nil, "snapshot %s/%s", req.Source, req.Snapshot) + } + if ref.info.State == SnapDeleting { + return SnapshotInfo{}, catErr(CodeSnapshotDeleting, false, nil, "snapshot %s/%s is being deleted", req.Source, req.Snapshot) + } + claims := decodeClaims(ref.entry) + if red := true; red { // RED: no claim written + return ref.info, nil + } + for _, cl := range claims { + if cl == token { + return ref.info, nil + } + } + raw := ref.entry.Extended[extSnapClaims] + next := proto.Clone(ref.entry).(*filerpb.Entry) + setClaims(next, append(claims, token)) + err = c.f.UpdateEntry(ctx, dir, next, map[string][]byte{extSnapState: []byte(SnapActive), extSnapClaims: raw}) + if errors.Is(err, ErrPrecondition) || errors.Is(err, ErrNotFound) { + continue // a mark, another claim or a delete landed: read again + } + if err != nil { + // The claim may have landed; a retry finds and reuses it. + return SnapshotInfo{}, catErr(CodeOutcomeUnknown, true, err, "fork %s: claim on %s/%s outcome unknown; retry with the same request id", req.Target, req.Source, req.Snapshot) + } + return ref.info, nil } - return ref.rec.Attempt, nil + return SnapshotInfo{}, catErr(CodeOutcomeUnknown, true, nil, "fork %s: snapshot %s/%s kept changing; retry", req.Target, req.Source, req.Snapshot) } -// dropForkHold removes a completed fork's hold (best effort: a stale hold -// is ignored once the target has a HEAD). -func (c *Catalog) dropForkHold(ctx context.Context, srcRoot string, req ForkRequest, attempt string) { - if attempt == "" { +// dropForkClaim removes fork req's claim from its parent attempt once the +// fork no longer needs it (best effort: retention treats a claim whose +// target has a HEAD as dead anyway). +func (c *Catalog) dropForkClaim(ctx context.Context, req ForkRequest, attempt string) { + root, err := c.volRoot(req.Source) + if err != nil || attempt == "" { return } - _ = c.f.DeleteEntry(ctx, forkHoldDir(srcRoot, req.Snapshot, attempt), req.Target, nil) + token := forkClaim(req.Target, req.RequestID) + dir := path.Join(root, snapsDir, req.Snapshot) + for try := 0; try < 3; try++ { + e, err := c.f.LookupEntry(ctx, dir, attempt) + if err != nil { + return + } + claims := decodeClaims(e) + kept := claims[:0:0] + for _, cl := range claims { + if cl != token { + kept = append(kept, cl) + } + } + if len(kept) == len(claims) { + return + } + raw := e.Extended[extSnapClaims] + next := proto.Clone(e).(*filerpb.Entry) + setClaims(next, kept) + if err := c.f.UpdateEntry(ctx, dir, next, map[string][]byte{extSnapClaims: raw}); !errors.Is(err, ErrPrecondition) { + return + } + } } // AbortFork settles a dead fork for a GC sweep (W5 ruling, 2026-11-15 diff --git a/seaweed-block/core/frontend/chunkstore/retention.go b/seaweed-block/core/frontend/chunkstore/retention.go index bbec3c3793..a10790b8a7 100644 --- a/seaweed-block/core/frontend/chunkstore/retention.go +++ b/seaweed-block/core/frontend/chunkstore/retention.go @@ -8,6 +8,7 @@ import ( "path" "sort" "strconv" + "strings" "time" "google.golang.org/protobuf/proto" @@ -49,22 +50,31 @@ import ( // record is removed only while it still names that attempt, so a // same-name replacement made after planning is never touched. // -// Fork parents. A fork records a hold on the parent attempt before it -// reads it (forkholds///, see Fork). Retain marks -// the attempt deleting first and then reads its holds: a hold whose fork -// target has no HEAD yet reverts the mark and keeps the snapshot. A fork -// that creates its hold after that read finds the attempt deleting and -// refuses before installing anything. Either way no incomplete fork loses -// its parent. A hold counts while its target has no HEAD and either the -// target's VOLUME records this fork, or the hold is younger than the -// operation deadline (the fork may still be about to publish its VOLUME); -// a hold left by a fork that died before its VOLUME is stale after that. -// A fork published before holds existed is still found by the fork-record -// scan (forkParentsNeeded). +// Fork parents (codex01's design, review of #142 round 2). Protection is +// one conditional write on the parent attempt's own entry, nothing else: // -// A pass interrupted after marking a snapshot deleting (e.g. a lost -// response) leaves it deleting with its name still held; the next pass -// finishes it the same way (holds checked again, then the name freed). +// - Fork, before it reads the parent, adds its claim (target/request) +// to the entry's claims, conditioned on {state active, claims as read}. +// A parent already deleting is refused. +// - Retain marks an attempt deleting only conditioned on {state active, +// gen, no claims}. A lost condition re-reads and decides again. +// +// The two writes hit the same entry, so one of them sees the other: either +// the claim landed first and retain keeps the snapshot (fork_held), or the +// mark landed first and the fork refuses before installing anything. +// +// A claim is removed by the fork once its HEAD is installed. Retain removes +// (conditionally) only claims that can never matter again: the target has +// a HEAD (the fork completed, or a sweep aborted it), or the target's +// VOLUME belongs to another request (this one can never publish there). +// Any other claim keeps the snapshot, however old: a fork that died before +// publishing its VOLUME holds it until the fork is retried to completion or +// settled by AbortFork. Forks published before claims existed are still +// found by the fork-record scan (forkParentsNeeded). +// +// A pass stopped after a mark (e.g. a lost response) leaves the attempt +// deleting with its name still held; the next pass (and its dry run) lists +// it and frees the name. A deleting attempt cannot gain claims. const ( SnapshotClassSemantic = "semantic" @@ -79,7 +89,7 @@ const ( extRetention = "retention" extRetentionRev = "retention_rev" - forkHoldsDir = "forkholds" + extSnapClaims = "swb.snap.claims" ) // ValidateSnapshotClass refuses a class other than "", "semantic" and @@ -350,7 +360,12 @@ func (c *Catalog) Retain(ctx context.Context, vol string, dryRun bool) (Retentio expired = append(expired, d) } for _, s := range unfinished { - expired = append(expired, RetentionDecision{Name: s.Name, Attempt: s.attempt, CreatedNs: s.CreatedNs, Class: s.Class, Reasons: []string{SnapDeleting}}) + d := RetentionDecision{Name: s.Name, Attempt: s.attempt, CreatedNs: s.CreatedNs, Class: s.Class, Pinned: s.Pinned(), Reasons: []string{SnapDeleting}} + if red := true; !red { // RED: unfinished attempts not listed + res.Decisions = append(res.Decisions, d) + res.Expired++ + } + expired = append(expired, d) } if dryRun { return res, nil @@ -389,7 +404,7 @@ type retainOutcome int const ( retainDeleted retainOutcome = iota // marked deleting (or already gone) and the name freed retainReplaced // the planned attempt is gone; another attempt holds the name - retainForkHeld // a fork holds the attempt: the mark was reverted, kept + retainForkHeld // a live fork claim is on the attempt: kept, nothing written ) // deleteRetainedAttempt deletes the planned attempt of vol/name and only @@ -401,76 +416,64 @@ func (c *Catalog) deleteRetainedAttempt(ctx context.Context, vol, name, attempt return 0, false, err } dir := path.Join(root, snapsDir, name) - e, err := c.f.LookupEntry(ctx, dir, attempt) - if errors.Is(err, ErrNotFound) { - return c.freeName(ctx, root, name, attempt) - } - if err != nil { - return 0, false, remoteErr(err, "read snapshot %s/%s attempt %s", vol, name, attempt) - } - if string(e.Extended[extSnapState]) == SnapDeleting { - // A pass stopped after its mark: decide the holds again. - held, err := c.forkHeld(ctx, vol, root, name, attempt) - if err != nil { - return 0, false, err - } - if held { - return c.revertMark(ctx, dir, e, name, attempt) - } - return c.freeName(ctx, root, name, attempt) - } - if string(e.Extended[extSnapState]) == SnapActive { - marked := proto.Clone(e).(*filerpb.Entry) - marked.Extended[extSnapState] = []byte(SnapDeleting) - marked.Extended[extSnapDeletedNs] = []byte(strconv.FormatInt(c.now().UnixNano(), 10)) - err := c.f.UpdateEntry(ctx, dir, marked, map[string][]byte{ - extSnapState: []byte(SnapActive), - extSnapGen: e.Extended[extSnapGen], - }) - switch { - case errors.Is(err, ErrPrecondition) || errors.Is(err, ErrNotFound): - // changed under us: decided again from a fresh read below - case err != nil: - return 0, true, remoteErr(err, "mark snapshot %s/%s attempt %s deleting", vol, name, attempt) - default: - held, err := c.forkHeld(ctx, vol, root, name, attempt) - if err != nil { - return 0, false, err // marked deleting; a rerun keeps or completes it - } - if held { - return c.revertMark(ctx, dir, marked, name, attempt) - } - c.hook(hookUnheld, name) - } - e, err = c.f.LookupEntry(ctx, dir, attempt) + for try := 0; try < 5; try++ { + e, err := c.f.LookupEntry(ctx, dir, attempt) if errors.Is(err, ErrNotFound) { return c.freeName(ctx, root, name, attempt) } if err != nil { - return 0, false, remoteErr(err, "re-read snapshot %s/%s attempt %s", vol, name, attempt) + return 0, false, remoteErr(err, "read snapshot %s/%s attempt %s", vol, name, attempt) } - if string(e.Extended[extSnapState]) == SnapActive { - return 0, false, remoteErr(nil, "snapshot %s/%s attempt %s is still active after the delete mark", vol, name, attempt) + if string(e.Extended[extSnapState]) != SnapActive { + // Deleting (a stopped pass) or aborted: no fork can claim it. + return c.freeName(ctx, root, name, attempt) } + raw := string(e.Extended[extSnapClaims]) + claims := decodeClaims(e) + live, err := c.liveClaims(ctx, vol, name, claims) + if err != nil { + return 0, false, err + } + if len(live) > 0 { + return retainForkHeld, false, nil + } + c.hook(hookChecked, name) + next := proto.Clone(e).(*filerpb.Entry) + if len(claims) > 0 { + // Every claim is dead: clear them, then decide again. + delete(next.Extended, extSnapClaims) + err := c.f.UpdateEntry(ctx, dir, next, map[string][]byte{extSnapState: []byte(SnapActive), extSnapClaims: []byte(raw)}) + if errors.Is(err, ErrPrecondition) || errors.Is(err, ErrNotFound) { + continue + } + if err != nil { + return 0, true, remoteErr(err, "clear the dead fork claims of %s/%s attempt %s", vol, name, attempt) + } + continue + } + next.Extended[extSnapState] = []byte(SnapDeleting) + next.Extended[extSnapDeletedNs] = []byte(strconv.FormatInt(c.now().UnixNano(), 10)) + err = c.f.UpdateEntry(ctx, dir, next, map[string][]byte{ + extSnapState: []byte(SnapActive), // RED: no claims condition + extSnapGen: e.Extended[extSnapGen], + }) + if errors.Is(err, ErrPrecondition) || errors.Is(err, ErrNotFound) { + continue // a claim, a delete or a replacement landed: decide again + } + if err != nil { + return 0, true, remoteErr(err, "mark snapshot %s/%s attempt %s deleting", vol, name, attempt) + } + c.hook(hookMarked, name) + return c.freeName(ctx, root, name, attempt) } - return c.freeName(ctx, root, name, attempt) -} - -// revertMark returns a deleting attempt to active: a fork holds it. -func (c *Catalog) revertMark(ctx context.Context, dir string, e *filerpb.Entry, name, attempt string) (retainOutcome, bool, error) { - back := proto.Clone(e).(*filerpb.Entry) - back.Extended[extSnapState] = []byte(SnapActive) - delete(back.Extended, extSnapDeletedNs) - if err := c.f.UpdateEntry(ctx, dir, back, map[string][]byte{extSnapState: []byte(SnapDeleting)}); err != nil { - return 0, true, remoteErr(err, "revert snapshot %s attempt %s: a fork holds it", name, attempt) - } - return retainForkHeld, false, nil + return 0, false, remoteErr(nil, "snapshot %s/%s attempt %s kept changing", vol, name, attempt) } // Test seams: hook stages in a Retain pass. const ( hookPlanned = "planned" // after planning, before any deletion - hookUnheld = "unheld" // a snapshot is marked and no hold was found, before its name is freed + hookChecked = "checked" // an attempt's claims were read and none is live, before its mark + hookMarked = "marked" // an attempt is marked deleting, before its name is freed ) func (c *Catalog) hook(stage, name string) { @@ -491,46 +494,59 @@ func (c *Catalog) freeName(ctx context.Context, root, name, attempt string) (ret return 0, true, remoteErr(err, "remove the name record %s", name) } -// forkHoldDir is where forks record their holds on a parent attempt. -func forkHoldDir(root, name, attempt string) string { - return path.Join(root, forkHoldsDir, name, attempt) +// forkClaim is the claim a fork puts on its parent attempt. +func forkClaim(target, requestID string) string { return target + "/" + requestID } + +func decodeClaims(e *filerpb.Entry) []string { + raw := e.Extended[extSnapClaims] + if len(raw) == 0 { + return nil + } + var out []string + if json.Unmarshal(raw, &out) != nil { + return []string{string(raw)} // unreadable: kept as one live claim (safe) + } + return out } -// forkHeld reports whether a fork still needs attempt of vol/name: one of -// its holds names a target with no HEAD yet whose VOLUME records this -// fork, or whose hold is younger than the operation deadline (its VOLUME -// may be about to land). A hold whose target has a real or aborted HEAD -// is stale (that fork completed or lost), as is an old hold with no -// matching VOLUME (that fork died before publishing). -func (c *Catalog) forkHeld(ctx context.Context, vol, root, name, attempt string) (bool, error) { - holds, err := c.f.ListEntries(ctx, forkHoldDir(root, name, attempt), "", "", 0) - if err != nil { - return false, remoteErr(err, "list the fork holds of %s/%s", name, attempt) +func setClaims(e *filerpb.Entry, claims []string) { + if len(claims) == 0 { + delete(e.Extended, extSnapClaims) + return } - for _, h := range holds { - if h.GetIsDirectory() { + sort.Strings(claims) + body, _ := json.Marshal(claims) + e.Extended[extSnapClaims] = body +} + +// liveClaims returns the claims on vol/name that a fork may still need: a +// claim is dead only when its target has a HEAD, or its target's VOLUME +// was made by another request (or from another parent). +func (c *Catalog) liveClaims(ctx context.Context, vol, name string, claims []string) ([]string, error) { + var live []string + for _, cl := range claims { + target, req, ok := strings.Cut(cl, "/") + if !ok || CheckVolumeID(target) != nil { + live = append(live, cl) // not ours to judge: keep the snapshot continue } - target := h.GetName() _, has, err := c.ReadHead(ctx, target) if err != nil { - return false, err + return nil, err } if has { continue } v, ok, err := c.ReadVolume(ctx, target) if err != nil { - return false, err + return nil, err } - if ok && v.Fork != nil && v.Fork.Source == vol && v.Fork.Snapshot == name { - return true, nil - } - if c.now().Sub(time.Unix(h.GetAttributes().GetCrtime(), 0)) < c.deadline() { - return true, nil + if ok && (v.Fork == nil || v.Fork.RequestID != req || v.Fork.Source != vol || v.Fork.Snapshot != name) { + continue } + live = append(live, cl) } - return false, nil + return live, nil } // allSnapshots lists every published, not-deleting snapshot of vol, with diff --git a/seaweed-block/core/frontend/chunkstore/retention_integration_test.go b/seaweed-block/core/frontend/chunkstore/retention_integration_test.go index d5353c70a2..9563341961 100644 --- a/seaweed-block/core/frontend/chunkstore/retention_integration_test.go +++ b/seaweed-block/core/frontend/chunkstore/retention_integration_test.go @@ -140,7 +140,9 @@ func TestIntegration_RetainAndUsage(t *testing.T) { // (1) a same-name pinned replacement made after planning survives (the // filer's conditional name delete refuses the stale attempt); (2) a fork // that starts after the scan and stops before its HEAD (VOLUME published, -// deadline exceeded) keeps its parent, and completes on retry. +// deadline exceeded) keeps its parent, and completes on retry; (3) a fork +// that claims between retention's claim check and its mark makes the +// filer refuse the mark (conditioned on no claims), so the parent is kept. func TestIntegration_RetainHeldSchedules(t *testing.T) { c := startWeed(t) ctx := context.Background() @@ -180,7 +182,23 @@ func TestIntegration_RetainHeldSchedules(t *testing.T) { clock = time.Now() var pinnedAttempt string - cat.retainHook = func(stage, _ string) { + stoppedFork := func(snap, target string) { + t.Helper() + cat.OpDeadline = time.Nanosecond + _, err := cat.Fork(ctx, ForkRequest{Source: "v1", Snapshot: snap, Target: target, RequestID: "f"}) + cat.OpDeadline = 0 + if CodeOf(err) != CodeDeadlineExceeded { + t.Fatalf("fork %s past its deadline: %v; want deadline_exceeded", target, err) + } + if _, ok, err := cat.ReadVolume(ctx, target); !ok || err != nil { + t.Fatalf("the stopped fork %s VOLUME: ok=%t %v", target, ok, err) + } + } + cat.retainHook = func(stage, name string) { + if stage == hookChecked && name == "s02" { + stoppedFork("s02", "v3") // (3) lands between the check and the mark + return + } if stage != hookPlanned { return } @@ -197,36 +215,30 @@ func TestIntegration_RetainHeldSchedules(t *testing.T) { } pinnedAttempt = b.attempt // (2) a fork of s01 publishes its VOLUME and stops before HEAD. - cat.OpDeadline = time.Nanosecond - _, err = cat.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s01", Target: "v2", RequestID: "f"}) - cat.OpDeadline = 0 - if CodeOf(err) != CodeDeadlineExceeded { - t.Fatalf("fork past its deadline: %v; want deadline_exceeded", err) - } - if _, ok, err := cat.ReadVolume(ctx, "v2"); !ok || err != nil { - t.Fatalf("the stopped fork's VOLUME: ok=%t %v", ok, err) - } + stoppedFork("s01", "v2") } res, err := cat.Retain(ctx, "v1", false) if err != nil { t.Fatal(err) } cat.retainHook = nil - if fmt.Sprint(res.Deleted) != "[s02]" || fmt.Sprint(res.Replaced) != "[s00]" || fmt.Sprint(res.ForkHeld) != "[s01]" { - t.Fatalf("retain: deleted=%v replaced=%v forkHeld=%v; want s02 / s00 / s01", res.Deleted, res.Replaced, res.ForkHeld) + if len(res.Deleted) != 0 || fmt.Sprint(res.Replaced) != "[s00]" || fmt.Sprint(res.ForkHeld) != "[s02 s01]" { + t.Fatalf("retain: deleted=%v replaced=%v forkHeld=%v; want none / s00 / s02 s01", res.Deleted, res.Replaced, res.ForkHeld) } b, err := cat.readSnap(ctx, "v1", "s00") if err != nil || b.attempt != pinnedAttempt || b.State != SnapActive || b.Class != SnapshotClassPinned { t.Fatalf("pinned replacement: %+v %v (attempt %s, want %s)", b, err, b.attempt, pinnedAttempt) } - if s, err := cat.readSnap(ctx, "v1", "s01"); err != nil || s.State != SnapActive { - t.Fatalf("fork parent: %+v %v; want active", s, err) - } - if _, err := cat.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s01", Target: "v2", RequestID: "f"}); err != nil { - t.Fatalf("fork retry: %v", err) + for _, fk := range []struct{ snap, target string }{{"s01", "v2"}, {"s02", "v3"}} { + if s, err := cat.readSnap(ctx, "v1", fk.snap); err != nil || s.State != SnapActive { + t.Fatalf("fork parent %s: %+v %v; want active", fk.snap, s, err) + } + if _, err := cat.Fork(ctx, ForkRequest{Source: "v1", Snapshot: fk.snap, Target: fk.target, RequestID: "f"}); err != nil { + t.Fatalf("fork %s retry: %v", fk.target, err) + } } res, err = cat.Retain(ctx, "v1", false) - if err != nil || fmt.Sprint(res.Deleted) != "[s01]" { - t.Fatalf("after the fork completed: deleted=%v %v; want s01 (s00 is pinned)", res.Deleted, err) + if err != nil || fmt.Sprint(res.Deleted) != "[s02 s01]" { + t.Fatalf("after the forks completed: deleted=%v %v; want s02 s01 (s00 is pinned)", res.Deleted, err) } } diff --git a/seaweed-block/core/frontend/chunkstore/retention_review_test.go b/seaweed-block/core/frontend/chunkstore/retention_review_test.go index 1af7fc7308..be0ac93094 100644 --- a/seaweed-block/core/frontend/chunkstore/retention_review_test.go +++ b/seaweed-block/core/frontend/chunkstore/retention_review_test.go @@ -10,7 +10,7 @@ import ( "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" ) -// Controls for the review of #142: attempt-bound deletion, fork holds, +// Controls for the review of #142: attempt-bound deletion, fork claims, // rolling windows, cross-volume holders and partial results. // Log-spaced keeps use rolling windows anchored at now, not calendar @@ -104,8 +104,8 @@ func forkFixture(t *testing.T) (*fakeFiler, *Catalog) { } // A fork that starts after the retention scan (its VOLUME published, its -// HEAD not yet) holds the parent: the mark is reverted, the parent kept, -// and the fork completes on retry. +// HEAD not yet) has claimed the parent: retention keeps it, and the fork +// completes on retry. func TestCatalog_RetainKeepsAParentForkedAfterTheScan(t *testing.T) { f, c := forkFixture(t) ctx := context.Background() @@ -139,14 +139,23 @@ func TestCatalog_RetainKeepsAParentForkedAfterTheScan(t *testing.T) { } } -// A fork that takes its hold after retention checked the holds finds the -// attempt deleting and refuses before installing anything. -func TestCatalog_ForkAfterTheHoldCheckRefuses(t *testing.T) { - f, c := forkFixture(t) +func claimsOf(t *testing.T, c *Catalog, name string) []string { + t.Helper() + ref, ok, err := c.resolveSnap(context.Background(), "v1", name) + if err != nil || !ok || ref.entry == nil { + t.Fatalf("read %s: ok=%t %v", name, ok, err) + } + return decodeClaims(ref.entry) +} + +// A fork arriving after the mark finds the parent deleting and refuses +// before installing anything (and leaves no claim). +func TestCatalog_ForkAfterTheMarkRefuses(t *testing.T) { + _, c := forkFixture(t) ctx := context.Background() ran := false c.retainHook = func(stage, name string) { - if stage != hookUnheld || name != "s01" { + if stage != hookMarked || name != "s01" { return } ran = true @@ -164,39 +173,104 @@ func TestCatalog_ForkAfterTheHoldCheckRefuses(t *testing.T) { if _, ok, err := c.ReadVolume(ctx, "v2"); ok || err != nil { t.Fatalf("a refused fork published its VOLUME (%v)", err) } - if holds, _ := f.ListEntries(ctx, forkHoldDir(catBase+"/v1", "s01", res.Decisions[1].Attempt), "", "", 0); len(holds) != 0 { - t.Fatalf("a refused fork left %d holds", len(holds)) - } } -// A hold whose fork died before publishing its VOLUME counts only within -// the operation deadline. -func TestCatalog_StaleForkHoldExpires(t *testing.T) { +// Schedule 1: retention read no claims, then a fork claims before the +// mark. The mark's condition (no claims) fails; retention reads again, +// sees the live claim and keeps the parent. +func TestCatalog_ClaimBetweenCheckAndMarkWins(t *testing.T) { f, c := forkFixture(t) ctx := context.Background() - s, err := c.readSnap(ctx, "v1", "s01") + c.retainHook = func(stage, name string) { + if stage != hookChecked || name != "s01" { + return + } + c.retainHook = nil + holdFirst(f, catBase+"/v2/HEAD") + if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s01", Target: "v2", RequestID: "f"}); CodeOf(err) != CodeOutcomeUnknown { + t.Fatalf("fork with a held HEAD create: %v", err) + } + } + res, err := c.Retain(ctx, "v1", false) if err != nil { t.Fatal(err) } - now := c.now() - hold := func(target string, at time.Time) { - e := &filerpb.Entry{Name: target, Attributes: &filerpb.FuseAttributes{Crtime: at.Unix(), Mtime: at.Unix()}} - if err := f.CreateEntry(ctx, forkHoldDir(catBase+"/v1", "s01", s.attempt), e, true); err != nil { - t.Fatal(err) - } + if strings.Join(res.ForkHeld, ",") != "s01" || strings.Join(res.Deleted, ",") != "s02,s00" { + t.Fatalf("deleted=%v forkHeld=%v; want s01 kept", res.Deleted, res.ForkHeld) } - hold("v8", now.Add(-time.Second)) // young: the fork may still publish + if s, err := c.readSnap(ctx, "v1", "s01"); err != nil || s.State != SnapActive { + t.Fatalf("parent: %+v %v; want active", s, err) + } + if got := claimsOf(t, c, "s01"); strings.Join(got, ",") != "v2/f" { + t.Fatalf("claims %v; want v2/f", got) + } +} + +// Schedule 2: a fork that claimed and died before publishing its VOLUME +// keeps the parent however much later retention runs (no lifetimes); the +// fork retried to completion releases it. +func TestCatalog_DeadForkClaimKeepsTheParent(t *testing.T) { + f, c := forkFixture(t) + ctx := context.Background() + f.failCreate = func(p string) error { + if p == catBase+"/v2/"+volumeName { + return errors.New("filer unavailable") + } + return nil + } + if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s01", Target: "v2", RequestID: "f"}); err == nil { + t.Fatal("fork with a failing VOLUME create succeeded") + } + f.failCreate = nil + if _, ok, _ := c.ReadVolume(ctx, "v2"); ok { + t.Fatal("VOLUME published") + } + saved := c.now + c.SetClock(func() time.Time { return saved().Add(30 * 24 * time.Hour) }) res, err := c.Retain(ctx, "v1", false) if err != nil || strings.Join(res.ForkHeld, ",") != "s01" { - t.Fatalf("young hold: forkHeld=%v %v; want s01", res.ForkHeld, err) + t.Fatalf("30 days later: forkHeld=%v %v; want s01 still kept", res.ForkHeld, err) } - if err := f.DeleteEntry(ctx, forkHoldDir(catBase+"/v1", "s01", s.attempt), "v8", nil); err != nil { - t.Fatal(err) + if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s01", Target: "v2", RequestID: "f"}); err != nil { + t.Fatalf("fork retry: %v", err) + } + if got := claimsOf(t, c, "s01"); len(got) != 0 { + t.Fatalf("claims after the fork completed: %v; want none", got) } - hold("v9", now.Add(-2*c.deadline())) // old, no VOLUME: the fork died res, err = c.Retain(ctx, "v1", false) if err != nil || strings.Join(res.Deleted, ",") != "s01" { - t.Fatalf("stale hold: deleted=%v %v; want s01", res.Deleted, err) + t.Fatalf("after completion: deleted=%v %v; want s01", res.Deleted, err) + } +} + +// Schedule 3: a second request for the same target is refused without +// touching the first request's claim (claims are per target AND request, +// and a fork drops only its own, only once its HEAD exists). +func TestCatalog_RefusedSameTargetForkLeavesTheOtherClaim(t *testing.T) { + f, c := forkFixture(t) + ctx := context.Background() + holdFirst(f, catBase+"/v2/HEAD") + if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s01", Target: "v2", RequestID: "a"}); CodeOf(err) != CodeOutcomeUnknown { + t.Fatalf("fork a: %v", err) + } + if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s01", Target: "v2", RequestID: "b"}); CodeOf(err) != CodeTargetExists { + t.Fatalf("fork b (same target, other request): %v; want target_exists", err) + } + if _, err := c.Retain(ctx, "v1", false); err != nil { + t.Fatal(err) + } + if s, err := c.readSnap(ctx, "v1", "s01"); err != nil || s.State != SnapActive { + t.Fatalf("parent after retain: %+v %v; want kept for request a", s, err) + } + if got := claimsOf(t, c, "s01"); strings.Join(got, ",") != "v2/a" { + t.Fatalf("claims %v; want only a's, intact", got) + } + if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s01", Target: "v2", RequestID: "a"}); err != nil { + t.Fatalf("fork a retry: %v", err) + } + res, err := c.Retain(ctx, "v1", false) + if err != nil || strings.Join(res.Deleted, ",") != "s01" { + t.Fatalf("after a completed: deleted=%v %v; want s01 (b's claim dead)", res.Deleted, err) } } @@ -233,6 +307,19 @@ func TestCatalog_RetainReportsPartialProgress(t *testing.T) { t.Fatalf("lost response: %+v %v", res, err) } f.failUpdateAfterApply = nil + dry, err := c.Retain(ctx, "v1", true) + if err != nil { + t.Fatal(err) + } + listed := false + for _, d := range dry.Decisions { + if d.Name == "s03" && !d.Keep && strings.Join(d.Reasons, ",") == SnapDeleting { + listed = true + } + } + if !listed || dry.Expired != 4 { + t.Fatalf("dry run after the lost response: expired=%d decisions=%+v; want s03 listed as deleting", dry.Expired, dry.Decisions) + } res, err = c.Retain(ctx, "v1", false) if err != nil || strings.Join(res.Deleted, ",") != "s02,s01,s00,s03" { t.Fatalf("rerun: deleted=%v %v; want the rest and the half-deleted s03", res.Deleted, err) From 02d06311f928fcb624d5655c22c12a67f4c313ba Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 15 Nov 2026 15:53:04 -0800 Subject: [PATCH 06/10] chunkstore: fork claims on the parent snapshot entry Replaces the separate hold objects with one conditional write on the parent attempt's own entry (codex01's design): - Fork adds its claim (target/request) to the entry before using it, conditioned on {state active, claims as read}; a deleting parent is refused. It removes its claim once its HEAD exists (or a sweep's tombstone settles the target). - Retain marks deleting only conditioned on {state active, gen, no claims}; a lost condition re-reads and decides again. Claims that can never matter (target has a HEAD, or its VOLUME is another request's) are cleared conditionally first; any other claim keeps the snapshot, with no lifetime. No listing, so no paging. - A dry run lists attempts a stopped pass left deleting, as apply frees them. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/frontend/chunkstore/catalog.go | 3 --- seaweed-block/core/frontend/chunkstore/retention.go | 11 +++++------ 2 files changed, 5 insertions(+), 9 deletions(-) diff --git a/seaweed-block/core/frontend/chunkstore/catalog.go b/seaweed-block/core/frontend/chunkstore/catalog.go index e20a4b62f3..39f5dc737a 100644 --- a/seaweed-block/core/frontend/chunkstore/catalog.go +++ b/seaweed-block/core/frontend/chunkstore/catalog.go @@ -1297,9 +1297,6 @@ func (c *Catalog) claimForkParent(ctx context.Context, req ForkRequest) (Snapsho return SnapshotInfo{}, catErr(CodeSnapshotDeleting, false, nil, "snapshot %s/%s is being deleted", req.Source, req.Snapshot) } claims := decodeClaims(ref.entry) - if red := true; red { // RED: no claim written - return ref.info, nil - } for _, cl := range claims { if cl == token { return ref.info, nil diff --git a/seaweed-block/core/frontend/chunkstore/retention.go b/seaweed-block/core/frontend/chunkstore/retention.go index a10790b8a7..bff617f678 100644 --- a/seaweed-block/core/frontend/chunkstore/retention.go +++ b/seaweed-block/core/frontend/chunkstore/retention.go @@ -361,10 +361,8 @@ func (c *Catalog) Retain(ctx context.Context, vol string, dryRun bool) (Retentio } for _, s := range unfinished { d := RetentionDecision{Name: s.Name, Attempt: s.attempt, CreatedNs: s.CreatedNs, Class: s.Class, Pinned: s.Pinned(), Reasons: []string{SnapDeleting}} - if red := true; !red { // RED: unfinished attempts not listed - res.Decisions = append(res.Decisions, d) - res.Expired++ - } + res.Decisions = append(res.Decisions, d) + res.Expired++ expired = append(expired, d) } if dryRun { @@ -454,8 +452,9 @@ func (c *Catalog) deleteRetainedAttempt(ctx context.Context, vol, name, attempt next.Extended[extSnapState] = []byte(SnapDeleting) next.Extended[extSnapDeletedNs] = []byte(strconv.FormatInt(c.now().UnixNano(), 10)) err = c.f.UpdateEntry(ctx, dir, next, map[string][]byte{ - extSnapState: []byte(SnapActive), // RED: no claims condition - extSnapGen: e.Extended[extSnapGen], + extSnapState: []byte(SnapActive), + extSnapGen: e.Extended[extSnapGen], + extSnapClaims: nil, // no claims: a fork that claimed meanwhile wins }) if errors.Is(err, ErrPrecondition) || errors.Is(err, ErrNotFound) { continue // a claim, a delete or a replacement landed: decide again From 6db62358fe94c685db6303ff516e5a5d4f6ccacd Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 15 Nov 2026 16:01:54 -0800 Subject: [PATCH 07/10] chunkstore: RED control: delete refuses a fork-claimed parent claude05's ruling (2026-11-15 23:58Z): an explicit DeleteSnapshot of a snapshot an incomplete fork claims is refused with snapshot_claimed (409, not retryable, naming the fork volume); a completed or aborted fork no longer blocks. Controls, failing against the old mark (blind to claims) restored as a stub: TestCatalog_DeleteRefusesAClaimedParent, the 409 mapping, the real-filer refusal in TestIntegration_RetainHeldSchedules, and TestFork_IncompleteRetryBoundToOriginalImage, which now expects the refusal and drops the claim (as a pre-claim fork) to keep testing the image binding. Co-Authored-By: Claude Opus 5.5 --- .../core/frontend/chunkstore/catalog.go | 35 ++++++--- .../chunkstore/catalog_settle_test.go | 17 +++++ .../core/frontend/chunkstore/retention.go | 71 +++++++++++++++---- .../chunkstore/retention_integration_test.go | 4 ++ .../chunkstore/retention_review_test.go | 41 +++++++++++ .../host/volume/chunk_control_class_test.go | 3 + 6 files changed, 147 insertions(+), 24 deletions(-) diff --git a/seaweed-block/core/frontend/chunkstore/catalog.go b/seaweed-block/core/frontend/chunkstore/catalog.go index 39f5dc737a..61e9ae8bf0 100644 --- a/seaweed-block/core/frontend/chunkstore/catalog.go +++ b/seaweed-block/core/frontend/chunkstore/catalog.go @@ -1053,18 +1053,33 @@ func (c *Catalog) DeleteSnapshot(ctx context.Context, vol, name string) (string, } continue // re-read: the path now holds a tombstone or the late snapshot case ref.info.State == SnapActive: - e := ref.entry - e.Extended[extSnapState] = []byte(SnapDeleting) - e.Extended[extSnapDeletedNs] = []byte(strconv.FormatInt(c.now().UnixNano(), 10)) - err := c.f.UpdateEntry(ctx, dir, e, map[string][]byte{ - extSnapState: []byte(SnapActive), - extSnapGen: []byte(strconv.FormatUint(ref.info.HeadGen, 10)), - }) - if errors.Is(err, ErrPrecondition) || errors.Is(err, ErrNotFound) { - continue + // The one mark path shared with retention: a live fork claim + // refuses (claude05's ruling, 23:58Z). + if red := true; red { // RED: the old mark, blind to claims + e := ref.entry + e.Extended[extSnapState] = []byte(SnapDeleting) + e.Extended[extSnapDeletedNs] = []byte(strconv.FormatInt(c.now().UnixNano(), 10)) + err := c.f.UpdateEntry(ctx, dir, e, map[string][]byte{ + extSnapState: []byte(SnapActive), + extSnapGen: []byte(strconv.FormatUint(ref.info.HeadGen, 10)), + }) + if errors.Is(err, ErrPrecondition) || errors.Is(err, ErrNotFound) { + continue + } + if err != nil { + return "", remoteErr(err, "mark snapshot %s/%s deleting", vol, name) + } + break } + m, live, _, err := c.markDeleting(ctx, vol, name, ref.rec.Attempt) if err != nil { - return "", remoteErr(err, "mark snapshot %s/%s deleting", vol, name) + return "", err + } + switch m { + case markClaimed: + return "", claimedErr(vol, name, live) + case markGone: + continue } } // The attempt is deleting or aborted: free the name. diff --git a/seaweed-block/core/frontend/chunkstore/catalog_settle_test.go b/seaweed-block/core/frontend/chunkstore/catalog_settle_test.go index 1600b696d1..e746498279 100644 --- a/seaweed-block/core/frontend/chunkstore/catalog_settle_test.go +++ b/seaweed-block/core/frontend/chunkstore/catalog_settle_test.go @@ -4,6 +4,7 @@ import ( "context" "crypto/sha256" "errors" + "path" "sort" "strings" "testing" @@ -166,6 +167,22 @@ func TestFork_IncompleteRetryBoundToOriginalImage(t *testing.T) { t.Fatalf("request id reused for another snapshot: %v, want target_exists", err) } + // The fork claims s1, so an explicit delete is refused (claude05's + // ruling, 2026-11-15 23:58Z). The image binding below still guards a + // fork made before claims existed: drop the claim as such a fork would + // never have written one. + if _, err := c.DeleteSnapshot(ctx, "v1", "s1"); CodeOf(err) != CodeSnapshotClaimed { + t.Fatalf("delete of a claimed parent: %v, want snapshot_claimed", err) + } + ref, _, err := c.resolveSnap(ctx, "v1", "s1") + if err != nil || ref.entry == nil { + t.Fatalf("read s1: %v", err) + } + delete(ref.entry.Extended, extSnapClaims) + if err := f.UpdateEntry(ctx, path.Join(catBase, "v1", snapsDir, "s1"), ref.entry, nil); err != nil { + t.Fatal(err) + } + // s1 is deleted and recreated over a newer source image. if _, err := c.DeleteSnapshot(ctx, "v1", "s1"); err != nil { // frees the name t.Fatal(err) diff --git a/seaweed-block/core/frontend/chunkstore/retention.go b/seaweed-block/core/frontend/chunkstore/retention.go index bff617f678..a17a3a5795 100644 --- a/seaweed-block/core/frontend/chunkstore/retention.go +++ b/seaweed-block/core/frontend/chunkstore/retention.go @@ -72,6 +72,9 @@ import ( // settled by AbortFork. Forks published before claims existed are still // found by the fork-record scan (forkParentsNeeded). // +// An explicit DeleteSnapshot goes through the same check and mark +// (markDeleting): it refuses a live claim with snapshot_claimed. +// // A pass stopped after a mark (e.g. a lost response) leaves the attempt // deleting with its name still held; the next pass (and its dry run) lists // it and frees the name. A deleting attempt cannot gain claims. @@ -82,6 +85,10 @@ const ( CodeInvalidClass = "invalid_class" CodeInvalidPolicy = "invalid_policy" + // CodeSnapshotClaimed: an explicit delete of a snapshot a fork still + // claims (claude05's ruling, 23:58Z). Not retryable as such: it clears + // when the fork publishes its HEAD or is aborted. + CodeSnapshotClaimed = "snapshot_claimed" DefaultKeepNewest = 10 DefaultKeepYounger = time.Hour @@ -413,27 +420,56 @@ func (c *Catalog) deleteRetainedAttempt(ctx context.Context, vol, name, attempt if err != nil { return 0, false, err } + m, _, uncertain, err := c.markDeleting(ctx, vol, name, attempt) + if err != nil { + return 0, uncertain, err + } + if m == markClaimed { + return retainForkHeld, false, nil + } + return c.freeName(ctx, root, name, attempt) +} + +type markResult int + +const ( + markDone markResult = iota // this call marked the attempt deleting + markGone // the attempt's entry is gone + markSettled // already deleting or aborted (no fork can claim it) + markClaimed // a live fork claim is on it: nothing written +) + +// markDeleting marks attempt of vol/name deleting under the fork-claim +// rule, the one path for retention and explicit delete: the mark is +// conditioned on {state active, gen, no claims}; dead claims are cleared +// conditionally first; a lost condition re-reads and decides again. live +// lists the live claims when the result is markClaimed. uncertain +// reports, with an error, a mutation whose outcome is unknown. +func (c *Catalog) markDeleting(ctx context.Context, vol, name, attempt string) (markResult, []string, bool, error) { + root, err := c.volRoot(vol) + if err != nil { + return 0, nil, false, err + } dir := path.Join(root, snapsDir, name) for try := 0; try < 5; try++ { e, err := c.f.LookupEntry(ctx, dir, attempt) if errors.Is(err, ErrNotFound) { - return c.freeName(ctx, root, name, attempt) + return markGone, nil, false, nil } if err != nil { - return 0, false, remoteErr(err, "read snapshot %s/%s attempt %s", vol, name, attempt) + return 0, nil, false, remoteErr(err, "read snapshot %s/%s attempt %s", vol, name, attempt) } if string(e.Extended[extSnapState]) != SnapActive { - // Deleting (a stopped pass) or aborted: no fork can claim it. - return c.freeName(ctx, root, name, attempt) + return markSettled, nil, false, nil } raw := string(e.Extended[extSnapClaims]) claims := decodeClaims(e) live, err := c.liveClaims(ctx, vol, name, claims) if err != nil { - return 0, false, err + return 0, nil, false, err } if len(live) > 0 { - return retainForkHeld, false, nil + return markClaimed, live, false, nil } c.hook(hookChecked, name) next := proto.Clone(e).(*filerpb.Entry) @@ -441,11 +477,8 @@ func (c *Catalog) deleteRetainedAttempt(ctx context.Context, vol, name, attempt // Every claim is dead: clear them, then decide again. delete(next.Extended, extSnapClaims) err := c.f.UpdateEntry(ctx, dir, next, map[string][]byte{extSnapState: []byte(SnapActive), extSnapClaims: []byte(raw)}) - if errors.Is(err, ErrPrecondition) || errors.Is(err, ErrNotFound) { - continue - } - if err != nil { - return 0, true, remoteErr(err, "clear the dead fork claims of %s/%s attempt %s", vol, name, attempt) + if err != nil && !errors.Is(err, ErrPrecondition) && !errors.Is(err, ErrNotFound) { + return 0, nil, true, remoteErr(err, "clear the dead fork claims of %s/%s attempt %s", vol, name, attempt) } continue } @@ -460,12 +493,22 @@ func (c *Catalog) deleteRetainedAttempt(ctx context.Context, vol, name, attempt continue // a claim, a delete or a replacement landed: decide again } if err != nil { - return 0, true, remoteErr(err, "mark snapshot %s/%s attempt %s deleting", vol, name, attempt) + return 0, nil, true, remoteErr(err, "mark snapshot %s/%s attempt %s deleting", vol, name, attempt) } c.hook(hookMarked, name) - return c.freeName(ctx, root, name, attempt) + return markDone, nil, false, nil } - return 0, false, remoteErr(nil, "snapshot %s/%s attempt %s kept changing", vol, name, attempt) + return 0, nil, false, remoteErr(nil, "snapshot %s/%s attempt %s kept changing", vol, name, attempt) +} + +// claimedErr is snapshot_claimed naming the claiming fork volumes. +func claimedErr(vol, name string, live []string) error { + targets := make([]string, 0, len(live)) + for _, cl := range live { + t, _, _ := strings.Cut(cl, "/") + targets = append(targets, t) + } + return catErr(CodeSnapshotClaimed, false, nil, "snapshot %s/%s is the parent of incomplete fork %s; it can be deleted once that fork completes or is aborted", vol, name, strings.Join(targets, ", ")) } // Test seams: hook stages in a Retain pass. diff --git a/seaweed-block/core/frontend/chunkstore/retention_integration_test.go b/seaweed-block/core/frontend/chunkstore/retention_integration_test.go index 9563341961..abb287aad8 100644 --- a/seaweed-block/core/frontend/chunkstore/retention_integration_test.go +++ b/seaweed-block/core/frontend/chunkstore/retention_integration_test.go @@ -229,6 +229,10 @@ func TestIntegration_RetainHeldSchedules(t *testing.T) { if err != nil || b.attempt != pinnedAttempt || b.State != SnapActive || b.Class != SnapshotClassPinned { t.Fatalf("pinned replacement: %+v %v (attempt %s, want %s)", b, err, b.attempt, pinnedAttempt) } + // An explicit delete of a claimed parent is refused (claude05, 23:58Z). + if _, err := cat.DeleteSnapshot(ctx, "v1", "s01"); CodeOf(err) != CodeSnapshotClaimed { + t.Fatalf("delete of the claimed s01: %v; want snapshot_claimed", err) + } for _, fk := range []struct{ snap, target string }{{"s01", "v2"}, {"s02", "v3"}} { if s, err := cat.readSnap(ctx, "v1", fk.snap); err != nil || s.State != SnapActive { t.Fatalf("fork parent %s: %+v %v; want active", fk.snap, s, err) diff --git a/seaweed-block/core/frontend/chunkstore/retention_review_test.go b/seaweed-block/core/frontend/chunkstore/retention_review_test.go index be0ac93094..750b224d3f 100644 --- a/seaweed-block/core/frontend/chunkstore/retention_review_test.go +++ b/seaweed-block/core/frontend/chunkstore/retention_review_test.go @@ -354,3 +354,44 @@ func TestCatalog_UsageCountsForkHolders(t *testing.T) { t.Fatalf("s1 after v1's HEAD moved, v2 forked from it: %+v; want 0 exclusive (v2 holds both chunks)", u.Snapshots) } } + +// claude05's ruling (23:58Z): an explicit delete of a snapshot an +// incomplete fork claims is refused (snapshot_claimed, not retryable, +// naming the fork); once the fork completes or is aborted the delete goes +// through. Retention and delete share the check (markDeleting). +func TestCatalog_DeleteRefusesAClaimedParent(t *testing.T) { + f, c := forkFixture(t) + ctx := context.Background() + holdFirst(f, catBase+"/v2/HEAD") + if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s01", Target: "v2", RequestID: "f"}); CodeOf(err) != CodeOutcomeUnknown { + t.Fatalf("fork v2: %v", err) + } + holdFirst(f, catBase+"/v3/HEAD") + if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s02", Target: "v3", RequestID: "g"}); CodeOf(err) != CodeOutcomeUnknown { + t.Fatalf("fork v3: %v", err) + } + for _, tc := range []struct{ snap, target string }{{"s01", "v2"}, {"s02", "v3"}} { + _, err := c.DeleteSnapshot(ctx, "v1", tc.snap) + var ce *CatalogError + if !errors.As(err, &ce) || ce.Code != CodeSnapshotClaimed || ce.Retryable || !strings.Contains(ce.Detail(), tc.target) { + t.Fatalf("delete %s claimed by %s: %v; want snapshot_claimed, not retryable, naming %s", tc.snap, tc.target, err, tc.target) + } + if s, err := c.readSnap(ctx, "v1", tc.snap); err != nil || s.State != SnapActive { + t.Fatalf("%s after the refused delete: %+v %v; want active", tc.snap, s, err) + } + } + // Completed fork: its claim no longer blocks. + if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s01", Target: "v2", RequestID: "f"}); err != nil { + t.Fatalf("fork v2 retry: %v", err) + } + if got, err := c.DeleteSnapshot(ctx, "v1", "s01"); err != nil || got != SnapDeleting { + t.Fatalf("delete after the fork completed: %q %v", got, err) + } + // Aborted fork (a sweep's tombstone): neither does its claim. + if claimed, err := c.AbortFork(ctx, "v3"); err != nil || !claimed { + t.Fatalf("abort v3: claimed=%t %v", claimed, err) + } + if got, err := c.DeleteSnapshot(ctx, "v1", "s02"); err != nil || got != SnapDeleting { + t.Fatalf("delete after the fork was aborted: %q %v", got, err) + } +} diff --git a/seaweed-block/core/host/volume/chunk_control_class_test.go b/seaweed-block/core/host/volume/chunk_control_class_test.go index 89d333a9bc..918ead3a02 100644 --- a/seaweed-block/core/host/volume/chunk_control_class_test.go +++ b/seaweed-block/core/host/volume/chunk_control_class_test.go @@ -29,6 +29,9 @@ func TestChunkControl_InvalidClassRefusedBeforeCut(t *testing.T) { t.Fatalf("%s maps to %d, want 400", code, s) } } + if s := catalogStatus(chunkstore.CodeSnapshotClaimed); s != http.StatusConflict { + t.Fatalf("snapshot_claimed maps to %d, want 409", s) + } info, err := ctl.Snapshot(ctx, "v1", ChunkSnapshotRequest{Name: "s1", RequestID: "r1", Class: chunkstore.SnapshotClassPinned}) if err != nil || info.Class != chunkstore.SnapshotClassPinned || fp.cuts != 1 { From e7fc9a5254e3e74fd1afcd813f185dd856408ec6 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 15 Nov 2026 16:01:55 -0800 Subject: [PATCH 08/10] chunkstore: one mark path for retention and explicit delete markDeleting is the only way an attempt is marked deleting: conditioned on {state active, gen, no claims}, dead claims cleared first, a lost condition decided again. Retain keeps a claimed snapshot (fork_held); DeleteSnapshot refuses it with snapshot_claimed naming the fork (claude05's ruling, 23:58Z). Co-Authored-By: Claude Opus 5.5 --- .../core/frontend/chunkstore/catalog.go | 16 ---------------- 1 file changed, 16 deletions(-) diff --git a/seaweed-block/core/frontend/chunkstore/catalog.go b/seaweed-block/core/frontend/chunkstore/catalog.go index 61e9ae8bf0..289d8b841f 100644 --- a/seaweed-block/core/frontend/chunkstore/catalog.go +++ b/seaweed-block/core/frontend/chunkstore/catalog.go @@ -1055,22 +1055,6 @@ func (c *Catalog) DeleteSnapshot(ctx context.Context, vol, name string) (string, case ref.info.State == SnapActive: // The one mark path shared with retention: a live fork claim // refuses (claude05's ruling, 23:58Z). - if red := true; red { // RED: the old mark, blind to claims - e := ref.entry - e.Extended[extSnapState] = []byte(SnapDeleting) - e.Extended[extSnapDeletedNs] = []byte(strconv.FormatInt(c.now().UnixNano(), 10)) - err := c.f.UpdateEntry(ctx, dir, e, map[string][]byte{ - extSnapState: []byte(SnapActive), - extSnapGen: []byte(strconv.FormatUint(ref.info.HeadGen, 10)), - }) - if errors.Is(err, ErrPrecondition) || errors.Is(err, ErrNotFound) { - continue - } - if err != nil { - return "", remoteErr(err, "mark snapshot %s/%s deleting", vol, name) - } - break - } m, live, _, err := c.markDeleting(ctx, vol, name, ref.rec.Attempt) if err != nil { return "", err From cbe6e8e1503fcb718136451b02c4be86040becb3 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 15 Nov 2026 16:03:35 -0800 Subject: [PATCH 09/10] chunkstore: RED control: claim cleanup never undoes a delete Review of 02d0631 (P2): dropForkClaim conditioned its write on the claims only, so a completed fork's cleanup that read the parent, paused while an explicit delete marked it, then wrote back its stale copy, resurrecting an unnamed active snapshot. TestCatalog_ClaimCleanupNever UndoesADelete fails against the old cleanup condition and the old (claim-blind) delete mark, restored as stubs: state "active", deleted_ns gone. Co-Authored-By: Claude Opus 5.5 --- .../core/frontend/chunkstore/catalog.go | 21 ++++++++++ .../core/frontend/chunkstore/retention.go | 3 ++ .../chunkstore/retention_review_test.go | 41 +++++++++++++++++++ 3 files changed, 65 insertions(+) diff --git a/seaweed-block/core/frontend/chunkstore/catalog.go b/seaweed-block/core/frontend/chunkstore/catalog.go index 289d8b841f..722ff151a8 100644 --- a/seaweed-block/core/frontend/chunkstore/catalog.go +++ b/seaweed-block/core/frontend/chunkstore/catalog.go @@ -1055,6 +1055,22 @@ func (c *Catalog) DeleteSnapshot(ctx context.Context, vol, name string) (string, case ref.info.State == SnapActive: // The one mark path shared with retention: a live fork claim // refuses (claude05's ruling, 23:58Z). + if red := true; red { // RED: the old mark, blind to claims + e := ref.entry + e.Extended[extSnapState] = []byte(SnapDeleting) + e.Extended[extSnapDeletedNs] = []byte(strconv.FormatInt(c.now().UnixNano(), 10)) + err := c.f.UpdateEntry(ctx, dir, e, map[string][]byte{ + extSnapState: []byte(SnapActive), + extSnapGen: []byte(strconv.FormatUint(ref.info.HeadGen, 10)), + }) + if errors.Is(err, ErrPrecondition) || errors.Is(err, ErrNotFound) { + continue + } + if err != nil { + return "", remoteErr(err, "mark snapshot %s/%s deleting", vol, name) + } + break + } m, live, _, err := c.markDeleting(ctx, vol, name, ref.rec.Attempt) if err != nil { return "", err @@ -1342,6 +1358,11 @@ func (c *Catalog) dropForkClaim(ctx context.Context, req ForkRequest, attempt st if len(kept) == len(claims) { return } + c.hook(hookClaimDrop, req.Snapshot) + // RED: conditioned on the claims only + // Conditioned on the state read too (review of f42e723): a + // delete that marked the entry meanwhile must never be undone by + // this stale copy. A lost condition re-reads a fresh copy. raw := e.Extended[extSnapClaims] next := proto.Clone(e).(*filerpb.Entry) setClaims(next, kept) diff --git a/seaweed-block/core/frontend/chunkstore/retention.go b/seaweed-block/core/frontend/chunkstore/retention.go index a17a3a5795..5818ccd88d 100644 --- a/seaweed-block/core/frontend/chunkstore/retention.go +++ b/seaweed-block/core/frontend/chunkstore/retention.go @@ -516,6 +516,9 @@ const ( hookPlanned = "planned" // after planning, before any deletion hookChecked = "checked" // an attempt's claims were read and none is live, before its mark hookMarked = "marked" // an attempt is marked deleting, before its name is freed + // hookClaimDrop: a completed fork read its parent entry to drop its + // claim, before the conditional write. + hookClaimDrop = "claim-drop" ) func (c *Catalog) hook(stage, name string) { diff --git a/seaweed-block/core/frontend/chunkstore/retention_review_test.go b/seaweed-block/core/frontend/chunkstore/retention_review_test.go index 750b224d3f..d9c1baad78 100644 --- a/seaweed-block/core/frontend/chunkstore/retention_review_test.go +++ b/seaweed-block/core/frontend/chunkstore/retention_review_test.go @@ -3,6 +3,7 @@ package chunkstore import ( "context" "errors" + "path" "strings" "testing" "time" @@ -395,3 +396,43 @@ func TestCatalog_DeleteRefusesAClaimedParent(t *testing.T) { t.Fatalf("delete after the fork was aborted: %q %v", got, err) } } + +// Review of f42e723: a completed fork's claim cleanup that read the parent +// entry, then paused while an explicit delete marked it, must not write +// its stale copy back (resurrecting an unnamed snapshot as a GC root). +func TestCatalog_ClaimCleanupNeverUndoesADelete(t *testing.T) { + f, c := forkFixture(t) + ctx := context.Background() + holdFirst(f, catBase+"/v2/HEAD") + if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s01", Target: "v2", RequestID: "f"}); CodeOf(err) != CodeOutcomeUnknown { + t.Fatalf("fork: %v", err) + } + parent, err := c.readSnap(ctx, "v1", "s01") + if err != nil { + t.Fatal(err) + } + ran := false + c.retainHook = func(stage, name string) { + if stage != hookClaimDrop || name != "s01" || ran { + return + } + ran = true // the fork's HEAD exists now: its claim is dead + if _, err := c.DeleteSnapshot(ctx, "v1", "s01"); err != nil { + t.Fatalf("delete during the claim cleanup: %v", err) + } + } + if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s01", Target: "v2", RequestID: "f"}); err != nil { + t.Fatalf("fork retry: %v", err) + } + c.retainHook = nil + e, err := f.LookupEntry(ctx, path.Join(catBase, "v1", snapsDir, "s01"), parent.attempt) + if err != nil { + t.Fatal(err) + } + if !ran || string(e.Extended[extSnapState]) != SnapDeleting || len(e.Extended[extSnapDeletedNs]) == 0 { + t.Fatalf("ran=%t state=%q deleted_ns=%q; want the delete mark kept", ran, e.Extended[extSnapState], e.Extended[extSnapDeletedNs]) + } + if _, ok, err := c.resolveSnap(ctx, "v1", "s01"); ok || err != nil { + t.Fatalf("s01's name is back (%v)", err) + } +} From 1b764f1b3b9212a5412405c8433ce0204349bc23 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 15 Nov 2026 16:03:35 -0800 Subject: [PATCH 10/10] chunkstore: claim cleanup conditioned on the state it read dropForkClaim's write is conditioned on {state, claims} as read; a lost condition re-reads a fresh copy, so delete metadata is never overwritten. (With the shared mark path a delete also clears the dead claim first, which changes the condition on its own.) Co-Authored-By: Claude Opus 5.5 --- .../core/frontend/chunkstore/catalog.go | 19 +------------------ 1 file changed, 1 insertion(+), 18 deletions(-) diff --git a/seaweed-block/core/frontend/chunkstore/catalog.go b/seaweed-block/core/frontend/chunkstore/catalog.go index 722ff151a8..2ce0cc98a0 100644 --- a/seaweed-block/core/frontend/chunkstore/catalog.go +++ b/seaweed-block/core/frontend/chunkstore/catalog.go @@ -1055,22 +1055,6 @@ func (c *Catalog) DeleteSnapshot(ctx context.Context, vol, name string) (string, case ref.info.State == SnapActive: // The one mark path shared with retention: a live fork claim // refuses (claude05's ruling, 23:58Z). - if red := true; red { // RED: the old mark, blind to claims - e := ref.entry - e.Extended[extSnapState] = []byte(SnapDeleting) - e.Extended[extSnapDeletedNs] = []byte(strconv.FormatInt(c.now().UnixNano(), 10)) - err := c.f.UpdateEntry(ctx, dir, e, map[string][]byte{ - extSnapState: []byte(SnapActive), - extSnapGen: []byte(strconv.FormatUint(ref.info.HeadGen, 10)), - }) - if errors.Is(err, ErrPrecondition) || errors.Is(err, ErrNotFound) { - continue - } - if err != nil { - return "", remoteErr(err, "mark snapshot %s/%s deleting", vol, name) - } - break - } m, live, _, err := c.markDeleting(ctx, vol, name, ref.rec.Attempt) if err != nil { return "", err @@ -1359,14 +1343,13 @@ func (c *Catalog) dropForkClaim(ctx context.Context, req ForkRequest, attempt st return } c.hook(hookClaimDrop, req.Snapshot) - // RED: conditioned on the claims only // Conditioned on the state read too (review of f42e723): a // delete that marked the entry meanwhile must never be undone by // this stale copy. A lost condition re-reads a fresh copy. raw := e.Extended[extSnapClaims] next := proto.Clone(e).(*filerpb.Entry) setClaims(next, kept) - if err := c.f.UpdateEntry(ctx, dir, next, map[string][]byte{extSnapClaims: raw}); !errors.Is(err, ErrPrecondition) { + if err := c.f.UpdateEntry(ctx, dir, next, map[string][]byte{extSnapState: e.Extended[extSnapState], extSnapClaims: raw}); !errors.Is(err, ErrPrecondition) { return } }