From acc1258015fcf86ef552cc317d8e3233b5107366 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 22:56:53 -0800 Subject: [PATCH 1/4] chunkstore: snapshot delete in any order with forks (remove fork claims) A fork or restore no longer claims its parent snapshot, and neither DeleteSnapshot nor retention reads a claim: a deadline-exceeded fork or a failed restore can no longer make its parent (and so its volume) undeletable. Safety now rests on time: a fork takes its deadline start before it reads the parent, every attempt (a retry included) reads it again, and it publishes its HEAD only before start + operation deadline; GC keeps a deleted attempt rooted for its grace, and NewCollector now requires grace >= operation deadline + clock skew + CAS apply bound (new GCConfig field, default: the operation deadline). An unknown publish keeps the fork intent, which roots the keys until the target is resolved. Removed: claimForkParent/dropForkClaim/removeForkClaim (replaced by readForkParent), the claim branch of markDeleting, liveClaims, claimedErr and snapshot_claimed, retention's ForkHeld outcome and the fork_parent keep (forkParentsNeeded). A claims xattr written by an older version is ignored. Tests: three new tests (fork retry after delete re-reads the parent; delete during a fork in flight; unknown publish keeps the keys while its intent exists), each red on the base with snapshot_claimed; the construction check with its boundary; claim-mechanics tests removed, the others rewritten to the new rule. Docs: invariants.md M6 rows, INV-SNAP-DELETE-ANY-ORDER-001 (new), INV-SNAP-EXPLICIT-DELETE-001 and INV-GC-GRACE-DEADLINE-001 restated, INV-RESTORE-PARENT-HOLD-001 archived; workspace design section 6. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/cmd/sw-block/chunk_gc.go | 2 +- .../core/frontend/chunkstore/catalog.go | 134 ++-------- .../chunkstore/catalog_settle_test.go | 19 +- seaweed-block/core/frontend/chunkstore/gc.go | 32 ++- .../frontend/chunkstore/gc_volume_test.go | 22 +- .../core/frontend/chunkstore/restore_test.go | 45 ---- .../core/frontend/chunkstore/retention.go | 241 +++--------------- .../chunkstore/retention_integration_test.go | 23 +- .../chunkstore/retention_review_test.go | 228 +---------------- .../frontend/chunkstore/retention_test.go | 60 +---- .../chunkstore/snapshot_delete_test.go | 158 ++++++++++++ .../volume_delete_integration_test.go | 2 +- .../frontend/chunkstore/volume_delete_test.go | 13 +- .../host/volume/chunk_control_class_test.go | 3 - .../docs/design/agent-workspace-design.md | 13 +- seaweed-block/docs/design/invariants.md | 15 +- 16 files changed, 302 insertions(+), 708 deletions(-) create mode 100644 seaweed-block/core/frontend/chunkstore/snapshot_delete_test.go diff --git a/seaweed-block/cmd/sw-block/chunk_gc.go b/seaweed-block/cmd/sw-block/chunk_gc.go index a5a8cdfc61..a1bf496f26 100644 --- a/seaweed-block/cmd/sw-block/chunk_gc.go +++ b/seaweed-block/cmd/sw-block/chunk_gc.go @@ -27,7 +27,7 @@ func chunkGC(args []string, stdout, stderr io.Writer) int { fs.StringVar(&base, "chunk-path", defaultChunkPathCLI, "chunk catalog namespace") fs.StringVar(&master, "master", "", "authoritative blockmaster gRPC address") fs.BoolVar(&apply, "apply", false, "settle intents, save completed marks and reclaim eligible chunks; default is read-only") - fs.DurationVar(&grace, "grace", time.Hour, "two-mark interval and minimum upload age (must exceed the operation deadline plus mark time)") + fs.DurationVar(&grace, "grace", time.Hour, "two-mark interval and minimum upload age (at least the operation deadline + clock skew + CAS apply bound, and more than the operation deadline plus mark time)") fs.DurationVar(&ttl, "intent-ttl", time.Hour, "minimum capture-intent age before authoritative epoch expiry") fs.DurationVar(&timeout, "timeout", time.Minute, "bound for this pass, including master/filer/blob calls") if e := fs.Parse(args); e != nil { diff --git a/seaweed-block/core/frontend/chunkstore/catalog.go b/seaweed-block/core/frontend/chunkstore/catalog.go index 2fff8ee9ef..dcd18a41c2 100644 --- a/seaweed-block/core/frontend/chunkstore/catalog.go +++ b/seaweed-block/core/frontend/chunkstore/catalog.go @@ -36,7 +36,6 @@ import ( "time" "github.com/seaweedfs/seaweed-block/core/geometry" - "google.golang.org/protobuf/proto" "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" "github.com/seaweedfs/seaweed-block/core/storage" @@ -1126,16 +1125,12 @@ 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: - // The one mark path shared with retention: a live fork claim - // refuses. - m, live, _, err := c.markDeleting(ctx, vol, name, ref.rec.Attempt) + // The one mark path shared with retention; forks do not hold it. + m, _, err := c.markDeleting(ctx, vol, name, ref.rec.Attempt) if err != nil { return "", err } - switch m { - case markClaimed: - return "", claimedErr(vol, name, live) - case markGone: + if m == markGone { continue } } @@ -1266,22 +1261,19 @@ func (c *Catalog) fork(ctx context.Context, req ForkRequest, origin string) (For } } - // 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). + // The deadline starts before the parent is read, and every attempt + // (a retry included) reads it again: a snapshot deleted before the read + // is refused, and one deleted after it stays rooted by GC's grace past + // readAt + deadline, the last moment this fork can publish + // (INV-SNAP-DELETE-ANY-ORDER-001). The parent is not claimed. readAt := c.now() - snap, err := c.claimForkParent(ctx, req) + snap, err := c.readForkParent(ctx, req) if err != nil { return ForkResult{}, err } - // Read after the claim: a delete of the source marks its HEAD deleting - // before it reads claims, so either it sees this claim (and gives its - // mark back) or this read sees the mark and the fork gives the claim - // back before installing anything. if gone, err := c.volumeGone(ctx, req.Source); err != nil { return ForkResult{}, err } else if gone { - c.dropForkClaim(ctx, req, snap.attempt) return ForkResult{}, refuseDeleted(req.Source, "its snapshots cannot be forked") } if snap.geo == (Geometry{}) { @@ -1382,115 +1374,33 @@ func (c *Catalog) fork(ctx context.Context, req ForkRequest, origin string) (For return ForkResult{}, err } if h.State == storage.ChunkHeadAborted || headDeletingOrDeleted(h) { - 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 + c.dropIntent(ctx, dstRoot, id) // the tombstone is permanent: this create never lands 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.dropForkClaim(ctx, req, snap.attempt) // the fork has its HEAD: the parent is no longer needed for it return forkResult(existing, outcome != createdNow), nil } -// 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) +// readForkParent returns the published snapshot fork req names. A parent +// deleting is refused (snapshot_deleting), an absent or aborted one +// (snapshot_not_found). +func (c *Catalog) readForkParent(ctx context.Context, req ForkRequest) (SnapshotInfo, error) { + ref, ok, err := c.resolveSnap(ctx, req.Source, req.Snapshot) if err != nil { return SnapshotInfo{}, err } - 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) - } - if ref.info.geo.BlockSize != 0 && ref.info.geo.NumBlocks > geometry.MaxVolumeBytes/uint64(ref.info.geo.BlockSize) { - return SnapshotInfo{}, catErr(CodeGeometryMismatch, false, nil, "fork size exceeds maximum %d bytes (16 TiB - 4 KiB; uint32 LBA)", geometry.MaxVolumeBytes) - } - claims := decodeClaims(ref.entry) - 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 + if !ok || ref.entry == nil || ref.info.State == SnapAborted { + return SnapshotInfo{}, catErr(CodeSnapshotNotFound, false, nil, "snapshot %s/%s", req.Source, req.Snapshot) } - return SnapshotInfo{}, catErr(CodeOutcomeUnknown, true, nil, "fork %s: snapshot %s/%s kept changing; retry", req.Target, req.Source, req.Snapshot) -} - -// 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) { - _, _ = c.removeForkClaim(ctx, req, attempt) -} - -// removeForkClaim removes fork req's claim from its parent attempt and -// reports whether this call confirmed its removal (false with no error: -// the claim was not there). -func (c *Catalog) removeForkClaim(ctx context.Context, req ForkRequest, attempt string) (bool, error) { - root, err := c.volRoot(req.Source) - if err != nil || attempt == "" { - return false, err + if ref.info.State == SnapDeleting { + return SnapshotInfo{}, catErr(CodeSnapshotDeleting, false, nil, "snapshot %s/%s is being deleted", req.Source, req.Snapshot) } - 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 errors.Is(err, ErrNotFound) { - return false, nil - } - if err != nil { - return false, remoteErr(err, "read %s/%s attempt %s", req.Source, req.Snapshot, attempt) - } - claims := decodeClaims(e) - kept := claims[:0:0] - for _, cl := range claims { - if cl != token { - kept = append(kept, cl) - } - } - if len(kept) == len(claims) { - return false, nil - } - c.hook(hookClaimDrop, req.Snapshot) - // 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) - err = c.f.UpdateEntry(ctx, dir, next, map[string][]byte{extSnapState: e.Extended[extSnapState], extSnapClaims: raw}) - if err == nil { - return true, nil - } - if !errors.Is(err, ErrPrecondition) { - return false, remoteErr(err, "remove the claim of %s on %s/%s", req.Target, req.Source, req.Snapshot) - } + if ref.info.geo.BlockSize != 0 && ref.info.geo.NumBlocks > geometry.MaxVolumeBytes/uint64(ref.info.geo.BlockSize) { + return SnapshotInfo{}, catErr(CodeGeometryMismatch, false, nil, "fork size exceeds maximum %d bytes (16 TiB - 4 KiB; uint32 LBA)", geometry.MaxVolumeBytes) } - return false, remoteErr(nil, "claim of %s on %s/%s kept changing", req.Target, req.Source, req.Snapshot) + return ref.info, nil } // AbortFork settles a dead fork for a GC sweep (W5): it claims the diff --git a/seaweed-block/core/frontend/chunkstore/catalog_settle_test.go b/seaweed-block/core/frontend/chunkstore/catalog_settle_test.go index 44b67dffaa..b3fe22a6f5 100644 --- a/seaweed-block/core/frontend/chunkstore/catalog_settle_test.go +++ b/seaweed-block/core/frontend/chunkstore/catalog_settle_test.go @@ -4,7 +4,6 @@ import ( "context" "crypto/sha256" "errors" - "path" "sort" "strings" "testing" @@ -166,22 +165,8 @@ 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. 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) - } - + // Forks do not hold their parent: the delete goes through while the + // fork is incomplete, and the image binding below guards the retry. // 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/gc.go b/seaweed-block/core/frontend/chunkstore/gc.go index 678e243df2..d46175a8cf 100644 --- a/seaweed-block/core/frontend/chunkstore/gc.go +++ b/seaweed-block/core/frontend/chunkstore/gc.go @@ -41,9 +41,20 @@ type GCConfig struct { Grace, IntentTTL time.Duration // ClockSkew bounds pairwise wall-clock differences. Zero uses the default. // Binding creation timestamps additionally lose up to one second of precision. - ClockSkew time.Duration - IssuedEpoch func(context.Context, string) (uint64, error) - Now func() time.Time + ClockSkew time.Duration + // CASApplyBound is the margin for a publish applied after its fork's + // deadline check. Zero uses the catalog operation deadline. A publish + // known to have succeeded was applied before its context ended, and that + // context ends at readAt + deadline, so it is inside the deadline; an + // unknown outcome keeps the fork intent, which roots the keys until the + // target is resolved, with no time bound. This bound covers apply delay + // and clock-rate drift beyond those two. NewCollector requires + // Grace >= operation deadline + ClockSkew + CASApplyBound, so a snapshot + // deleted while a fork of it is in flight stays rooted until the fork can + // no longer publish (INV-SNAP-DELETE-ANY-ORDER-001). + CASApplyBound time.Duration + IssuedEpoch func(context.Context, string) (uint64, error) + Now func() time.Time } type GCRoot struct { @@ -105,8 +116,8 @@ type Collector struct { } func NewCollector(cat *Catalog, blobs BlobDeleter, cfg GCConfig) (*Collector, error) { - if cat == nil || blobs == nil || cfg.Grace <= cat.deadline() || cfg.IntentTTL <= 0 || cfg.IssuedEpoch == nil { - return nil, errors.New("chunkstore: GC requires catalog, blob deletion, grace > operation deadline, positive intent TTL and epoch authority") + if cat == nil || blobs == nil || cfg.IntentTTL <= 0 || cfg.IssuedEpoch == nil { + return nil, errors.New("chunkstore: GC requires catalog, blob deletion, positive intent TTL and epoch authority") } if cfg.ClockSkew == 0 { cfg.ClockSkew = DefaultGCClockSkew @@ -114,6 +125,17 @@ func NewCollector(cat *Catalog, blobs BlobDeleter, cfg GCConfig) (*Collector, er if cfg.ClockSkew < 0 || cfg.ClockSkew > time.Duration(1<<63-1)-time.Second { return nil, errors.New("chunkstore: invalid GC clock skew bound") } + if cfg.CASApplyBound == 0 { + cfg.CASApplyBound = cat.deadline() + } + const maxDur = time.Duration(1<<63 - 1) + d := cat.deadline() + if cfg.CASApplyBound < 0 || cfg.CASApplyBound > maxDur-d-cfg.ClockSkew { + return nil, errors.New("chunkstore: invalid GC CAS apply bound") + } + if need := d + cfg.ClockSkew + cfg.CASApplyBound; cfg.Grace < need { + return nil, fmt.Errorf("chunkstore: GC grace %v is below operation deadline %v + clock skew %v + CAS apply bound %v = %v", cfg.Grace, d, cfg.ClockSkew, cfg.CASApplyBound, need) + } if cfg.Now == nil { cfg.Now = time.Now } diff --git a/seaweed-block/core/frontend/chunkstore/gc_volume_test.go b/seaweed-block/core/frontend/chunkstore/gc_volume_test.go index f45bd190a4..ea5cfdc98f 100644 --- a/seaweed-block/core/frontend/chunkstore/gc_volume_test.go +++ b/seaweed-block/core/frontend/chunkstore/gc_volume_test.go @@ -51,20 +51,32 @@ func TestVolumeGC_ForeignIntentRootsAndLocalCandidates(t *testing.T) { } } -func TestGC_GraceConstructorRejectsCopyDeadline(t *testing.T) { +// Grace must cover the operation deadline, the clock skew and the CAS apply +// bound (default: the deadline), so a snapshot deleted while a fork of it is +// in flight stays rooted until that fork can no longer publish. +func TestGC_GraceConstructorRequiresDeadlineSkewAndApplyBound(t *testing.T) { _, b, c, g, _ := gcFixture(t) - for _, grace := range []time.Duration{0, c.deadline() - time.Nanosecond, c.deadline()} { + need := c.deadline() + DefaultGCClockSkew + c.deadline() + for _, grace := range []time.Duration{0, c.deadline(), c.deadline() + DefaultGCClockSkew, need - time.Nanosecond} { cfg := g.cfg - cfg.Grace = grace + cfg.Grace, cfg.ClockSkew, cfg.CASApplyBound = grace, 0, 0 if _, err := NewCollector(c, b, cfg); err == nil { - t.Errorf("accepted grace %s <= copy deadline", grace) + t.Errorf("accepted grace %s < deadline + skew + apply bound %s", grace, need) } } cfg := g.cfg - cfg.Grace = c.deadline() + time.Nanosecond + cfg.Grace, cfg.ClockSkew, cfg.CASApplyBound = need, 0, 0 + if _, err := NewCollector(c, b, cfg); err != nil { + t.Fatalf("grace = deadline + skew + apply bound: %v", err) + } + cfg.Grace, cfg.CASApplyBound = need, time.Second // an explicit, smaller bound if _, err := NewCollector(c, b, cfg); err != nil { t.Fatal(err) } + cfg.CASApplyBound = -1 + if _, err := NewCollector(c, b, cfg); err == nil { + t.Fatal("accepted a negative CAS apply bound") + } } func TestVolumeGC_DoesNotImportGlobalMark(t *testing.T) { diff --git a/seaweed-block/core/frontend/chunkstore/restore_test.go b/seaweed-block/core/frontend/chunkstore/restore_test.go index 25588987c4..bcda46abf0 100644 --- a/seaweed-block/core/frontend/chunkstore/restore_test.go +++ b/seaweed-block/core/frontend/chunkstore/restore_test.go @@ -390,48 +390,3 @@ func TestRestore_SnapshotOfAStalePreIndependenceImageRefused(t *testing.T) { t.Fatalf("the own image must still be accepted: %v", err) } } - -// Retention disposition with an aborted first HEAD on a restore target: the -// fork claim alone no longer holds the parent (liveClaims counts any HEAD, -// aborted included), but the fork-record scan does (forkParentsNeeded treats -// an aborted HEAD as no HEAD), so the parent snapshot is kept as fork_parent -// until the aborted target is deleted. That conservative hold is the rule. -func TestRestore_AbortedFirstHeadKeepsTheParentUntilTheTargetIsDeleted(t *testing.T) { - f, c, _, _ := retentionFixture(t, 1) - 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) - } - } - holdFirst(f, catBase+"/v2/HEAD") - if _, err := c.Restore(ctx, ForkRequest{Source: "v1", Snapshot: "s00", Target: "v2", RequestID: "rs"}); CodeOf(err) != CodeOutcomeUnknown { - t.Fatalf("restore with a held HEAD create: %v", err) - } - if claimed, err := c.AbortFork(ctx, "v2"); err != nil || !claimed { - t.Fatalf("abort the unpublished restore: claimed=%v %v", claimed, err) - } - if live, err := c.liveClaims(ctx, "v1", "s00", []string{forkClaim("v2", "rs")}); err != nil || len(live) != 0 { - t.Fatalf("claim on an aborted target: live=%v %v, want not live (any HEAD ends the claim)", live, err) - } - res, err := c.Retain(ctx, "v1", false) - if err != nil { - t.Fatal(err) - } - if k := kept(res.Decisions); len(k) != 1 || k["s00"] == nil || k["s00"][0] != keepForkParent || len(res.Deleted) != 0 { - t.Fatalf("aborted restore: kept %v deleted %v; want s00 kept as fork_parent", k, res.Deleted) - } - if s, err := c.allSnapshots(ctx, "v1"); err != nil || len(s) != 1 { - t.Fatalf("parent after retention: %v %v", s, err) - } - if _, err := c.DeleteVolume(ctx, "v2", nil); err != nil { - t.Fatalf("delete the aborted restore: %v", err) - } - res, err = c.Retain(ctx, "v1", false) - if err != nil || len(res.Deleted) != 1 || res.Deleted[0] != "s00" { - t.Fatalf("after the target is gone: deleted %v (%v), want s00", res.Deleted, err) - } -} diff --git a/seaweed-block/core/frontend/chunkstore/retention.go b/seaweed-block/core/frontend/chunkstore/retention.go index a714cb82bc..2873849236 100644 --- a/seaweed-block/core/frontend/chunkstore/retention.go +++ b/seaweed-block/core/frontend/chunkstore/retention.go @@ -8,13 +8,11 @@ import ( "path" "sort" "strconv" - "strings" "time" "google.golang.org/protobuf/proto" "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" - "github.com/seaweedfs/seaweed-block/core/storage" ) // Snapshot retention. @@ -34,7 +32,6 @@ import ( // + every snapshot younger than KeepYounger (a creation time in the // future, from clock skew, counts as young) // + the log-spaced keeps (below) -// + every snapshot a fork still needs // // and deletes every other snapshot. A pinned snapshot past its ExpiresAtNs // is treated as unpinned. GC reclaims the chunks. @@ -50,34 +47,18 @@ import ( // record is removed only while it still names that attempt, so a // same-name replacement made after planning is never touched. // -// Fork parents (design from the review of #142). Protection is -// one conditional write on the parent attempt's own entry, nothing else: -// -// - 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). -// -// An explicit DeleteSnapshot goes through the same check and mark -// (markDeleting): it refuses a live claim with snapshot_claimed. +// Forks and restores do not hold their parent (INV-SNAP-DELETE-ANY-ORDER-001). +// A snapshot is deleted by retention or DeleteSnapshot whatever forks read +// it: a fork reads the parent after taking its deadline start and publishes +// its HEAD only before readAt + deadline, and GC keeps a deleted attempt +// rooted for its grace, which exceeds deadline + clock skew + CAS apply +// bound (NewCollector). A fork that reads after the delete mark gets +// snapshot_deleting or snapshot_not_found, also on a retry. A claims +// xattr left by an older version is ignored. // // 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. +// it and frees the name. const ( SnapshotClassSemantic = "semantic" @@ -85,18 +66,12 @@ const ( CodeInvalidClass = "invalid_class" CodeInvalidPolicy = "invalid_policy" - // CodeSnapshotClaimed: an explicit delete of a snapshot a fork still - // claims. Not retryable as such: it clears - // when the fork publishes its HEAD or is aborted. - CodeSnapshotClaimed = "snapshot_claimed" DefaultKeepNewest = 10 DefaultKeepYounger = time.Hour extRetention = "retention" extRetentionRev = "retention_rev" - - extSnapClaims = "swb.snap.claims" ) // ValidateSnapshotClass refuses a class other than "", "semantic" and @@ -217,21 +192,20 @@ type RetentionDecision struct { // 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" + keepNewest = "newest" + keepPinned = "pinned" + keepYoung = "younger_than_policy" + keepHourly = "hourly" + keepDaily = "daily" + keepWeekly = "weekly" + reasonExpired = "expired" ) // planRetention decides, from one listing, which snapshots policy keeps at -// now. needed names the snapshots a fork still needs. Unpinned snapshots +// now. 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 { +func planRetention(p RetentionPolicy, snaps []SnapshotInfo, now time.Time) []RetentionDecision { ordered := append([]SnapshotInfo(nil), snaps...) sort.SliceStable(ordered, func(i, j int) bool { if ordered[i].CreatedNs != ordered[j].CreatedNs { @@ -280,9 +254,6 @@ func planRetention(p RetentionPolicy, snaps []SnapshotInfo, needed map[string]bo 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} @@ -314,7 +285,6 @@ type RetentionResult struct { Decisions []RetentionDecision `json:"decisions"` 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. @@ -350,13 +320,9 @@ func (c *Catalog) Retain(ctx context.Context, vol string, dryRun bool) (Retentio 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{}, Replaced: []string{}, ForkHeld: []string{}, NotAttempted: []string{}} - res.Decisions = planRetention(p, snaps, needed, c.now()) + Deleted: []string{}, Replaced: []string{}, NotAttempted: []string{}} + res.Decisions = planRetention(p, snaps, c.now()) var expired []RetentionDecision for _, d := range res.Decisions { if d.Keep { @@ -390,8 +356,6 @@ func (c *Catalog) Retain(ctx context.Context, vol string, dryRun bool) (Retentio 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 @@ -409,7 +373,6 @@ 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 live fork claim is on the attempt: kept, nothing written ) // deleteRetainedAttempt deletes the planned attempt of vol/name and only @@ -420,13 +383,9 @@ 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 { + if _, uncertain, err := c.markDeleting(ctx, vol, name, attempt); err != nil { return 0, uncertain, err } - if m == markClaimed { - return retainForkHeld, false, nil - } return c.freeName(ctx, root, name, attempt) } @@ -435,90 +394,56 @@ 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 + markSettled // already deleting or aborted ) -// 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) { +// markDeleting marks attempt of vol/name deleting, the one path for +// retention and explicit delete: the mark is conditioned on {state active, +// gen}; a lost condition re-reads and decides again. No fork claim is read +// (INV-SNAP-DELETE-ANY-ORDER-001). uncertain reports, with an error, a +// mutation whose outcome is unknown. +func (c *Catalog) markDeleting(ctx context.Context, vol, name, attempt string) (markResult, bool, error) { root, err := c.volRoot(vol) if err != nil { - return 0, nil, false, err + return 0, 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 markGone, nil, false, nil + return markGone, false, nil } if err != nil { - return 0, nil, false, remoteErr(err, "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 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, nil, false, err - } - if len(live) > 0 { - return markClaimed, live, false, nil + return markSettled, 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 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 - } 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), - extSnapGen: e.Extended[extSnapGen], - extSnapClaims: nil, // no claims: a fork that claimed meanwhile wins + extSnapState: []byte(SnapActive), + extSnapGen: e.Extended[extSnapGen], }) if errors.Is(err, ErrPrecondition) || errors.Is(err, ErrNotFound) { - continue // a claim, a delete or a replacement landed: decide again + continue // a delete or a replacement landed: decide again } if err != nil { - return 0, nil, true, remoteErr(err, "mark snapshot %s/%s attempt %s deleting", vol, name, attempt) + return 0, true, remoteErr(err, "mark snapshot %s/%s attempt %s deleting", vol, name, attempt) } c.hook(hookMarked, name) - return markDone, nil, false, nil + return markDone, false, nil } - 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, ", ")) + 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 - hookChecked = "checked" // an attempt's claims were read and none is live, before its mark + hookChecked = "checked" // an attempt was read active, 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) { @@ -539,61 +464,6 @@ func (c *Catalog) freeName(ctx context.Context, root, name, attempt string) (ret return 0, true, remoteErr(err, "remove the name record %s", name) } -// 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 -} - -func setClaims(e *filerpb.Entry, claims []string) { - if len(claims) == 0 { - delete(e.Extended, extSnapClaims) - return - } - 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 - } - _, has, err := c.ReadHead(ctx, target) - if err != nil { - return nil, err - } - if has { - continue - } - v, ok, err := c.ReadVolume(ctx, target) - if err != nil { - return nil, err - } - if ok && (v.Fork == nil || v.Fork.RequestID != req || v.Fork.Source != vol || v.Fork.Snapshot != name) { - continue - } - live = append(live, cl) - } - return live, 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) { @@ -618,36 +488,3 @@ func (c *Catalog) listSnapshots(ctx context.Context, vol string, deleting bool) after = next } } - -// 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 { - 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 index 1570b55000..d04475e01c 100644 --- a/seaweed-block/core/frontend/chunkstore/retention_integration_test.go +++ b/seaweed-block/core/frontend/chunkstore/retention_integration_test.go @@ -143,7 +143,7 @@ func TestIntegration_RetainAndUsage(t *testing.T) { // 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) { +func TestIntegration_RetainIgnoresIncompleteForks(t *testing.T) { c := startWeed(t) ctx := context.Background() const base = "/swblock/chunks" @@ -222,27 +222,18 @@ func TestIntegration_RetainHeldSchedules(t *testing.T) { t.Fatal(err) } cat.retainHook = nil - 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) + if fmt.Sprint(res.Deleted) != "[s02 s01]" || fmt.Sprint(res.Replaced) != "[s00]" { + t.Fatalf("retain: deleted=%v replaced=%v; want s02 s01 / s00 (forks do not hold their parent)", res.Deleted, res.Replaced) } 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) } - // An explicit delete of a claimed parent is refused. - if _, err := cat.DeleteSnapshot(ctx, "v1", "s01"); CodeOf(err) != CodeSnapshotClaimed { - t.Fatalf("delete of the claimed s01: %v; want snapshot_claimed", err) - } + // A retry of either stopped fork reads its parent again and is refused. 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) + _, err := cat.Fork(ctx, ForkRequest{Source: "v1", Snapshot: fk.snap, Target: fk.target, RequestID: "f"}) + if code := CodeOf(err); code != CodeSnapshotNotFound && code != CodeSnapshotDeleting { + t.Fatalf("fork %s retry after its parent was deleted: %v; want snapshot_not_found or snapshot_deleting", fk.target, 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) != "[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 ab074525b3..0ebd5b8081 100644 --- a/seaweed-block/core/frontend/chunkstore/retention_review_test.go +++ b/seaweed-block/core/frontend/chunkstore/retention_review_test.go @@ -3,7 +3,6 @@ package chunkstore import ( "context" "errors" - "path" "strings" "testing" "time" @@ -26,7 +25,7 @@ func TestPlanRetention_RollingWindows(t *testing.T) { for _, a := range ages { snaps = append(snaps, snapAt(nm(a), a, SnapshotClassSemantic, time.Time{}, nil)) } - return kept(planRetention(p, snaps, nil, now)) + return kept(planRetention(p, snaps, 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 { @@ -104,51 +103,6 @@ func forkFixture(t *testing.T) (*fakeFiler, *Catalog) { return f, c } -// A fork that starts after the retention scan (its VOLUME published, its -// 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() - 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) - } -} - -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) { @@ -176,105 +130,6 @@ func TestCatalog_ForkAfterTheMarkRefuses(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() - 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) - } - 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) - } - 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("30 days later: forkHeld=%v %v; want s01 still kept", res.ForkHeld, 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) - } - res, err = c.Retain(ctx, "v1", false) - if err != nil || strings.Join(res.Deleted, ",") != "s01" { - 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) - } -} - // 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 @@ -355,84 +210,3 @@ 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) } } - -// 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) - } -} - -// 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) - } -} diff --git a/seaweed-block/core/frontend/chunkstore/retention_test.go b/seaweed-block/core/frontend/chunkstore/retention_test.go index 10109d3916..f329ed96be 100644 --- a/seaweed-block/core/frontend/chunkstore/retention_test.go +++ b/seaweed-block/core/frontend/chunkstore/retention_test.go @@ -9,7 +9,6 @@ import ( "testing" "time" - "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" "github.com/seaweedfs/seaweed-block/core/storage" ) @@ -45,7 +44,7 @@ func TestPlanRetention_NewestNWithNameTieBreak(t *testing.T) { 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)) + k := kept(planRetention(noYoung(), snaps, now)) if len(k) != 10 { t.Fatalf("kept %d, want 10: %v", len(k), k) } @@ -55,7 +54,7 @@ func TestPlanRetention_NewestNWithNameTieBreak(t *testing.T) { } } 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 { + if k := kept(planRetention(RetentionPolicy{KeepNewest: 1}, tie, now)); len(k) != 1 || k["a"] == nil { t.Fatalf("tie: kept %v, want only a (name order)", k) } } @@ -71,7 +70,7 @@ func TestPlanRetention_PinnedSemanticAndLabels(t *testing.T) { 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)) + k := kept(planRetention(RetentionPolicy{}, snaps, 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) } @@ -87,7 +86,7 @@ func TestPlanRetention_YoungAndClockSkew(t *testing.T) { 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)) + k := kept(planRetention(p, snaps, now)) if len(k) != 2 || k["young"] == nil || k["future"] == nil { t.Fatalf("kept %v; want young and future", k) } @@ -100,7 +99,7 @@ func TestPlanRetention_HourlyBuckets(t *testing.T) { 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)) + k := kept(planRetention(RetentionPolicy{KeepHourly: 3}, snaps, now)) if len(k) != 3 { t.Fatalf("kept %d, want 3 (one per hour for the last 3 hours): %v", len(k), k) } @@ -111,16 +110,6 @@ func TestPlanRetention_HourlyBuckets(t *testing.T) { } } -// 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) { @@ -132,14 +121,14 @@ func TestPlanRetention_AgentCheckpointingEveryStepStaysBounded(t *testing.T) { } 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 { + if k := kept(planRetention(p, snaps, 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 { + if k := kept(planRetention(p, snaps, start.Add(7*24*time.Hour))); len(k) > bound { t.Fatalf("after a week: kept %d; want at most %d", len(k), bound) } } @@ -283,41 +272,6 @@ func TestCatalog_SnapshotClass(t *testing.T) { } } -// 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() diff --git a/seaweed-block/core/frontend/chunkstore/snapshot_delete_test.go b/seaweed-block/core/frontend/chunkstore/snapshot_delete_test.go new file mode 100644 index 0000000000..84405652db --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/snapshot_delete_test.go @@ -0,0 +1,158 @@ +package chunkstore + +import ( + "bytes" + "context" + "path" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" +) + +// INV-SNAP-DELETE-ANY-ORDER-001: forks and restores do not hold their parent. + +// A fork stopped past its deadline does not keep its parent: the snapshot is +// deleted, and a retry of the same request reads the parent again and is +// refused; it never publishes from its first read. +func TestSnapshotDelete_ForkRetryAfterDeleteRereadsTheParent(t *testing.T) { + f, _, c, h := catalogFixture(t) + ctx := context.Background() + if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); err != nil { + t.Fatal(err) + } + req := ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "f"} + clock := time.Now() + c.SetClock(func() time.Time { clock = clock.Add(time.Second); return clock }) // every read advances + c.OpDeadline = time.Nanosecond + if _, err := c.Fork(ctx, req); CodeOf(err) != CodeDeadlineExceeded { + t.Fatalf("fork past its deadline: %v, want deadline_exceeded", err) + } + c.OpDeadline = 0 + if _, ok, err := c.ReadVolume(ctx, "v2"); !ok || err != nil { + t.Fatalf("the stopped fork's VOLUME: ok=%v %v", ok, err) + } + if got, err := c.DeleteSnapshot(ctx, "v1", "s1"); err != nil || got != SnapDeleting { + t.Fatalf("delete the parent of an incomplete fork: %q %v, want deleting", got, err) + } + _, err := c.Fork(ctx, req) + if code := CodeOf(err); code != CodeSnapshotNotFound && code != CodeSnapshotDeleting { + t.Fatalf("retry after the parent was deleted: %v, want snapshot_not_found or snapshot_deleting", err) + } + if _, err := f.LookupEntry(ctx, catBase+"/v2", headName); err == nil { + t.Fatal("the retry published a HEAD from its first read of a deleted parent") + } +} + +// A delete that lands between a fork's read of its parent and its HEAD +// publish succeeds; the fork still publishes inside its deadline, and the +// target keeps every chunk after the source snapshot and volume are gone and +// GC has run past its grace. +func TestSnapshotDelete_DeleteDuringAForkInFlight(t *testing.T) { + f, b, c, g, now := gcFixture(t) + ctx := context.Background() + want := map[uint64][]byte{0: chunkBytes(0x41), 2: chunkBytes(0x42)} + h := publishSource(t, f, b.fakeBlobs, "v1", want) + if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); err != nil { + t.Fatal(err) + } + if err := f.CreateEntry(ctx, catBase, &filerpb.Entry{Name: "v2", IsDirectory: true}, true); err != nil { + t.Fatal(err) + } + deleted := false + f.stallCreate = func(p string) bool { // runs before the fake takes its lock + if p == catBase+"/v2/"+headName && !deleted { + deleted = true + if got, err := c.DeleteSnapshot(ctx, "v1", "s1"); err != nil || got != SnapDeleting { + t.Errorf("delete while the fork is in flight: %q %v", got, err) + } + } + return false + } + if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "f"}); err != nil { + t.Fatalf("fork whose parent was deleted after its read: %v", err) + } + f.stallCreate = nil + if !deleted { + t.Fatal("the delete never ran inside the fork") + } + detachHead(t, f, b.fakeBlobs, "v1") + if _, err := c.DeleteVolume(ctx, "v1", nil); err != nil { + t.Fatalf("delete the source volume: %v", err) + } + for i := 0; i < 3; i++ { + if _, err := g.Run(ctx); err != nil { + t.Fatalf("gc: %v", err) + } + *now = now.Add(2 * time.Hour) + } + r2, _ := NewChunkRemote(f, b, path.Join(catBase, "v2")) + h2, err := r2.GetHead(ctx) + if err != nil { + t.Fatal(err) + } + for idx, ref := range h2.Chunks { + if got, err := r2.Get(ctx, ref.Key); err != nil || !bytes.Equal(got, want[idx]) { + t.Fatalf("fork chunk %d lost: %v", idx, err) + } + } +} + +// An unknown publish outcome keeps the fork's intent, and that intent roots +// the parent's keys with no time bound: the snapshot deleted, the source +// volume deleted, GC run well past its grace, the keys survive while the +// intent exists. +func TestSnapshotDelete_UnknownPublishKeepsTheKeysWhileItsIntentExists(t *testing.T) { + f, b, c, g, now := gcFixture(t) + ctx := context.Background() + want := map[uint64][]byte{0: chunkBytes(0x51), 1: chunkBytes(0x52)} + h := publishSource(t, f, b.fakeBlobs, "v1", want) + if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); err != nil { + t.Fatal(err) + } + if err := f.CreateEntry(ctx, catBase, &filerpb.Entry{Name: "v2", IsDirectory: true}, true); err != nil { + t.Fatal(err) + } + f.failCreate = func(p string) error { + if p == catBase+"/v2/"+headName { + return errTransport + } + return nil + } + if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "f"}); CodeOf(err) != CodeOutcomeUnknown { + t.Fatalf("fork with an unknown HEAD create: %v", err) + } + f.failCreate = nil + if got, err := c.DeleteSnapshot(ctx, "v1", "s1"); err != nil || got != SnapDeleting { + t.Fatalf("delete the parent: %q %v", got, err) + } + detachHead(t, f, b.fakeBlobs, "v1") + if _, err := c.DeleteVolume(ctx, "v1", nil); err != nil { + t.Fatalf("delete the source volume: %v", err) + } + intents := func() int { + list, err := f.ListEntries(ctx, path.Join(catBase, "v2", intentsDir), "", "", 0) + if err != nil { + t.Fatal(err) + } + return len(list) + } + if intents() == 0 { + t.Fatal("the unknown publish left no intent") + } + for i := 0; i < 4; i++ { + if _, err := g.Run(ctx); err != nil { + t.Fatalf("gc: %v", err) + } + *now = now.Add(2 * time.Hour) // far past the grace + } + if intents() == 0 { + t.Fatal("GC settled the fork intent without the target being resolved") + } + r1, _ := NewChunkRemote(f, b, path.Join(catBase, "v1")) + for idx, ref := range h.Chunks { + if got, err := r1.Get(ctx, ref.Key); err != nil || !bytes.Equal(got, want[idx]) { + t.Fatalf("parent chunk %d reclaimed while the fork intent exists: %v", idx, err) + } + } +} diff --git a/seaweed-block/core/frontend/chunkstore/volume_delete_integration_test.go b/seaweed-block/core/frontend/chunkstore/volume_delete_integration_test.go index b1f4501a4d..28cc7b0e09 100644 --- a/seaweed-block/core/frontend/chunkstore/volume_delete_integration_test.go +++ b/seaweed-block/core/frontend/chunkstore/volume_delete_integration_test.go @@ -120,7 +120,7 @@ func TestIntegration_DeleteVolumeThenGC(t *testing.T) { // GC: two marks past grace reclaim exactly A (only S1 and w2 reached // it) and D (only w2); B and C (w1's HEAD and S2) stay. - grace := 2 * DefaultOpDeadline + grace := 3 * DefaultOpDeadline // >= deadline + skew + CAS apply bound at := time.Now().Add(3 * grace) g, err := NewCollector(cat, cl, GCConfig{Grace: grace, IntentTTL: time.Hour, Now: func() time.Time { return at }, IssuedEpoch: func(context.Context, string) (uint64, error) { return 1, nil }}) diff --git a/seaweed-block/core/frontend/chunkstore/volume_delete_test.go b/seaweed-block/core/frontend/chunkstore/volume_delete_test.go index 0bb854fa48..c554bb76f0 100644 --- a/seaweed-block/core/frontend/chunkstore/volume_delete_test.go +++ b/seaweed-block/core/frontend/chunkstore/volume_delete_test.go @@ -331,7 +331,7 @@ func TestCatalog_InFlightSnapshotRefusesTheDelete(t *testing.T) { } } -// A fork that claims during the delete mark sees the deleting source and +// A fork that reads during the delete mark sees the deleting source and // refuses before installing anything; the delete refuses too (the forked // snapshot exists) and reverts. func TestCatalog_ForkDuringTheDeleteMarkRefuses(t *testing.T) { @@ -355,9 +355,6 @@ func TestCatalog_ForkDuringTheDeleteMarkRefuses(t *testing.T) { if _, ok, _ := c.ReadVolume(ctx, "w2"); ok { t.Fatal("the refused fork published its VOLUME") } - if got := claimsOf(t, c, "s1"); len(got) != 0 { - t.Fatalf("the refused fork left claims %v", got) - } } // P2 (incarnation): D1 checks under deleting generation G and pauses @@ -504,14 +501,14 @@ func TestCatalog_DeleteVolumeTombstonesAndRefusesReuse(t *testing.T) { if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s2", Target: "w3", RequestID: "f3"}); CodeOf(err) != CodeOutcomeUnknown { t.Fatalf("fork w3: %v", err) } - if _, err := c.DeleteSnapshot(ctx, "v1", "s2"); CodeOf(err) != CodeSnapshotClaimed { - t.Fatalf("delete s2 under the incomplete fork: %v; want snapshot_claimed", err) + if got, err := c.DeleteSnapshot(ctx, "v1", "s2"); err != nil || got != SnapDeleting { + t.Fatalf("delete s2 under the incomplete fork: %q %v; forks do not hold their parent", got, err) } if res, err := c.DeleteVolume(ctx, "w3", nil); err != nil || !res.Completed { t.Fatalf("delete w3: %+v %v", res, err) } - if _, err := c.DeleteSnapshot(ctx, "v1", "s2"); err != nil { - t.Fatalf("delete s2 after w3 was deleted (its claim is dead): %v", err) + if got, err := c.DeleteSnapshot(ctx, "v1", "s2"); err != nil || got != SnapAbsent { + t.Fatalf("delete s2 again: %q %v; want absent", 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 918ead3a02..89d333a9bc 100644 --- a/seaweed-block/core/host/volume/chunk_control_class_test.go +++ b/seaweed-block/core/host/volume/chunk_control_class_test.go @@ -29,9 +29,6 @@ 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 { diff --git a/seaweed-block/docs/design/agent-workspace-design.md b/seaweed-block/docs/design/agent-workspace-design.md index 480573c503..790fd99811 100644 --- a/seaweed-block/docs/design/agent-workspace-design.md +++ b/seaweed-block/docs/design/agent-workspace-design.md @@ -186,9 +186,10 @@ stateDiagram-v2 ## 6. Snapshots, forks, retention, GC, volume delete - **Snapshot** (`Catalog.CreateSnapshot`): claim the name with an exclusive name record `{request, attempt}` (a retry gets its own attempt back); check the volume is not being deleted; write an intent with a deadline; re-check the deadline; exclusively create `snaps//` holding a copy of the HEAD root. An unknown outcome keeps the intent; the caller retries with the same request id. -- **Fork** (`Catalog.Fork`): claim the parent snapshot, check the source is not being deleted, write the target `VOLUME` (origin fork), then a HEAD at gen 1, epoch 0, no holder, with the parent's `RemoteLSN` and references. No segment or chunk is copied: the fork's references are owner-qualified, so it reads the parent's objects, and its root alone keeps them live after the parent snapshot is deleted. -- **Restore** (`Catalog.Restore`, independent restore): the fork steps with `VOLUME` origin `restore`; the claim is the fork's (live until the target has a HEAD), and from then on the target's owner-qualified refs keep the source's chunks live, so deleting the source snapshot or volume mid-restore is normal. The background walker (`HydrateAll`) makes every chunk local through the shared fill flights, under one host fill permit per flight. Bounded batch cuts then upload the chunks under the target's own keys; when the resolved HEAD holds no ref to another volume, the write-once `RESTORE-INDEPENDENT` entry is created (`MarkIndependent`). Snapshots of the target are refused until then, and a snapshot image that still names another volume's chunks is refused even after it. An aborted first HEAD keeps the parent snapshot as `fork_parent` until the target is deleted. Model: `docs/spec/RestoreIndependence.tla`. -- **Retention** (`retention.go`): classes `semantic` and `pinned`; newest N, recent window and log-spaced keeps; a snapshot with a live fork claim is always kept; deletion uses the same conditional mark as `DeleteSnapshot`. +- **Fork** (`Catalog.Fork`): take the deadline start and read the parent snapshot (every attempt reads it again; a parent deleting or gone refuses; the parent is not claimed), check the source is not being deleted, write the target `VOLUME` (origin fork), then a HEAD at gen 1, epoch 0, no holder, with the parent's `RemoteLSN` and references. No segment or chunk is copied: the fork's references are owner-qualified, so it reads the parent's objects, and its root alone keeps them live after the parent snapshot is deleted. +- **Restore** (`Catalog.Restore`, independent restore): the fork steps with `VOLUME` origin `restore`; until its first HEAD the parent stays rooted by GC's grace after any delete, and from then on the target's owner-qualified refs keep the source's chunks live, so deleting the source snapshot or volume mid-restore is normal. The background walker (`HydrateAll`) makes every chunk local through the shared fill flights, under one host fill permit per flight. Bounded batch cuts then upload the chunks under the target's own keys; when the resolved HEAD holds no ref to another volume, the write-once `RESTORE-INDEPENDENT` entry is created (`MarkIndependent`). Snapshots of the target are refused until then, and a snapshot image that still names another volume's chunks is refused even after it. Model: `docs/spec/RestoreIndependence.tla`. +- **Retention** (`retention.go`): classes `semantic` and `pinned`; newest N, recent window and log-spaced keeps; no snapshot is kept because of a fork or restore; deletion uses the same conditional mark as `DeleteSnapshot`. +- **Snapshot delete in any order with forks** (no claims): a fork publishes only before its read time + operation deadline, and GC keeps a deleted attempt rooted for a grace of at least deadline + clock skew + CAS apply bound (`NewCollector` refuses otherwise); an unknown publish keeps the fork intent, which roots the keys until the target is resolved. Model: `ForkDelete` (`G >= D + E + P`). - **GC** (`gc.go` `Collector.run`, operator-driven through `sw-block ops chunk gc`, preview by default; see also `core/frontend/chunkstore/GC.md`): - roots: every HEAD, every named snapshot (including one whose delete is still in progress), every snapshot attempt that is not aborted, live intents, and segment objects; an unreadable segment aborts the mark. A deleted snapshot's attempt stays a root for one grace period after its delete time, then stops counting (`Collector.snapshotAttemptHeads` in `gc_copy.go`); - a capture intent expires only if it is older than the TTL, blockmaster has issued a higher epoch, and the remote HEAD has moved to a higher epoch; copy intents are settled only by a permanent tombstone at their publication target; @@ -228,7 +229,7 @@ stateDiagram-v2 [*] --> NameHeld: exclusive name record {request, attempt} NameHeld --> Published: exclusive create snaps/name/attempt NameHeld --> Aborted: DeleteSnapshot or GC tombstones the attempt path - Published --> Deleting: DeleteSnapshot or retention (no live fork claim) + Published --> Deleting: DeleteSnapshot or retention (forks do not hold it) Deleting --> NameFreed: name record removed Aborted --> NameFreed: name record removed NameFreed --> [*] @@ -242,7 +243,7 @@ Restore (target volume): stateDiagram-v2 [*] --> Claimed: claim parent snapshot, write VOLUME (origin restore) Claimed --> Restoring: first HEAD (parent's refs, owner-qualified); claim dropped - Claimed --> Aborted: GC tombstones the HEAD (parent kept as fork_parent) + Claimed --> Aborted: GC tombstones the HEAD Restoring --> Restoring: walker fills; batch cut replaces foreign refs with own keys Restoring --> Independent: no foreign ref in the resolved HEAD; RESTORE-INDEPENDENT created Independent --> [*] @@ -376,7 +377,7 @@ Not done yet: | Chunks and segments are write-once; keys are never rebound | `chunk_remote.go` `putObject`; `gc.go` tombstones | `TestChunkRemote_KeysAreWriteOnce` (`core/frontend/chunkstore/chunk_remote_test.go`); `TestChunkLayer_C5_ChunksAreImmutable` (`core/storage/chunk_layer_contract_test.go`) | yes | | Intents are durable before the first upload and removed only after the CAS outcome is known | `captureLocked` | `TestChunkIntent_WrittenBeforeFirstUploadAndDeletedAfterCAS`, `TestChunkIntent_UncertainCASKeepsIntentUntilSettled` (`core/storage/chunk_layer_intent_test.go`) | yes | | GC never deletes a chunk reachable from a HEAD, snapshot, attempt or intent, and deletes only after two graced marks | `gc.go` `Collector.run` | `TestGC_UnreachableRequiresTwoMarksAndUploadAge`, `TestGC_StalledCutRemainsReadableAfterTwoMarks`, `TestGC_IntentExpiryNeedsTTLAuthorityAndRemoteFence` (`core/frontend/chunkstore/gc_test.go`) | yes | -| A published snapshot is removed only by `DeleteSnapshot` or retention for the planned attempt, never while a fork claim is live | `catalog.go` `DeleteSnapshot`; `retention.go` `markDeleting` | `TestCatalog_DeleteMarksThenIdempotent` (`core/frontend/chunkstore/catalog_test.go`); `TestCatalog_ClaimBetweenCheckAndMarkWins` (`core/frontend/chunkstore/retention_review_test.go`) | yes | +| A published snapshot is removed only by `DeleteSnapshot` or retention for the planned attempt, in any order with forks (no claims) | `catalog.go` `DeleteSnapshot`; `retention.go` `markDeleting` | `TestCatalog_DeleteMarksThenIdempotent` (`core/frontend/chunkstore/catalog_test.go`); `TestSnapshotDelete_DeleteDuringAForkInFlight` (`core/frontend/chunkstore/snapshot_delete_test.go`) | yes | | Volume delete commits only with no snapshot name records; past the commit point it is irreversible | `volume_delete.go` | `TestCatalog_DeleteVolumeRefusesWhileSnapshotsExist`, `TestCatalog_ConcurrentDeleteCannotRollBackACommittedOne`, `TestCatalog_DeletedHeadCannotBeRevivedByAClaim` (`core/frontend/chunkstore/volume_delete_test.go`) | yes | | Volume ids are never reused | `core/host/master/services.go`; `catalog.go` `EnsureVolume` | `TestCatalog_DeleteVolumeTombstonesAndRefusesReuse` (`core/frontend/chunkstore/volume_delete_test.go`) | yes | | A host serves and cuts only under a valid lease; a fenced guard never reopens | `workspace_lease.go` | `TestWorkspaceLeaseExpiryFencesWithoutTimerAndCannotReopen`, `TestWorkspaceDelayedRenewalCannotUndoExpiry` (`core/host/volume/workspace_lease_test.go`); `TestWorkspaceHostRequiresLeaseBeforeFrontendAndCut` (`core/host/volume/workspace_runtime_test.go`) | yes | diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index ba83dc3ba6..6c61a9147a 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -290,9 +290,9 @@ HEAD states, snapshots, forks, intents, key bindings, GC and volume delete in th |---|---|---|---|---| | — | name held | exclusive name record `{request, attempt}`; a retry with the same request id gets its own attempt back | `core/frontend/chunkstore/catalog.go` `CreateSnapshot`, `claimName` | `INV-SNAP-EXPLICIT-DELETE-001` | | name held | published | the volume is not being deleted; an intent with a deadline is written and the deadline is re-checked; exclusive create of the attempt path | `core/frontend/chunkstore/catalog.go` `CreateSnapshot` | `INV-SNAP-EXPLICIT-DELETE-001` | -| published | deleting | `DeleteSnapshot` or retention for this attempt, never while a fork claim is live | `core/frontend/chunkstore/catalog.go` `DeleteSnapshot`; `core/frontend/chunkstore/retention.go` `markDeleting` | `INV-SNAP-EXPLICIT-DELETE-001` | -| published | fork | claim the parent snapshot, check the source is not being deleted, write the target `VOLUME`, then its HEAD; no chunk is copied | `core/frontend/chunkstore/catalog.go` `Fork`, `claimForkParent` | `INV-GC-REACHABLE-001` | -| published | restore | the fork steps with `VOLUME` origin `restore`: the claim is live until the target has a HEAD (the fork's semantics); after that the target's owner-qualified refs keep the source's chunks live through GC rooting by owner, with the source snapshot and the source volume both gone; a replay onto a volume of the other origin is refused | `core/frontend/chunkstore/catalog.go` `Restore`, `fork`, `checkForkRecord`; `core/frontend/chunkstore/gc.go` `Collector.run` (qualified refs rooted by owner) | `INV-GC-REACHABLE-001`, `INV-RESTORE-PARENT-HOLD-001` | +| published | deleting | `DeleteSnapshot` or retention for this attempt, whatever forks or restores read it (no claim is read); the mark records its delete time and GC keeps the attempt rooted for its grace | `core/frontend/chunkstore/catalog.go` `DeleteSnapshot`; `core/frontend/chunkstore/retention.go` `markDeleting` | `INV-SNAP-EXPLICIT-DELETE-001`, `INV-SNAP-DELETE-ANY-ORDER-001` | +| published | fork | take the deadline start, read the parent snapshot (every attempt reads it again; deleting or absent refuses), check the source is not being deleted, write the target `VOLUME`, then its HEAD only before start + deadline; no chunk is copied and the parent is not claimed | `core/frontend/chunkstore/catalog.go` `Fork`, `readForkParent` | `INV-GC-REACHABLE-001`, `INV-SNAP-DELETE-ANY-ORDER-001` | +| published | restore | the fork steps with `VOLUME` origin `restore`: until the first HEAD the parent stays rooted by GC's grace after any delete (the fork deadline bound), after that the target's owner-qualified refs keep the source's chunks live through GC rooting by owner, with the source snapshot and the source volume both gone; a replay onto a volume of the other origin is refused | `core/frontend/chunkstore/catalog.go` `Restore`, `fork`, `checkForkRecord`; `core/frontend/chunkstore/gc.go` `Collector.run` (qualified refs rooted by owner) | `INV-GC-REACHABLE-001`, `INV-SNAP-DELETE-ANY-ORDER-001` | | restore | independent | the write-once `RESTORE-INDEPENDENT` entry is created only on a live HEAD whose resolved image (segments and every chunk ref inside) holds no ref owned by another volume | `core/frontend/chunkstore/restore.go` `MarkIndependent`, `foreignRefsOf`, `ForeignRefs` | `INV-RESTORE-INDEPENDENT-001` | | restore (not independent) | name held | refused: `CreateSnapshot` on a restore volume needs the marker, and the supplied image itself must hold no foreign ref; a refused request leaves no name or attempt | `core/frontend/chunkstore/catalog.go` `CreateSnapshot` | `INV-RESTORE-SNAPSHOT-001` | @@ -382,7 +382,7 @@ with a separate scope/config-bound mark. Incomplete marks carry no coverage. ## Part B. Invariant ledger -135 rows: 116 ACTIVE, 17 STUB, 2 ARCHIVED; 15 kept from the internal ledger, 120 new. +136 rows: 116 ACTIVE, 17 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 121 new. The "Machine / transition" column refers to Part A. Notes under a table record what a row does not cover and, for kept rows, what was narrowed from the internal ledger. @@ -568,14 +568,15 @@ Notes: | `INV-GC-UNREADABLE-SEGMENT-001` | An unreadable published segment aborts the whole GC pass before any deletion. | M6 GC mark | `core/frontend/chunkstore/gc.go` `Collector.run` | `TestManifest_UnreadablePublishedSegmentRefusesWholeGC` (`core/frontend/chunkstore/manifest_test.go`) | — | ACTIVE | | `INV-GC-DELETE-PROGRESS-001` | A definite HTTP400 DELETE refusal cannot starve later eligible bindings or erase younger candidates' completed-mark coverage. The rejected fid stays in its immutable tombstone, is retried later and is never counted reclaimed. FailedDeletes reports the object; ExecuteGC saves the complete mark before returning partial failure. Other/unknown errors and cancellation remain pass failures. | M6 bound/tombstoned → physical reclamation | `core/frontend/chunkstore/gc.go` `run`; `gc_execution.go` `executeGC`; `swfs.go` `DeleteBlob` | `TestGCPermanentDeleteDoesNotStarveLaterBindings`, `TestSWFS_DeleteBlobStatusesAndExactPath` | `GCDeleteProgress` `NoFalseSuccess`, `FailureVisible`, `LaterProgress` | ACTIVE | | `INV-GC-CLOCK-SKEW-001` | Time-based GC eligibility subtracts configured pairwise clock skew (default one minute), plus one second for binding timestamps. Future valid intent/deletion stamps retain roots without blocking unrelated work. Future/backward or differently configured marks supply no elapsed coverage; malformed marks still refuse. This assumes clocks stay within the configured pairwise bound. | M6 intent expiry, deleting snapshot roots, bound → tombstoned | `core/frontend/chunkstore/gc.go` `oldEnough`, `run`; `gc_copy.go` `SweepCopies`, `snapshotAttemptHeads`; `gc_execution.go` `readMark`, `executeGC` | `TestGCSkewSnapshotDeleteGraceBothDirections`, `TestGCSkewIntentExpiryUsesConservativeAge`, `TestGCSkewFutureIntentKeepsRootsWithoutBlockingProgress`, `TestGCSkewPersistedCoverageAcrossHosts`, `TestGCSkewBindingAgeIncludesSecondResolution`, `TestGCSkewConfigAndMarkCoverage`, `TestGCSkewBackwardStepDiscardsCoverageAndPreviewDoesNotMutate`, `TestGCSkewFutureCopyDoesNotBlockOtherSettlement` (`core/frontend/chunkstore/gc_clock_skew_test.go`) | `GCClockSkew` `NoEarlyExpiry`, `FutureProtects`, `IndependentProgress`, `EventuallyEligibleAtBound` | ACTIVE | -| `INV-GC-GRACE-DEADLINE-001` | A GC collector cannot be built unless its grace period exceeds the catalog operation deadline. | M6 GC configuration | `core/frontend/chunkstore/gc.go` `NewCollector` | `TestGC_GraceConstructorRejectsCopyDeadline` | `RetentionGCTiming` `NoLiveDelete` | ACTIVE | -| `INV-SNAP-EXPLICIT-DELETE-001` | A published snapshot is removed only by `DeleteSnapshot` or retention for its own attempt, and never while a fork claim on it is live. | M6 snapshot: Published → Deleting | `core/frontend/chunkstore/catalog.go` `DeleteSnapshot`; `core/frontend/chunkstore/retention.go` `markDeleting` | `TestCatalog_DeleteMarksThenIdempotent` (`core/frontend/chunkstore/catalog_test.go`); `TestCatalog_ClaimBetweenCheckAndMarkWins` (`core/frontend/chunkstore/retention_review_test.go`) | `ChunkLifecycleFixed` `SnapOnlyExplicitDelete` | ACTIVE | +| `INV-GC-GRACE-DEADLINE-001` | A GC collector cannot be built unless its grace period is at least the catalog operation deadline plus the clock skew bound plus the CAS apply bound (default: the operation deadline). | M6 GC configuration | `core/frontend/chunkstore/gc.go` `NewCollector` | `TestGC_GraceConstructorRequiresDeadlineSkewAndApplyBound` (`core/frontend/chunkstore/gc_volume_test.go`) | `RetentionGCTiming` `NoLiveDelete`; `ForkDelete` `NoGap` (G >= D + E + P) | ACTIVE | +| `INV-SNAP-EXPLICIT-DELETE-001` | A published snapshot is removed only by `DeleteSnapshot` or retention for its own attempt. | M6 snapshot: Published → Deleting | `core/frontend/chunkstore/catalog.go` `DeleteSnapshot`; `core/frontend/chunkstore/retention.go` `markDeleting` | `TestCatalog_DeleteMarksThenIdempotent` (`core/frontend/chunkstore/catalog_test.go`); `TestCatalog_RetainSkipsASameNameReplacement` (`core/frontend/chunkstore/retention_review_test.go`) | `ChunkLifecycleFixed` `SnapOnlyExplicitDelete` | ACTIVE | +| `INV-SNAP-DELETE-ANY-ORDER-001` | A snapshot can be deleted (explicitly or by retention) whatever forks or restores read it, in any order: no fork claim refuses or delays it. A fork reads its parent after taking its deadline start, every attempt (a retry included) reads it again, and it publishes only before start + deadline; GC keeps a deleted attempt rooted for a grace of at least deadline + clock skew + CAS apply bound; an unknown publish keeps the fork intent, which roots the keys until the target is resolved. | M6 snapshot: published → deleting, published → fork \| restore | `core/frontend/chunkstore/catalog.go` `Fork`, `readForkParent`, `DeleteSnapshot`; `core/frontend/chunkstore/retention.go` `markDeleting`; `core/frontend/chunkstore/gc.go` `NewCollector` | `TestSnapshotDelete_ForkRetryAfterDeleteRereadsTheParent`, `TestSnapshotDelete_DeleteDuringAForkInFlight`, `TestSnapshotDelete_UnknownPublishKeepsTheKeysWhileItsIntentExists` (`core/frontend/chunkstore/snapshot_delete_test.go`) | `ForkDelete` `NoGap` (simulation; exhaustive run pending) | ACTIVE | | `INV-VOLDEL-COMMIT-001` | A volume delete commits only when no snapshot name record exists, and after its commit point no concurrent delete can roll it back. | M6 HEAD: deleting → purging | `core/frontend/chunkstore/volume_delete.go` `DeleteVolume`, `snapshotsBlock`, `commitHeadPurging` | `TestCatalog_DeleteVolumeRefusesWhileSnapshotsExist`, `TestCatalog_ConcurrentDeleteCannotRollBackACommittedOne` (`core/frontend/chunkstore/volume_delete_test.go`) | `ChunkLifecycleFixed` `CommitClean` | ACTIVE | | `INV-VOLDEL-HELD-HEAD-001` | A delete marks HEAD `deleting` only while no holder holds it; an attach that reaches HEAD first wins. | M6 HEAD: detached → deleting | `core/frontend/chunkstore/volume_delete.go` `markHeadDeleting`, `headHeld` | `TestCatalog_DeleteVolumeLosesToAnAttachAtTheMark` (`core/frontend/chunkstore/volume_delete_test.go`) | — | ACTIVE | | `INV-HEAD-DELETE-FROZEN-001` | Once HEAD is `deleting`, `purging` or `deleted`, `CASHead` refuses every claim or cut; only the delete's own transitions move it. | M6 HEAD: deleting \| purging \| deleted | `core/frontend/chunkstore/chunk_remote.go` `CASHead` | `TestCatalog_DeletedHeadCannotBeRevivedByAClaim` (`core/frontend/chunkstore/volume_delete_test.go`) | `ChunkLifecycleFixed` `NoPublishAfterCommit` | ACTIVE | | `INV-RESTORE-INDEPENDENT-001` | `RESTORE-INDEPENDENT` is written once, only for a restore volume with a live HEAD whose resolved image holds no ref owned by another volume; a restore without a live HEAD (absent or aborted) never attaches and is never marked. | M6 snapshot: restore → independent | `core/frontend/chunkstore/restore.go` `MarkIndependent`, `foreignRefsOf`; `core/frontend/chunkstore/catalog.go` `EnsureVolume` | `TestRestore_MarkIndependentOnlyWithoutQualifiedRefs`, `TestRestore_WithoutLiveHeadNeverAttaches`, `TestRestore_SourceGoneIsNormal` (`core/frontend/chunkstore/restore_test.go`) | `RestoreIndependence` `Independent`, `NoForeignList` | ACTIVE | | `INV-RESTORE-SNAPSHOT-001` | A snapshot of a restore volume is refused until it is independent, and the snapshot image itself must hold no ref owned by another volume (a cut saved before the marker is refused after it); a refused request leaves no name or attempt. | M6 snapshot: restore (not independent) → name held (refused) | `core/frontend/chunkstore/catalog.go` `CreateSnapshot` | `TestRestore_SnapshotsRefusedUntilIndependent`, `TestRestore_SnapshotOfAStalePreIndependenceImageRefused` (`core/frontend/chunkstore/restore_test.go`) | `RestoreIndependence` `Independent` (`red_snap_during_restore`) | ACTIVE | -| `INV-RESTORE-PARENT-HOLD-001` | A restore target with an aborted first HEAD no longer has a live fork claim (any HEAD ends the claim), but retention still keeps the parent snapshot as `fork_parent` (the fork-record scan treats an aborted HEAD as no HEAD) until the target volume is deleted. | M6 snapshot: published (parent of an aborted restore) | `core/frontend/chunkstore/retention.go` `liveClaims`, `forkParentsNeeded` | `TestRestore_AbortedFirstHeadKeepsTheParentUntilTheTargetIsDeleted` (`core/frontend/chunkstore/restore_test.go`) | — (Go only: the model's `ClaimUntilHead` does not cover retention of an aborted target) | ACTIVE | +| `INV-RESTORE-PARENT-HOLD-001` | Retired: retention no longer keeps a snapshot because of a fork or restore (`INV-SNAP-DELETE-ANY-ORDER-001`). | — | — | — | — | ARCHIVED | | `INV-RESTORE-HYDRATE-001` | The background hydrate walker fills only through the shared fill flights (one fetch per chunk, never over a local write), yields while a guest waits, and holds one host fill permit (no cut payload, the caller's class) per flight until that flight's I/O is over, also when it returns early on cancel or revocation. | M4 Holder (background hydrate) | `core/storage/chunk_hydrate_all.go` `HydrateAll`, `startWalkerFill`, `admitFill` | `TestHydrateAll_YieldsToGuestReadsAndNeverFetchesTwice`, `TestHydrateAll_NeverOverwritesALocalWrite`, `TestHydrateAll_RealBackgroundFillLimiterAdmitsEveryFill`, `TestHydrateAll_PermitIsHeldUntilTheOwnedFetchSettles`, `TestHydrateAll_RevocationStopsTheWalker`, `TestHydrateAll_CancelReturnsWhileTheFetchIsHeld` (`core/storage/chunk_hydrate_all_test.go`) | — | ACTIVE | | `INV-CAT-INTENT-DROP-BOUNDED-001` | Dropping an operation's intent outlives the caller's cancellation (cleanup after a refused or cancelled request) but is bounded by `dropIntentTimeout`; a failed or timed-out delete leaves the intent, which only over-protects. | M6 intent: Live → Removed | `core/frontend/chunkstore/catalog.go` `dropIntent` | `TestCatalog_DropIntentIsBoundedAfterTheCallerIsCancelled` (`core/frontend/chunkstore/restore_test.go`) | — | ACTIVE | From f676da0424398b74710970f17a64d84ecc8bc8c2 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 23:09:29 -0800 Subject: [PATCH 2/4] docs: condense INV-SNAP-DELETE-ANY-ORDER-001 (statement <= 300 chars, detail in the notes) Co-Authored-By: Claude Opus 5.5 --- seaweed-block/docs/design/invariants.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 6c61a9147a..e826296eca 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -570,7 +570,7 @@ Notes: | `INV-GC-CLOCK-SKEW-001` | Time-based GC eligibility subtracts configured pairwise clock skew (default one minute), plus one second for binding timestamps. Future valid intent/deletion stamps retain roots without blocking unrelated work. Future/backward or differently configured marks supply no elapsed coverage; malformed marks still refuse. This assumes clocks stay within the configured pairwise bound. | M6 intent expiry, deleting snapshot roots, bound → tombstoned | `core/frontend/chunkstore/gc.go` `oldEnough`, `run`; `gc_copy.go` `SweepCopies`, `snapshotAttemptHeads`; `gc_execution.go` `readMark`, `executeGC` | `TestGCSkewSnapshotDeleteGraceBothDirections`, `TestGCSkewIntentExpiryUsesConservativeAge`, `TestGCSkewFutureIntentKeepsRootsWithoutBlockingProgress`, `TestGCSkewPersistedCoverageAcrossHosts`, `TestGCSkewBindingAgeIncludesSecondResolution`, `TestGCSkewConfigAndMarkCoverage`, `TestGCSkewBackwardStepDiscardsCoverageAndPreviewDoesNotMutate`, `TestGCSkewFutureCopyDoesNotBlockOtherSettlement` (`core/frontend/chunkstore/gc_clock_skew_test.go`) | `GCClockSkew` `NoEarlyExpiry`, `FutureProtects`, `IndependentProgress`, `EventuallyEligibleAtBound` | ACTIVE | | `INV-GC-GRACE-DEADLINE-001` | A GC collector cannot be built unless its grace period is at least the catalog operation deadline plus the clock skew bound plus the CAS apply bound (default: the operation deadline). | M6 GC configuration | `core/frontend/chunkstore/gc.go` `NewCollector` | `TestGC_GraceConstructorRequiresDeadlineSkewAndApplyBound` (`core/frontend/chunkstore/gc_volume_test.go`) | `RetentionGCTiming` `NoLiveDelete`; `ForkDelete` `NoGap` (G >= D + E + P) | ACTIVE | | `INV-SNAP-EXPLICIT-DELETE-001` | A published snapshot is removed only by `DeleteSnapshot` or retention for its own attempt. | M6 snapshot: Published → Deleting | `core/frontend/chunkstore/catalog.go` `DeleteSnapshot`; `core/frontend/chunkstore/retention.go` `markDeleting` | `TestCatalog_DeleteMarksThenIdempotent` (`core/frontend/chunkstore/catalog_test.go`); `TestCatalog_RetainSkipsASameNameReplacement` (`core/frontend/chunkstore/retention_review_test.go`) | `ChunkLifecycleFixed` `SnapOnlyExplicitDelete` | ACTIVE | -| `INV-SNAP-DELETE-ANY-ORDER-001` | A snapshot can be deleted (explicitly or by retention) whatever forks or restores read it, in any order: no fork claim refuses or delays it. A fork reads its parent after taking its deadline start, every attempt (a retry included) reads it again, and it publishes only before start + deadline; GC keeps a deleted attempt rooted for a grace of at least deadline + clock skew + CAS apply bound; an unknown publish keeps the fork intent, which roots the keys until the target is resolved. | M6 snapshot: published → deleting, published → fork \| restore | `core/frontend/chunkstore/catalog.go` `Fork`, `readForkParent`, `DeleteSnapshot`; `core/frontend/chunkstore/retention.go` `markDeleting`; `core/frontend/chunkstore/gc.go` `NewCollector` | `TestSnapshotDelete_ForkRetryAfterDeleteRereadsTheParent`, `TestSnapshotDelete_DeleteDuringAForkInFlight`, `TestSnapshotDelete_UnknownPublishKeepsTheKeysWhileItsIntentExists` (`core/frontend/chunkstore/snapshot_delete_test.go`) | `ForkDelete` `NoGap` (simulation; exhaustive run pending) | ACTIVE | +| `INV-SNAP-DELETE-ANY-ORDER-001` | A snapshot can be deleted (explicitly or by retention) in any order with forks and restores: no fork claim refuses or delays it. A fork publishes only before its read time + deadline, and GC keeps a deleted attempt rooted for its grace (see note). | M6 snapshot: published → deleting, published → fork \| restore | `core/frontend/chunkstore/catalog.go` `Fork`, `readForkParent`, `DeleteSnapshot`; `core/frontend/chunkstore/retention.go` `markDeleting`; `core/frontend/chunkstore/gc.go` `NewCollector` | `TestSnapshotDelete_ForkRetryAfterDeleteRereadsTheParent`, `TestSnapshotDelete_DeleteDuringAForkInFlight`, `TestSnapshotDelete_UnknownPublishKeepsTheKeysWhileItsIntentExists` (`core/frontend/chunkstore/snapshot_delete_test.go`) | `ForkDelete` `NoGap` (simulation; exhaustive run pending) | ACTIVE | | `INV-VOLDEL-COMMIT-001` | A volume delete commits only when no snapshot name record exists, and after its commit point no concurrent delete can roll it back. | M6 HEAD: deleting → purging | `core/frontend/chunkstore/volume_delete.go` `DeleteVolume`, `snapshotsBlock`, `commitHeadPurging` | `TestCatalog_DeleteVolumeRefusesWhileSnapshotsExist`, `TestCatalog_ConcurrentDeleteCannotRollBackACommittedOne` (`core/frontend/chunkstore/volume_delete_test.go`) | `ChunkLifecycleFixed` `CommitClean` | ACTIVE | | `INV-VOLDEL-HELD-HEAD-001` | A delete marks HEAD `deleting` only while no holder holds it; an attach that reaches HEAD first wins. | M6 HEAD: detached → deleting | `core/frontend/chunkstore/volume_delete.go` `markHeadDeleting`, `headHeld` | `TestCatalog_DeleteVolumeLosesToAnAttachAtTheMark` (`core/frontend/chunkstore/volume_delete_test.go`) | — | ACTIVE | | `INV-HEAD-DELETE-FROZEN-001` | Once HEAD is `deleting`, `purging` or `deleted`, `CASHead` refuses every claim or cut; only the delete's own transitions move it. | M6 HEAD: deleting \| purging \| deleted | `core/frontend/chunkstore/chunk_remote.go` `CASHead` | `TestCatalog_DeletedHeadCannotBeRevivedByAClaim` (`core/frontend/chunkstore/volume_delete_test.go`) | `ChunkLifecycleFixed` `NoPublishAfterCommit` | ACTIVE | @@ -582,6 +582,7 @@ Notes: Notes: +- `INV-SNAP-DELETE-ANY-ORDER-001`: a fork takes its deadline start before it reads the parent, and every attempt (a retry included) reads it again, so a parent deleted before the read refuses. GC keeps a deleted attempt rooted for a grace of at least deadline + clock skew + CAS apply bound (`NewCollector`). An unknown publish keeps the fork intent, which roots the keys until the target is resolved. ### B.7 Rows kept from the internal ledger: Kubernetes line and replica fencing From 5bb512d0f03cb2ad55ac8cfe99b1734d6f312ca6 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 01:22:15 -0800 Subject: [PATCH 3/4] spec: ForkDelete model and its configurations (exhausted) The fork/restore versus snapshot delete model this change rests on, byte for byte as checked (sha256 c9c7c7fa), with its 28 configurations: 11 safe (exhausted, no error, 18,672 to 15.7 M states, including every boundary G = D + E + P), 12 reds and 5 witnesses each on its expected property. README rows; the invariant rows drop the simulation tag. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/docs/design/invariants.md | 2 +- seaweed-block/docs/spec/ForkDelete.tla | 305 ++++++++++++++++++ seaweed-block/docs/spec/README.md | 2 + .../spec/cfg/ForkDelete_red_bnd_D1E1G1.cfg | 19 ++ .../spec/cfg/ForkDelete_red_bnd_D2E0G1.cfg | 19 ++ .../spec/cfg/ForkDelete_red_bnd_D2E1G2.cfg | 19 ++ .../spec/cfg/ForkDelete_red_bnd_D3E2G4.cfg | 19 ++ .../cfg/ForkDelete_red_bnd_nc2_D2E1G2.cfg | 19 ++ .../cfg/ForkDelete_red_deletedNotRooted.cfg | 19 ++ .../spec/cfg/ForkDelete_red_na_P0_D2E1G2.cfg | 19 ++ .../spec/cfg/ForkDelete_red_na_P1_D2E1G3.cfg | 19 ++ .../spec/cfg/ForkDelete_red_na_P2_D1E2G4.cfg | 19 ++ .../spec/cfg/ForkDelete_red_na_P2_D2E1G4.cfg | 19 ++ .../cfg/ForkDelete_red_noDeadlineCheck.cfg | 19 ++ .../spec/cfg/ForkDelete_red_noRetryReread.cfg | 19 ++ .../docs/spec/cfg/ForkDelete_safe_D1E1G2.cfg | 19 ++ .../docs/spec/cfg/ForkDelete_safe_D2E0G2.cfg | 19 ++ .../docs/spec/cfg/ForkDelete_safe_D2E1G3.cfg | 19 ++ .../docs/spec/cfg/ForkDelete_safe_D2E1G4.cfg | 19 ++ .../docs/spec/cfg/ForkDelete_safe_D2E2G6.cfg | 19 ++ .../docs/spec/cfg/ForkDelete_safe_D3E2G5.cfg | 19 ++ .../spec/cfg/ForkDelete_safe_na_P0_D2E1G3.cfg | 19 ++ .../spec/cfg/ForkDelete_safe_na_P1_D2E1G4.cfg | 19 ++ .../spec/cfg/ForkDelete_safe_na_P2_D1E2G5.cfg | 19 ++ .../spec/cfg/ForkDelete_safe_na_P2_D2E1G5.cfg | 19 ++ .../spec/cfg/ForkDelete_safe_nc2_D2E1G3.cfg | 19 ++ .../docs/spec/cfg/ForkDelete_wit_benefit.cfg | 20 ++ .../spec/cfg/ForkDelete_wit_benefit_na_P1.cfg | 20 ++ .../spec/cfg/ForkDelete_wit_deadlineLoss.cfg | 20 ++ .../spec/cfg/ForkDelete_wit_gcDeletes.cfg | 20 ++ .../spec/cfg/ForkDelete_wit_retryNotFound.cfg | 20 ++ 31 files changed, 845 insertions(+), 1 deletion(-) create mode 100644 seaweed-block/docs/spec/ForkDelete.tla create mode 100644 seaweed-block/docs/spec/cfg/ForkDelete_red_bnd_D1E1G1.cfg create mode 100644 seaweed-block/docs/spec/cfg/ForkDelete_red_bnd_D2E0G1.cfg create mode 100644 seaweed-block/docs/spec/cfg/ForkDelete_red_bnd_D2E1G2.cfg create mode 100644 seaweed-block/docs/spec/cfg/ForkDelete_red_bnd_D3E2G4.cfg create mode 100644 seaweed-block/docs/spec/cfg/ForkDelete_red_bnd_nc2_D2E1G2.cfg create mode 100644 seaweed-block/docs/spec/cfg/ForkDelete_red_deletedNotRooted.cfg create mode 100644 seaweed-block/docs/spec/cfg/ForkDelete_red_na_P0_D2E1G2.cfg create mode 100644 seaweed-block/docs/spec/cfg/ForkDelete_red_na_P1_D2E1G3.cfg create mode 100644 seaweed-block/docs/spec/cfg/ForkDelete_red_na_P2_D1E2G4.cfg create mode 100644 seaweed-block/docs/spec/cfg/ForkDelete_red_na_P2_D2E1G4.cfg create mode 100644 seaweed-block/docs/spec/cfg/ForkDelete_red_noDeadlineCheck.cfg create mode 100644 seaweed-block/docs/spec/cfg/ForkDelete_red_noRetryReread.cfg create mode 100644 seaweed-block/docs/spec/cfg/ForkDelete_safe_D1E1G2.cfg create mode 100644 seaweed-block/docs/spec/cfg/ForkDelete_safe_D2E0G2.cfg create mode 100644 seaweed-block/docs/spec/cfg/ForkDelete_safe_D2E1G3.cfg create mode 100644 seaweed-block/docs/spec/cfg/ForkDelete_safe_D2E1G4.cfg create mode 100644 seaweed-block/docs/spec/cfg/ForkDelete_safe_D2E2G6.cfg create mode 100644 seaweed-block/docs/spec/cfg/ForkDelete_safe_D3E2G5.cfg create mode 100644 seaweed-block/docs/spec/cfg/ForkDelete_safe_na_P0_D2E1G3.cfg create mode 100644 seaweed-block/docs/spec/cfg/ForkDelete_safe_na_P1_D2E1G4.cfg create mode 100644 seaweed-block/docs/spec/cfg/ForkDelete_safe_na_P2_D1E2G5.cfg create mode 100644 seaweed-block/docs/spec/cfg/ForkDelete_safe_na_P2_D2E1G5.cfg create mode 100644 seaweed-block/docs/spec/cfg/ForkDelete_safe_nc2_D2E1G3.cfg create mode 100644 seaweed-block/docs/spec/cfg/ForkDelete_wit_benefit.cfg create mode 100644 seaweed-block/docs/spec/cfg/ForkDelete_wit_benefit_na_P1.cfg create mode 100644 seaweed-block/docs/spec/cfg/ForkDelete_wit_deadlineLoss.cfg create mode 100644 seaweed-block/docs/spec/cfg/ForkDelete_wit_gcDeletes.cfg create mode 100644 seaweed-block/docs/spec/cfg/ForkDelete_wit_retryNotFound.cfg diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index e826296eca..923982c787 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -570,7 +570,7 @@ Notes: | `INV-GC-CLOCK-SKEW-001` | Time-based GC eligibility subtracts configured pairwise clock skew (default one minute), plus one second for binding timestamps. Future valid intent/deletion stamps retain roots without blocking unrelated work. Future/backward or differently configured marks supply no elapsed coverage; malformed marks still refuse. This assumes clocks stay within the configured pairwise bound. | M6 intent expiry, deleting snapshot roots, bound → tombstoned | `core/frontend/chunkstore/gc.go` `oldEnough`, `run`; `gc_copy.go` `SweepCopies`, `snapshotAttemptHeads`; `gc_execution.go` `readMark`, `executeGC` | `TestGCSkewSnapshotDeleteGraceBothDirections`, `TestGCSkewIntentExpiryUsesConservativeAge`, `TestGCSkewFutureIntentKeepsRootsWithoutBlockingProgress`, `TestGCSkewPersistedCoverageAcrossHosts`, `TestGCSkewBindingAgeIncludesSecondResolution`, `TestGCSkewConfigAndMarkCoverage`, `TestGCSkewBackwardStepDiscardsCoverageAndPreviewDoesNotMutate`, `TestGCSkewFutureCopyDoesNotBlockOtherSettlement` (`core/frontend/chunkstore/gc_clock_skew_test.go`) | `GCClockSkew` `NoEarlyExpiry`, `FutureProtects`, `IndependentProgress`, `EventuallyEligibleAtBound` | ACTIVE | | `INV-GC-GRACE-DEADLINE-001` | A GC collector cannot be built unless its grace period is at least the catalog operation deadline plus the clock skew bound plus the CAS apply bound (default: the operation deadline). | M6 GC configuration | `core/frontend/chunkstore/gc.go` `NewCollector` | `TestGC_GraceConstructorRequiresDeadlineSkewAndApplyBound` (`core/frontend/chunkstore/gc_volume_test.go`) | `RetentionGCTiming` `NoLiveDelete`; `ForkDelete` `NoGap` (G >= D + E + P) | ACTIVE | | `INV-SNAP-EXPLICIT-DELETE-001` | A published snapshot is removed only by `DeleteSnapshot` or retention for its own attempt. | M6 snapshot: Published → Deleting | `core/frontend/chunkstore/catalog.go` `DeleteSnapshot`; `core/frontend/chunkstore/retention.go` `markDeleting` | `TestCatalog_DeleteMarksThenIdempotent` (`core/frontend/chunkstore/catalog_test.go`); `TestCatalog_RetainSkipsASameNameReplacement` (`core/frontend/chunkstore/retention_review_test.go`) | `ChunkLifecycleFixed` `SnapOnlyExplicitDelete` | ACTIVE | -| `INV-SNAP-DELETE-ANY-ORDER-001` | A snapshot can be deleted (explicitly or by retention) in any order with forks and restores: no fork claim refuses or delays it. A fork publishes only before its read time + deadline, and GC keeps a deleted attempt rooted for its grace (see note). | M6 snapshot: published → deleting, published → fork \| restore | `core/frontend/chunkstore/catalog.go` `Fork`, `readForkParent`, `DeleteSnapshot`; `core/frontend/chunkstore/retention.go` `markDeleting`; `core/frontend/chunkstore/gc.go` `NewCollector` | `TestSnapshotDelete_ForkRetryAfterDeleteRereadsTheParent`, `TestSnapshotDelete_DeleteDuringAForkInFlight`, `TestSnapshotDelete_UnknownPublishKeepsTheKeysWhileItsIntentExists` (`core/frontend/chunkstore/snapshot_delete_test.go`) | `ForkDelete` `NoGap` (simulation; exhaustive run pending) | ACTIVE | +| `INV-SNAP-DELETE-ANY-ORDER-001` | A snapshot can be deleted (explicitly or by retention) in any order with forks and restores: no fork claim refuses or delays it. A fork publishes only before its read time + deadline, and GC keeps a deleted attempt rooted for its grace (see note). | M6 snapshot: published → deleting, published → fork \| restore | `core/frontend/chunkstore/catalog.go` `Fork`, `readForkParent`, `DeleteSnapshot`; `core/frontend/chunkstore/retention.go` `markDeleting`; `core/frontend/chunkstore/gc.go` `NewCollector` | `TestSnapshotDelete_ForkRetryAfterDeleteRereadsTheParent`, `TestSnapshotDelete_DeleteDuringAForkInFlight`, `TestSnapshotDelete_UnknownPublishKeepsTheKeysWhileItsIntentExists` (`core/frontend/chunkstore/snapshot_delete_test.go`) | `ForkDelete` `NoGap` | ACTIVE | | `INV-VOLDEL-COMMIT-001` | A volume delete commits only when no snapshot name record exists, and after its commit point no concurrent delete can roll it back. | M6 HEAD: deleting → purging | `core/frontend/chunkstore/volume_delete.go` `DeleteVolume`, `snapshotsBlock`, `commitHeadPurging` | `TestCatalog_DeleteVolumeRefusesWhileSnapshotsExist`, `TestCatalog_ConcurrentDeleteCannotRollBackACommittedOne` (`core/frontend/chunkstore/volume_delete_test.go`) | `ChunkLifecycleFixed` `CommitClean` | ACTIVE | | `INV-VOLDEL-HELD-HEAD-001` | A delete marks HEAD `deleting` only while no holder holds it; an attach that reaches HEAD first wins. | M6 HEAD: detached → deleting | `core/frontend/chunkstore/volume_delete.go` `markHeadDeleting`, `headHeld` | `TestCatalog_DeleteVolumeLosesToAnAttachAtTheMark` (`core/frontend/chunkstore/volume_delete_test.go`) | — | ACTIVE | | `INV-HEAD-DELETE-FROZEN-001` | Once HEAD is `deleting`, `purging` or `deleted`, `CASHead` refuses every claim or cut; only the delete's own transitions move it. | M6 HEAD: deleting \| purging \| deleted | `core/frontend/chunkstore/chunk_remote.go` `CASHead` | `TestCatalog_DeletedHeadCannotBeRevivedByAClaim` (`core/frontend/chunkstore/volume_delete_test.go`) | `ChunkLifecycleFixed` `NoPublishAfterCommit` | ACTIVE | diff --git a/seaweed-block/docs/spec/ForkDelete.tla b/seaweed-block/docs/spec/ForkDelete.tla new file mode 100644 index 0000000000..f3014fe1c3 --- /dev/null +++ b/seaweed-block/docs/spec/ForkDelete.tla @@ -0,0 +1,305 @@ +---------------------------- MODULE ForkDelete ---------------------------- +(***************************************************************************) +(* Fork / restore versus snapshot delete with NO lock between them. *) +(* *) +(* Volume V has one published snapshot S naming the chunks 1..NC. A fork *) +(* creates a new volume T whose HEAD will name S's chunks. A delete of S *) +(* never waits for, and is never refused because of, a fork. Safety comes *) +(* from two time rules only: *) +(* (F) the fork reads S at its local time readAt and publishes T's HEAD *) +(* only if its local clock is still < readAt + D (checked right *) +(* before publishing: one atomic step, or, with PublishAtomic=FALSE, *) +(* a check step and a later publish step at most P ticks apart); *) +(* (G) the delete is stamped delAt on the catalog's local clock; GC keeps *) +(* S's chunks rooted while ITS local clock is < delAt + G. *) +(* GC is one atomic step deleting every chunk no root names. Roots: V's *) +(* HEAD (V may overwrite chunks), S while not deleted, S's deleted record *) +(* until the grace has passed, T's HEAD once published. *) +(* *) +(* Time: real time `now` ticks by 1. Actor a reads now + bias[a]; biases *) +(* are fixed at start in -E..E with pairwise difference <= E. Clocks do *) +(* not step and run at the same rate. *) +(* *) +(* Mutant switches are CONSTANTS; the design value is noted on each. *) +(***************************************************************************) +EXTENDS Integers, FiniteSets, TLC + +CONSTANTS + NC, \* chunks 1..NC, all named by S (and by V's HEAD at start) + D, \* operation deadline of the fork (on the fork's clock) + G, \* GC grace after a delete (delAt on the catalog clock, compared on the GC clock) + E, \* pairwise clock skew bound + P, \* max ticks between the deadline check and the publish (PublishAtomic=FALSE only) + MaxNow, \* real-time bound + MaxAttempts, \* fork attempts (1 = no retry) + MaxReads, \* reads of T after its publish (witness only) + VCanOverwrite, \* [TRUE] V may stop naming chunks (nondeterministic action) + \* ---- design switches (design value in brackets) ---- + PublishChecksDeadline, \* [TRUE] publish only if local clock < readAt + D + DeletedRecordRooted, \* [TRUE] deleted S roots its chunks until the grace has passed + PublishAtomic, \* [TRUE] check + publish in one step; FALSE: two steps <= P ticks apart + RetryAfterDelete \* [TRUE] a retry re-reads S (fails if deleted); FALSE: reuses old chunk set + +ASSUME NC \in Nat /\ D \in Nat /\ G \in Nat /\ E \in Nat /\ P \in Nat /\ MaxNow \in Nat + +Chunks == 1..NC +SChunks == Chunks +Actors == {"F", "C", "GC"} \* fork process, catalog (stamps delete), garbage collector +NoTime == -1000 +FStates == {"idle", "read", "created", "checked", "published", "failed", "crashed", "notfound"} + +VARIABLES + now, \* real time + bias, \* actor -> clock bias (fixed after Init) + vNames, \* chunks V's HEAD still names + sDeleted, \* S has been deleted + delAt, \* catalog-local time stamped on the delete (NoTime before) + exists, \* chunk -> still stored + fst, \* fork state + attempts, \* fork attempts started + readAt, \* fork-local time of the current attempt's read + readSet, \* chunk set held by the fork (from the last real read of S) + haveRead, \* some attempt has read S successfully + checkAt, \* real time of the deadline check (two-step publish only) + tPub, \* T's HEAD is published + tHead, \* chunks named by T's HEAD + nReads, \* reads of T done + \* ---- history (witnesses / trace readability) ---- + pubAfterDel, \* T's HEAD was published after S was deleted + lateReadOK, \* T read all its chunks after the grace passed, with V no longer naming them + deadlineLoss, \* a fork attempt failed cleanly on the deadline + retryNotFound, \* a retry got "snapshot not found" + lastAct \* name of the last action (for traces) + +forkVars == <> +tVars == <> +histVars == <> +vars == <> + +LC(a) == now + bias[a] \* local clock of actor a + +TypeOK == + /\ now \in 0..MaxNow + /\ bias \in [Actors -> -E..E] + /\ vNames \subseteq Chunks + /\ sDeleted \in BOOLEAN + /\ delAt \in Int + /\ exists \in [Chunks -> BOOLEAN] + /\ fst \in FStates + /\ attempts \in 0..MaxAttempts + /\ readAt \in Int + /\ readSet \subseteq Chunks + /\ haveRead \in BOOLEAN + /\ checkAt \in Int + /\ tPub \in BOOLEAN + /\ tHead \subseteq Chunks + /\ nReads \in 0..MaxReads + /\ pubAfterDel \in BOOLEAN + /\ lateReadOK \in BOOLEAN + /\ deadlineLoss \in BOOLEAN + /\ retryNotFound \in BOOLEAN + /\ lastAct \in STRING + +Init == + /\ now = 0 + /\ bias \in {b \in [Actors -> -E..E] : (\A x, y \in Actors : b[x] - b[y] <= E)} + /\ vNames = Chunks + /\ sDeleted = FALSE + /\ delAt = NoTime + /\ exists = [c \in Chunks |-> TRUE] + /\ fst = "idle" + /\ attempts = 0 + /\ readAt = NoTime + /\ readSet = {} + /\ haveRead = FALSE + /\ checkAt = NoTime + /\ tPub = FALSE + /\ tHead = {} + /\ nReads = 0 + /\ pubAfterDel = FALSE + /\ lateReadOK = FALSE + /\ deadlineLoss = FALSE + /\ retryNotFound = FALSE + /\ lastAct = "Init" + +(* ============================ time ============================ *) + +\* Real time advances. With a two-step publish, at most P ticks pass between check and publish. +Tick == + /\ now < MaxNow + /\ (PublishAtomic \/ fst # "checked" \/ now < checkAt + P) + /\ now' = now + 1 + /\ lastAct' = "Tick" + /\ UNCHANGED <> + +(* ============================ fork ============================ *) + +\* Start an attempt (first try, or retry after a clean failure or a crash). +ReadSnapshot == + /\ fst \in {"idle", "failed", "crashed"} + /\ attempts < MaxAttempts + /\ attempts' = attempts + 1 + /\ lastAct' = "ReadSnapshot" + /\ (IF ~RetryAfterDelete /\ haveRead + THEN \* mutant: reuse the chunk set of an earlier attempt, no re-read of S + /\ fst' = "read" + /\ readAt' = LC("F") + /\ UNCHANGED <> + ELSE (IF sDeleted + THEN /\ fst' = "notfound" \* "snapshot not found": T never gets a HEAD + /\ retryNotFound' = (retryNotFound \/ attempts > 0) + /\ UNCHANGED <> + ELSE /\ fst' = "read" + /\ readAt' = LC("F") + /\ readSet' = SChunks + /\ haveRead' = TRUE + /\ UNCHANGED retryNotFound)) + /\ UNCHANGED <> + +\* Create T's record (no HEAD yet, no effect on roots). +CreateTarget == + /\ fst = "read" + /\ fst' = "created" + /\ lastAct' = "CreateTarget" + /\ UNCHANGED <> + +DeadlineOK == (~PublishChecksDeadline) \/ (LC("F") < readAt + D) + +\* Publish T's HEAD = the chunk set held by the fork. +DoPublish == + /\ fst' = "published" + /\ tPub' = TRUE + /\ tHead' = readSet + /\ pubAfterDel' = (pubAfterDel \/ sDeleted) + +\* (F) atomic: deadline check and publish in one step. +PublishAtomicStep == + /\ PublishAtomic + /\ fst = "created" + /\ (IF DeadlineOK + THEN /\ DoPublish + /\ lastAct' = "Publish" + /\ UNCHANGED deadlineLoss + ELSE /\ fst' = "failed" + /\ deadlineLoss' = TRUE + /\ lastAct' = "PublishDeadlineFail" + /\ UNCHANGED <>) + /\ UNCHANGED <> + +\* (F) two-step, step 1: the deadline check. +CheckDeadline == + /\ ~PublishAtomic + /\ fst = "created" + /\ (IF DeadlineOK + THEN /\ fst' = "checked" + /\ checkAt' = now + /\ lastAct' = "CheckDeadlineOK" + /\ UNCHANGED deadlineLoss + ELSE /\ fst' = "failed" + /\ deadlineLoss' = TRUE + /\ lastAct' = "CheckDeadlineFail" + /\ UNCHANGED checkAt) + /\ UNCHANGED <> + +\* (F) two-step, step 2: the publish, no new check (Tick bounds it to <= P ticks after the check). +PublishAfterCheck == + /\ fst = "checked" + /\ DoPublish + /\ lastAct' = "PublishAfterCheck" + /\ UNCHANGED <> + +\* The fork crashes in the middle of an attempt; it may later retry or never continue. +Crash == + /\ fst \in {"read", "created", "checked"} + /\ fst' = "crashed" + /\ lastAct' = "Crash" + /\ UNCHANGED <> + +(* ========================== catalog / V ========================== *) + +\* (G) delete S at any time: stamped on the catalog clock; S stops being a live root. +DeleteS == + /\ ~sDeleted + /\ sDeleted' = TRUE + /\ delAt' = LC("C") + /\ lastAct' = "DeleteS" + /\ UNCHANGED <> + +\* V's HEAD stops naming chunk c (V overwrote it). +VOverwrite(c) == + /\ VCanOverwrite + /\ c \in vNames + /\ vNames' = vNames \ {c} + /\ lastAct' = "VOverwrite" + /\ UNCHANGED <> + +(* ============================== GC ============================== *) + +Rooted(c) == + \/ c \in vNames + \/ ~sDeleted + \/ (DeletedRecordRooted /\ LC("GC") < delAt + G) + \/ (tPub /\ c \in tHead) + +\* One step: delete every stored chunk no root names. +GC == + /\ (\E c \in Chunks : exists[c] /\ ~Rooted(c)) + /\ exists' = [c \in Chunks |-> exists[c] /\ Rooted(c)] + /\ lastAct' = "GC" + /\ UNCHANGED <> + +(* ============================ readers of T ============================ *) + +TRead == + /\ tPub + /\ nReads < MaxReads + /\ nReads' = nReads + 1 + /\ lateReadOK' = (lateReadOK \/ + (/\ sDeleted + /\ vNames \cap tHead = {} + /\ LC("GC") >= delAt + G + /\ (\A c \in tHead : exists[c]))) + /\ lastAct' = "TRead" + /\ UNCHANGED <> + +Next == + \/ Tick + \/ ReadSnapshot + \/ CreateTarget + \/ PublishAtomicStep + \/ CheckDeadline + \/ PublishAfterCheck + \/ Crash + \/ DeleteS + \/ (\E c \in Chunks : VOverwrite(c)) + \/ GC + \/ TRead + +Spec == Init /\ [][Next]_vars + +(* ============================ properties ============================ *) + +\* Whenever T's HEAD is published, every chunk it names exists (checked in every state). +NoGap == tPub => (\A c \in tHead : exists[c]) + +(* Witnesses: each is expected VIOLATED (= the behaviour is reachable). *) +\* Benefit: a fork that read S before the delete publishes after the delete and T reads fine +\* after the grace has passed (only T's HEAD roots the chunks then). +WitNoBenefit == ~(pubAfterDel /\ lateReadOK) +\* A fork loses cleanly because the deadline passed. +WitNoDeadlineLoss == ~deadlineLoss +\* A retry gets "snapshot not found". +WitNoRetryNotFound == ~retryNotFound +\* GC deletes some chunk at all (shows GC is not vacuous in a safe configuration). +WitNoGCDelete == \A c \in Chunks : exists[c] +============================================================================= diff --git a/seaweed-block/docs/spec/README.md b/seaweed-block/docs/spec/README.md index 920aa86a83..31d38356b5 100644 --- a/seaweed-block/docs/spec/README.md +++ b/seaweed-block/docs/spec/README.md @@ -98,6 +98,7 @@ Two kinds of config are **expected to violate**: | `ReplicationFailover.tla` | `cfg/S6_*` | design-level | | `RetentionGCTiming.tla` | `cfg/S9_*` | | | `RetentionGCMulti.tla` | `cfg/S9b_*` | | +| `ForkDelete.tla` | `cfg/ForkDelete_*` | snapshot delete in any order with forks | | `RestoreIndependence.tla` | `cfg/RestoreIndependence_*` | independent restore | Each `.cfg` names its spec on its first line. @@ -118,6 +119,7 @@ length of TLC's shortest counterexample. | S6 | `ReplicationFailover` | RF=2: P ships to R, R acks what is durable, the client is acked when both are durable; promotion of R at a new epoch with an evidence gate; R refuses old-epoch shipping; cuts and snapshots cover only the replicated-durable frontier; an in-flight snapshot create from the old primary may still land after the failover. Design-level. | `AckedSurvive`, `HeadOnLineage`, `SnapOnLineage`, `NoStaleAck` | `S6_design` pass (52,897), `S6_design_big` (598,353). **RED:** `S6_red_localCut` HeadOnLineage; `S6_red_noFence` AckedSurvive. `S6_red_noEvidence` passes: with synchronous RF=2 acks the gate is redundant (it matters for quorum or async shipping, not modelled). | `core/transport/replica.go:362` replica rejects a stale-lineage ship entry; `core/replication/volume.go:680` RebaseShipLSN; takeover CAS as in S2 | | S9 | `RetentionGCTiming`, `RetentionGCMulti` | GC timing with an explicit clock: a copy operation with deadline D, marks of duration up to MD, deletion only after two marks at least Grace apart; then marks across two volumes with a fork and a snapshot delete. | `NoLiveDelete` | **Single op:** `S9_rule_G4` (G > D + MD) pass (10,798; `_big` 43,780); G = D passes (`S9_red_G2_noguard`, 11,953). **RED:** `S9_red_G1_noguard`, `S9_red_G1_D3` (G < D) NoLiveDelete violated. **Two volumes:** `S9b_G1_MD2`, `_G2_MD2`, `_G2_MD3`, `_G3_MD1` pass (5,743-9,079). | `core/frontend/chunkstore/gc.go:89` grace > operation deadline, `:280` mark-duration margin, `:306-318` two-mark rule, `:214-221` intent expiry; `catalog.go:896-905` intent deadline re-checked before publish; `gc_copy.go:143`, `:177` a deleting attempt stays a root until grace | | S10 | `RestoreIndependence` | Independent restore: claim, two-step fork, hydrate, bounded batch cuts (own keys uploaded under an intent, one HEAD CAS per batch), the independence marker after the last foreign ref, claim drop; GC, source snapshot and volume delete, snapshot retention, and crashes with resume from remote facts at any point. `ClaimUntilHead` selects today's fork claim (dropped at the first HEAD); the strict variant keeps the claim until independent. | `NoGap` (the target's chunks are always rooted), `Independent`, `NoForeignList`, `ClaimUntilHead_Inv`, `LifecycleFree`, `StateRemote` | **Exhaustive (TLC breadth-first, complete state graph, no error)** at MaxCrash 2, MaxGc 3 (4 for `n4`): option 1 (claim dropped at the first HEAD, the code): `safe` (NIdx 3, Batch 1) 3,639 distinct states; `safe_b2` 4,492; `safe_n4` (NIdx 4, Batch 2) 25,240. Strict variant `strict_claim_until_independent` 1,599 (and 2,003 / 9,838 at the `b2` / `n4` sizes, not shipped as cfgs here). **RED** (each violated at its invariant): `red_drop_claim_at_fork` ClaimUntilHead_Inv; `red_cas_before_upload`, `red_no_intent` NoGap; `red_marker_early`, `red_marker_before_cas`, `red_snap_during_restore` Independent; `red_list_foreign` NoForeignList; `red_resume_local` StateRemote; `red_retention_ignores_marker` LifecycleFree. **Witnesses reached:** `wit_done`, `wit_crash_resume`. Limits: no guest writes to the target while it takes ownership, GC acts immediately (no grace), one restore per snapshot. | `core/frontend/chunkstore/catalog.go` `Restore`, `CreateSnapshot` (restore refusal); `restore.go` `MarkIndependent`, `foreignRefsOf`; `retention.go` `liveClaims`, `forkParentsNeeded`; `gc.go` `Collector.run` (qualified refs rooted by owner); `core/storage/chunk_hydrate_all.go` `HydrateAll`. Batch cuts and the restore driver are not merged yet. | +| S11 | `ForkDelete` | Fork or restore against snapshot delete with no claim: the fork reads the parent, may crash and retry (a retry re-reads it), and publishes only before its read time + D, as one atomic step or check-then-publish with up to P ticks between; delete stamps its time; GC (one atomic step) keeps a deleted attempt rooted while its clock is below delete time + G. Three clocks with pairwise skew up to E. | `NoGap` (a published fork HEAD names only existing chunks) | **Exhaustive (TLC breadth-first, complete state graph, no error)**: all 11 safe cfgs, from `safe_D2E0G2` (18,672 distinct states) to `safe_na_P2_D1E2G5` (15,730,209), including every boundary G = D + E + P (atomic and two-step, NC = 2). **RED**, each violating NoGap: the boundary minus one (`red_bnd_*`, `red_na_P*`), `red_noDeadlineCheck`, `red_deletedNotRooted`, `red_noRetryReread`. **Witnesses reached:** `wit_benefit`, `wit_benefit_na_P1`, `wit_deadlineLoss`, `wit_gcDeletes`, `wit_retryNotFound`. Safe iff G >= D + E + P. | `core/frontend/chunkstore/catalog.go` `Fork` (deadline start before `readForkParent`, publish before start + deadline); `retention.go` `markDeleting` (no claim); `gc.go` `NewCollector` (grace >= deadline + skew + CAS apply bound); `gc_copy.go` `snapshotAttemptHeads` (deleted attempt rooted for grace) | ## Limits diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_red_bnd_D1E1G1.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_red_bnd_D1E1G1.cfg new file mode 100644 index 0000000000..08a0f98ca5 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_red_bnd_D1E1G1.cfg @@ -0,0 +1,19 @@ +\* RED boundary (G = D+E-1). Expected: NoGap violated. +SPECIFICATION Spec +CONSTANTS + NC = 1 + D = 1 + G = 1 + E = 1 + P = 0 + MaxNow = 8 + MaxAttempts = 2 + MaxReads = 1 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = TRUE + PublishAtomic = TRUE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_red_bnd_D2E0G1.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_red_bnd_D2E0G1.cfg new file mode 100644 index 0000000000..2461983061 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_red_bnd_D2E0G1.cfg @@ -0,0 +1,19 @@ +\* RED boundary (G = D+E-1, E=0). Expected: NoGap violated. +SPECIFICATION Spec +CONSTANTS + NC = 1 + D = 2 + G = 1 + E = 0 + P = 0 + MaxNow = 7 + MaxAttempts = 2 + MaxReads = 1 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = TRUE + PublishAtomic = TRUE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_red_bnd_D2E1G2.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_red_bnd_D2E1G2.cfg new file mode 100644 index 0000000000..5231a1b4ed --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_red_bnd_D2E1G2.cfg @@ -0,0 +1,19 @@ +\* RED boundary (G = D+E-1). Expected: NoGap violated. +SPECIFICATION Spec +CONSTANTS + NC = 1 + D = 2 + G = 2 + E = 1 + P = 0 + MaxNow = 10 + MaxAttempts = 2 + MaxReads = 1 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = TRUE + PublishAtomic = TRUE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_red_bnd_D3E2G4.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_red_bnd_D3E2G4.cfg new file mode 100644 index 0000000000..ccb2842e87 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_red_bnd_D3E2G4.cfg @@ -0,0 +1,19 @@ +\* RED boundary (G = D+E-1). Expected: NoGap violated. +SPECIFICATION Spec +CONSTANTS + NC = 1 + D = 3 + G = 4 + E = 2 + P = 0 + MaxNow = 15 + MaxAttempts = 2 + MaxReads = 1 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = TRUE + PublishAtomic = TRUE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_red_bnd_nc2_D2E1G2.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_red_bnd_nc2_D2E1G2.cfg new file mode 100644 index 0000000000..dde4eaec5e --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_red_bnd_nc2_D2E1G2.cfg @@ -0,0 +1,19 @@ +\* RED boundary with 2 chunks. Expected: NoGap violated. +SPECIFICATION Spec +CONSTANTS + NC = 2 + D = 2 + G = 2 + E = 1 + P = 0 + MaxNow = 10 + MaxAttempts = 3 + MaxReads = 2 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = TRUE + PublishAtomic = TRUE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_red_deletedNotRooted.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_red_deletedNotRooted.cfg new file mode 100644 index 0000000000..350144738f --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_red_deletedNotRooted.cfg @@ -0,0 +1,19 @@ +\* RED: a deleted snapshot stops being a root at once. Expected: NoGap violated. +SPECIFICATION Spec +CONSTANTS + NC = 1 + D = 2 + G = 3 + E = 1 + P = 0 + MaxNow = 11 + MaxAttempts = 2 + MaxReads = 1 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = FALSE + PublishAtomic = TRUE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_red_na_P0_D2E1G2.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_red_na_P0_D2E1G2.cfg new file mode 100644 index 0000000000..51d3895c09 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_red_na_P0_D2E1G2.cfg @@ -0,0 +1,19 @@ +\* RED two-step, P=0 (G = D+E+P-1). Expected: NoGap violated. +SPECIFICATION Spec +CONSTANTS + NC = 1 + D = 2 + G = 2 + E = 1 + P = 0 + MaxNow = 10 + MaxAttempts = 2 + MaxReads = 1 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = TRUE + PublishAtomic = FALSE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_red_na_P1_D2E1G3.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_red_na_P1_D2E1G3.cfg new file mode 100644 index 0000000000..95f97f1fd1 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_red_na_P1_D2E1G3.cfg @@ -0,0 +1,19 @@ +\* RED two-step, P=1 at the atomic grace G = D+E. Expected: NoGap violated. +SPECIFICATION Spec +CONSTANTS + NC = 1 + D = 2 + G = 3 + E = 1 + P = 1 + MaxNow = 12 + MaxAttempts = 2 + MaxReads = 1 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = TRUE + PublishAtomic = FALSE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_red_na_P2_D1E2G4.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_red_na_P2_D1E2G4.cfg new file mode 100644 index 0000000000..ced2c0e10d --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_red_na_P2_D1E2G4.cfg @@ -0,0 +1,19 @@ +\* RED two-step, P=2, E=2 (G = D+E+P-1). Expected: NoGap violated. +SPECIFICATION Spec +CONSTANTS + NC = 1 + D = 1 + G = 4 + E = 2 + P = 2 + MaxNow = 15 + MaxAttempts = 2 + MaxReads = 1 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = TRUE + PublishAtomic = FALSE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_red_na_P2_D2E1G4.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_red_na_P2_D2E1G4.cfg new file mode 100644 index 0000000000..7a07ed8ad3 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_red_na_P2_D2E1G4.cfg @@ -0,0 +1,19 @@ +\* RED two-step, P=2 (G = D+E+P-1). Expected: NoGap violated. +SPECIFICATION Spec +CONSTANTS + NC = 1 + D = 2 + G = 4 + E = 1 + P = 2 + MaxNow = 14 + MaxAttempts = 2 + MaxReads = 1 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = TRUE + PublishAtomic = FALSE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_red_noDeadlineCheck.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_red_noDeadlineCheck.cfg new file mode 100644 index 0000000000..aa381427c9 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_red_noDeadlineCheck.cfg @@ -0,0 +1,19 @@ +\* RED: publish without the deadline check. Expected: NoGap violated. +SPECIFICATION Spec +CONSTANTS + NC = 1 + D = 2 + G = 3 + E = 1 + P = 0 + MaxNow = 11 + MaxAttempts = 2 + MaxReads = 1 + VCanOverwrite = TRUE + PublishChecksDeadline = FALSE + DeletedRecordRooted = TRUE + PublishAtomic = TRUE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_red_noRetryReread.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_red_noRetryReread.cfg new file mode 100644 index 0000000000..6460befc5f --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_red_noRetryReread.cfg @@ -0,0 +1,19 @@ +\* RED: a retry reuses the earlier chunk set without re-reading S. Expected: NoGap violated. +SPECIFICATION Spec +CONSTANTS + NC = 1 + D = 2 + G = 3 + E = 1 + P = 0 + MaxNow = 11 + MaxAttempts = 2 + MaxReads = 1 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = TRUE + PublishAtomic = TRUE + RetryAfterDelete = FALSE +INVARIANTS + TypeOK + NoGap diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_safe_D1E1G2.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_safe_D1E1G2.cfg new file mode 100644 index 0000000000..73d4fdfd71 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_safe_D1E1G2.cfg @@ -0,0 +1,19 @@ +\* SAFE boundary (G = D+E). Expected: no violation. +SPECIFICATION Spec +CONSTANTS + NC = 1 + D = 1 + G = 2 + E = 1 + P = 0 + MaxNow = 9 + MaxAttempts = 2 + MaxReads = 1 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = TRUE + PublishAtomic = TRUE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_safe_D2E0G2.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_safe_D2E0G2.cfg new file mode 100644 index 0000000000..e696bfb904 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_safe_D2E0G2.cfg @@ -0,0 +1,19 @@ +\* SAFE boundary (G = D+E, E=0; the brief's 'G <= D' case). Expected: no violation. +SPECIFICATION Spec +CONSTANTS + NC = 1 + D = 2 + G = 2 + E = 0 + P = 0 + MaxNow = 8 + MaxAttempts = 2 + MaxReads = 1 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = TRUE + PublishAtomic = TRUE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_safe_D2E1G3.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_safe_D2E1G3.cfg new file mode 100644 index 0000000000..0aa22d44df --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_safe_D2E1G3.cfg @@ -0,0 +1,19 @@ +\* SAFE boundary (G = D+E). Expected: no violation. +SPECIFICATION Spec +CONSTANTS + NC = 1 + D = 2 + G = 3 + E = 1 + P = 0 + MaxNow = 11 + MaxAttempts = 2 + MaxReads = 1 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = TRUE + PublishAtomic = TRUE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_safe_D2E1G4.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_safe_D2E1G4.cfg new file mode 100644 index 0000000000..8cb5038239 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_safe_D2E1G4.cfg @@ -0,0 +1,19 @@ +\* SAFE margin (G = D+E+1). Expected: no violation. +SPECIFICATION Spec +CONSTANTS + NC = 1 + D = 2 + G = 4 + E = 1 + P = 0 + MaxNow = 12 + MaxAttempts = 2 + MaxReads = 1 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = TRUE + PublishAtomic = TRUE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_safe_D2E2G6.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_safe_D2E2G6.cfg new file mode 100644 index 0000000000..64c5cc8045 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_safe_D2E2G6.cfg @@ -0,0 +1,19 @@ +\* SAFE margin (G = D+2E). Expected: no violation. +SPECIFICATION Spec +CONSTANTS + NC = 1 + D = 2 + G = 6 + E = 2 + P = 0 + MaxNow = 16 + MaxAttempts = 2 + MaxReads = 1 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = TRUE + PublishAtomic = TRUE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_safe_D3E2G5.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_safe_D3E2G5.cfg new file mode 100644 index 0000000000..fbdcd1ee9a --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_safe_D3E2G5.cfg @@ -0,0 +1,19 @@ +\* SAFE boundary (G = D+E). Expected: no violation. +SPECIFICATION Spec +CONSTANTS + NC = 1 + D = 3 + G = 5 + E = 2 + P = 0 + MaxNow = 16 + MaxAttempts = 2 + MaxReads = 1 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = TRUE + PublishAtomic = TRUE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_safe_na_P0_D2E1G3.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_safe_na_P0_D2E1G3.cfg new file mode 100644 index 0000000000..1c85552c5c --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_safe_na_P0_D2E1G3.cfg @@ -0,0 +1,19 @@ +\* SAFE two-step, P=0 (G = D+E+P). Expected: no violation. +SPECIFICATION Spec +CONSTANTS + NC = 1 + D = 2 + G = 3 + E = 1 + P = 0 + MaxNow = 11 + MaxAttempts = 2 + MaxReads = 1 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = TRUE + PublishAtomic = FALSE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_safe_na_P1_D2E1G4.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_safe_na_P1_D2E1G4.cfg new file mode 100644 index 0000000000..d95d95dd61 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_safe_na_P1_D2E1G4.cfg @@ -0,0 +1,19 @@ +\* SAFE two-step, P=1 (G = D+E+P). Expected: no violation. +SPECIFICATION Spec +CONSTANTS + NC = 1 + D = 2 + G = 4 + E = 1 + P = 1 + MaxNow = 13 + MaxAttempts = 2 + MaxReads = 1 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = TRUE + PublishAtomic = FALSE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_safe_na_P2_D1E2G5.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_safe_na_P2_D1E2G5.cfg new file mode 100644 index 0000000000..22712e7e9f --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_safe_na_P2_D1E2G5.cfg @@ -0,0 +1,19 @@ +\* SAFE two-step, P=2, E=2 (G = D+E+P). Expected: no violation. +SPECIFICATION Spec +CONSTANTS + NC = 1 + D = 1 + G = 5 + E = 2 + P = 2 + MaxNow = 16 + MaxAttempts = 2 + MaxReads = 1 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = TRUE + PublishAtomic = FALSE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_safe_na_P2_D2E1G5.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_safe_na_P2_D2E1G5.cfg new file mode 100644 index 0000000000..d9ade18294 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_safe_na_P2_D2E1G5.cfg @@ -0,0 +1,19 @@ +\* SAFE two-step, P=2 (G = D+E+P). Expected: no violation. +SPECIFICATION Spec +CONSTANTS + NC = 1 + D = 2 + G = 5 + E = 1 + P = 2 + MaxNow = 15 + MaxAttempts = 2 + MaxReads = 1 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = TRUE + PublishAtomic = FALSE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_safe_nc2_D2E1G3.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_safe_nc2_D2E1G3.cfg new file mode 100644 index 0000000000..d5b21cec71 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_safe_nc2_D2E1G3.cfg @@ -0,0 +1,19 @@ +\* SAFE boundary with 2 chunks, 3 attempts, 2 reads. Expected: no violation. +SPECIFICATION Spec +CONSTANTS + NC = 2 + D = 2 + G = 3 + E = 1 + P = 0 + MaxNow = 11 + MaxAttempts = 3 + MaxReads = 2 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = TRUE + PublishAtomic = TRUE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_wit_benefit.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_wit_benefit.cfg new file mode 100644 index 0000000000..96ab829d76 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_wit_benefit.cfg @@ -0,0 +1,20 @@ +\* WITNESS (expected VIOLATED = reachable): fork read before the delete, published after it, T reads fine after the grace. +SPECIFICATION Spec +CONSTANTS + NC = 1 + D = 2 + G = 3 + E = 1 + P = 0 + MaxNow = 11 + MaxAttempts = 2 + MaxReads = 1 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = TRUE + PublishAtomic = TRUE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap + WitNoBenefit diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_wit_benefit_na_P1.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_wit_benefit_na_P1.cfg new file mode 100644 index 0000000000..c1ad118800 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_wit_benefit_na_P1.cfg @@ -0,0 +1,20 @@ +\* WITNESS two-step P=1 at its safe grace (expected VIOLATED = reachable): benefit still reachable. +SPECIFICATION Spec +CONSTANTS + NC = 1 + D = 2 + G = 4 + E = 1 + P = 1 + MaxNow = 13 + MaxAttempts = 2 + MaxReads = 1 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = TRUE + PublishAtomic = FALSE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap + WitNoBenefit diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_wit_deadlineLoss.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_wit_deadlineLoss.cfg new file mode 100644 index 0000000000..278b224e07 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_wit_deadlineLoss.cfg @@ -0,0 +1,20 @@ +\* WITNESS (expected VIOLATED = reachable): a fork fails cleanly on the deadline. +SPECIFICATION Spec +CONSTANTS + NC = 1 + D = 2 + G = 3 + E = 1 + P = 0 + MaxNow = 11 + MaxAttempts = 2 + MaxReads = 1 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = TRUE + PublishAtomic = TRUE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap + WitNoDeadlineLoss diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_wit_gcDeletes.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_wit_gcDeletes.cfg new file mode 100644 index 0000000000..c8e81bc147 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_wit_gcDeletes.cfg @@ -0,0 +1,20 @@ +\* WITNESS (expected VIOLATED = reachable): GC deletes S's chunks in a safe configuration. +SPECIFICATION Spec +CONSTANTS + NC = 1 + D = 2 + G = 3 + E = 1 + P = 0 + MaxNow = 11 + MaxAttempts = 2 + MaxReads = 1 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = TRUE + PublishAtomic = TRUE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap + WitNoGCDelete diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_wit_retryNotFound.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_wit_retryNotFound.cfg new file mode 100644 index 0000000000..ab7b41316a --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_wit_retryNotFound.cfg @@ -0,0 +1,20 @@ +\* WITNESS (expected VIOLATED = reachable): a retry gets snapshot-not-found. +SPECIFICATION Spec +CONSTANTS + NC = 1 + D = 2 + G = 3 + E = 1 + P = 0 + MaxNow = 11 + MaxAttempts = 2 + MaxReads = 1 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = TRUE + PublishAtomic = TRUE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap + WitNoRetryNotFound From 93298f9fa602621c4dd10d54c871d7c6602abc9f Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 02:08:31 -0800 Subject: [PATCH 4/4] fold: restore diagram and model row without claims; post-GC checks name every expected chunk The restore diagram's first state reads the parent (no claim, publish before read time + deadline); the S10 model row is marked as the claim-era model. The two post-GC checks go through chunksMismatch, which requires exactly the expected indexes and every payload; a negative test shows a missing index is caught. Co-Authored-By: Claude Opus 5.5 --- .../chunkstore/snapshot_delete_test.go | 60 ++++++++++++++++--- .../docs/design/agent-workspace-design.md | 8 +-- seaweed-block/docs/spec/README.md | 2 +- 3 files changed, 58 insertions(+), 12 deletions(-) diff --git a/seaweed-block/core/frontend/chunkstore/snapshot_delete_test.go b/seaweed-block/core/frontend/chunkstore/snapshot_delete_test.go index 84405652db..35b05e3ed0 100644 --- a/seaweed-block/core/frontend/chunkstore/snapshot_delete_test.go +++ b/seaweed-block/core/frontend/chunkstore/snapshot_delete_test.go @@ -3,11 +3,13 @@ package chunkstore import ( "bytes" "context" + "fmt" "path" "testing" "time" "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" + "github.com/seaweedfs/seaweed-block/core/storage" ) // INV-SNAP-DELETE-ANY-ORDER-001: forks and restores do not hold their parent. @@ -91,11 +93,7 @@ func TestSnapshotDelete_DeleteDuringAForkInFlight(t *testing.T) { if err != nil { t.Fatal(err) } - for idx, ref := range h2.Chunks { - if got, err := r2.Get(ctx, ref.Key); err != nil || !bytes.Equal(got, want[idx]) { - t.Fatalf("fork chunk %d lost: %v", idx, err) - } - } + requireChunks(t, ctx, r2, h2, want, "fork") } // An unknown publish outcome keeps the fork's intent, and that intent roots @@ -150,9 +148,57 @@ func TestSnapshotDelete_UnknownPublishKeepsTheKeysWhileItsIntentExists(t *testin t.Fatal("GC settled the fork intent without the target being resolved") } r1, _ := NewChunkRemote(f, b, path.Join(catBase, "v1")) + requireChunks(t, ctx, r1, h, want, "parent (fork intent still present)") +} + +// requireChunks fails unless h names exactly the indexes of want and each one +// reads back want's bytes (a missing index cannot pass by iterating h alone). +func requireChunks(t *testing.T, ctx context.Context, r *ChunkRemote, h storage.ChunkHead, want map[uint64][]byte, what string) { + t.Helper() + if err := chunksMismatch(ctx, r, h, want); err != nil { + t.Fatalf("%s: %v", what, err) + } +} + +func chunksMismatch(ctx context.Context, r *ChunkRemote, h storage.ChunkHead, want map[uint64][]byte) error { + if len(h.Chunks) != len(want) { + return fmt.Errorf("HEAD names %d chunks, want %d", len(h.Chunks), len(want)) + } + for idx, data := range want { + ref, ok := h.Chunks[idx] + if !ok { + return fmt.Errorf("HEAD lost chunk %d", idx) + } + if got, err := r.Get(ctx, ref.Key); err != nil || !bytes.Equal(got, data) { + return fmt.Errorf("chunk %d unreadable or changed: %v", idx, err) + } + } + return nil +} + +// The check refuses a HEAD that lost an index, even when every chunk it +// still names reads back correctly. +func TestSnapshotDelete_ChunkCheckCatchesAMissingIndex(t *testing.T) { + f, b, _, h := catalogFixture(t) + ctx := context.Background() + r, _ := NewChunkRemote(f, b, path.Join(catBase, "v1")) + want := map[uint64][]byte{} + missing := uint64(0) for idx, ref := range h.Chunks { - if got, err := r1.Get(ctx, ref.Key); err != nil || !bytes.Equal(got, want[idx]) { - t.Fatalf("parent chunk %d reclaimed while the fork intent exists: %v", idx, err) + data, err := r.Get(ctx, ref.Key) + if err != nil { + t.Fatal(err) + } + want[idx] = data + if idx >= missing { + missing = idx + 1 } + } + if err := chunksMismatch(ctx, r, h, want); err != nil { + t.Fatalf("the matching HEAD failed the check: %v", err) + } + want[missing] = chunkBytes(0x62) // an index the HEAD does not name + if err := chunksMismatch(ctx, r, h, want); err == nil { + t.Fatal("a HEAD missing an expected chunk passed the check") } } diff --git a/seaweed-block/docs/design/agent-workspace-design.md b/seaweed-block/docs/design/agent-workspace-design.md index 790fd99811..e01e8abaf2 100644 --- a/seaweed-block/docs/design/agent-workspace-design.md +++ b/seaweed-block/docs/design/agent-workspace-design.md @@ -241,16 +241,16 @@ Restore (target volume): ```mermaid stateDiagram-v2 - [*] --> Claimed: claim parent snapshot, write VOLUME (origin restore) - Claimed --> Restoring: first HEAD (parent's refs, owner-qualified); claim dropped - Claimed --> Aborted: GC tombstones the HEAD + [*] --> Forking: read the parent snapshot, write VOLUME (origin restore) + Forking --> Restoring: first HEAD (parent's refs, owner-qualified) before read time + deadline + Forking --> Aborted: GC tombstones the HEAD Restoring --> Restoring: walker fills; batch cut replaces foreign refs with own keys Restoring --> Independent: no foreign ref in the resolved HEAD; RESTORE-INDEPENDENT created Independent --> [*] Aborted --> [*]: target deleted ``` -Snapshots of the target are refused in `Claimed` and `Restoring`. +Snapshots of the target are refused in `Forking` and `Restoring`. ### Attached-volume scheduling diff --git a/seaweed-block/docs/spec/README.md b/seaweed-block/docs/spec/README.md index 31d38356b5..a6380bb678 100644 --- a/seaweed-block/docs/spec/README.md +++ b/seaweed-block/docs/spec/README.md @@ -118,7 +118,7 @@ length of TLC's shortest counterexample. | S5 | `ControlPlane` | Blockmaster authority store: one volume record `{epoch, holder, move journal}`, two retried move requests, durable Puts that succeed, fail, or land with the reply lost, and restarts. | `UniqueEpoch` (issued epochs strictly increase), `Idempotent` (one epoch per request id), `JournalComplete` | `S5_code` pass (298). **RED:** `S5_red_noUncertain` UniqueEpoch violated (5-step: a lost-reply Put, then a reservation from stale memory puts the old assignment back). `S5_red_noReserve` passes (the reservation step is not needed for these invariants). | `core/authority/authority.go:436` applyWithWorkspaceMove (uncertain refusal `:442-444`, Put `:564`, mark uncertain `:568`); `core/authority/workspace.go:309` prepareWorkspaceMoveLocked (expected line `:313`, resume a reserved entry `:324-333`, reserve max+1 `:344-355`), journal replay `:192-219`, persist and mark uncertain `:276-288` | | S6 | `ReplicationFailover` | RF=2: P ships to R, R acks what is durable, the client is acked when both are durable; promotion of R at a new epoch with an evidence gate; R refuses old-epoch shipping; cuts and snapshots cover only the replicated-durable frontier; an in-flight snapshot create from the old primary may still land after the failover. Design-level. | `AckedSurvive`, `HeadOnLineage`, `SnapOnLineage`, `NoStaleAck` | `S6_design` pass (52,897), `S6_design_big` (598,353). **RED:** `S6_red_localCut` HeadOnLineage; `S6_red_noFence` AckedSurvive. `S6_red_noEvidence` passes: with synchronous RF=2 acks the gate is redundant (it matters for quorum or async shipping, not modelled). | `core/transport/replica.go:362` replica rejects a stale-lineage ship entry; `core/replication/volume.go:680` RebaseShipLSN; takeover CAS as in S2 | | S9 | `RetentionGCTiming`, `RetentionGCMulti` | GC timing with an explicit clock: a copy operation with deadline D, marks of duration up to MD, deletion only after two marks at least Grace apart; then marks across two volumes with a fork and a snapshot delete. | `NoLiveDelete` | **Single op:** `S9_rule_G4` (G > D + MD) pass (10,798; `_big` 43,780); G = D passes (`S9_red_G2_noguard`, 11,953). **RED:** `S9_red_G1_noguard`, `S9_red_G1_D3` (G < D) NoLiveDelete violated. **Two volumes:** `S9b_G1_MD2`, `_G2_MD2`, `_G2_MD3`, `_G3_MD1` pass (5,743-9,079). | `core/frontend/chunkstore/gc.go:89` grace > operation deadline, `:280` mark-duration margin, `:306-318` two-mark rule, `:214-221` intent expiry; `catalog.go:896-905` intent deadline re-checked before publish; `gc_copy.go:143`, `:177` a deleting attempt stays a root until grace | -| S10 | `RestoreIndependence` | Independent restore: claim, two-step fork, hydrate, bounded batch cuts (own keys uploaded under an intent, one HEAD CAS per batch), the independence marker after the last foreign ref, claim drop; GC, source snapshot and volume delete, snapshot retention, and crashes with resume from remote facts at any point. `ClaimUntilHead` selects today's fork claim (dropped at the first HEAD); the strict variant keeps the claim until independent. | `NoGap` (the target's chunks are always rooted), `Independent`, `NoForeignList`, `ClaimUntilHead_Inv`, `LifecycleFree`, `StateRemote` | **Exhaustive (TLC breadth-first, complete state graph, no error)** at MaxCrash 2, MaxGc 3 (4 for `n4`): option 1 (claim dropped at the first HEAD, the code): `safe` (NIdx 3, Batch 1) 3,639 distinct states; `safe_b2` 4,492; `safe_n4` (NIdx 4, Batch 2) 25,240. Strict variant `strict_claim_until_independent` 1,599 (and 2,003 / 9,838 at the `b2` / `n4` sizes, not shipped as cfgs here). **RED** (each violated at its invariant): `red_drop_claim_at_fork` ClaimUntilHead_Inv; `red_cas_before_upload`, `red_no_intent` NoGap; `red_marker_early`, `red_marker_before_cas`, `red_snap_during_restore` Independent; `red_list_foreign` NoForeignList; `red_resume_local` StateRemote; `red_retention_ignores_marker` LifecycleFree. **Witnesses reached:** `wit_done`, `wit_crash_resume`. Limits: no guest writes to the target while it takes ownership, GC acts immediately (no grace), one restore per snapshot. | `core/frontend/chunkstore/catalog.go` `Restore`, `CreateSnapshot` (restore refusal); `restore.go` `MarkIndependent`, `foreignRefsOf`; `retention.go` `liveClaims`, `forkParentsNeeded`; `gc.go` `Collector.run` (qualified refs rooted by owner); `core/storage/chunk_hydrate_all.go` `HydrateAll`. Batch cuts and the restore driver are not merged yet. | +| S10 | `RestoreIndependence` | Independent restore: claim, two-step fork, hydrate, bounded batch cuts (own keys uploaded under an intent, one HEAD CAS per batch), the independence marker after the last foreign ref, claim drop; GC, source snapshot and volume delete, snapshot retention, and crashes with resume from remote facts at any point. Claim-era model: `ClaimUntilHead` selects the fork claim as it was before fork claims were removed (`INV-SNAP-DELETE-ANY-ORDER-001`), the strict variant keeps it until independent; the code no longer claims, and the no-claim variant ships with the restore driver. | `NoGap` (the target's chunks are always rooted), `Independent`, `NoForeignList`, `ClaimUntilHead_Inv`, `LifecycleFree`, `StateRemote` | **Exhaustive (TLC breadth-first, complete state graph, no error)** at MaxCrash 2, MaxGc 3 (4 for `n4`): option 1 (claim dropped at the first HEAD, the code): `safe` (NIdx 3, Batch 1) 3,639 distinct states; `safe_b2` 4,492; `safe_n4` (NIdx 4, Batch 2) 25,240. Strict variant `strict_claim_until_independent` 1,599 (and 2,003 / 9,838 at the `b2` / `n4` sizes, not shipped as cfgs here). **RED** (each violated at its invariant): `red_drop_claim_at_fork` ClaimUntilHead_Inv; `red_cas_before_upload`, `red_no_intent` NoGap; `red_marker_early`, `red_marker_before_cas`, `red_snap_during_restore` Independent; `red_list_foreign` NoForeignList; `red_resume_local` StateRemote; `red_retention_ignores_marker` LifecycleFree. **Witnesses reached:** `wit_done`, `wit_crash_resume`. Limits: no guest writes to the target while it takes ownership, GC acts immediately (no grace), one restore per snapshot. | `core/frontend/chunkstore/catalog.go` `Restore`, `CreateSnapshot` (restore refusal); `restore.go` `MarkIndependent`, `foreignRefsOf`; `retention.go` `liveClaims`, `forkParentsNeeded`; `gc.go` `Collector.run` (qualified refs rooted by owner); `core/storage/chunk_hydrate_all.go` `HydrateAll`. Batch cuts and the restore driver are not merged yet. | | S11 | `ForkDelete` | Fork or restore against snapshot delete with no claim: the fork reads the parent, may crash and retry (a retry re-reads it), and publishes only before its read time + D, as one atomic step or check-then-publish with up to P ticks between; delete stamps its time; GC (one atomic step) keeps a deleted attempt rooted while its clock is below delete time + G. Three clocks with pairwise skew up to E. | `NoGap` (a published fork HEAD names only existing chunks) | **Exhaustive (TLC breadth-first, complete state graph, no error)**: all 11 safe cfgs, from `safe_D2E0G2` (18,672 distinct states) to `safe_na_P2_D1E2G5` (15,730,209), including every boundary G = D + E + P (atomic and two-step, NC = 2). **RED**, each violating NoGap: the boundary minus one (`red_bnd_*`, `red_na_P*`), `red_noDeadlineCheck`, `red_deletedNotRooted`, `red_noRetryReread`. **Witnesses reached:** `wit_benefit`, `wit_benefit_na_P1`, `wit_deadlineLoss`, `wit_gcDeletes`, `wit_retryNotFound`. Safe iff G >= D + E + P. | `core/frontend/chunkstore/catalog.go` `Fork` (deadline start before `readForkParent`, publish before start + deadline); `retention.go` `markDeleting` (no claim); `gc.go` `NewCollector` (grace >= deadline + skew + CAS apply bound); `gc_copy.go` `snapshotAttemptHeads` (deleted attempt rooted for grace) | ## Limits