From 6a41bc40bbc4210e2ae3da3c9399b08ba80bafd2 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 15 Nov 2026 15:53:04 -0800 Subject: [PATCH] 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)