From 3001bfe63541071f7dc43850431c89f9098867a5 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 24 Nov 2026 16:16:17 -0800 Subject: [PATCH 1/7] layout: volume delete and the release of a dependent A volume delete runs in its order, each prefix safe and the whole re-runnable: HEAD deleting (only with no holder, checked immediately before, no open transaction and no snapshot with dependents), then this volume released from every source's dependents, then its objects deleted, then HEAD deleted. HEAD gains a state; from deleting on, every holder transition, a claim and a removal are refused. A dependent is released from a source by the target's volume id in one conditional update, the delete's step and the operator's remove-dependent command. The package guard allows DeleteVolume as the second remover and requires its order (controls: the pool before the release, no holder check); the stale-holder table now covers holder transitions only. Co-Authored-By: Claude Opus 5.5 --- .../core/frontend/chunkstore/layout/claim.go | 3 + .../core/frontend/chunkstore/layout/clean.go | 8 +- .../core/frontend/chunkstore/layout/commit.go | 4 +- .../core/frontend/chunkstore/layout/delete.go | 143 +++++++++++ .../frontend/chunkstore/layout/delete_test.go | 234 ++++++++++++++++++ .../frontend/chunkstore/layout/guard_test.go | 104 +++++++- .../core/frontend/chunkstore/layout/head.go | 32 ++- .../core/frontend/chunkstore/layout/remove.go | 4 +- .../frontend/chunkstore/layout/stale_test.go | 7 +- seaweed-block/docs/design/invariants.md | 10 +- 10 files changed, 522 insertions(+), 27 deletions(-) create mode 100644 seaweed-block/core/frontend/chunkstore/layout/delete.go create mode 100644 seaweed-block/core/frontend/chunkstore/layout/delete_test.go diff --git a/seaweed-block/core/frontend/chunkstore/layout/claim.go b/seaweed-block/core/frontend/chunkstore/layout/claim.go index 5b82a88de8..73d8e2c350 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/claim.go +++ b/seaweed-block/core/frontend/chunkstore/layout/claim.go @@ -28,6 +28,9 @@ func (h Head) Claim(me HolderID) (next Head, changed bool, err error) { if me.Epoch == 0 || me.Holder == "" || me.ClaimID == "" { return Head{}, false, errors.New("layout: Claim needs an epoch, a holder and a claim id") } + if h.State != StateLive { + return Head{}, false, fmt.Errorf("%w: HEAD is %s", ErrVolumeDeleting, h.State) + } switch { case me.Epoch < h.Epoch: return Head{}, false, fmt.Errorf("%w: HEAD epoch %d, caller %d", ErrStaleEpoch, h.Epoch, me.Epoch) diff --git a/seaweed-block/core/frontend/chunkstore/layout/clean.go b/seaweed-block/core/frontend/chunkstore/layout/clean.go index ba292a9869..887bdc466b 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/clean.go +++ b/seaweed-block/core/frontend/chunkstore/layout/clean.go @@ -14,8 +14,8 @@ func (h Head) BeginClean(me HolderID, session string) (next Head, changed bool, if session == "" { return Head{}, false, errors.New("layout: BeginClean needs a session id") } - if !h.heldBy(me) { - return Head{}, false, fmt.Errorf("%w: HEAD epoch %d holder %q, caller epoch %d holder %q", ErrNotHolder, h.Epoch, h.Holder, me.Epoch, me.Holder) + if err := h.holderErr(me); err != nil { + return Head{}, false, err } switch { case h.Activity == Activity{Kind: ActClean, Session: session}: @@ -36,8 +36,8 @@ func (h Head) EndClean(me HolderID, session string) (next Head, changed bool, er if session == "" { return Head{}, false, errors.New("layout: EndClean needs a session id") } - if !h.heldBy(me) { - return Head{}, false, fmt.Errorf("%w: HEAD epoch %d holder %q, caller epoch %d holder %q", ErrNotHolder, h.Epoch, h.Holder, me.Epoch, me.Holder) + if err := h.holderErr(me); err != nil { + return Head{}, false, err } switch { case h.Activity.Kind == ActIdle: diff --git a/seaweed-block/core/frontend/chunkstore/layout/commit.go b/seaweed-block/core/frontend/chunkstore/layout/commit.go index 3afbc378a1..b3a72f3735 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/commit.go +++ b/seaweed-block/core/frontend/chunkstore/layout/commit.go @@ -66,8 +66,8 @@ func (h Head) Commit(me HolderID, session string, root RootName, position uint64 if session == "" { return Head{}, false, errors.New("layout: Commit needs a session id") } - if !h.heldBy(me) { - return Head{}, false, fmt.Errorf("%w: HEAD epoch %d holder %q, caller epoch %d holder %q", ErrNotHolder, h.Epoch, h.Holder, me.Epoch, me.Holder) + if err := h.holderErr(me); err != nil { + return Head{}, false, err } if h.Activity.Kind == ActIdle && h.Current != nil && *h.Current == root && h.Position == position { if s, ok := h.Snapshots[snapshot]; snapshot == "" || ok && s.Root == root { diff --git a/seaweed-block/core/frontend/chunkstore/layout/delete.go b/seaweed-block/core/frontend/chunkstore/layout/delete.go new file mode 100644 index 0000000000..9f7ac1a43f --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout/delete.go @@ -0,0 +1,143 @@ +package layout + +import ( + "bytes" + "context" + "errors" + "fmt" +) + +// HEAD states: a live volume, one being deleted, one deleted. +const ( + StateLive = "" + StateDeleting = "deleting" + StateDeleted = "deleted" +) + +var ( + // ErrVolumeDeleting: the volume is being deleted or is deleted; no + // holder transition and no claim applies. + ErrVolumeDeleting = errors.New("layout: volume is being deleted") + // ErrHasDependents: a snapshot still has restore targets naming its + // chunks; the volume cannot be deleted. + ErrHasDependents = errors.New("layout: a snapshot has dependents") + // ErrHolderActive: a transaction is open on the volume. + ErrHolderActive = errors.New("layout: a holder is acting on the volume") +) + +// HolderGone is the deletion's premise: it returns nil only when no block +// holds the volume (no line or lease the master grants). DeleteVolume calls +// it immediately before marking HEAD deleting. +type HolderGone interface { + NoHolder(ctx context.Context) error +} + +// MarkDeleting is the first step of a volume delete: live -> deleting, +// refused while a transaction is open or any snapshot has dependents. +// Deleting or deleted again is a replay. +func (h Head) MarkDeleting() (next Head, changed bool, err error) { + switch h.State { + case StateDeleting, StateDeleted: + return h, false, nil + } + if h.Activity.Kind != ActIdle { + return Head{}, false, fmt.Errorf("%w: %s(%s)", ErrHolderActive, h.Activity.Kind, h.Activity.Session) + } + for n, s := range h.Snapshots { + if len(s.Dependents) > 0 { + return Head{}, false, fmt.Errorf("%w: snapshot %q has %d", ErrHasDependents, n, len(s.Dependents)) + } + } + next = h.clone() + next.State = StateDeleting + return next, true, nil +} + +// MarkDeleted is the last step: deleting -> deleted. Deleted again is a +// replay; a live HEAD is refused (the delete never began). +func (h Head) MarkDeleted() (next Head, changed bool, err error) { + switch h.State { + case StateDeleted: + return h, false, nil + case StateLive: + return Head{}, false, fmt.Errorf("layout: HEAD is live; a delete marks it deleting first") + } + next = h.clone() + next.State = StateDeleted + return next, true, nil +} + +// ReleaseDependent removes the target volume id from the dependents of +// every snapshot of this (source) HEAD: the step a deleted target makes on +// each source, and the operator's remove-dependent command. A HEAD with no +// such dependent is a replay. +func (h Head) ReleaseDependent(target VolumeID) (next Head, changed bool, err error) { + if target.IsZero() { + return Head{}, false, errors.New("layout: ReleaseDependent needs a target volume id") + } + next = h.clone() + for n, s := range next.Snapshots { + kept := s.Dependents[:0] + for _, d := range s.Dependents { + if !bytes.Equal(d.TargetID[:], target[:]) { + kept = append(kept, d) + } + } + if len(kept) != len(s.Dependents) { + s.Dependents = kept + next.Snapshots[n] = s + changed = true + } + } + if !changed { + return h, false, nil + } + return next, true, nil +} + +// RunMarkDeleting applies MarkDeleting by one conditional update. +func RunMarkDeleting(ctx context.Context, st HeadStore) (Head, error) { + return runTransition(ctx, st, func(h Head) (Head, bool, error) { return h.MarkDeleting() }) +} + +// RunMarkDeleted applies MarkDeleted by one conditional update. +func RunMarkDeleted(ctx context.Context, st HeadStore) (Head, error) { + return runTransition(ctx, st, func(h Head) (Head, bool, error) { return h.MarkDeleted() }) +} + +// RunReleaseDependent applies ReleaseDependent to a source's HEAD by one +// conditional update. +func RunReleaseDependent(ctx context.Context, source HeadStore, target VolumeID) (Head, error) { + return runTransition(ctx, source, func(h Head) (Head, bool, error) { return h.ReleaseDependent(target) }) +} + +// DeleteVolume runs a volume delete in its order, every prefix safe and +// the whole re-runnable: HEAD deleting (refused while a holder acts or a +// snapshot has dependents; no holder transition, claim or removal applies +// from here), then this volume released from every source it depends on, +// then every object of its pool, segments and roots deleted, then HEAD +// deleted. A source left out keeps an extra dependent, which over-protects +// and is released by the operator's command. +func DeleteVolume(ctx context.Context, st HeadStore, gone HolderGone, id VolumeID, sources []HeadStore, pool Pool, objects []string) error { + if gone == nil || pool == nil { + return errors.New("layout: delete needs a holder check and a pool") + } + if err := gone.NoHolder(ctx); err != nil { + return fmt.Errorf("%w: %v", ErrHolderActive, err) + } + if _, err := RunMarkDeleting(ctx, st); err != nil { + return err + } + for _, src := range sources { + if _, err := RunReleaseDependent(ctx, src, id); err != nil { + return err + } + } + for _, rel := range objects { + if err := pool.DeleteObject(ctx, rel); err != nil { + return fmt.Errorf("layout: delete %s: %w", rel, err) + } + } + _, err := RunMarkDeleted(ctx, st) + return err +} diff --git a/seaweed-block/core/frontend/chunkstore/layout/delete_test.go b/seaweed-block/core/frontend/chunkstore/layout/delete_test.go new file mode 100644 index 0000000000..d2a237b606 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout/delete_test.go @@ -0,0 +1,234 @@ +package layout + +import ( + "context" + "errors" + "fmt" + "path" + "testing" +) + +func deletingHead() Head { + h := idleHead() + h.State = StateDeleting + return h +} + +func TestMarkDeleting_Closure(t *testing.T) { + next, changed, err := idleHead().MarkDeleting() + if err != nil || !changed || next.State != StateDeleting { + t.Fatalf("MarkDeleting from live: %+v %t %v", next, changed, err) + } + for _, h := range []Head{deletingHead(), func() Head { h := idleHead(); h.State = StateDeleted; return h }()} { + if again, changed, err := h.MarkDeleting(); err != nil || changed || again.State != h.State { + t.Fatalf("MarkDeleting over %s: %+v %t %v; want a replay", h.State, again, changed, err) + } + } + if _, _, err := snapHead("s1").MarkDeleting(); !errors.Is(err, ErrHolderActive) { + t.Fatalf("MarkDeleting with a snapshot open: %v; want ErrHolderActive", err) + } + withDeps := idleHead() + rn := RootName{Hash: Sum([]byte("r"))} + withDeps.Snapshots = map[string]Snapshot{"daily": {Root: rn, Dependents: deps(rn, "t1")}} + if _, _, err := withDeps.MarkDeleting(); !errors.Is(err, ErrHasDependents) { + t.Fatalf("MarkDeleting with a dependent: %v; want ErrHasDependents", err) + } +} + +func TestMarkDeleted_Closure(t *testing.T) { + next, changed, err := deletingHead().MarkDeleted() + if err != nil || !changed || next.State != StateDeleted { + t.Fatalf("MarkDeleted from deleting: %+v %t %v", next, changed, err) + } + if _, changed, err := next.MarkDeleted(); err != nil || changed { + t.Fatalf("MarkDeleted over deleted: %t %v; want a replay", changed, err) + } + if _, _, err := idleHead().MarkDeleted(); err == nil { + t.Fatal("MarkDeleted over a live HEAD succeeded") + } +} + +func TestReleaseDependent_Closure(t *testing.T) { + rn := RootName{Hash: Sum([]byte("r"))} + old := RootName{Hash: Sum([]byte("old"))} + h := idleHead() + h.Snapshots = map[string]Snapshot{"daily": {Root: rn, Dependents: deps(rn, "t1", "t2")}, "weekly": {Root: old, Dependents: deps(old, "t1")}} + next, changed, err := h.ReleaseDependent(idFor("t1")) + if err != nil || !changed { + t.Fatalf("ReleaseDependent: %+v %t %v", next, changed, err) + } + if d := next.Snapshots["daily"].Dependents; len(d) != 1 || d[0].Target != "t2" || len(next.Snapshots["weekly"].Dependents) != 0 { + t.Fatalf("dependents after releasing t1: %+v", next.Snapshots) + } + if len(h.Snapshots["daily"].Dependents) != 2 { + t.Fatal("ReleaseDependent changed its receiver") + } + if _, changed, err := next.ReleaseDependent(idFor("t1")); err != nil || changed { + t.Fatalf("ReleaseDependent of an absent target: %t %v; want a replay", changed, err) + } + // A volume created again under t2's name has another id and releases nothing. + if _, changed, err := next.ReleaseDependent(idFor("t2 again")); err != nil || changed { + t.Fatalf("ReleaseDependent of another volume under the same name: %t %v; want nothing released", changed, err) + } + if _, _, err := h.ReleaseDependent(VolumeID{}); err == nil { + t.Fatal("ReleaseDependent of the zero id accepted") + } +} + +// Once deleting, no holder transition, no claim and no removal applies. +func TestDeleting_RefusesEveryHolderStep(t *testing.T) { + h := deletingHead() + rn := RootName{Hash: Sum([]byte("r"))} + for name, step := range map[string]func() error{ + "Begin": func() error { _, _, err := h.Begin(me, "s"); return err }, + "Abort": func() error { _, _, err := h.Abort(me, "s"); return err }, + "Commit": func() error { _, _, err := h.Commit(me, "s", rn, 1, ""); return err }, + "BeginClean": func() error { _, _, err := h.BeginClean(me, "c"); return err }, + "EndClean": func() error { _, _, err := h.EndClean(me, "c"); return err }, + "Claim": func() error { _, _, err := h.Claim(newer); return err }, + } { + if err := step(); !errors.Is(err, ErrVolumeDeleting) { + t.Errorf("%s over a deleting HEAD: %v; want ErrVolumeDeleting", name, err) + } + } + o, rh, _, orphans := removeFixture(t) + rh.State = StateDeleting + if _, err := removeShard0(t, &memHead{h: rh}, o, &fakeHeld{}, "c1", orphans); !errors.Is(err, ErrVolumeDeleting) || len(o.deletes) != 0 { + t.Fatalf("removal over a deleting HEAD: %v, %d deletes", err, len(o.deletes)) + } +} + +func TestRunMarkDeleting_InterruptAtEveryStep(t *testing.T) { + interruptHead(t, idleHead(), func(st HeadStore) error { _, err := RunMarkDeleting(context.Background(), st); return err }, + func(t *testing.T, h Head) { + if h.State != StateDeleting { + t.Fatalf("state %q", h.State) + } + }) +} + +func TestRunMarkDeleted_InterruptAtEveryStep(t *testing.T) { + interruptHead(t, deletingHead(), func(st HeadStore) error { _, err := RunMarkDeleted(context.Background(), st); return err }, + func(t *testing.T, h Head) { + if h.State != StateDeleted { + t.Fatalf("state %q", h.State) + } + }) +} + +func TestRunReleaseDependent_InterruptAtEveryStep(t *testing.T) { + rn := RootName{Hash: Sum([]byte("r"))} + h := idleHead() + h.Snapshots = map[string]Snapshot{"daily": {Root: rn, Dependents: deps(rn, "t1", "t2")}} + interruptHead(t, h, func(st HeadStore) error { + _, err := RunReleaseDependent(context.Background(), st, idFor("t1")) + return err + }, + func(t *testing.T, h Head) { + if d := h.Snapshots["daily"].Dependents; len(d) != 1 || d[0].Target != "t2" { + t.Fatalf("dependents %+v", d) + } + }) +} + +type gone struct{ err error } + +func (g gone) NoHolder(context.Context) error { return g.err } + +// deleteWorld: volume t (a restore target of src's snapshot "daily") with +// two objects in its pool; src's HEAD lists t as a dependent. +type deleteWorld struct { + t, src *memHead + objs map[string][]byte + rels []string +} + +func newDeleteWorld() *deleteWorld { + rn := RootName{Hash: Sum([]byte("src root"))} + src := idleHead() + src.VolumeID = idFor("src") + src.Snapshots = map[string]Snapshot{"daily": {Root: rn, Dependents: deps(rn, "t")}} + tgt := idleHead() + tgt.VolumeID = idFor("t") + rels := []string{NameChunk(1, []byte("x")).Path(), NameChunk(2, []byte("y")).Path()} + objs := map[string][]byte{} + for _, r := range rels { + objs[path.Join(volRoot, r)] = []byte("o") + } + return &deleteWorld{t: &memHead{h: &tgt}, src: &memHead{h: &src}, objs: objs, rels: rels} +} + +// A delete is refused while a holder acts and while the volume has +// dependents of its own; otherwise it runs in order and ends deleted with +// its pool empty and itself released from its source. +func TestDeleteVolume(t *testing.T) { + ctx := context.Background() + w := newDeleteWorld() + o := &objPool{objs: w.objs} + if err := DeleteVolume(ctx, w.t, gone{errors.New("leased to srv-a")}, idFor("t"), []HeadStore{w.src}, o, w.rels); !errors.Is(err, ErrHolderActive) || w.t.updates != 0 { + t.Fatalf("delete while held: %v (%d HEAD writes)", err, w.t.updates) + } + if err := DeleteVolume(ctx, w.src, gone{}, idFor("src"), nil, o, nil); !errors.Is(err, ErrHasDependents) { + t.Fatalf("delete of a volume with a dependent: %v; want ErrHasDependents", err) + } + if err := DeleteVolume(ctx, w.t, gone{}, idFor("t"), []HeadStore{w.src}, o, w.rels); err != nil { + t.Fatal(err) + } + if w.t.h.State != StateDeleted || len(o.objs) != 0 || len(w.src.h.Snapshots["daily"].Dependents) != 0 { + t.Fatalf("after the delete: state %q, %d objects, source dependents %+v", w.t.h.State, len(o.objs), w.src.h.Snapshots["daily"].Dependents) + } + if err := DeleteVolume(ctx, w.t, gone{}, idFor("t"), []HeadStore{w.src}, o, w.rels); err != nil { + t.Fatalf("a further re-run: %v", err) + } +} + +// Interrupt at every step of the volume delete (HEAD deleting, the release +// on the source, each object, HEAD deleted), before the write applies and +// after it applied with its reply lost. After every kill no step past the +// kill has run out of order (the pool is touched only once HEAD is +// deleting and the source released); the re-run ends deleted, the pool +// empty and the source released. +func TestDeleteVolume_InterruptAtEveryStep(t *testing.T) { + ctx := context.Background() + order := []string{"t HEAD", "src HEAD", "object", "object", "t HEAD"} + for k := range order { + for _, after := range []bool{false, true} { + t.Run(fmt.Sprintf("step%d %s/after=%t", k+1, order[k], after), func(t *testing.T) { + w := newDeleteWorld() + o := &objPool{objs: w.objs} + nth := 0 + for _, kind := range order[:k+1] { + if kind == order[k] { + nth++ + } + } + switch order[k] { + case "t HEAD": + w.t.killAt, w.t.after = nth, after + case "src HEAD": + w.src.killAt, w.src.after = nth, after + case "object": + o.killAt, o.after = nth, after + } + if err := DeleteVolume(ctx, w.t, gone{}, idFor("t"), []HeadStore{w.src}, o, w.rels); !errors.Is(err, errKilled) { + t.Fatalf("killed run: %v", err) + } + if len(o.objs) < len(w.rels) && (w.t.h.State == StateLive || len(w.src.h.Snapshots["daily"].Dependents) != 0) { + t.Fatal("the pool was touched before HEAD was deleting and the source released") + } + if len(w.src.h.Snapshots["daily"].Dependents) == 0 && w.t.h.State == StateLive { + t.Fatal("the source released the target before its HEAD was deleting") + } + w.t.restart() + w.src.restart() + o.dead, o.killAt = false, 0 + if err := DeleteVolume(ctx, w.t, gone{}, idFor("t"), []HeadStore{w.src}, o, w.rels); err != nil { + t.Fatalf("re-run: %v", err) + } + if w.t.h.State != StateDeleted || len(o.objs) != 0 || len(w.src.h.Snapshots["daily"].Dependents) != 0 { + t.Fatalf("after the re-run: state %q, %d objects, source dependents %+v", w.t.h.State, len(o.objs), w.src.h.Snapshots["daily"].Dependents) + } + }) + } + } +} diff --git a/seaweed-block/core/frontend/chunkstore/layout/guard_test.go b/seaweed-block/core/frontend/chunkstore/layout/guard_test.go index 626b603de6..89ae70c43b 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/guard_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout/guard_test.go @@ -124,9 +124,11 @@ func owners(m map[string]bool) []string { // RunClaim, when it is declared, uses it. // - Every declared exported Run function goes through runTransition. // - Pool: a name starting with Delete or Remove is used only in -// RemoveUnreachable, and there every delete is preceded, in the same -// loop body, by the remover's own lease check (StillHeld); see -// removerOrderFindings. +// RemoveUnreachable, where every delete is preceded, in the same loop +// body, by the remover's own lease check (StillHeld), and in +// DeleteVolume, whose steps run in the delete's order: no holder, HEAD +// deleting, the dependents released, the objects deleted, HEAD +// deleted; see removerOrderFindings and deleteOrderFindings. // // These are syntactic checks of this package's own files: they see any // use of these names, but not a store effect reached through a name they @@ -169,8 +171,8 @@ func guardFindings(code map[string]map[string]bool, decl, tests map[string]bool) for name, by := range code { if strings.HasPrefix(name, "Delete") || strings.HasPrefix(name, "Remove") { for _, fn := range owners(by) { - if fn != "RemoveUnreachable" { - bad = append(bad, fn+" uses "+name+": only RemoveUnreachable removes, after its lease re-check") + if fn != "RemoveUnreachable" && fn != "DeleteVolume" { + bad = append(bad, fn+" uses "+name+": only RemoveUnreachable (after its lease re-check) and DeleteVolume (after HEAD deleting and the dependents released) remove") } } } @@ -243,6 +245,57 @@ func removerOrderFindings(t *testing.T, srcs map[string]string) []string { return bad } +// deleteOrderFindings checks DeleteVolume's order in the sources: among its +// top-level statements, the first use of each step comes after the +// previous step's: NoHolder, RunMarkDeleting, RunReleaseDependent, +// DeleteObject, RunMarkDeleted. +func deleteOrderFindings(t *testing.T, srcs map[string]string) []string { + t.Helper() + steps := []string{"NoHolder", "RunMarkDeleting", "RunReleaseDependent", "DeleteObject", "RunMarkDeleted"} + var bad []string + for fname, src := range srcs { + file, err := parser.ParseFile(token.NewFileSet(), fname, src, 0) + if err != nil { + t.Fatal(err) + } + for _, d := range file.Decls { + fn, ok := d.(*ast.FuncDecl) + if !ok || fn.Body == nil || fn.Name.Name != "DeleteVolume" { + continue + } + first := map[string]int{} + for i, st := range fn.Body.List { + ast.Inspect(st, func(n ast.Node) bool { + var name string + switch x := n.(type) { + case *ast.SelectorExpr: + name = x.Sel.Name + case *ast.Ident: + name = x.Name + } + if _, seen := first[name]; !seen && name != "" { + first[name] = i + } + return true + }) + } + for k, step := range steps { + at, ok := first[step] + if !ok { + bad = append(bad, "DeleteVolume has no "+step) + continue + } + if k > 0 { + if prev, ok := first[steps[k-1]]; ok && prev >= at { + bad = append(bad, "DeleteVolume runs "+step+" before "+steps[k-1]+" has run") + } + } + } + } + } + return bad +} + // declared returns the names of the functions the sources declare. func declared(t *testing.T, srcs map[string]string) map[string]bool { t.Helper() @@ -268,6 +321,9 @@ func TestGuard_WritersTransitionsAndRemovers(t *testing.T) { if bad := append(guardFindings(code, declared(t, src), tests), removerOrderFindings(t, src)...); len(bad) != 0 { t.Fatalf("guard: %s", strings.Join(bad, "\n")) } + if bad := deleteOrderFindings(t, src); len(bad) != 0 { + t.Fatalf("guard: %s", strings.Join(bad, "\n")) + } st := reflect.TypeOf((*HeadStore)(nil)).Elem() var methods []string for i := 0; i < st.NumMethod(); i++ { @@ -299,7 +355,7 @@ func TestGuard_Controls(t *testing.T) { "untested transition": {src: `func RunZz(ctx context.Context, st HeadStore) (Head, error) { return runTransition(ctx, st, nil) }`, want: "has no TestZz_Closure"}, "lease wait outside claim": {src: `func w(ctx context.Context, l LeaseWait) error { return l.OldLeaseEnded(ctx, 1) }`, want: "only RunClaim claims"}, "remover outside RemoveUnreachable": {src: `type p interface{ DeleteObject(context.Context, string) error } -func w(ctx context.Context, x p) error { return x.DeleteObject(ctx, "o") }`, want: "only RemoveUnreachable removes"}, +func w(ctx context.Context, x p) error { return x.DeleteObject(ctx, "o") }`, want: "only RemoveUnreachable (after its lease re-check) and DeleteVolume"}, "removal without lease check": {file: "remove.go", src: `type p interface{ DeleteObject(context.Context, string) error } type l interface{ StillHeld(context.Context) error } func RemoveUnreachable(ctx context.Context, x p, h l, names []string) error { @@ -340,8 +396,40 @@ func RemoveUnreachable(ctx context.Context, x p, h l, names []string) error { return runTransition(ctx, st, func(h Head) (Head, bool, error) { return h, false, nil }) }`, want: "does not wait for the old lease", file: "claim.go"}, "transition not through runTransition": {src: `func RunZz(ctx context.Context, st HeadStore) (Head, error) { h, _, err := st.ReadHead(ctx); return h, err }`, want: "does not go through runTransition"}, + "delete removes the pool before releasing dependents": {file: "delete.go", src: `type p interface{ DeleteObject(context.Context, string) error } +type g interface{ NoHolder(context.Context) error } +func RunMarkDeleting(ctx context.Context, st HeadStore) (Head, error) { return runTransition(ctx, st, nil) } +func RunMarkDeleted(ctx context.Context, st HeadStore) (Head, error) { return runTransition(ctx, st, nil) } +func RunReleaseDependent(ctx context.Context, st HeadStore, id VolumeID) (Head, error) { return runTransition(ctx, st, nil) } +func DeleteVolume(ctx context.Context, st HeadStore, x g, id VolumeID, srcs []HeadStore, pool p, objs []string) error { + _ = x.NoHolder(ctx) + _, _ = RunMarkDeleting(ctx, st) + for _, o := range objs { + _ = pool.DeleteObject(ctx, o) + } + for _, s := range srcs { + _, _ = RunReleaseDependent(ctx, s, id) + } + _, _ = RunMarkDeleted(ctx, st) + return nil +}`, want: "runs DeleteObject before RunReleaseDependent"}, + "delete without the holder check": {file: "delete.go", src: `type p interface{ DeleteObject(context.Context, string) error } +func RunMarkDeleting(ctx context.Context, st HeadStore) (Head, error) { return runTransition(ctx, st, nil) } +func RunMarkDeleted(ctx context.Context, st HeadStore) (Head, error) { return runTransition(ctx, st, nil) } +func RunReleaseDependent(ctx context.Context, st HeadStore, id VolumeID) (Head, error) { return runTransition(ctx, st, nil) } +func DeleteVolume(ctx context.Context, st HeadStore, id VolumeID, srcs []HeadStore, pool p, objs []string) error { + _, _ = RunMarkDeleting(ctx, st) + for _, s := range srcs { + _, _ = RunReleaseDependent(ctx, s, id) + } + for _, o := range objs { + _ = pool.DeleteObject(ctx, o) + } + _, _ = RunMarkDeleted(ctx, st) + return nil +}`, want: "DeleteVolume has no NoHolder"}, "remover method value": {src: `type p interface{ RemoveName(string) } -func w(x p) { f := x.RemoveName; f("o") }`, want: "only RemoveUnreachable removes"}, +func w(x p) { f := x.RemoveName; f("o") }`, want: "only RemoveUnreachable (after its lease re-check) and DeleteVolume"}, } { srcs := packageSources(t, false) file := c.file @@ -349,7 +437,7 @@ func w(x p) { f := x.RemoveName; f("o") }`, want: "only RemoveUnreachable remove file = "zz_control.go" } srcs[file] = "package layout\n\nimport \"context\"\n\nvar _ context.Context\n\n" + c.src + "\n" - bad := append(guardFindings(refs(t, srcs), declared(t, srcs), tests), removerOrderFindings(t, srcs)...) + bad := append(append(guardFindings(refs(t, srcs), declared(t, srcs), tests), removerOrderFindings(t, srcs)...), deleteOrderFindings(t, srcs)...) if !strings.Contains(strings.Join(bad, "\n"), c.want) { t.Errorf("control %q: findings %q; want one containing %q", name, bad, c.want) } diff --git a/seaweed-block/core/frontend/chunkstore/layout/head.go b/seaweed-block/core/frontend/chunkstore/layout/head.go index fd8b71024d..2725259277 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/head.go +++ b/seaweed-block/core/frontend/chunkstore/layout/head.go @@ -63,6 +63,7 @@ type Head struct { Current *RootName // nil: no image committed yet Position uint64 Snapshots map[string]Snapshot + State string // StateLive, StateDeleting or StateDeleted } type headDoc struct { @@ -74,6 +75,7 @@ type headDoc struct { Current string `json:"current,omitempty"` Position uint64 `json:"position"` Snapshots map[string]snapDoc `json:"snapshots,omitempty"` + State string `json:"state,omitempty"` } type snapDoc struct { @@ -101,6 +103,11 @@ func (h Head) check() error { if h.VolumeID.IsZero() { return fmt.Errorf("%w: HEAD without a volume id", ErrMalformed) } + switch h.State { + case StateLive, StateDeleting, StateDeleted: + default: + return fmt.Errorf("%w: HEAD state %q", ErrMalformed, h.State) + } for field, v := range map[string]string{"holder": h.Holder, "session": h.Activity.Session, "claim id": h.ClaimID} { if err := validName(field, v); err != nil { return err @@ -157,7 +164,7 @@ func (h Head) Encode() ([]byte, error) { if err := h.check(); err != nil { return nil, err } - d := headDoc{VolumeID: h.VolumeID.String(), Epoch: h.Epoch, Holder: h.Holder, ClaimID: h.ClaimID, Activity: h.Activity, Position: h.Position} + d := headDoc{VolumeID: h.VolumeID.String(), Epoch: h.Epoch, Holder: h.Holder, ClaimID: h.ClaimID, Activity: h.Activity, Position: h.Position, State: h.State} if h.Current != nil { d.Current = h.Current.String() } @@ -187,7 +194,7 @@ func DecodeHead(b []byte, gen uint64) (Head, error) { if err != nil { return Head{}, err } - h := Head{Gen: gen, VolumeID: vid, Epoch: d.Epoch, Holder: d.Holder, ClaimID: d.ClaimID, Activity: d.Activity, Position: d.Position} + h := Head{Gen: gen, VolumeID: vid, Epoch: d.Epoch, Holder: d.Holder, ClaimID: d.ClaimID, Activity: d.Activity, Position: d.Position, State: d.State} if d.Current != "" { rn, err := ParseRootName(d.Current) if err != nil { @@ -249,6 +256,19 @@ func (h Head) heldBy(me HolderID) bool { return h.Epoch == me.Epoch && h.Holder == me.Holder && h.ClaimID == me.ClaimID } +// holderErr is the refusal of a holder transition: the volume is being +// deleted or is deleted (ErrVolumeDeleting), or the caller is not the +// holder at HEAD's epoch (ErrNotHolder); nil when it may act. +func (h Head) holderErr(me HolderID) error { + if h.State != StateLive { + return fmt.Errorf("%w: HEAD is %s", ErrVolumeDeleting, h.State) + } + if !h.heldBy(me) { + return fmt.Errorf("%w: HEAD epoch %d holder %q claim %q, caller epoch %d holder %q claim %q", ErrNotHolder, h.Epoch, h.Holder, h.ClaimID, me.Epoch, me.Holder, me.ClaimID) + } + return nil +} + // Begin is transition 2: activity idle -> snap(session), by the holder at // HEAD's epoch. Begin of the session already open is a replay: it returns // HEAD unchanged and changed=false. Any other open activity is ErrBusy. @@ -256,8 +276,8 @@ func (h Head) Begin(me HolderID, session string) (next Head, changed bool, err e if session == "" { return Head{}, false, errors.New("layout: Begin needs a session id") } - if !h.heldBy(me) { - return Head{}, false, fmt.Errorf("%w: HEAD epoch %d holder %q, caller epoch %d holder %q", ErrNotHolder, h.Epoch, h.Holder, me.Epoch, me.Holder) + if err := h.holderErr(me); err != nil { + return Head{}, false, err } switch { case h.Activity == Activity{Kind: ActSnap, Session: session}: @@ -317,8 +337,8 @@ func (h Head) Abort(me HolderID, session string) (next Head, changed bool, err e if session == "" { return Head{}, false, errors.New("layout: Abort needs a session id") } - if !h.heldBy(me) { - return Head{}, false, fmt.Errorf("%w: HEAD epoch %d holder %q, caller epoch %d holder %q", ErrNotHolder, h.Epoch, h.Holder, me.Epoch, me.Holder) + if err := h.holderErr(me); err != nil { + return Head{}, false, err } switch { case h.Activity.Kind == ActIdle: diff --git a/seaweed-block/core/frontend/chunkstore/layout/remove.go b/seaweed-block/core/frontend/chunkstore/layout/remove.go index 319b7f02dc..cd150a03f9 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/remove.go +++ b/seaweed-block/core/frontend/chunkstore/layout/remove.go @@ -47,8 +47,8 @@ func RemoveUnreachable(ctx context.Context, st HeadStore, r *Reader, pool Pool, if !found { return nil, ErrHeadAbsent } - if !h.heldBy(me) { - return nil, fmt.Errorf("%w: HEAD epoch %d holder %q", ErrNotHolder, h.Epoch, h.Holder) + if err := h.holderErr(me); err != nil { + return nil, err } if h.Activity != (Activity{Kind: ActClean, Session: session}) { return nil, fmt.Errorf("%w: HEAD has %s(%s), not clean(%s)", ErrNoSession, h.Activity.Kind, h.Activity.Session, session) diff --git a/seaweed-block/core/frontend/chunkstore/layout/stale_test.go b/seaweed-block/core/frontend/chunkstore/layout/stale_test.go index ecb44b9f22..078ebfd011 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/stale_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout/stale_test.go @@ -9,8 +9,8 @@ import ( // Every pure transition refuses a caller that is not the holder at HEAD's // epoch: an older epoch of the same server, and the same epoch held by // another server, in idle, snap and clean. The table must name every -// method of Head that returns (Head, bool, error), so a new transition -// fails here until it is added. +// method of Head that takes a HolderID and returns (Head, bool, error), so +// a new holder transition fails here until it is added. func TestTransitions_RefuseAStaleHolder(t *testing.T) { rn := RootName{Hash: Sum([]byte("r"))} steps := map[string]func(Head, HolderID) error{ @@ -40,7 +40,8 @@ func TestTransitions_RefuseAStaleHolder(t *testing.T) { var missing []string for i := 0; i < headT.NumMethod(); i++ { m := headT.Method(i).Type - if m.NumOut() == 3 && m.Out(0) == headT && m.Out(1) == boolT && m.Out(2) == errT { + holderT := reflect.TypeOf(HolderID{}) + if m.NumOut() == 3 && m.Out(0) == headT && m.Out(1) == boolT && m.Out(2) == errT && m.NumIn() > 1 && m.In(1) == holderT { if _, ok := steps[headT.Method(i).Name]; !ok { missing = append(missing, headT.Method(i).Name) } diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index b388de3f63..d246579b4b 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -531,6 +531,8 @@ stateDiagram-v2 idle --> clean: BeginClean(c) clean --> idle: EndClean(c) clean --> clean: RemoveUnreachable(shard) + idle --> deleting: MarkDeleting (no holder, no dependents) + deleting --> deleted: MarkDeleted (after release and pool) ``` | From | To | Guard | Enforced in | Protects | @@ -542,10 +544,12 @@ stateDiagram-v2 | idle | clean(c) | holder at HEAD's epoch; activity idle (clean(c) again is a replay) | clean.go `Head.BeginClean` | `INV-SNAPK-CLEAN-EXCL-001` | | clean(c) | idle | holder at HEAD's epoch; activity clean(c); over idle it succeeds without a write | clean.go `Head.EndClean` | `INV-SNAPK-CLEAN-EXCL-001` | | clean(c) | clean(c), names removed | holder at HEAD's epoch with clean(c) open (HEAD read once, after BeginClean); a name is deleted only if no root in HEAD (current or snapshot) names it in this volume's pool; the remover's own lease is checked before every delete | remove.go `RemoveUnreachable` (`LeaseHeld.StillHeld`) | `INV-SNAPK-REMOVE-LEASE-001` | +| idle (live) | deleting | no holder (checked immediately before), no open activity, no snapshot with dependents; deleting again is a replay | delete.go `Head.MarkDeleting`, `DeleteVolume` (`HolderGone.NoHolder`) | `INV-SNAPK-DELETE-ORDER-001` | +| deleting | deleted | after this volume is released from every source it names and its objects are deleted; deleted again is a replay; a live HEAD is refused | delete.go `Head.MarkDeleted`, `DeleteVolume` | `INV-SNAPK-DELETE-ORDER-001` | ## Part B. Invariant ledger -340 rows: 269 ACTIVE, 67 STUB, 4 ARCHIVED; 15 kept from the internal ledger, 325 new. +342 rows: 271 ACTIVE, 67 STUB, 4 ARCHIVED; 15 kept from the internal ledger, 327 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. @@ -1085,7 +1089,7 @@ Notes: | ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | |---|---|---|---|---|---|---| | `INV-SNAPK-NAME-CANONICAL-001` | A chunk is named by its index and the SHA-256 of its bytes under `pool//`; a segment and a root are named by the SHA-256 of their canonical encoding, and decoding refuses any bytes the encoder would not write, so an object has one encoding and one name. | Content-named layout (no state transition) | `core/frontend/chunkstore/layout` `layout.go` `ParseChunkName`, `DecodeSegment`, `DecodeRoot` | `TestParseChunkName_RoundTripAndRefusals`, `TestDecodeSegment_RefusesNonCanonical`, `TestRoot_Refusals`, `TestBuild_ShardsAndIncrementalReuse` | — (the snapshot kernel model is not in this repository) | ACTIVE | -| `INV-SNAPK-HEAD-WRITE-001` | HEAD changes only by one conditional update on its generation through `runTransition`; no path in the package creates a HEAD, and an absent HEAD is refused. A source scan refuses any other use of `UpdateHead`, a transition without its closure and interrupt tests, and any store remover other than the lease-checked RemoveUnreachable. | M9 every transition | `core/frontend/chunkstore/layout` `head.go` `runTransition`; `HeadStore` (read and conditional update only) | `TestGuard_WritersTransitionsAndRemovers`, `TestGuard_Controls`, `TestRunBegin` | — (the snapshot kernel model is not in this repository) | ACTIVE | +| `INV-SNAPK-HEAD-WRITE-001` | HEAD changes only by one conditional update on its generation through `runTransition`; no path in the package creates a HEAD, and an absent HEAD is refused. A source scan refuses any other use of `UpdateHead`, a transition without its closure and interrupt tests, and any store remover other than the lease-checked RemoveUnreachable and the ordered DeleteVolume. | M9 every transition | `core/frontend/chunkstore/layout` `head.go` `runTransition`; `HeadStore` (read and conditional update only) | `TestGuard_WritersTransitionsAndRemovers`, `TestGuard_Controls`, `TestRunBegin` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-HEAD-CODEC-001` | HEAD is canonical JSON with at most 100 snapshots and sorted unique dependents; unknown fields, non-canonical bytes and names that are not valid UTF-8 are refused at encode and decode, and the next HEAD is checked before it is written. | M9 every transition | `core/frontend/chunkstore/layout` `head.go` `Head.check`, `Head.Encode`, `DecodeHead` | `TestHead_GoldenEncodingRoundTrip`, `TestHead_Refusals`, `TestHead_RefusesInvalidUTF8` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-BEGIN-001` | Begin opens snap(s) only for the holder at HEAD's epoch and only from idle; a re-run of the open session writes nothing; killed at its write and re-run, it ends in snap(s) at one generation step. | M9 idle → snap | `core/frontend/chunkstore/layout` `head.go` `Head.Begin`, `RunBegin` | `TestBegin_Closure`, `TestRunBegin_InterruptAtEveryStep` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-ABORT-001` | Abort closes the holder's own snap(s) and changes nothing else; after its own crash a holder rolls the open session back before beginning another; over idle Abort writes nothing and its success never says whether the work was committed. | M9 snap → idle (Abort) | `core/frontend/chunkstore/layout` `head.go` `Head.Abort`, `RunAbort` | `TestAbort_Closure`, `TestAbort_IdleMeansNoActivityRemains`, `TestAbort_RollBackAfterOwnCrash`, `TestRunAbort_InterruptAtEveryStep` | — (the snapshot kernel model is not in this repository) | ACTIVE | @@ -1096,6 +1100,8 @@ Notes: | `INV-SNAPK-READ-MISSING-001` | A read resolves root, segment, chunk; an index the root does not name is zeros; a root, segment or chunk the root reaches but the store lacks is ErrMissing, never zeros; bytes that do not hash to their name are ErrCorrupt; a foreign chunk is read from its owner's pool. | Content-named layout (read path, no state transition) | `core/frontend/chunkstore/layout` `read.go` `Reader.Open`, `Image.Segment`, `Image.Chunk` | `TestRead_AbsentIndexIsZeros`, `TestRead_ForeignChunkFromSourcePool`, `TestRead_MissingObjectIsAnErrorNeverZeros`, `TestRead_FetchFailureAndCorruption`, `TestRead_SegmentOfAnotherShardRefused` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-REMOVE-LEASE-001` | A pool name is removed only inside the holder's own cleaning, only when no root in HEAD names it, and only after the remover's own lease is checked immediately before that delete; a lapsed lease stops the pass, an unreadable root or segment stops it before any delete, and a snapshot open on the volume refuses it. A source scan requires the lease check before every delete in the same block and refuses any other remover. | M9 clean → clean (RemoveUnreachable) | `core/frontend/chunkstore/layout` `remove.go` `RemoveUnreachable` | `TestRemoveUnreachable_RemovesOnlyWhatNoRootNames`, `TestRemoveUnreachable_RefusedOutsideItsCleaning`, `TestRemoveUnreachable_StopsWhenTheLeaseLapses`, `TestRemoveUnreachable_NothingRemovedOnAPartialView`, `TestCleaningPass_InterruptAtEveryStep`, `TestGuard_Controls` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-IDENTITY-001` | A volume is identified by the random id in its VOLUME record, never by its name alone: HEAD carries the volume id; every chunk reference in a segment carries its owner's volume id, and a read checks it against the owner's VOLUME before fetching (a volume created again under the name is ErrIdentity); every dependent records the target's volume id and the snapshot's root hash; a holder is the epoch, the server and the claim id its claim wrote into HEAD, so the same server with another claim id is refused by every transition. | M9 every transition; content-named layout | `core/frontend/chunkstore/layout` `volume.go` `Volume`, `VolumeID`; `head.go` `Head.check`, `heldBy`; `claim.go` `Head.Claim`; `read.go` `Image.Chunk`; `layout.go` `Segment.Encode` | `TestVolumeID_RandomAndParsed`, `TestVolume_GoldenEncodingRoundTrip`, `TestHead_GoldenEncodingRoundTrip`, `TestHead_Refusals`, `TestSegment_EncodeRefusals`, `TestRead_ForeignChunkNeedsTheOwnersVolumeID`, `TestClaim_WritesItsClaimID`, `TestTransitions_RefuseAStaleHolder`, `TestRemoveUnreachable_NeedsItsOwnVolumeID` | — (the snapshot kernel model is not in this repository) | ACTIVE | +| `INV-SNAPK-DELETE-ORDER-001` | A volume delete runs in its order, each prefix safe and the whole re-runnable: HEAD deleting (only with no holder, no open activity and no snapshot with dependents), then this volume released from every source, then its objects deleted, then HEAD deleted; from deleting on, no holder transition, claim or removal applies. A source scan requires that order in DeleteVolume and refuses any other remover. | M9 idle → deleting → deleted | `core/frontend/chunkstore/layout` `delete.go` `DeleteVolume`, `Head.MarkDeleting`, `Head.MarkDeleted`; `head.go` `holderErr` | `TestMarkDeleting_Closure`, `TestMarkDeleted_Closure`, `TestDeleting_RefusesEveryHolderStep`, `TestDeleteVolume`, `TestDeleteVolume_InterruptAtEveryStep`, `TestRunMarkDeleting_InterruptAtEveryStep`, `TestRunMarkDeleted_InterruptAtEveryStep`, `TestGuard_Controls` | — (the snapshot kernel model is not in this repository) | ACTIVE | +| `INV-SNAPK-RELEASE-001` | A target is released from a source's dependents by its volume id, from every snapshot of that source, by one conditional update (the delete's release step and the operator's remove-dependent command); a volume created again under the target's name releases nothing; releasing an absent target writes nothing. | M9 source HEAD, dependents (no activity change) | `core/frontend/chunkstore/layout` `delete.go` `Head.ReleaseDependent`, `RunReleaseDependent` | `TestReleaseDependent_Closure`, `TestRunReleaseDependent_InterruptAtEveryStep` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-STALE-HOLDER-001` | Every transition refuses an older epoch of the same server, the same epoch held by another server, and the same epoch and server with another claim id, in idle, snap and clean; a new transition must be added to the table. | M9 every transition | `core/frontend/chunkstore/layout` `Head.heldBy` and each transition | `TestTransitions_RefuseAStaleHolder` | — (the snapshot kernel model is not in this repository) | ACTIVE | Notes: From 804bde1832f2d9d628ecad7055ba96802a7bb72c Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 24 Nov 2026 16:22:52 -0800 Subject: [PATCH 2/7] layout: the operator's remove-dependent checks the target first The release step alone does not look at the target, so as the operator's command it could release a live restore target and leave its foreign references unprotected. It is now used only by the target's own delete (its HEAD already deleting) and by OperatorReleaseDependent, which reads the target first and releases only if it exists and is deleted (HEAD deleting or deleted, or its name holding another volume id) or no root in its live HEAD names a chunk of the source. A live target still naming the source, one being created and one never created (the restore could still create it) are refused, and the source is not written. The package guard restricts the release's callers and requires the operator's read of the target; the HEAD reader enumeration classifies it. Co-Authored-By: Claude Opus 5.5 --- .../frontend/chunkstore/head_readers_test.go | 92 +++++++++++++----- .../core/frontend/chunkstore/layout/delete.go | 93 ++++++++++++++++++- .../frontend/chunkstore/layout/delete_test.go | 87 +++++++++++++++++ .../frontend/chunkstore/layout/guard_test.go | 15 +++ seaweed-block/docs/design/invariants.md | 2 +- 5 files changed, 259 insertions(+), 30 deletions(-) diff --git a/seaweed-block/core/frontend/chunkstore/head_readers_test.go b/seaweed-block/core/frontend/chunkstore/head_readers_test.go index 434da26d5c..dacb9c1b35 100644 --- a/seaweed-block/core/frontend/chunkstore/head_readers_test.go +++ b/seaweed-block/core/frontend/chunkstore/head_readers_test.go @@ -24,31 +24,32 @@ import ( // one; a change that treats an absent HEAD as unknown flips those probes. var headReaders = map[string]string{ // chunkstore: the two raw reads every other reader goes through - "core/frontend/chunkstore/catalog.go ReadHead -> LookupEntry": "ok=false, no error (probe ReadHead)", - "core/frontend/chunkstore/chunk_remote.go getHeadRoot -> LookupEntry": "zero HEAD, no error (probe GetHead)", - "core/frontend/chunkstore/catalog.go headExists -> LookupEntry": "false (probe EnsureVolume)", - "core/frontend/chunkstore/chunk_remote.go GetHead -> getHeadRoot": "zero HEAD, no error (probe GetHead)", - "core/frontend/chunkstore/chunk_remote.go GetHeadRoot -> getHeadRoot": "zero HEAD, no error (probe GetHeadRoot)", - "core/frontend/chunkstore/chunk_remote.go CASHead -> getHeadRoot": "GAP: expected gen 0 creates a HEAD over existing keys (probe CASHead)", - "core/frontend/chunkstore/catalog.go ensureInitialHead -> headExists": "GAP: creates an empty gen-1 HEAD over existing keys (probe EnsureVolume)", - "core/frontend/chunkstore/catalog.go EnsureVolume -> ReadHead": "GAP: attaches the recreated empty HEAD (probe EnsureVolume)", - "core/frontend/chunkstore/catalog.go fork -> ReadHead": "replay falls through and publishes the fork-time HEAD (probe ForkReplay)", - "core/frontend/chunkstore/catalog.go AbortFork -> ReadHead": "GAP: exclusive-creates an aborted HEAD (probe AbortFork)", - "core/frontend/chunkstore/gc.go run -> GetHead": "GAP: zero HEAD roots nothing; the volume's keys become candidates (probe GCMark)", - "core/frontend/chunkstore/gc_copy.go SweepCopies -> ReadHead": "after AbortFork: settles from the HEAD it created (probe AbortFork)", - "core/frontend/chunkstore/restore.go MarkIndependent -> ReadHead": "refuses (not a restore / no HEAD) (probe MarkIndependent)", - "core/frontend/chunkstore/share_guard.go beginShare -> ReadHead": "refuses outcome_unknown: the HEAD to share is no longer current", - "core/frontend/chunkstore/usage.go Usage -> ReadHead": "GAP: reports an empty image, no error (probe Usage)", - "core/frontend/chunkstore/verify.go readHead -> LookupEntry": "finding ROOT_INVALID (probe Verify)", - "core/frontend/chunkstore/layout/remove.go RemoveUnreachable -> ReadHead": "refuses ErrHeadAbsent and deletes nothing (probe LayoutRemoval)", - "core/frontend/chunkstore/layout/head.go runTransition -> ReadHead": "refuses ErrHeadAbsent and writes nothing; no layout transition creates a HEAD (probe LayoutTransition)", - "core/frontend/chunkstore/verify.go run -> LookupEntry": "finding ROOT_INVALID (probe Verify)", - "core/frontend/chunkstore/volume_delete.go DeleteVolume -> ReadHead": "operator delete writes a deleting HEAD from nothing and completes (probe DeleteVolume)", - "core/frontend/chunkstore/volume_delete.go markHeadDeleting -> ReadHead": "zero HEAD: creates the deleting HEAD (probe DeleteVolume)", - "core/frontend/chunkstore/volume_delete.go commitHeadPurging -> ReadHead": "reads the HEAD markHeadDeleting wrote (probe DeleteVolume)", - "core/frontend/chunkstore/volume_delete.go finishHeadDeleted -> ReadHead": "reads the HEAD markHeadDeleting wrote (probe DeleteVolume)", - "core/frontend/chunkstore/volume_delete.go revertHeadDeleting -> ReadHead": "reads the HEAD markHeadDeleting wrote (probe DeleteVolume)", - "core/frontend/chunkstore/volume_delete.go volumeGone -> ReadHead": "absent HEAD = not gone (probe DeleteVolume)", + "core/frontend/chunkstore/catalog.go ReadHead -> LookupEntry": "ok=false, no error (probe ReadHead)", + "core/frontend/chunkstore/chunk_remote.go getHeadRoot -> LookupEntry": "zero HEAD, no error (probe GetHead)", + "core/frontend/chunkstore/catalog.go headExists -> LookupEntry": "false (probe EnsureVolume)", + "core/frontend/chunkstore/chunk_remote.go GetHead -> getHeadRoot": "zero HEAD, no error (probe GetHead)", + "core/frontend/chunkstore/chunk_remote.go GetHeadRoot -> getHeadRoot": "zero HEAD, no error (probe GetHeadRoot)", + "core/frontend/chunkstore/chunk_remote.go CASHead -> getHeadRoot": "GAP: expected gen 0 creates a HEAD over existing keys (probe CASHead)", + "core/frontend/chunkstore/catalog.go ensureInitialHead -> headExists": "GAP: creates an empty gen-1 HEAD over existing keys (probe EnsureVolume)", + "core/frontend/chunkstore/catalog.go EnsureVolume -> ReadHead": "GAP: attaches the recreated empty HEAD (probe EnsureVolume)", + "core/frontend/chunkstore/catalog.go fork -> ReadHead": "replay falls through and publishes the fork-time HEAD (probe ForkReplay)", + "core/frontend/chunkstore/catalog.go AbortFork -> ReadHead": "GAP: exclusive-creates an aborted HEAD (probe AbortFork)", + "core/frontend/chunkstore/gc.go run -> GetHead": "GAP: zero HEAD roots nothing; the volume's keys become candidates (probe GCMark)", + "core/frontend/chunkstore/gc_copy.go SweepCopies -> ReadHead": "after AbortFork: settles from the HEAD it created (probe AbortFork)", + "core/frontend/chunkstore/restore.go MarkIndependent -> ReadHead": "refuses (not a restore / no HEAD) (probe MarkIndependent)", + "core/frontend/chunkstore/share_guard.go beginShare -> ReadHead": "refuses outcome_unknown: the HEAD to share is no longer current", + "core/frontend/chunkstore/usage.go Usage -> ReadHead": "GAP: reports an empty image, no error (probe Usage)", + "core/frontend/chunkstore/verify.go readHead -> LookupEntry": "finding ROOT_INVALID (probe Verify)", + "core/frontend/chunkstore/layout/delete.go OperatorReleaseDependent -> ReadHead": "reads the source's HEAD (absent: refuses ErrHeadAbsent) and the target's: a target with no HEAD and no VOLUME was never created and is refused, one with VOLUME and no HEAD is being created and is refused; nothing is written (probe LayoutOperatorRelease)", + "core/frontend/chunkstore/layout/remove.go RemoveUnreachable -> ReadHead": "refuses ErrHeadAbsent and deletes nothing (probe LayoutRemoval)", + "core/frontend/chunkstore/layout/head.go runTransition -> ReadHead": "refuses ErrHeadAbsent and writes nothing; no layout transition creates a HEAD (probe LayoutTransition)", + "core/frontend/chunkstore/verify.go run -> LookupEntry": "finding ROOT_INVALID (probe Verify)", + "core/frontend/chunkstore/volume_delete.go DeleteVolume -> ReadHead": "operator delete writes a deleting HEAD from nothing and completes (probe DeleteVolume)", + "core/frontend/chunkstore/volume_delete.go markHeadDeleting -> ReadHead": "zero HEAD: creates the deleting HEAD (probe DeleteVolume)", + "core/frontend/chunkstore/volume_delete.go commitHeadPurging -> ReadHead": "reads the HEAD markHeadDeleting wrote (probe DeleteVolume)", + "core/frontend/chunkstore/volume_delete.go finishHeadDeleted -> ReadHead": "reads the HEAD markHeadDeleting wrote (probe DeleteVolume)", + "core/frontend/chunkstore/volume_delete.go revertHeadDeleting -> ReadHead": "reads the HEAD markHeadDeleting wrote (probe DeleteVolume)", + "core/frontend/chunkstore/volume_delete.go volumeGone -> ReadHead": "absent HEAD = not gone (probe DeleteVolume)", // above the chunk store: they read through storage.ChunkRemote GetHead / // GetHeadRoot, so an absent HEAD reaches them as the zero HEAD (probe GetHead) "cmd/sw-block/chunk.go chunkShow -> ReadHead": "ok=false: reports no HEAD (probe ReadHead)", @@ -278,6 +279,33 @@ func TestHeadReaders_AbsentHeadProbes(t *testing.T) { t.Fatalf("layout removal over an absent HEAD deleted %d objects", pool.deletes) } }) + t.Run("LayoutOperatorRelease", func(t *testing.T) { + tid, err := layout.NewVolumeID() + if err != nil { + t.Fatal(err) + } + vb, err := layout.Volume{ID: tid, Name: "t", Format: layout.VolumeFormat}.Encode() + if err != nil { + t.Fatal(err) + } + withVolume := func(context.Context, string) ([]byte, bool, error) { return vb, true, nil } + r, err := layout.NewReader("/swblock/chunks", "t", withVolume) + if err != nil { + t.Fatal(err) + } + src := &presentLayoutHead{} + if _, err := layout.OperatorReleaseDependent(ctx, src, &absentLayoutHead{}, r, tid); !errors.Is(err, layout.ErrTargetLive) || src.updates != 0 { + t.Fatalf("operator release of a target with VOLUME and no HEAD: %v, %d writes; want ErrTargetLive and none", err, src.updates) + } + none, _ := layout.NewReader("/swblock/chunks", "t", func(context.Context, string) ([]byte, bool, error) { return nil, false, nil }) + if _, err := layout.OperatorReleaseDependent(ctx, src, &absentLayoutHead{}, none, tid); !errors.Is(err, layout.ErrTargetNeverCreated) || src.updates != 0 { + t.Fatalf("operator release of a target never created: %v, %d writes; want ErrTargetNeverCreated and none", err, src.updates) + } + absent := &absentLayoutHead{} + if _, err := layout.OperatorReleaseDependent(ctx, absent, &absentLayoutHead{}, r, tid); !errors.Is(err, layout.ErrHeadAbsent) || absent.updates != 0 { + t.Fatalf("operator release with the source HEAD absent: %v; want ErrHeadAbsent", err) + } + }) t.Run("ForkReplay", func(t *testing.T) { f, b := headReaderForkFixture(t) c, err := NewCatalog(manifestFilerBlobs{f, gcBlobs{b}}, catBase) @@ -319,3 +347,17 @@ func (p *countingPool) DeleteObject(context.Context, string) error { p.deletes++ type okLease struct{} func (okLease) StillHeld(context.Context) error { return nil } + +// presentLayoutHead is a layout HEAD store whose HEAD is present (a live, +// idle volume); it counts updates. +type presentLayoutHead struct{ updates int } + +func (p *presentLayoutHead) ReadHead(context.Context) (layout.Head, bool, error) { + id, _ := layout.NewVolumeID() + return layout.Head{Gen: 1, VolumeID: id, Epoch: 1, Holder: "h", Activity: layout.Activity{Kind: layout.ActIdle}}, true, nil +} + +func (p *presentLayoutHead) UpdateHead(context.Context, uint64, layout.Head) error { + p.updates++ + return nil +} diff --git a/seaweed-block/core/frontend/chunkstore/layout/delete.go b/seaweed-block/core/frontend/chunkstore/layout/delete.go index 9f7ac1a43f..a0fb1e9a7e 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/delete.go +++ b/seaweed-block/core/frontend/chunkstore/layout/delete.go @@ -23,6 +23,12 @@ var ( ErrHasDependents = errors.New("layout: a snapshot has dependents") // ErrHolderActive: a transaction is open on the volume. ErrHolderActive = errors.New("layout: a holder is acting on the volume") + // ErrTargetLive: the operator asked to release a dependent whose + // target still exists and may still name the source's chunks. + ErrTargetLive = errors.New("layout: the dependent's target is live") + // ErrTargetNeverCreated: the dependent's target has neither VOLUME nor + // HEAD; the restore that registered it could still create it. + ErrTargetNeverCreated = errors.New("layout: the dependent's target was never created") ) // HolderGone is the deletion's premise: it returns nil only when no block @@ -68,9 +74,10 @@ func (h Head) MarkDeleted() (next Head, changed bool, err error) { } // ReleaseDependent removes the target volume id from the dependents of -// every snapshot of this (source) HEAD: the step a deleted target makes on -// each source, and the operator's remove-dependent command. A HEAD with no -// such dependent is a replay. +// every snapshot of this (source) HEAD: the step a target being deleted +// makes on each source. It does not look at the target; the operator's +// command goes through OperatorReleaseDependent, which does. A HEAD with +// no such dependent is a replay. func (h Head) ReleaseDependent(target VolumeID) (next Head, changed bool, err error) { if target.IsZero() { return Head{}, false, errors.New("layout: ReleaseDependent needs a target volume id") @@ -106,7 +113,8 @@ func RunMarkDeleted(ctx context.Context, st HeadStore) (Head, error) { } // RunReleaseDependent applies ReleaseDependent to a source's HEAD by one -// conditional update. +// conditional update. Its callers know the target is gone: DeleteVolume +// (the target's HEAD is deleting) and OperatorReleaseDependent (checked). func RunReleaseDependent(ctx context.Context, source HeadStore, target VolumeID) (Head, error) { return runTransition(ctx, source, func(h Head) (Head, bool, error) { return h.ReleaseDependent(target) }) } @@ -141,3 +149,80 @@ func DeleteVolume(ctx context.Context, st HeadStore, gone HolderGone, id VolumeI _, err := RunMarkDeleted(ctx, st) return err } + +// OperatorReleaseDependent is the operator's remove-dependent command: it +// releases the target from the source's dependents only when the target +// exists and is deleted or no longer names the source, read first: its +// HEAD is deleting or deleted; its name now holds another volume (another +// VOLUME id); or its HEAD is live and no root in it (current or snapshot) +// names a chunk of the source. A live target that still names the source, +// or one being created (VOLUME without HEAD), is refused (ErrTargetLive). +// A target never created (no VOLUME, no HEAD) is refused too +// (ErrTargetNeverCreated): the restore could still create it after the +// release. The source is not written when refused. +func OperatorReleaseDependent(ctx context.Context, source, target HeadStore, r *Reader, targetID VolumeID) (Head, error) { + sh, found, err := source.ReadHead(ctx) + if err != nil { + return Head{}, err + } + if !found { + return Head{}, ErrHeadAbsent + } + id, err := r.VolumeID(ctx, r.vol) + hasVolume := err == nil + if err != nil && !errors.Is(err, ErrMissing) { + return Head{}, err + } + th, hasHead, err := target.ReadHead(ctx) + if err != nil { + return Head{}, err + } + switch { + case hasHead && (th.State == StateDeleting || th.State == StateDeleted): + case hasVolume && id != targetID: + case !hasVolume && !hasHead: + return Head{}, fmt.Errorf("%w: %s", ErrTargetNeverCreated, r.vol) + case hasVolume && hasHead: + names, err := namesVolume(ctx, r, th, sh.VolumeID) + if err != nil { + return Head{}, err + } + if names { + return Head{}, fmt.Errorf("%w: %s still names chunks of the source", ErrTargetLive, r.vol) + } + default: + return Head{}, fmt.Errorf("%w: %s is being created", ErrTargetLive, r.vol) + } + return RunReleaseDependent(ctx, source, targetID) +} + +// namesVolume reports whether any root in h names a chunk owned by owner. +// Every shard of every root is read; an unreadable one is an error, never +// "names nothing". +func namesVolume(ctx context.Context, r *Reader, h Head, owner VolumeID) (bool, error) { + roots := map[RootName]bool{} + if h.Current != nil { + roots[*h.Current] = true + } + for _, s := range h.Snapshots { + roots[s.Root] = true + } + for rn := range roots { + img, err := r.Open(ctx, rn) + if err != nil { + return false, err + } + for shard := range img.root.Segments { + seg, _, err := img.Segment(ctx, shard) + if err != nil { + return false, err + } + for _, ref := range seg.Chunks { + if ref.OwnerID == owner { + return true, nil + } + } + } + } + return false, nil +} diff --git a/seaweed-block/core/frontend/chunkstore/layout/delete_test.go b/seaweed-block/core/frontend/chunkstore/layout/delete_test.go index d2a237b606..bab3d06fd0 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/delete_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout/delete_test.go @@ -232,3 +232,90 @@ func TestDeleteVolume_InterruptAtEveryStep(t *testing.T) { } } } + +// operatorCase: source src (id of "src") lists target t as a dependent; +// t's VOLUME, HEAD and root objects are as the case sets them. When the +// target names chunks, namesSource decides whether one of them is src's. +func operatorCase(t *testing.T, tgtHead *Head, tgtVolume *VolumeID, namesSource bool) (*memHead, *memHead, *Reader) { + t.Helper() + w := newDeleteWorld() + objs := map[string][]byte{} + put := func(rel string, b []byte) { objs[path.Join(removeBase, "t", rel)] = b } + if tgtVolume != nil { + b, err := Volume{ID: *tgtVolume, Name: "t", Format: VolumeFormat}.Encode() + if err != nil { + t.Fatal(err) + } + put(VolumeName, b) + } + if tgtHead != nil { + m := manifest(Ref{Owner: "t", OwnerID: idFor("t"), Chunk: NameChunk(1, []byte("own"))}) + if namesSource { + m[2] = Ref{Owner: "src", OwnerID: idFor("src"), Chunk: NameChunk(2, []byte("from src"))} + } + root, segs, err := Build(m) + if err != nil { + t.Fatal(err) + } + for n, b := range segs { + put(n.Path(), b) + } + rn, rb, err := NameRoot(root) + if err != nil { + t.Fatal(err) + } + put(rn.Path(), rb) + h := *tgtHead + h.Current = &rn + tgtHead = &h + } + r, err := NewReader(removeBase, "t", func(_ context.Context, p string) ([]byte, bool, error) { + b, ok := objs[p] + return b, ok, nil + }) + if err != nil { + t.Fatal(err) + } + return w.src, &memHead{h: tgtHead}, r +} + +// The operator's remove-dependent releases a target only when the target +// exists and is deleted or no longer names the source: its HEAD deleting +// or deleted, its name holding another volume (another VOLUME id), or a +// live HEAD none of whose roots names a chunk of the source. A live target +// that still names the source, one being created (VOLUME without HEAD) and +// one never created (no VOLUME, no HEAD: the restore could still create +// it) are refused and the source is unchanged. +func TestOperatorReleaseDependent(t *testing.T) { + ctx := context.Background() + live := idleHead() + live.VolumeID = idFor("t") + deleting := live + deleting.State = StateDeleting + tid, other := idFor("t"), idFor("t again") + for name, tc := range map[string]struct { + head *Head + volume *VolumeID + namesSource bool + release bool + want error + }{ + "live target naming the source": {&live, &tid, true, false, ErrTargetLive}, + "live target no longer naming it": {&live, &tid, false, true, nil}, + "target being created": {nil, &tid, false, false, ErrTargetLive}, + "target never created": {nil, nil, false, false, ErrTargetNeverCreated}, + "target deleting": {&deleting, &tid, true, true, nil}, + "name holds another volume": {nil, &other, false, true, nil}, + } { + src, tgt, r := operatorCase(t, tc.head, tc.volume, tc.namesSource) + before := src.updates + _, err := OperatorReleaseDependent(ctx, src, tgt, r, tid) + released := len(src.h.Snapshots["daily"].Dependents) == 0 + if tc.release && (err != nil || !released) { + t.Errorf("%s: %v, released %t; want released", name, err, released) + } + if !tc.release && (!errors.Is(err, tc.want) || released || src.updates != before) { + t.Errorf("%s: %v, released %t; want %v and the source unchanged", name, err, released, tc.want) + } + } +} diff --git a/seaweed-block/core/frontend/chunkstore/layout/guard_test.go b/seaweed-block/core/frontend/chunkstore/layout/guard_test.go index 89ae70c43b..6ef1f3bf84 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/guard_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout/guard_test.go @@ -123,6 +123,9 @@ func owners(m map[string]bool) []string { // - Lease, claim half: OldLeaseEnded is used only in RunClaim, and // RunClaim, when it is declared, uses it. // - Every declared exported Run function goes through runTransition. +// - Release of a dependent: RunReleaseDependent is used only by +// DeleteVolume (its own HEAD is deleting) and OperatorReleaseDependent, +// which reads the target's HEAD before it releases. // - Pool: a name starting with Delete or Remove is used only in // RemoveUnreachable, where every delete is preceded, in the same loop // body, by the remover's own lease check (StillHeld), and in @@ -168,6 +171,14 @@ func guardFindings(code map[string]map[string]bool, decl, tests map[string]bool) bad = append(bad, fn+" is declared and does not go through runTransition") } } + for _, fn := range owners(code["RunReleaseDependent"]) { + if fn != "DeleteVolume" && fn != "OperatorReleaseDependent" { + bad = append(bad, fn+" uses RunReleaseDependent: only DeleteVolume (target deleting) and OperatorReleaseDependent (target checked) release") + } + } + if decl["OperatorReleaseDependent"] && !code["ReadHead"]["OperatorReleaseDependent"] { + bad = append(bad, "OperatorReleaseDependent does not read the target's HEAD before releasing") + } for name, by := range code { if strings.HasPrefix(name, "Delete") || strings.HasPrefix(name, "Remove") { for _, fn := range owners(by) { @@ -428,6 +439,10 @@ func DeleteVolume(ctx context.Context, st HeadStore, id VolumeID, srcs []HeadSto _, _ = RunMarkDeleted(ctx, st) return nil }`, want: "DeleteVolume has no NoHolder"}, + "release outside delete and the operator's check": {src: `func w(ctx context.Context, st HeadStore, id VolumeID) { _, _ = RunReleaseDependent(ctx, st, id) }`, want: "only DeleteVolume (target deleting) and OperatorReleaseDependent"}, + "operator release without reading the target": {file: "delete.go", src: `func OperatorReleaseDependent(ctx context.Context, source HeadStore, id VolumeID) (Head, error) { + return RunReleaseDependent(ctx, source, id) +}`, want: "does not read the target's HEAD"}, "remover method value": {src: `type p interface{ RemoveName(string) } func w(x p) { f := x.RemoveName; f("o") }`, want: "only RemoveUnreachable (after its lease re-check) and DeleteVolume"}, } { diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index d246579b4b..8adfdcabfd 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -1101,7 +1101,7 @@ Notes: | `INV-SNAPK-REMOVE-LEASE-001` | A pool name is removed only inside the holder's own cleaning, only when no root in HEAD names it, and only after the remover's own lease is checked immediately before that delete; a lapsed lease stops the pass, an unreadable root or segment stops it before any delete, and a snapshot open on the volume refuses it. A source scan requires the lease check before every delete in the same block and refuses any other remover. | M9 clean → clean (RemoveUnreachable) | `core/frontend/chunkstore/layout` `remove.go` `RemoveUnreachable` | `TestRemoveUnreachable_RemovesOnlyWhatNoRootNames`, `TestRemoveUnreachable_RefusedOutsideItsCleaning`, `TestRemoveUnreachable_StopsWhenTheLeaseLapses`, `TestRemoveUnreachable_NothingRemovedOnAPartialView`, `TestCleaningPass_InterruptAtEveryStep`, `TestGuard_Controls` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-IDENTITY-001` | A volume is identified by the random id in its VOLUME record, never by its name alone: HEAD carries the volume id; every chunk reference in a segment carries its owner's volume id, and a read checks it against the owner's VOLUME before fetching (a volume created again under the name is ErrIdentity); every dependent records the target's volume id and the snapshot's root hash; a holder is the epoch, the server and the claim id its claim wrote into HEAD, so the same server with another claim id is refused by every transition. | M9 every transition; content-named layout | `core/frontend/chunkstore/layout` `volume.go` `Volume`, `VolumeID`; `head.go` `Head.check`, `heldBy`; `claim.go` `Head.Claim`; `read.go` `Image.Chunk`; `layout.go` `Segment.Encode` | `TestVolumeID_RandomAndParsed`, `TestVolume_GoldenEncodingRoundTrip`, `TestHead_GoldenEncodingRoundTrip`, `TestHead_Refusals`, `TestSegment_EncodeRefusals`, `TestRead_ForeignChunkNeedsTheOwnersVolumeID`, `TestClaim_WritesItsClaimID`, `TestTransitions_RefuseAStaleHolder`, `TestRemoveUnreachable_NeedsItsOwnVolumeID` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-DELETE-ORDER-001` | A volume delete runs in its order, each prefix safe and the whole re-runnable: HEAD deleting (only with no holder, no open activity and no snapshot with dependents), then this volume released from every source, then its objects deleted, then HEAD deleted; from deleting on, no holder transition, claim or removal applies. A source scan requires that order in DeleteVolume and refuses any other remover. | M9 idle → deleting → deleted | `core/frontend/chunkstore/layout` `delete.go` `DeleteVolume`, `Head.MarkDeleting`, `Head.MarkDeleted`; `head.go` `holderErr` | `TestMarkDeleting_Closure`, `TestMarkDeleted_Closure`, `TestDeleting_RefusesEveryHolderStep`, `TestDeleteVolume`, `TestDeleteVolume_InterruptAtEveryStep`, `TestRunMarkDeleting_InterruptAtEveryStep`, `TestRunMarkDeleted_InterruptAtEveryStep`, `TestGuard_Controls` | — (the snapshot kernel model is not in this repository) | ACTIVE | -| `INV-SNAPK-RELEASE-001` | A target is released from a source's dependents by its volume id, from every snapshot of that source, by one conditional update (the delete's release step and the operator's remove-dependent command); a volume created again under the target's name releases nothing; releasing an absent target writes nothing. | M9 source HEAD, dependents (no activity change) | `core/frontend/chunkstore/layout` `delete.go` `Head.ReleaseDependent`, `RunReleaseDependent` | `TestReleaseDependent_Closure`, `TestRunReleaseDependent_InterruptAtEveryStep` | — (the snapshot kernel model is not in this repository) | ACTIVE | +| `INV-SNAPK-RELEASE-001` | A target is released from a source's dependents by its volume id, from every snapshot of that source, by one conditional update; a volume created again under the target's name releases nothing; releasing an absent target writes nothing. Only two callers release: the delete of the target itself (its HEAD already deleting) and the operator's command, which first reads the target and releases only if it exists and is deleted (HEAD deleting or deleted, or its name holding another volume id) or no root in its live HEAD names a chunk of the source; a live target still naming the source, one being created and one never created are refused. A source scan restricts the callers and requires the operator's read of the target. | M9 source HEAD, dependents (no activity change) | `core/frontend/chunkstore/layout` `delete.go` `Head.ReleaseDependent`, `RunReleaseDependent`, `OperatorReleaseDependent` | `TestReleaseDependent_Closure`, `TestRunReleaseDependent_InterruptAtEveryStep`, `TestOperatorReleaseDependent`, `TestGuard_Controls` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-STALE-HOLDER-001` | Every transition refuses an older epoch of the same server, the same epoch held by another server, and the same epoch and server with another claim id, in idle, snap and clean; a new transition must be added to the table. | M9 every transition | `core/frontend/chunkstore/layout` `Head.heldBy` and each transition | `TestTransitions_RefuseAStaleHolder` | — (the snapshot kernel model is not in this repository) | ACTIVE | Notes: From 455984013429f99d8b5b9107e036df2485cfe86b Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 24 Nov 2026 18:33:59 -0800 Subject: [PATCH 3/7] layout: volume directories never reused; a tombstone for a target never created A volume's directory is -, created exclusively and never reused; the reader reads a foreign chunk from the directory its reference's owner name and id give, after checking that directory's VOLUME id. For a restore target never created, the operator's remove-dependent writes a deleted HEAD exclusively in the target's directory (a tombstone, which needs no holder) and only then releases the dependent, so the restore can never create the target afterwards; if the target's HEAD appears first, the release is refused. Only that command creates a tombstone (source guard). Co-Authored-By: Claude Opus 5.5 --- .../frontend/chunkstore/head_readers_test.go | 20 +++++-- .../core/frontend/chunkstore/layout/delete.go | 41 ++++++++++---- .../frontend/chunkstore/layout/delete_test.go | 40 +++++++++++-- .../frontend/chunkstore/layout/guard_test.go | 14 +++-- .../core/frontend/chunkstore/layout/head.go | 15 +++-- .../frontend/chunkstore/layout/head_test.go | 23 ++++++++ .../core/frontend/chunkstore/layout/read.go | 10 ++-- .../frontend/chunkstore/layout/read_test.go | 56 ++++++++++--------- .../core/frontend/chunkstore/layout/volume.go | 8 +++ seaweed-block/docs/design/invariants.md | 8 ++- 10 files changed, 173 insertions(+), 62 deletions(-) diff --git a/seaweed-block/core/frontend/chunkstore/head_readers_test.go b/seaweed-block/core/frontend/chunkstore/head_readers_test.go index dc152c6de3..7443284957 100644 --- a/seaweed-block/core/frontend/chunkstore/head_readers_test.go +++ b/seaweed-block/core/frontend/chunkstore/head_readers_test.go @@ -40,7 +40,7 @@ var headReaders = map[string]string{ "core/frontend/chunkstore/share_guard.go beginShare -> ReadHead": "refuses outcome_unknown: the HEAD to share is no longer current", "core/frontend/chunkstore/usage.go Usage -> ReadHead": "GAP: reports an empty image, no error (probe Usage)", "core/frontend/chunkstore/verify.go readHead -> LookupEntry": "finding ROOT_INVALID (probe Verify)", - "core/frontend/chunkstore/layout/delete.go OperatorReleaseDependent -> ReadHead": "reads the source's HEAD (absent: refuses ErrHeadAbsent) and the target's: a target with no HEAD and no VOLUME was never created and is refused, one with VOLUME and no HEAD is being created and is refused; nothing is written (probe LayoutOperatorRelease)", + "core/frontend/chunkstore/layout/delete.go OperatorReleaseDependent -> ReadHead": "reads the source's HEAD (absent: refuses ErrHeadAbsent) and the target's: with no HEAD and no VOLUME the target was never created and gets a deleted HEAD written exclusively before the release; with VOLUME and no HEAD it is being created and is refused (probe LayoutOperatorRelease)", "core/frontend/chunkstore/layout/remove.go RemoveUnreachable -> ReadHead": "refuses ErrHeadAbsent and writes nothing to the objects (probe LayoutRemoval)", "core/frontend/chunkstore/layout/head.go runTransition -> ReadHead": "refuses ErrHeadAbsent and writes nothing; no layout transition creates a HEAD (probe LayoutTransition)", "core/frontend/chunkstore/verify.go run -> LookupEntry": "finding ROOT_INVALID (probe Verify)", @@ -298,8 +298,9 @@ func TestHeadReaders_AbsentHeadProbes(t *testing.T) { t.Fatalf("operator release of a target with VOLUME and no HEAD: %v, %d writes; want ErrTargetLive and none", err, src.updates) } none, _ := layout.NewReader("/swblock/chunks", "t", func(context.Context, string) ([]byte, bool, error) { return nil, false, nil }) - if _, err := layout.OperatorReleaseDependent(ctx, src, &absentLayoutHead{}, none, tid); !errors.Is(err, layout.ErrTargetNeverCreated) || src.updates != 0 { - t.Fatalf("operator release of a target never created: %v, %d writes; want ErrTargetNeverCreated and none", err, src.updates) + tomb := &absentLayoutHead{} + if _, err := layout.OperatorReleaseDependent(ctx, src, tomb, none, tid); err != nil || tomb.created == nil || tomb.created.State != layout.StateDeleted || tomb.created.VolumeID != tid { + t.Fatalf("operator release of a target never created: %v, tombstone %+v; want a deleted HEAD of the target's id written before the release", err, tomb.created) } absent := &absentLayoutHead{} if _, err := layout.OperatorReleaseDependent(ctx, absent, &absentLayoutHead{}, r, tid); !errors.Is(err, layout.ErrHeadAbsent) || absent.updates != 0 { @@ -328,8 +329,17 @@ func TestHeadReaders_AbsentHeadProbes(t *testing.T) { }) } -// absentLayoutHead is a layout HEAD store whose HEAD is absent. -type absentLayoutHead struct{ updates int } +// absentLayoutHead is a layout HEAD store whose HEAD is absent; it records +// a tombstone created in it. +type absentLayoutHead struct { + updates int + created *layout.Head +} + +func (a *absentLayoutHead) CreateDeletedHead(_ context.Context, h layout.Head) error { + a.created = &h + return nil +} func (a *absentLayoutHead) ReadHead(context.Context) (layout.Head, bool, error) { return layout.Head{}, false, nil diff --git a/seaweed-block/core/frontend/chunkstore/layout/delete.go b/seaweed-block/core/frontend/chunkstore/layout/delete.go index ab8f860f7a..642423b43f 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/delete.go +++ b/seaweed-block/core/frontend/chunkstore/layout/delete.go @@ -26,11 +26,17 @@ var ( // ErrTargetLive: the operator asked to release a dependent whose // target still exists and may still name the source's chunks. ErrTargetLive = errors.New("layout: the dependent's target is live") - // ErrTargetNeverCreated: the dependent's target has neither VOLUME nor - // HEAD; the restore that registered it could still create it. - ErrTargetNeverCreated = errors.New("layout: the dependent's target was never created") ) +// TargetStore is a restore target's HEAD entry as the operator's +// remove-dependent sees it: read, and one exclusive create of a deleted +// HEAD (a tombstone) in the target's never-reused directory; ErrExists if +// a HEAD is already there. +type TargetStore interface { + ReadHead(ctx context.Context) (h Head, found bool, err error) + CreateDeletedHead(ctx context.Context, h Head) error +} + // HolderGone is the deletion's premise: it returns nil only when no block // holds the volume (no line or lease the master grants). DeleteVolume calls // it immediately before marking HEAD deleting. @@ -158,14 +164,15 @@ func DeleteVolume(ctx context.Context, st HeadStore, gone HolderGone, id VolumeI // OperatorReleaseDependent is the operator's remove-dependent command: it // releases the target from the source's dependents only when the target // exists and is deleted or no longer names the source, read first: its -// HEAD is deleting or deleted; its name now holds another volume (another -// VOLUME id); or its HEAD is live and no root in it (current or snapshot) -// names a chunk of the source. A live target that still names the source, -// or one being created (VOLUME without HEAD), is refused (ErrTargetLive). -// A target never created (no VOLUME, no HEAD) is refused too -// (ErrTargetNeverCreated): the restore could still create it after the -// release. The source is not written when refused. -func OperatorReleaseDependent(ctx context.Context, source, target HeadStore, r *Reader, targetID VolumeID) (Head, error) { +// HEAD is deleting or deleted; its directory's VOLUME carries another id; +// or its HEAD is live and no root in it (current or snapshot) names a +// chunk of the source. A target never created (no VOLUME, no HEAD) first +// gets a deleted HEAD written exclusively in its never-reused directory, +// so the restore that registered it can never create it later, and is +// then released. A live target that still names the source, one being +// created (VOLUME without HEAD), and one whose HEAD appeared before the +// tombstone are refused (ErrTargetLive); the source is not written then. +func OperatorReleaseDependent(ctx context.Context, source HeadStore, target TargetStore, r *Reader, targetID VolumeID) (Head, error) { sh, found, err := source.ReadHead(ctx) if err != nil { return Head{}, err @@ -186,7 +193,17 @@ func OperatorReleaseDependent(ctx context.Context, source, target HeadStore, r * case hasHead && (th.State == StateDeleting || th.State == StateDeleted): case hasVolume && id != targetID: case !hasVolume && !hasHead: - return Head{}, fmt.Errorf("%w: %s", ErrTargetNeverCreated, r.vol) + // Never created: a deleted HEAD written exclusively in the target's + // never-reused directory makes sure the restore can never create it + // later; only then is the dependent released. If a HEAD appeared + // first, the restore got there: refused, re-run decides. + tomb := Head{VolumeID: targetID, Activity: Activity{Kind: ActIdle}, State: StateDeleted} + if err := target.CreateDeletedHead(ctx, tomb); err != nil { + if errors.Is(err, ErrExists) { + return Head{}, fmt.Errorf("%w: %s appeared while being tombstoned; run again", ErrTargetLive, r.vol) + } + return Head{}, err + } case hasVolume && hasHead: names, err := namesVolume(ctx, r, th, sh.VolumeID) if err != nil { diff --git a/seaweed-block/core/frontend/chunkstore/layout/delete_test.go b/seaweed-block/core/frontend/chunkstore/layout/delete_test.go index b675f4d0ff..94b56516ed 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/delete_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout/delete_test.go @@ -315,9 +315,11 @@ func operatorCase(t *testing.T, tgtHead *Head, tgtVolume *VolumeID, namesSource // exists and is deleted or no longer names the source: its HEAD deleting // or deleted, its name holding another volume (another VOLUME id), or a // live HEAD none of whose roots names a chunk of the source. A live target -// that still names the source, one being created (VOLUME without HEAD) and -// one never created (no VOLUME, no HEAD: the restore could still create -// it) are refused and the source is unchanged. +// that still names the source and one being created (VOLUME without HEAD) +// are refused and the source is unchanged. A target never created (no +// VOLUME, no HEAD) gets a deleted HEAD written exclusively in its +// never-reused directory, so the restore can never create it later, and +// only then is released. func TestOperatorReleaseDependent(t *testing.T) { ctx := context.Background() live := idleHead() @@ -335,7 +337,7 @@ func TestOperatorReleaseDependent(t *testing.T) { "live target naming the source": {&live, &tid, true, false, ErrTargetLive}, "live target no longer naming it": {&live, &tid, false, true, nil}, "target being created": {nil, &tid, false, false, ErrTargetLive}, - "target never created": {nil, nil, false, false, ErrTargetNeverCreated}, + "target never created": {nil, nil, false, true, nil}, "target deleting": {&deleting, &tid, true, true, nil}, "name holds another volume": {nil, &other, false, true, nil}, } { @@ -343,6 +345,9 @@ func TestOperatorReleaseDependent(t *testing.T) { before := src.updates _, err := OperatorReleaseDependent(ctx, src, tgt, r, tid) released := len(src.h.Snapshots["daily"].Dependents) == 0 + if tc.head == nil && tc.volume == nil && (tgt.h == nil || tgt.h.State != StateDeleted || tgt.h.VolumeID != tid) { + t.Errorf("%s: target HEAD %+v; want a deleted HEAD (tombstone) of the target's id written before the release", name, tgt.h) + } if tc.release && (err != nil || !released) { t.Errorf("%s: %v, released %t; want released", name, err, released) } @@ -351,3 +356,30 @@ func TestOperatorReleaseDependent(t *testing.T) { } } } + +// If the restore creates the target's HEAD between the operator's read and +// its tombstone, the exclusive create fails and nothing is released. +func TestOperatorReleaseDependent_TombstoneLosesToTheRestore(t *testing.T) { + src, tgt, r := operatorCase(t, nil, nil, false) + live := idleHead() + live.VolumeID = idFor("t") + created := &raceTarget{memHead: tgt, appear: &live} + before := src.updates + if _, err := OperatorReleaseDependent(context.Background(), src, created, r, idFor("t")); !errors.Is(err, ErrTargetLive) || src.updates != before { + t.Fatalf("tombstone after the restore created the HEAD: %v (%d source writes); want ErrTargetLive and none", err, src.updates-before) + } +} + +// raceTarget makes a HEAD appear right before the tombstone's create. +type raceTarget struct { + *memHead + appear *Head +} + +func (r *raceTarget) CreateDeletedHead(ctx context.Context, h Head) error { + if r.appear != nil { + n := r.appear.clone() + r.memHead.h, r.appear = &n, nil + } + return r.memHead.CreateDeletedHead(ctx, h) +} diff --git a/seaweed-block/core/frontend/chunkstore/layout/guard_test.go b/seaweed-block/core/frontend/chunkstore/layout/guard_test.go index afbe14bdc3..38e9210b1e 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/guard_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout/guard_test.go @@ -171,6 +171,11 @@ func guardFindings(code map[string]map[string]bool, decl, tests map[string]bool) bad = append(bad, fn+" is declared and does not go through runTransition") } } + for _, fn := range owners(code["CreateDeletedHead"]) { + if fn != "OperatorReleaseDependent" { + bad = append(bad, fn+" uses CreateDeletedHead: only the operator's release writes a tombstone, for a target never created") + } + } for _, fn := range owners(code["RunReleaseDependent"]) { if fn != "DeleteVolume" && fn != "OperatorReleaseDependent" { bad = append(bad, fn+" uses RunReleaseDependent: only DeleteVolume (target deleting) and OperatorReleaseDependent (target checked) release") @@ -449,10 +454,11 @@ func DeleteVolume(ctx context.Context, st HeadStore, id VolumeID, srcs []HeadSto "operator release without reading the target": {file: "delete.go", src: `func OperatorReleaseDependent(ctx context.Context, source HeadStore, id VolumeID) (Head, error) { return RunReleaseDependent(ctx, source, id) }`, want: "does not read the target's HEAD"}, - "unconditional delete": {file: "remove.go", src: removeVariant(t, "unconditional"), want: "its only removal is DeleteMarked"}, - "ignored mark": {file: "remove.go", src: removeVariant(t, "ignored"), want: "without a mark gate immediately before it"}, - "one mark, two deletes": {file: "remove.go", src: removeVariant(t, "second"), want: "without a mark gate immediately before it"}, - "unlisted removal method": {file: "remove.go", src: removeVariant(t, "other"), want: "without a mark gate immediately before it"}, + "unconditional delete": {file: "remove.go", src: removeVariant(t, "unconditional"), want: "its only removal is DeleteMarked"}, + "ignored mark": {file: "remove.go", src: removeVariant(t, "ignored"), want: "without a mark gate immediately before it"}, + "one mark, two deletes": {file: "remove.go", src: removeVariant(t, "second"), want: "without a mark gate immediately before it"}, + "unlisted removal method": {file: "remove.go", src: removeVariant(t, "other"), want: "without a mark gate immediately before it"}, + "tombstone outside the operator's release": {src: `func w(ctx context.Context, t TargetStore, h Head) { _ = t.CreateDeletedHead(ctx, h) }`, want: "only the operator's release writes a tombstone"}, "remover method value": {src: `type p interface{ RemoveName(string) } func w(x p) { f := x.RemoveName; f("o") }`, want: "only RemoveUnreachable (mark-gated) and DeleteVolume"}, } { diff --git a/seaweed-block/core/frontend/chunkstore/layout/head.go b/seaweed-block/core/frontend/chunkstore/layout/head.go index b89dbec9a5..48ab207aa9 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/head.go +++ b/seaweed-block/core/frontend/chunkstore/layout/head.go @@ -125,11 +125,16 @@ func (h Head) check() error { default: return fmt.Errorf("%w: activity %q", ErrMalformed, h.Activity.Kind) } - if h.Epoch == 0 || h.Holder == "" { - return fmt.Errorf("%w: HEAD without epoch or holder", ErrMalformed) - } - if h.ClaimID == "" { - return fmt.Errorf("%w: HEAD holder %q without a claim id", ErrMalformed, h.Holder) + // A deleted HEAD written as a tombstone for a restore target never + // created has no holder; every other HEAD has an epoch, a holder and + // the claim id of its claim. + if h.State != StateDeleted || h.Holder != "" { + if h.Epoch == 0 || h.Holder == "" { + return fmt.Errorf("%w: HEAD without epoch or holder", ErrMalformed) + } + if h.ClaimID == "" { + return fmt.Errorf("%w: HEAD holder %q without a claim id", ErrMalformed, h.Holder) + } } if len(h.Snapshots) > MaxSnapshots { return fmt.Errorf("%w: %d snapshots, at most %d", ErrMalformed, len(h.Snapshots), MaxSnapshots) diff --git a/seaweed-block/core/frontend/chunkstore/layout/head_test.go b/seaweed-block/core/frontend/chunkstore/layout/head_test.go index ca166d531c..0f101ffb87 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/head_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout/head_test.go @@ -207,6 +207,29 @@ func (m *memHead) UpdateHead(_ context.Context, gen uint64, next Head) error { return nil } +// CreateDeletedHead writes a deleted HEAD exclusively (a tombstone). +func (m *memHead) CreateDeletedHead(_ context.Context, h Head) error { + m.mu.Lock() + defer m.mu.Unlock() + if m.dead { + return errKilled + } + if m.h != nil { + return ErrExists + } + if h.State != StateDeleted { + return errors.New("only a deleted HEAD is created") + } + if _, err := h.Encode(); err != nil { + return err + } + n := h.clone() + n.Gen = 1 + m.h = &n + m.updates++ + return nil +} + func (m *memHead) restart() { m.mu.Lock(); m.dead = false; m.killAt = 0; m.mu.Unlock() } func TestRunBegin(t *testing.T) { diff --git a/seaweed-block/core/frontend/chunkstore/layout/read.go b/seaweed-block/core/frontend/chunkstore/layout/read.go index 3fa7de05ff..b05cfd6c84 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/read.go +++ b/seaweed-block/core/frontend/chunkstore/layout/read.go @@ -147,8 +147,9 @@ func (img *Image) Resolve(ctx context.Context, index uint64) (ref Ref, zero bool } // Chunk resolves index and reads its bytes from the pool of the volume -// that owns it, after checking that volume's VOLUME id is the one the -// reference carries (ErrIdentity otherwise). A chunk the root names but the +// that owns it, in that volume's directory (VolumeDir of the reference's +// owner name and id), after checking the directory's VOLUME id is the one +// the reference carries (ErrIdentity otherwise). A chunk the root names but the // owner's pool lacks is ErrMissing. func (img *Image) Chunk(ctx context.Context, index uint64) (Chunk, error) { ref, zero, err := img.Resolve(ctx, index) @@ -158,14 +159,15 @@ func (img *Image) Chunk(ctx context.Context, index uint64) (Chunk, error) { if zero { return Chunk{Zero: true}, nil } - id, err := img.r.VolumeID(ctx, ref.Owner) + dir := VolumeDir(ref.Owner, ref.OwnerID) + id, err := img.r.VolumeID(ctx, dir) if err != nil { return Chunk{}, err } if id != ref.OwnerID { return Chunk{}, fmt.Errorf("%w: chunk %d names %s id %s, VOLUME has %s", ErrIdentity, index, ref.Owner, ref.OwnerID, id) } - b, err := img.r.get(ctx, ref.Owner, ref.Chunk.Path(), ref.Chunk.Hash) + b, err := img.r.get(ctx, dir, ref.Chunk.Path(), ref.Chunk.Hash) if err != nil { return Chunk{}, err } diff --git a/seaweed-block/core/frontend/chunkstore/layout/read_test.go b/seaweed-block/core/frontend/chunkstore/layout/read_test.go index 67de891f2f..be87aa5bb8 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/read_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout/read_test.go @@ -27,6 +27,12 @@ func (s *objStore) fetch(_ context.Context, p string) ([]byte, bool, error) { const base = "/swblock/chunks" +// The test volumes' directories: -. +var ( + tDir = VolumeDir("t", idFor("t")) + srcDir = VolumeDir("src", idFor("src")) +) + // readFixture: volume "t" (a restore target) whose root names chunk 3 // ("own") in its own pool, chunk 10002 ("src data") in the pool of "src", // and nothing else; every object is written. @@ -36,29 +42,29 @@ func readFixture(t *testing.T) (*objStore, RootName, map[uint64]Ref) { put := func(vol, rel string, b []byte) { s.obj[path.Join(base, vol, rel)] = b } own := NameChunk(3, []byte("own")) foreign := NameChunk(10002, []byte("src data")) - put("t", own.Path(), []byte("own")) - put("src", foreign.Path(), []byte("src data")) + put(tDir, own.Path(), []byte("own")) + put(srcDir, foreign.Path(), []byte("src data")) m := map[uint64]Ref{3: {Owner: "t", OwnerID: idFor("t"), Chunk: own}, 10002: {Owner: "src", OwnerID: idFor("src"), Chunk: foreign}} - putVolume(t, put, "t") - putVolume(t, put, "src") + putVolume(t, put, "t", tDir) + putVolume(t, put, "src", srcDir) root, segs, err := Build(m) if err != nil { t.Fatal(err) } for n, b := range segs { - put("t", n.Path(), b) + put(tDir, n.Path(), b) } rn, rb, err := NameRoot(root) if err != nil { t.Fatal(err) } - put("t", rn.Path(), rb) + put(tDir, rn.Path(), rb) return s, rn, m } func newReader(t *testing.T, s *objStore) *Reader { t.Helper() - r, err := NewReader(base, "t", s.fetch) + r, err := NewReader(base, tDir, s.fetch) if err != nil { t.Fatal(err) } @@ -106,7 +112,7 @@ func TestRead_AbsentIndexIsZeros(t *testing.T) { func TestRead_ForeignChunkFromSourcePool(t *testing.T) { s, rn, m := readFixture(t) // A same-named object in t's own pool must not be what is read. - s.obj[path.Join(base, "t", m[10002].Chunk.Path())] = []byte("decoy") + s.obj[path.Join(base, tDir, m[10002].Chunk.Path())] = []byte("decoy") r := newReader(t, s) img, err := r.Open(context.Background(), rn) if err != nil { @@ -117,7 +123,7 @@ func TestRead_ForeignChunkFromSourcePool(t *testing.T) { if err != nil || c.Zero || !bytes.Equal(c.Data, []byte("src data")) || c.Ref.Owner != "src" { t.Fatalf("chunk 10002: %+v %v", c, err) } - want := path.Join(base, "src", m[10002].Chunk.Path()) + want := path.Join(base, srcDir, m[10002].Chunk.Path()) if got := s.asked[len(s.asked)-1]; got != want { t.Fatalf("read %s; want the source pool path %s", got, want) } @@ -129,7 +135,7 @@ func TestRead_MissingObjectIsAnErrorNeverZeros(t *testing.T) { ctx := context.Background() t.Run("root", func(t *testing.T) { s, rn, _ := readFixture(t) - delete(s.obj, path.Join(base, "t", rn.Path())) + delete(s.obj, path.Join(base, tDir, rn.Path())) if _, err := newReader(t, s).Open(ctx, rn); !errors.Is(err, ErrMissing) { t.Fatalf("open of a missing root: %v; want ErrMissing", err) } @@ -140,7 +146,7 @@ func TestRead_MissingObjectIsAnErrorNeverZeros(t *testing.T) { if err != nil { t.Fatal(err) } - delete(s.obj, path.Join(base, "t", img.root.Segments[1].Path())) + delete(s.obj, path.Join(base, tDir, img.root.Segments[1].Path())) for _, idx := range []uint64{10002, 10003} { // named, and not named, in that shard c, err := img.Chunk(ctx, idx) if !errors.Is(err, ErrMissing) || c.Zero { @@ -150,7 +156,7 @@ func TestRead_MissingObjectIsAnErrorNeverZeros(t *testing.T) { }) t.Run("own chunk", func(t *testing.T) { s, rn, m := readFixture(t) - delete(s.obj, path.Join(base, "t", m[3].Chunk.Path())) + delete(s.obj, path.Join(base, tDir, m[3].Chunk.Path())) img, err := newReader(t, s).Open(ctx, rn) if err != nil { t.Fatal(err) @@ -161,7 +167,7 @@ func TestRead_MissingObjectIsAnErrorNeverZeros(t *testing.T) { }) t.Run("foreign chunk", func(t *testing.T) { s, rn, m := readFixture(t) - delete(s.obj, path.Join(base, "src", m[10002].Chunk.Path())) + delete(s.obj, path.Join(base, srcDir, m[10002].Chunk.Path())) img, err := newReader(t, s).Open(ctx, rn) if err != nil { t.Fatal(err) @@ -182,14 +188,14 @@ func TestRead_FetchFailureAndCorruption(t *testing.T) { if err != nil { t.Fatal(err) } - s.fail = path.Join(base, "t", m[3].Chunk.Path()) + s.fail = path.Join(base, tDir, m[3].Chunk.Path()) if _, err := img.Chunk(ctx, 3); err == nil || errors.Is(err, ErrMissing) { t.Fatalf("failed fetch: %v; want an error that is not ErrMissing", err) } s.fail = "" for name, p := range map[string]string{ - "chunk": path.Join(base, "t", m[3].Chunk.Path()), - "segment": path.Join(base, "t", img.root.Segments[0].Path()), + "chunk": path.Join(base, tDir, m[3].Chunk.Path()), + "segment": path.Join(base, tDir, img.root.Segments[0].Path()), } { s2, rn2, _ := readFixture(t) s2.obj[p] = append(append([]byte(nil), s2.obj[p]...), 'x') @@ -202,7 +208,7 @@ func TestRead_FetchFailureAndCorruption(t *testing.T) { } } s3, rn3, _ := readFixture(t) - rp := path.Join(base, "t", rn3.Path()) + rp := path.Join(base, tDir, rn3.Path()) s3.obj[rp] = append(append([]byte(nil), s3.obj[rp]...), 0) if _, err := newReader(t, s3).Open(ctx, rn3); !errors.Is(err, ErrCorrupt) { t.Errorf("root altered: %v; want ErrCorrupt", err) @@ -220,13 +226,13 @@ func TestRead_SegmentOfAnotherShardRefused(t *testing.T) { t.Fatal(err) } lie := SegName{Shard: 0, Hash: sn.Hash} - s.obj[path.Join(base, "t", lie.Path())] = sb + s.obj[path.Join(base, tDir, lie.Path())] = sb root := Root{Segments: map[uint64]SegName{0: lie}} rn, rb, err := NameRoot(root) if err != nil { t.Fatal(err) } - s.obj[path.Join(base, "t", rn.Path())] = rb + s.obj[path.Join(base, tDir, rn.Path())] = rb img, err := newReader(t, s).Open(ctx, rn) if err != nil { t.Fatal(err) @@ -247,13 +253,13 @@ func TestNewReader_RefusesBadInput(t *testing.T) { } // putVolume writes vol's VOLUME record with its test id. -func putVolume(t *testing.T, put func(vol, rel string, b []byte), vol string) { +func putVolume(t *testing.T, put func(dir, rel string, b []byte), name, dir string) { t.Helper() - b, err := Volume{ID: idFor(vol), Name: vol, Format: VolumeFormat}.Encode() + b, err := Volume{ID: idFor(name), Name: name, Format: VolumeFormat}.Encode() if err != nil { t.Fatal(err) } - put(vol, VolumeName, b) + put(dir, VolumeName, b) } // A foreign chunk is read only if its owner's VOLUME carries the id the @@ -267,7 +273,7 @@ func TestRead_ForeignChunkNeedsTheOwnersVolumeID(t *testing.T) { if err != nil { t.Fatal(err) } - s.obj[path.Join(base, "src", VolumeName)] = b + s.obj[path.Join(base, srcDir, VolumeName)] = b img, err := newReader(t, s).Open(ctx, rn) if err != nil { t.Fatal(err) @@ -277,11 +283,11 @@ func TestRead_ForeignChunkNeedsTheOwnersVolumeID(t *testing.T) { t.Fatalf("chunk of a re-created source: %v; want ErrIdentity", err) } for _, p := range s.asked { - if p == path.Join(base, "src", m[10002].Chunk.Path()) { + if p == path.Join(base, srcDir, m[10002].Chunk.Path()) { t.Fatal("the chunk was fetched from a source whose id does not match") } } - delete(s.obj, path.Join(base, "src", VolumeName)) + delete(s.obj, path.Join(base, srcDir, VolumeName)) img, _ = newReader(t, s).Open(ctx, rn) if _, err := img.Chunk(ctx, 10002); !errors.Is(err, ErrMissing) { t.Fatalf("chunk of a source without VOLUME: %v; want ErrMissing", err) diff --git a/seaweed-block/core/frontend/chunkstore/layout/volume.go b/seaweed-block/core/frontend/chunkstore/layout/volume.go index a15efbca4b..3da1a6fbd9 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/volume.go +++ b/seaweed-block/core/frontend/chunkstore/layout/volume.go @@ -47,6 +47,14 @@ func ParseVolumeID(s string) (VolumeID, error) { return id, nil } +// VolumeDir is the directory of a volume under the store's base: +// -. It is created exclusively and +// never reused, so a volume created again under a name gets another +// directory; it is resolved only from the master's volume record. +func VolumeDir(name string, id VolumeID) string { + return name + "-" + id.String()[:8] +} + // VolumeFormat is the layout format a VOLUME record declares. const VolumeFormat = 1 diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 0d288861d9..73b6ab0889 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -549,7 +549,7 @@ stateDiagram-v2 ## Part B. Invariant ledger -356 rows: 285 ACTIVE, 67 STUB, 4 ARCHIVED; 15 kept from the internal ledger, 341 new. +358 rows: 287 ACTIVE, 67 STUB, 4 ARCHIVED; 15 kept from the internal ledger, 343 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. @@ -1112,10 +1112,12 @@ Notes: | `INV-SNAPK-DELETE-OWNED-001` | Every object entry carries the id of its volume; a volume delete removes an object only if it carries that id, so a late delete of a finished run never removes the object of a volume created again under the name. | M9 deleting → deleted | `core/frontend/chunkstore/layout` `delete.go` `DeleteVolume`; `objects.go` `ObjectStore.DeleteOfVolume` | `TestDeleteVolume_ALateDeleteSparesTheNameReused`, `TestDeleteVolume` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-DELETE-GATE-001` | HEAD becomes deleting only with no holder (checked immediately before), no open activity and no snapshot with dependents; from deleting on, no holder transition, claim or removal applies. | M9 idle → deleting | `core/frontend/chunkstore/layout` `delete.go` `Head.MarkDeleting`; `head.go` `holderErr` | `TestMarkDeleting_Closure`, `TestMarkDeleted_Closure`, `TestDeleting_RefusesEveryHolderStep`, `TestDeleteVolume` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-DELETE-GUARD-001` | A source scan requires DeleteVolume to run no-holder check, deleting, release, object deletes and deleted in that order, and allows it as the only remover besides RemoveUnreachable. | M9 idle → deleting → deleted | `core/frontend/chunkstore/layout` (source scan of `delete.go`) | `TestGuard_WritersTransitionsAndRemovers`, `TestGuard_Controls` | — (the snapshot kernel model is not in this repository) | ACTIVE | +| `INV-SNAPK-VOLUME-DIR-001` | A volume lives in the directory -, created exclusively and never reused; a foreign chunk is read from the directory its reference's owner name and id give, after that directory's VOLUME id is checked. | Content-named layout | `core/frontend/chunkstore/layout` `volume.go` `VolumeDir`; `read.go` `Image.Chunk` | `TestRead_ForeignChunkFromSourcePool`, `TestRead_ForeignChunkNeedsTheOwnersVolumeID` | — (the snapshot kernel model is not in this repository) | ACTIVE | +| `INV-SNAPK-TOMBSTONE-001` | For a restore target never created the operator writes a deleted HEAD exclusively in its directory before releasing the dependent, so the restore cannot create it later; only that command creates a tombstone (source scan). | M9 source HEAD, dependents | `core/frontend/chunkstore/layout` `delete.go` `OperatorReleaseDependent`, `TargetStore.CreateDeletedHead` | `TestOperatorReleaseDependent`, `TestOperatorReleaseDependent_TombstoneLosesToTheRestore`, `TestGuard_Controls` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-RELEASE-001` | A target is released from a source's dependents by its volume id, from every snapshot, in one conditional update; a volume created again under its name releases nothing; an absent target writes nothing. | M9 source HEAD, dependents | `core/frontend/chunkstore/layout` `delete.go` `Head.ReleaseDependent`, `RunReleaseDependent` | `TestReleaseDependent_Closure`, `TestRunReleaseDependent_InterruptAtEveryStep` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-RELEASE-CALLERS-001` | Only the target's own delete (its HEAD already deleting) and the operator's command release a dependent; a source scan restricts the callers and requires the operator's read of the target. | M9 source HEAD, dependents | `core/frontend/chunkstore/layout` (source scan of `delete.go`) | `TestGuard_Controls` | — (the snapshot kernel model is not in this repository) | ACTIVE | -| `INV-SNAPK-RELEASE-OPERATOR-001` | The operator's command releases only a target that exists and is deleted (HEAD deleting or deleted, or its name holding another volume id) or whose live roots name no chunk of the source. | M9 source HEAD, dependents | `core/frontend/chunkstore/layout` `delete.go` `OperatorReleaseDependent` | `TestOperatorReleaseDependent` | — (the snapshot kernel model is not in this repository) | ACTIVE | -| `INV-SNAPK-RELEASE-REFUSE-001` | The operator's command refuses a live target still naming the source, a target being created and a target never created, and then writes nothing to the source. | M9 source HEAD, dependents | `core/frontend/chunkstore/layout` `delete.go` `OperatorReleaseDependent` | `TestOperatorReleaseDependent` | — (the snapshot kernel model is not in this repository) | ACTIVE | +| `INV-SNAPK-RELEASE-OPERATOR-001` | The operator's command releases a target that is deleted (HEAD deleting or deleted, or its directory's VOLUME of another id), one whose live roots name no chunk of the source, or one never created, after its tombstone. | M9 source HEAD, dependents | `core/frontend/chunkstore/layout` `delete.go` `OperatorReleaseDependent` | `TestOperatorReleaseDependent` | — (the snapshot kernel model is not in this repository) | ACTIVE | +| `INV-SNAPK-RELEASE-REFUSE-001` | The operator's command refuses a live target still naming the source, a target being created (VOLUME without HEAD) and one whose HEAD appeared before its tombstone, and then writes nothing to the source. | M9 source HEAD, dependents | `core/frontend/chunkstore/layout` `delete.go` `OperatorReleaseDependent` | `TestOperatorReleaseDependent` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-STALE-HOLDER-001` | Every transition refuses an older epoch of the same server, the same epoch held by another server, and the same epoch and server with another claim id, in idle, snap and clean; a new transition must be added to the table. | M9 every transition | `core/frontend/chunkstore/layout` `Head.heldBy` and each transition | `TestTransitions_RefuseAStaleHolder` | — (the snapshot kernel model is not in this repository) | ACTIVE | Notes: From 2fa488bedbf6a1ce6508a5adc3c05791bc243ef5 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 24 Nov 2026 18:42:43 -0800 Subject: [PATCH 4/7] layout: tombstone any restore target without HEAD; nothing removes a HEAD The operator's remove-dependent now writes the deleted HEAD for any target without HEAD, not only one without VOLUME too: a restore that died between its VOLUME and its HEAD would otherwise leave a target that could be neither released nor deleted, pinning the source's snapshot for ever. The later HEAD create of such a restore fails on the tombstone, as before. A volume delete refuses, before any write, a listed path that is not a pool, segment or root object, so HEAD (which stays, deleted), VOLUME and the directory are never removed. A source scan lists every delete and every directory-naming site in core/ and cmd/ and fails on a new one. Co-Authored-By: Claude Opus 5.5 --- .../frontend/chunkstore/delete_sites_test.go | 102 ++++++++++++++++++ .../frontend/chunkstore/head_readers_test.go | 7 +- .../core/frontend/chunkstore/layout/delete.go | 42 +++++--- .../frontend/chunkstore/layout/delete_test.go | 32 ++++-- .../core/frontend/chunkstore/layout/volume.go | 4 + seaweed-block/docs/design/invariants.md | 9 +- 6 files changed, 167 insertions(+), 29 deletions(-) create mode 100644 seaweed-block/core/frontend/chunkstore/delete_sites_test.go diff --git a/seaweed-block/core/frontend/chunkstore/delete_sites_test.go b/seaweed-block/core/frontend/chunkstore/delete_sites_test.go new file mode 100644 index 0000000000..cae327fd80 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/delete_sites_test.go @@ -0,0 +1,102 @@ +package chunkstore + +import ( + "go/ast" + "go/parser" + "go/token" + "os" + "path/filepath" + "sort" + "strings" + "testing" +) + +// deleteSites is every non-test function in core/ and cmd/ that deletes a +// filer entry (DeleteEntry) or builds a volume directory name (VolumeDir), +// with what it deletes or where the name comes from. Nothing removes a +// deleted HEAD, a VOLUME or a volume directory, and a volume directory is +// named only from a reference (a root's owner name and id) or from the +// master's volume record, never from a name given plus an id read from +// that same directory. A new site fails until it is classified here. +var deleteSites = map[string]string{ + "core/frontend/chunkstore/catalog.go Catalog.dropIntent -> DeleteEntry": "an intent entry (old store)", + "core/frontend/chunkstore/catalog.go Catalog.DeleteSnapshot -> DeleteEntry": "a snapshot name entry, conditional on its attempt (old store)", + "core/frontend/chunkstore/chunk_remote.go ChunkRemote.DeleteIntent -> DeleteEntry": "an intent entry (old store)", + "core/frontend/chunkstore/retention.go Catalog.freeName -> DeleteEntry": "a snapshot name entry, conditional on its attempt (old store)", + "core/frontend/chunkstore/swfs.go SWFS.DeleteEntry -> DeleteEntry": "the filer client itself", + "core/frontend/chunkstore/layout/read.go Image.Chunk -> VolumeDir": "a foreign chunk's directory from the reference's owner name and id", +} + +func TestDeleteAndDirectorySites_Enumeration(t *testing.T) { + root := filepath.Join("..", "..", "..") + found := map[string]bool{} + for _, top := range []string{"core", "cmd"} { + err := filepath.Walk(filepath.Join(root, top), func(p string, fi os.FileInfo, err error) error { + if err != nil { + return err + } + if fi.IsDir() || !strings.HasSuffix(p, ".go") || strings.HasSuffix(p, "_test.go") || strings.Contains(p, "filerpb") { + return nil + } + file, err := parser.ParseFile(token.NewFileSet(), p, nil, 0) + if err != nil { + return err + } + rel, _ := filepath.Rel(root, p) + rel = filepath.ToSlash(rel) + for _, d := range file.Decls { + fn, ok := d.(*ast.FuncDecl) + if !ok || fn.Body == nil { + continue + } + name := fn.Name.Name + if fn.Recv != nil && len(fn.Recv.List) == 1 { + switch x := fn.Recv.List[0].Type.(type) { + case *ast.Ident: + name = x.Name + "." + name + case *ast.StarExpr: + name = x.X.(*ast.Ident).Name + "." + name + } + } + ast.Inspect(fn.Body, func(n ast.Node) bool { + c, ok := n.(*ast.CallExpr) + if !ok { + return true + } + var callee string + switch x := c.Fun.(type) { + case *ast.SelectorExpr: + callee = x.Sel.Name + case *ast.Ident: + callee = x.Name + } + if callee == "DeleteEntry" || callee == "VolumeDir" { + key := rel + " " + strings.TrimPrefix(name, "*") + " -> " + callee + found[key] = true + } + return true + }) + } + return nil + }) + if err != nil { + t.Fatal(err) + } + } + var added, gone []string + for k := range found { + if _, ok := deleteSites[k]; !ok { + added = append(added, k) + } + } + for k := range deleteSites { + if !found[k] { + gone = append(gone, k) + } + } + sort.Strings(added) + sort.Strings(gone) + if len(added) != 0 || len(gone) != 0 { + t.Fatalf("delete or directory-naming sites changed: classify each (it must not remove a HEAD, a VOLUME or a volume directory, and a directory name must come from a reference or the master's record).\nnew: %v\ngone: %v", added, gone) + } +} diff --git a/seaweed-block/core/frontend/chunkstore/head_readers_test.go b/seaweed-block/core/frontend/chunkstore/head_readers_test.go index 7443284957..b612cb859d 100644 --- a/seaweed-block/core/frontend/chunkstore/head_readers_test.go +++ b/seaweed-block/core/frontend/chunkstore/head_readers_test.go @@ -40,7 +40,7 @@ var headReaders = map[string]string{ "core/frontend/chunkstore/share_guard.go beginShare -> ReadHead": "refuses outcome_unknown: the HEAD to share is no longer current", "core/frontend/chunkstore/usage.go Usage -> ReadHead": "GAP: reports an empty image, no error (probe Usage)", "core/frontend/chunkstore/verify.go readHead -> LookupEntry": "finding ROOT_INVALID (probe Verify)", - "core/frontend/chunkstore/layout/delete.go OperatorReleaseDependent -> ReadHead": "reads the source's HEAD (absent: refuses ErrHeadAbsent) and the target's: with no HEAD and no VOLUME the target was never created and gets a deleted HEAD written exclusively before the release; with VOLUME and no HEAD it is being created and is refused (probe LayoutOperatorRelease)", + "core/frontend/chunkstore/layout/delete.go OperatorReleaseDependent -> ReadHead": "reads the source's HEAD (absent: refuses ErrHeadAbsent) and the target's: a target without HEAD (never created, or a restore that died between its VOLUME and its HEAD) gets a deleted HEAD written exclusively before the release (probe LayoutOperatorRelease)", "core/frontend/chunkstore/layout/remove.go RemoveUnreachable -> ReadHead": "refuses ErrHeadAbsent and writes nothing to the objects (probe LayoutRemoval)", "core/frontend/chunkstore/layout/head.go runTransition -> ReadHead": "refuses ErrHeadAbsent and writes nothing; no layout transition creates a HEAD (probe LayoutTransition)", "core/frontend/chunkstore/verify.go run -> LookupEntry": "finding ROOT_INVALID (probe Verify)", @@ -294,8 +294,9 @@ func TestHeadReaders_AbsentHeadProbes(t *testing.T) { t.Fatal(err) } src := &presentLayoutHead{} - if _, err := layout.OperatorReleaseDependent(ctx, src, &absentLayoutHead{}, r, tid); !errors.Is(err, layout.ErrTargetLive) || src.updates != 0 { - t.Fatalf("operator release of a target with VOLUME and no HEAD: %v, %d writes; want ErrTargetLive and none", err, src.updates) + withVol := &absentLayoutHead{} + if _, err := layout.OperatorReleaseDependent(ctx, src, withVol, r, tid); err != nil || withVol.created == nil || withVol.created.State != layout.StateDeleted { + t.Fatalf("operator release of a target with VOLUME and no HEAD: %v, tombstone %+v; want a deleted HEAD written, then the release", err, withVol.created) } none, _ := layout.NewReader("/swblock/chunks", "t", func(context.Context, string) ([]byte, bool, error) { return nil, false, nil }) tomb := &absentLayoutHead{} diff --git a/seaweed-block/core/frontend/chunkstore/layout/delete.go b/seaweed-block/core/frontend/chunkstore/layout/delete.go index 642423b43f..376be4a8d3 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/delete.go +++ b/seaweed-block/core/frontend/chunkstore/layout/delete.go @@ -5,6 +5,7 @@ import ( "context" "errors" "fmt" + "strings" ) // HEAD states: a live volume, one being deleted, one deleted. @@ -138,6 +139,11 @@ func DeleteVolume(ctx context.Context, st HeadStore, gone HolderGone, id VolumeI if gone == nil || os == nil { return errors.New("layout: delete needs a holder check and an object store") } + for _, rel := range objects { + if !isObjectPath(rel) { + return fmt.Errorf("%w: %q is not a pool, segment or root object; HEAD, VOLUME and the directory stay", ErrMalformed, rel) + } + } if err := gone.NoHolder(ctx); err != nil { return fmt.Errorf("%w: %v", ErrHolderActive, err) } @@ -166,12 +172,13 @@ func DeleteVolume(ctx context.Context, st HeadStore, gone HolderGone, id VolumeI // exists and is deleted or no longer names the source, read first: its // HEAD is deleting or deleted; its directory's VOLUME carries another id; // or its HEAD is live and no root in it (current or snapshot) names a -// chunk of the source. A target never created (no VOLUME, no HEAD) first -// gets a deleted HEAD written exclusively in its never-reused directory, -// so the restore that registered it can never create it later, and is -// then released. A live target that still names the source, one being -// created (VOLUME without HEAD), and one whose HEAD appeared before the -// tombstone are refused (ErrTargetLive); the source is not written then. +// chunk of the source. A target without HEAD (never created, or a restore +// that died between its VOLUME and its HEAD) first gets a deleted HEAD +// written exclusively in its never-reused directory, so the restore that +// registered it can never create it later, and is then released. A live +// target that still names the source, and one whose HEAD appeared before +// the tombstone, are refused (ErrTargetLive); the source is not written +// then. func OperatorReleaseDependent(ctx context.Context, source HeadStore, target TargetStore, r *Reader, targetID VolumeID) (Head, error) { sh, found, err := source.ReadHead(ctx) if err != nil { @@ -192,11 +199,12 @@ func OperatorReleaseDependent(ctx context.Context, source HeadStore, target Targ switch { case hasHead && (th.State == StateDeleting || th.State == StateDeleted): case hasVolume && id != targetID: - case !hasVolume && !hasHead: - // Never created: a deleted HEAD written exclusively in the target's + case !hasHead: + // No HEAD (never created, or a restore that died between its VOLUME + // and its HEAD): a deleted HEAD written exclusively in the target's // never-reused directory makes sure the restore can never create it // later; only then is the dependent released. If a HEAD appeared - // first, the restore got there: refused, re-run decides. + // first, the restore got there: refused, a re-run decides. tomb := Head{VolumeID: targetID, Activity: Activity{Kind: ActIdle}, State: StateDeleted} if err := target.CreateDeletedHead(ctx, tomb); err != nil { if errors.Is(err, ErrExists) { @@ -204,7 +212,7 @@ func OperatorReleaseDependent(ctx context.Context, source HeadStore, target Targ } return Head{}, err } - case hasVolume && hasHead: + default: names, err := namesVolume(ctx, r, th, sh.VolumeID) if err != nil { return Head{}, err @@ -212,8 +220,6 @@ func OperatorReleaseDependent(ctx context.Context, source HeadStore, target Targ if names { return Head{}, fmt.Errorf("%w: %s still names chunks of the source", ErrTargetLive, r.vol) } - default: - return Head{}, fmt.Errorf("%w: %s is being created", ErrTargetLive, r.vol) } return RunReleaseDependent(ctx, source, targetID) } @@ -248,3 +254,15 @@ func namesVolume(ctx context.Context, r *Reader, h Head, owner VolumeID) (bool, } return false, nil } + +// isObjectPath reports whether rel names a content-named object of the +// volume (a chunk, a segment or a root): the only entries a volume delete +// removes. HEAD (which stays, deleted), VOLUME and the directory are not. +func isObjectPath(rel string) bool { + for _, dir := range []string{PoolDir + "/", SegDir + "/", RootDir + "/"} { + if strings.HasPrefix(rel, dir) && len(rel) > len(dir) && !strings.Contains(rel, "..") { + return true + } + } + return false +} diff --git a/seaweed-block/core/frontend/chunkstore/layout/delete_test.go b/seaweed-block/core/frontend/chunkstore/layout/delete_test.go index 94b56516ed..b2ac465f09 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/delete_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout/delete_test.go @@ -315,9 +315,9 @@ func operatorCase(t *testing.T, tgtHead *Head, tgtVolume *VolumeID, namesSource // exists and is deleted or no longer names the source: its HEAD deleting // or deleted, its name holding another volume (another VOLUME id), or a // live HEAD none of whose roots names a chunk of the source. A live target -// that still names the source and one being created (VOLUME without HEAD) -// are refused and the source is unchanged. A target never created (no -// VOLUME, no HEAD) gets a deleted HEAD written exclusively in its +// that still names the source is refused and the source is unchanged. A +// target without HEAD (never created, or a restore that died between its +// VOLUME and its HEAD) gets a deleted HEAD written exclusively in its // never-reused directory, so the restore can never create it later, and // only then is released. func TestOperatorReleaseDependent(t *testing.T) { @@ -334,18 +334,18 @@ func TestOperatorReleaseDependent(t *testing.T) { release bool want error }{ - "live target naming the source": {&live, &tid, true, false, ErrTargetLive}, - "live target no longer naming it": {&live, &tid, false, true, nil}, - "target being created": {nil, &tid, false, false, ErrTargetLive}, - "target never created": {nil, nil, false, true, nil}, - "target deleting": {&deleting, &tid, true, true, nil}, - "name holds another volume": {nil, &other, false, true, nil}, + "live target naming the source": {&live, &tid, true, false, ErrTargetLive}, + "live target no longer naming it": {&live, &tid, false, true, nil}, + "restore died between its creates": {nil, &tid, false, true, nil}, + "target never created": {nil, nil, false, true, nil}, + "target deleting": {&deleting, &tid, true, true, nil}, + "name holds another volume": {nil, &other, false, true, nil}, } { src, tgt, r := operatorCase(t, tc.head, tc.volume, tc.namesSource) before := src.updates _, err := OperatorReleaseDependent(ctx, src, tgt, r, tid) released := len(src.h.Snapshots["daily"].Dependents) == 0 - if tc.head == nil && tc.volume == nil && (tgt.h == nil || tgt.h.State != StateDeleted || tgt.h.VolumeID != tid) { + if tc.head == nil && (tc.volume == nil || *tc.volume == tid) && (tgt.h == nil || tgt.h.State != StateDeleted || tgt.h.VolumeID != tid) { t.Errorf("%s: target HEAD %+v; want a deleted HEAD (tombstone) of the target's id written before the release", name, tgt.h) } if tc.release && (err != nil || !released) { @@ -383,3 +383,15 @@ func (r *raceTarget) CreateDeletedHead(ctx context.Context, h Head) error { } return r.memHead.CreateDeletedHead(ctx, h) } + +// A volume delete removes only content-named objects: HEAD (which stays, +// deleted), VOLUME and the directory are refused before any write. +func TestDeleteVolume_RemovesOnlyObjects(t *testing.T) { + for _, bad := range []string{HeadName, VolumeName, "", "pool/", "pool/../HEAD", "other/x"} { + w := newDeleteWorld() + o := w.objects() + if err := DeleteVolume(context.Background(), w.t, gone{}, idFor("t"), []HeadStore{w.src}, o, append(append([]string(nil), w.rels...), bad)); !errors.Is(err, ErrMalformed) || w.t.updates != 0 || len(o.writes) != 0 { + t.Errorf("delete listing %q: %v (%d HEAD writes, %d object writes); want ErrMalformed and nothing written", bad, err, w.t.updates, len(o.writes)) + } + } +} diff --git a/seaweed-block/core/frontend/chunkstore/layout/volume.go b/seaweed-block/core/frontend/chunkstore/layout/volume.go index 3da1a6fbd9..a83a913eeb 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/volume.go +++ b/seaweed-block/core/frontend/chunkstore/layout/volume.go @@ -12,6 +12,10 @@ import ( // identity: written once, never changed. const VolumeName = "VOLUME" +// HeadName is the entry, under the volume root, that holds the volume's +// HEAD; it is never removed (a deleted volume keeps its deleted HEAD). +const HeadName = "HEAD" + // VolumeID is a volume's identity: random, chosen when the volume is // created. A volume's name is a path and can be created again after a // delete; its id cannot, so a volume created again satisfies no reference diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 73b6ab0889..dd5d94576f 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -549,7 +549,7 @@ stateDiagram-v2 ## Part B. Invariant ledger -358 rows: 287 ACTIVE, 67 STUB, 4 ARCHIVED; 15 kept from the internal ledger, 343 new. +359 rows: 288 ACTIVE, 67 STUB, 4 ARCHIVED; 15 kept from the internal ledger, 344 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. @@ -1113,11 +1113,12 @@ Notes: | `INV-SNAPK-DELETE-GATE-001` | HEAD becomes deleting only with no holder (checked immediately before), no open activity and no snapshot with dependents; from deleting on, no holder transition, claim or removal applies. | M9 idle → deleting | `core/frontend/chunkstore/layout` `delete.go` `Head.MarkDeleting`; `head.go` `holderErr` | `TestMarkDeleting_Closure`, `TestMarkDeleted_Closure`, `TestDeleting_RefusesEveryHolderStep`, `TestDeleteVolume` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-DELETE-GUARD-001` | A source scan requires DeleteVolume to run no-holder check, deleting, release, object deletes and deleted in that order, and allows it as the only remover besides RemoveUnreachable. | M9 idle → deleting → deleted | `core/frontend/chunkstore/layout` (source scan of `delete.go`) | `TestGuard_WritersTransitionsAndRemovers`, `TestGuard_Controls` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-VOLUME-DIR-001` | A volume lives in the directory -, created exclusively and never reused; a foreign chunk is read from the directory its reference's owner name and id give, after that directory's VOLUME id is checked. | Content-named layout | `core/frontend/chunkstore/layout` `volume.go` `VolumeDir`; `read.go` `Image.Chunk` | `TestRead_ForeignChunkFromSourcePool`, `TestRead_ForeignChunkNeedsTheOwnersVolumeID` | — (the snapshot kernel model is not in this repository) | ACTIVE | -| `INV-SNAPK-TOMBSTONE-001` | For a restore target never created the operator writes a deleted HEAD exclusively in its directory before releasing the dependent, so the restore cannot create it later; only that command creates a tombstone (source scan). | M9 source HEAD, dependents | `core/frontend/chunkstore/layout` `delete.go` `OperatorReleaseDependent`, `TargetStore.CreateDeletedHead` | `TestOperatorReleaseDependent`, `TestOperatorReleaseDependent_TombstoneLosesToTheRestore`, `TestGuard_Controls` | — (the snapshot kernel model is not in this repository) | ACTIVE | +| `INV-SNAPK-TOMBSTONE-001` | For a restore target without HEAD (never created, or a restore died between its two creates) the operator writes a deleted HEAD exclusively in its directory before releasing, so the restore cannot create it later. | M9 source HEAD, dependents | `core/frontend/chunkstore/layout` `delete.go` `OperatorReleaseDependent`, `TargetStore.CreateDeletedHead` | `TestOperatorReleaseDependent`, `TestOperatorReleaseDependent_TombstoneLosesToTheRestore`, `TestGuard_Controls` | — (the snapshot kernel model is not in this repository) | ACTIVE | +| `INV-SNAPK-KEEP-HEAD-001` | Nothing removes a HEAD, a VOLUME or a volume directory: a volume delete removes only pool, segment and root objects; a source scan lists every delete and every directory-naming site in core/ and cmd/. | M9 deleting → deleted | `core/frontend/chunkstore/layout` `delete.go` `DeleteVolume`; (source scan) | `TestDeleteVolume_RemovesOnlyObjects`, `TestDeleteAndDirectorySites_Enumeration` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-RELEASE-001` | A target is released from a source's dependents by its volume id, from every snapshot, in one conditional update; a volume created again under its name releases nothing; an absent target writes nothing. | M9 source HEAD, dependents | `core/frontend/chunkstore/layout` `delete.go` `Head.ReleaseDependent`, `RunReleaseDependent` | `TestReleaseDependent_Closure`, `TestRunReleaseDependent_InterruptAtEveryStep` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-RELEASE-CALLERS-001` | Only the target's own delete (its HEAD already deleting) and the operator's command release a dependent; a source scan restricts the callers and requires the operator's read of the target. | M9 source HEAD, dependents | `core/frontend/chunkstore/layout` (source scan of `delete.go`) | `TestGuard_Controls` | — (the snapshot kernel model is not in this repository) | ACTIVE | -| `INV-SNAPK-RELEASE-OPERATOR-001` | The operator's command releases a target that is deleted (HEAD deleting or deleted, or its directory's VOLUME of another id), one whose live roots name no chunk of the source, or one never created, after its tombstone. | M9 source HEAD, dependents | `core/frontend/chunkstore/layout` `delete.go` `OperatorReleaseDependent` | `TestOperatorReleaseDependent` | — (the snapshot kernel model is not in this repository) | ACTIVE | -| `INV-SNAPK-RELEASE-REFUSE-001` | The operator's command refuses a live target still naming the source, a target being created (VOLUME without HEAD) and one whose HEAD appeared before its tombstone, and then writes nothing to the source. | M9 source HEAD, dependents | `core/frontend/chunkstore/layout` `delete.go` `OperatorReleaseDependent` | `TestOperatorReleaseDependent` | — (the snapshot kernel model is not in this repository) | ACTIVE | +| `INV-SNAPK-RELEASE-OPERATOR-001` | The operator's command releases a target that is deleted (HEAD deleting or deleted, or its directory's VOLUME of another id), one whose live roots name no chunk of the source, or one without HEAD, after its tombstone. | M9 source HEAD, dependents | `core/frontend/chunkstore/layout` `delete.go` `OperatorReleaseDependent` | `TestOperatorReleaseDependent` | — (the snapshot kernel model is not in this repository) | ACTIVE | +| `INV-SNAPK-RELEASE-REFUSE-001` | The operator's command refuses a live target still naming the source and one whose HEAD appeared before its tombstone, and then writes nothing to the source. | M9 source HEAD, dependents | `core/frontend/chunkstore/layout` `delete.go` `OperatorReleaseDependent` | `TestOperatorReleaseDependent` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-STALE-HOLDER-001` | Every transition refuses an older epoch of the same server, the same epoch held by another server, and the same epoch and server with another claim id, in idle, snap and clean; a new transition must be added to the table. | M9 every transition | `core/frontend/chunkstore/layout` `Head.heldBy` and each transition | `TestTransitions_RefuseAStaleHolder` | — (the snapshot kernel model is not in this repository) | ACTIVE | Notes: From 74a17f96fbf12dc7f91204a28a56b9979fc14f9c Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 24 Nov 2026 19:08:08 -0800 Subject: [PATCH 5/7] layout: a volume delete holds its no-holder premise with the master The delete checked once that no block held the volume, then marked HEAD deleting by a separate read: a grant and claim in between let it delete a live volume. The delete now first has the master record its delete reservation (no line is granted for the volume after it), then checks that no line holds a live lease between the HEAD read and the conditional update that marks HEAD deleting. After the reservation no live lease can appear, and a claim landing between the read and the update fails the update. Co-Authored-By: Claude Opus 5.5 --- .../core/frontend/chunkstore/layout/delete.go | 55 +++++++--- .../frontend/chunkstore/layout/delete_test.go | 102 ++++++++++++++++-- .../frontend/chunkstore/layout/guard_test.go | 36 +++++-- seaweed-block/docs/design/invariants.md | 10 +- 4 files changed, 160 insertions(+), 43 deletions(-) diff --git a/seaweed-block/core/frontend/chunkstore/layout/delete.go b/seaweed-block/core/frontend/chunkstore/layout/delete.go index 376be4a8d3..641e84e526 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/delete.go +++ b/seaweed-block/core/frontend/chunkstore/layout/delete.go @@ -38,11 +38,17 @@ type TargetStore interface { CreateDeletedHead(ctx context.Context, h Head) error } -// HolderGone is the deletion's premise: it returns nil only when no block -// holds the volume (no line or lease the master grants). DeleteVolume calls -// it immediately before marking HEAD deleting. -type HolderGone interface { - NoHolder(ctx context.Context) error +// DeleteAuthority is the master's side of a volume delete. Reserve durably +// records the volume's delete reservation, after which the master grants +// no line for it, ever (re-running it is a replay). NoLiveLease returns nil +// only when no line of the volume holds a live lease, granted but +// unclaimed lines included. After Reserve, "no live lease" can never +// become false again, so DeleteVolume checks it between its HEAD read and +// the conditional update that marks HEAD deleting: a claim landing in +// between changes HEAD and the update fails. +type DeleteAuthority interface { + Reserve(ctx context.Context) error + NoLiveLease(ctx context.Context) error } // MarkDeleting is the first step of a volume delete: live -> deleting, @@ -110,8 +116,23 @@ func (h Head) ReleaseDependent(target VolumeID) (next Head, changed bool, err er } // RunMarkDeleting applies MarkDeleting by one conditional update. -func RunMarkDeleting(ctx context.Context, st HeadStore) (Head, error) { - return runTransition(ctx, st, func(h Head) (Head, bool, error) { return h.MarkDeleting() }) +// +// The authority's no-live-lease check runs after the read and before the +// update, as the claim's lease wait does. +func RunMarkDeleting(ctx context.Context, st HeadStore, auth DeleteAuthority) (Head, error) { + if auth == nil { + return Head{}, errors.New("layout: MarkDeleting needs the master's delete authority") + } + return runTransition(ctx, st, func(h Head) (Head, bool, error) { + next, changed, err := h.MarkDeleting() + if err != nil || !changed { + return next, changed, err + } + if err := auth.NoLiveLease(ctx); err != nil { + return Head{}, false, fmt.Errorf("%w: %v", ErrHolderActive, err) + } + return next, true, nil + }) } // RunMarkDeleted applies MarkDeleted by one conditional update. @@ -127,27 +148,29 @@ func RunReleaseDependent(ctx context.Context, source HeadStore, target VolumeID) } // DeleteVolume runs a volume delete in its order, every prefix safe and -// the whole re-runnable: HEAD deleting (refused while a holder acts or a -// snapshot has dependents; no holder transition, claim or removal applies -// from here), then this volume released from every source it depends on, +// the whole re-runnable: the master's delete reservation (no line is +// granted for the volume from then on), then HEAD deleting (refused while +// any line holds a live lease, checked between the HEAD read and its +// conditional update, or while a snapshot has dependents; no holder +// transition, claim or removal applies from here), then this volume released from every source it depends on, // then every object of its pool, segments and roots deleted, each // conditional on belonging to this volume (a late delete of this run never // removes the object of a volume created again under the name), then HEAD // deleted. A source left out keeps an extra dependent, which over-protects // and is released by the operator's command. -func DeleteVolume(ctx context.Context, st HeadStore, gone HolderGone, id VolumeID, sources []HeadStore, os ObjectStore, objects []string) error { - if gone == nil || os == nil { - return errors.New("layout: delete needs a holder check and an object store") +func DeleteVolume(ctx context.Context, st HeadStore, auth DeleteAuthority, id VolumeID, sources []HeadStore, os ObjectStore, objects []string) error { + if auth == nil || os == nil { + return errors.New("layout: delete needs the master's delete authority and an object store") } for _, rel := range objects { if !isObjectPath(rel) { return fmt.Errorf("%w: %q is not a pool, segment or root object; HEAD, VOLUME and the directory stay", ErrMalformed, rel) } } - if err := gone.NoHolder(ctx); err != nil { - return fmt.Errorf("%w: %v", ErrHolderActive, err) + if err := auth.Reserve(ctx); err != nil { + return fmt.Errorf("layout: delete reservation: %w", err) } - if _, err := RunMarkDeleting(ctx, st); err != nil { + if _, err := RunMarkDeleting(ctx, st, auth); err != nil { return err } for _, src := range sources { diff --git a/seaweed-block/core/frontend/chunkstore/layout/delete_test.go b/seaweed-block/core/frontend/chunkstore/layout/delete_test.go index b2ac465f09..8a19b46860 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/delete_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout/delete_test.go @@ -99,7 +99,10 @@ func TestDeleting_RefusesEveryHolderStep(t *testing.T) { } func TestRunMarkDeleting_InterruptAtEveryStep(t *testing.T) { - interruptHead(t, idleHead(), func(st HeadStore) error { _, err := RunMarkDeleting(context.Background(), st); return err }, + interruptHead(t, idleHead(), func(st HeadStore) error { + _, err := RunMarkDeleting(context.Background(), st, &fakeMaster{}) + return err + }, func(t *testing.T, h Head) { if h.State != StateDeleting { t.Fatalf("state %q", h.State) @@ -131,9 +134,39 @@ func TestRunReleaseDependent_InterruptAtEveryStep(t *testing.T) { }) } -type gone struct{ err error } +// fakeMaster is the master's delete authority: a reservation after which +// it grants no line, and the lines holding a live lease. +type fakeMaster struct { + reserved bool + leases int + err error // NoLiveLease's answer while leases is 0, when set + onReserve func() // runs after Reserve recorded the reservation +} -func (g gone) NoHolder(context.Context) error { return g.err } +func (m *fakeMaster) Reserve(context.Context) error { + m.reserved = true + if f := m.onReserve; f != nil { + m.onReserve = nil + f() + } + return nil +} + +func (m *fakeMaster) NoLiveLease(context.Context) error { + if m.leases > 0 { + return fmt.Errorf("%d lines hold a live lease", m.leases) + } + return m.err +} + +// grant grants a line (a live lease), refused after the reservation. +func (m *fakeMaster) grant() error { + if m.reserved { + return errors.New("volume reserved for delete") + } + m.leases++ + return nil +} // deleteWorld: volume t (a restore target of src's snapshot "daily") with // two objects in its pool; src's HEAD lists t as a dependent. @@ -175,7 +208,7 @@ func TestDeleteVolume_ALateDeleteSparesTheNameReused(t *testing.T) { ctx := context.Background() w := newDeleteWorld() o := w.objects() - if err := DeleteVolume(ctx, w.t, gone{}, idFor("t"), []HeadStore{w.src}, o, w.rels); err != nil { + if err := DeleteVolume(ctx, w.t, &fakeMaster{}, idFor("t"), []HeadStore{w.src}, o, w.rels); err != nil { t.Fatal(err) } o.volume = idFor("t again") // the name holds a new volume, which writes the same content name @@ -197,19 +230,19 @@ func TestDeleteVolume(t *testing.T) { ctx := context.Background() w := newDeleteWorld() o := w.objects() - if err := DeleteVolume(ctx, w.t, gone{errors.New("leased to srv-a")}, idFor("t"), []HeadStore{w.src}, o, w.rels); !errors.Is(err, ErrHolderActive) || w.t.updates != 0 { + if err := DeleteVolume(ctx, w.t, &fakeMaster{leases: 1}, idFor("t"), []HeadStore{w.src}, o, w.rels); !errors.Is(err, ErrHolderActive) || w.t.updates != 0 { t.Fatalf("delete while held: %v (%d HEAD writes)", err, w.t.updates) } - if err := DeleteVolume(ctx, w.src, gone{}, idFor("src"), nil, o, nil); !errors.Is(err, ErrHasDependents) { + if err := DeleteVolume(ctx, w.src, &fakeMaster{}, idFor("src"), nil, o, nil); !errors.Is(err, ErrHasDependents) { t.Fatalf("delete of a volume with a dependent: %v; want ErrHasDependents", err) } - if err := DeleteVolume(ctx, w.t, gone{}, idFor("t"), []HeadStore{w.src}, o, w.rels); err != nil { + if err := DeleteVolume(ctx, w.t, &fakeMaster{}, idFor("t"), []HeadStore{w.src}, o, w.rels); err != nil { t.Fatal(err) } if w.t.h.State != StateDeleted || len(o.objs) != 0 || len(w.src.h.Snapshots["daily"].Dependents) != 0 { t.Fatalf("after the delete: state %q, %d objects, source dependents %+v", w.t.h.State, len(o.objs), w.src.h.Snapshots["daily"].Dependents) } - if err := DeleteVolume(ctx, w.t, gone{}, idFor("t"), []HeadStore{w.src}, o, w.rels); err != nil { + if err := DeleteVolume(ctx, w.t, &fakeMaster{}, idFor("t"), []HeadStore{w.src}, o, w.rels); err != nil { t.Fatalf("a further re-run: %v", err) } } @@ -242,7 +275,7 @@ func TestDeleteVolume_InterruptAtEveryStep(t *testing.T) { case "object": o.killAt, o.after = nth, after } - if err := DeleteVolume(ctx, w.t, gone{}, idFor("t"), []HeadStore{w.src}, o, w.rels); !errors.Is(err, errKilled) { + if err := DeleteVolume(ctx, w.t, &fakeMaster{}, idFor("t"), []HeadStore{w.src}, o, w.rels); !errors.Is(err, errKilled) { t.Fatalf("killed run: %v", err) } if len(o.objs) < len(w.rels) && (w.t.h.State == StateLive || len(w.src.h.Snapshots["daily"].Dependents) != 0) { @@ -254,7 +287,7 @@ func TestDeleteVolume_InterruptAtEveryStep(t *testing.T) { w.t.restart() w.src.restart() o.dead, o.killAt = false, 0 - if err := DeleteVolume(ctx, w.t, gone{}, idFor("t"), []HeadStore{w.src}, o, w.rels); err != nil { + if err := DeleteVolume(ctx, w.t, &fakeMaster{}, idFor("t"), []HeadStore{w.src}, o, w.rels); err != nil { t.Fatalf("re-run: %v", err) } if w.t.h.State != StateDeleted || len(o.objs) != 0 || len(w.src.h.Snapshots["daily"].Dependents) != 0 { @@ -390,8 +423,55 @@ func TestDeleteVolume_RemovesOnlyObjects(t *testing.T) { for _, bad := range []string{HeadName, VolumeName, "", "pool/", "pool/../HEAD", "other/x"} { w := newDeleteWorld() o := w.objects() - if err := DeleteVolume(context.Background(), w.t, gone{}, idFor("t"), []HeadStore{w.src}, o, append(append([]string(nil), w.rels...), bad)); !errors.Is(err, ErrMalformed) || w.t.updates != 0 || len(o.writes) != 0 { + if err := DeleteVolume(context.Background(), w.t, &fakeMaster{}, idFor("t"), []HeadStore{w.src}, o, append(append([]string(nil), w.rels...), bad)); !errors.Is(err, ErrMalformed) || w.t.updates != 0 || len(o.writes) != 0 { t.Errorf("delete listing %q: %v (%d HEAD writes, %d object writes); want ErrMalformed and nothing written", bad, err, w.t.updates, len(o.writes)) } } } + +// The delete's premise is held by the master, not read once: a grant and +// claim before the reservation is seen as a live lease and refuses; a +// grant after it is refused by the master; a claim landing between the +// HEAD read and the update fails the update. In every case no object is +// deleted from a volume a holder acts on. +func TestDeleteVolume_AGrantRaceNeverDeletesALiveVolume(t *testing.T) { + ctx := context.Background() + claim := func(h *memHead) { h.h.Epoch, h.h.Holder, h.h.ClaimID = h.h.Epoch+1, "srv-new", "k-new"; h.h.Gen++ } + t.Run("granted and claimed before the reservation", func(t *testing.T) { + w := newDeleteWorld() + o := w.objects() + m := &fakeMaster{} + if err := m.grant(); err != nil { + t.Fatal(err) + } + claim(w.t) + if err := DeleteVolume(ctx, w.t, m, idFor("t"), []HeadStore{w.src}, o, w.rels); !errors.Is(err, ErrHolderActive) || len(o.writes) != 0 || w.t.h.State != StateLive { + t.Fatalf("delete of a volume with a granted line: %v, %d object writes, HEAD %s; want ErrHolderActive, nothing deleted", err, len(o.writes), w.t.h.State) + } + }) + t.Run("grant attempted after the reservation", func(t *testing.T) { + w := newDeleteWorld() + o := w.objects() + m := &fakeMaster{} + var grantErr error + m.onReserve = func() { + if grantErr = m.grant(); grantErr == nil { + claim(w.t) + } + } + if err := DeleteVolume(ctx, w.t, m, idFor("t"), []HeadStore{w.src}, o, w.rels); err != nil { + t.Fatalf("delete: %v", err) + } + if grantErr == nil { + t.Fatal("the master granted a line after the delete reservation") + } + }) + t.Run("a claim between the HEAD read and the update", func(t *testing.T) { + w := newDeleteWorld() + o := w.objects() + w.t.afterRead = func() { claim(w.t) } + if err := DeleteVolume(ctx, w.t, &fakeMaster{}, idFor("t"), []HeadStore{w.src}, o, w.rels); err == nil || len(o.writes) != 0 || w.t.h.State != StateLive { + t.Fatalf("delete with a claim after its HEAD read: %v, %d object writes, HEAD %s; want the update refused, nothing deleted", err, len(o.writes), w.t.h.State) + } + }) +} diff --git a/seaweed-block/core/frontend/chunkstore/layout/guard_test.go b/seaweed-block/core/frontend/chunkstore/layout/guard_test.go index 38e9210b1e..10c0d7c311 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/guard_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout/guard_test.go @@ -166,6 +166,14 @@ func guardFindings(code map[string]map[string]bool, decl, tests map[string]bool) if decl["RunClaim"] && !code["OldLeaseEnded"]["RunClaim"] { bad = append(bad, "RunClaim is declared and does not wait for the old lease") } + for _, fn := range owners(code["NoLiveLease"]) { + if fn != "RunMarkDeleting" { + bad = append(bad, fn+" uses NoLiveLease; only RunMarkDeleting checks it, between its HEAD read and update") + } + } + if decl["RunMarkDeleting"] && !code["NoLiveLease"]["RunMarkDeleting"] { + bad = append(bad, "RunMarkDeleting is declared and does not check the master's live leases") + } for fn := range decl { if strings.HasPrefix(fn, "Run") && !code["runTransition"][fn] { bad = append(bad, fn+" is declared and does not go through runTransition") @@ -305,11 +313,11 @@ func removerOrderFindings(t *testing.T, srcs map[string]string) []string { // deleteOrderFindings checks DeleteVolume's order in the sources: among its // top-level statements, the first use of each step comes after the -// previous step's: NoHolder, RunMarkDeleting, RunReleaseDependent, +// previous step's: Reserve, RunMarkDeleting, RunReleaseDependent, // DeleteOfVolume, RunMarkDeleted. func deleteOrderFindings(t *testing.T, srcs map[string]string) []string { t.Helper() - steps := []string{"NoHolder", "RunMarkDeleting", "RunReleaseDependent", "DeleteOfVolume", "RunMarkDeleted"} + steps := []string{"Reserve", "RunMarkDeleting", "RunReleaseDependent", "DeleteOfVolume", "RunMarkDeleted"} var bad []string for fname, src := range srcs { file, err := parser.ParseFile(token.NewFileSet(), fname, src, 0) @@ -419,13 +427,13 @@ func w(ctx context.Context, x p) error { return x.DeleteObject(ctx, "o") }`, wan }`, want: "does not wait for the old lease", file: "claim.go"}, "transition not through runTransition": {src: `func RunZz(ctx context.Context, st HeadStore) (Head, error) { h, _, err := st.ReadHead(ctx); return h, err }`, want: "does not go through runTransition"}, "delete removes the pool before releasing dependents": {file: "delete.go", src: `type p interface{ DeleteOfVolume(context.Context, string, VolumeID) error } -type g interface{ NoHolder(context.Context) error } -func RunMarkDeleting(ctx context.Context, st HeadStore) (Head, error) { return runTransition(ctx, st, nil) } +type g interface{ Reserve(context.Context) error; NoLiveLease(context.Context) error } +func RunMarkDeleting(ctx context.Context, st HeadStore, x g) (Head, error) { _ = x.NoLiveLease(ctx); return runTransition(ctx, st, nil) } func RunMarkDeleted(ctx context.Context, st HeadStore) (Head, error) { return runTransition(ctx, st, nil) } func RunReleaseDependent(ctx context.Context, st HeadStore, id VolumeID) (Head, error) { return runTransition(ctx, st, nil) } func DeleteVolume(ctx context.Context, st HeadStore, x g, id VolumeID, srcs []HeadStore, pool p, objs []string) error { - _ = x.NoHolder(ctx) - _, _ = RunMarkDeleting(ctx, st) + _ = x.Reserve(ctx) + _, _ = RunMarkDeleting(ctx, st, x) for _, o := range objs { _ = pool.DeleteOfVolume(ctx, o, id) } @@ -435,12 +443,13 @@ func DeleteVolume(ctx context.Context, st HeadStore, x g, id VolumeID, srcs []He _, _ = RunMarkDeleted(ctx, st) return nil }`, want: "runs DeleteOfVolume before RunReleaseDependent"}, - "delete without the holder check": {file: "delete.go", src: `type p interface{ DeleteOfVolume(context.Context, string, VolumeID) error } -func RunMarkDeleting(ctx context.Context, st HeadStore) (Head, error) { return runTransition(ctx, st, nil) } + "delete without the reservation": {file: "delete.go", src: `type p interface{ DeleteOfVolume(context.Context, string, VolumeID) error } +type g interface{ NoLiveLease(context.Context) error } +func RunMarkDeleting(ctx context.Context, st HeadStore, x g) (Head, error) { _ = x.NoLiveLease(ctx); return runTransition(ctx, st, nil) } func RunMarkDeleted(ctx context.Context, st HeadStore) (Head, error) { return runTransition(ctx, st, nil) } func RunReleaseDependent(ctx context.Context, st HeadStore, id VolumeID) (Head, error) { return runTransition(ctx, st, nil) } -func DeleteVolume(ctx context.Context, st HeadStore, id VolumeID, srcs []HeadStore, pool p, objs []string) error { - _, _ = RunMarkDeleting(ctx, st) +func DeleteVolume(ctx context.Context, st HeadStore, x g, id VolumeID, srcs []HeadStore, pool p, objs []string) error { + _, _ = RunMarkDeleting(ctx, st, x) for _, s := range srcs { _, _ = RunReleaseDependent(ctx, s, id) } @@ -449,7 +458,12 @@ func DeleteVolume(ctx context.Context, st HeadStore, id VolumeID, srcs []HeadSto } _, _ = RunMarkDeleted(ctx, st) return nil -}`, want: "DeleteVolume has no NoHolder"}, +}`, want: "DeleteVolume has no Reserve"}, + "mark deleting without the live-lease check": {file: "delete.go", src: `func RunMarkDeleting(ctx context.Context, st HeadStore) (Head, error) { + return runTransition(ctx, st, func(h Head) (Head, bool, error) { return h.MarkDeleting() }) +}`, want: "does not check the master's live leases"}, + "live-lease check outside mark deleting": {src: `type g interface{ NoLiveLease(context.Context) error } +func w(ctx context.Context, x g) error { return x.NoLiveLease(ctx) }`, want: "only RunMarkDeleting checks it"}, "release outside delete and the operator's check": {src: `func w(ctx context.Context, st HeadStore, id VolumeID) { _, _ = RunReleaseDependent(ctx, st, id) }`, want: "only DeleteVolume (target deleting) and OperatorReleaseDependent"}, "operator release without reading the target": {file: "delete.go", src: `func OperatorReleaseDependent(ctx context.Context, source HeadStore, id VolumeID) (Head, error) { return RunReleaseDependent(ctx, source, id) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index b85a40ac85..5c6e262e8f 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -531,7 +531,7 @@ stateDiagram-v2 idle --> clean: BeginClean(c) clean --> idle: EndClean(c) clean --> clean: RemoveUnreachable(shard) - idle --> deleting: MarkDeleting (no holder, no dependents) + idle --> deleting: MarkDeleting (reserved, no live lease, no dependents) deleting --> deleted: MarkDeleted (after release and pool) ``` @@ -544,7 +544,7 @@ stateDiagram-v2 | idle | clean(c) | holder at HEAD's epoch (epoch, server and claim id); activity idle (clean(c) again is a replay) | clean.go `Head.BeginClean` | `INV-SNAPK-CLEAN-EXCL-001` | | clean(c) | idle | holder at HEAD's epoch (epoch, server and claim id); activity clean(c); over idle it succeeds without a write | clean.go `Head.EndClean` | `INV-SNAPK-CLEAN-EXCL-001` | | clean(c) | clean(c), names removed | holder at HEAD's epoch (epoch, server and claim id) with clean(c) open (HEAD read once, after BeginClean); a name is deleted only if no root in HEAD (current or snapshot) names it in this volume's pool; each removal is a mark conditional on the plan's metadata, then a delete conditional on that mark | remove.go `RemoveUnreachable` | `INV-SNAPK-REMOVE-MARK-001` | -| idle (live) | deleting | no holder (checked immediately before), no open activity, no snapshot with dependents; deleting again is a replay | delete.go `Head.MarkDeleting`, `DeleteVolume` (`HolderGone.NoHolder`) | `INV-SNAPK-DELETE-ORDER-001` | +| idle (live) | deleting | the master reserved the volume for delete (no line granted after), then no line holds a live lease, checked between the HEAD read and the update; no open activity, no snapshot with dependents; deleting again is a replay | delete.go `Head.MarkDeleting`, `RunMarkDeleting` (`DeleteAuthority`) | `INV-SNAPK-DELETE-ORDER-001` | | deleting | deleted | after this volume is released from every source it names and its objects are deleted; deleted again is a replay; a live HEAD is refused | delete.go `Head.MarkDeleted`, `DeleteVolume` | `INV-SNAPK-DELETE-ORDER-001` | ## Part B. Invariant ledger @@ -1089,7 +1089,7 @@ Notes: | ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | |---|---|---|---|---|---|---| | `INV-SNAPK-NAME-CANONICAL-001` | A chunk is named by its index and the SHA-256 of its bytes under `pool//`; a segment and a root are named by the SHA-256 of their canonical encoding, and decoding refuses any bytes the encoder would not write, so an object has one encoding and one name. | Content-named layout (no state transition) | `core/frontend/chunkstore/layout` `layout.go` `ParseChunkName`, `DecodeSegment`, `DecodeRoot` | `TestParseChunkName_RoundTripAndRefusals`, `TestDecodeSegment_RefusesNonCanonical`, `TestRoot_Refusals`, `TestBuild_ShardsAndIncrementalReuse` | — (the snapshot kernel model is not in this repository) | ACTIVE | -| `INV-SNAPK-HEAD-WRITE-001` | HEAD changes only by one conditional update on its generation through `runTransition`; no path in the package creates a HEAD, and an absent HEAD is refused. | M9 every transition | `core/frontend/chunkstore/layout` `head.go` `runTransition`; `HeadStore` (read and conditional update only) | `TestGuard_WritersTransitionsAndRemovers`, `TestRunBegin` | — (the snapshot kernel model is not in this repository) | ACTIVE | +| `INV-SNAPK-HEAD-WRITE-001` | HEAD changes only by one conditional update on its generation through `runTransition`; an absent HEAD is refused; the one HEAD the package creates is the exclusive deleted HEAD the operator writes (tombstone) for a restore target without HEAD. | M9 every transition | `core/frontend/chunkstore/layout` `head.go` `runTransition`; `HeadStore` (read and conditional update only) | `TestGuard_WritersTransitionsAndRemovers`, `TestRunBegin` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-HEAD-GUARD-001` | A source scan refuses any other use of `UpdateHead`, a transition without its closure and interrupt tests, and any store remover other than the mark-gated RemoveUnreachable and the ordered DeleteVolume. | M9 every transition | `core/frontend/chunkstore/layout` (source scan of the package) | `TestGuard_WritersTransitionsAndRemovers`, `TestGuard_Controls` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-HEAD-CODEC-001` | HEAD is canonical JSON with at most 100 snapshots and sorted unique dependents; unknown fields, non-canonical bytes and names that are not valid UTF-8 are refused at encode and decode, and the next HEAD is checked before it is written. | M9 every transition | `core/frontend/chunkstore/layout` `head.go` `Head.check`, `Head.Encode`, `DecodeHead` | `TestHead_GoldenEncodingRoundTrip`, `TestHead_Refusals`, `TestHead_RefusesInvalidUTF8` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-BEGIN-001` | Begin opens snap(s) only for the holder at HEAD's epoch and only from idle; a re-run of the open session writes nothing; killed at its write and re-run, it ends in snap(s) at one generation step. | M9 idle → snap | `core/frontend/chunkstore/layout` `head.go` `Head.Begin`, `RunBegin` | `TestBegin_Closure`, `TestRunBegin_InterruptAtEveryStep` | — (the snapshot kernel model is not in this repository) | ACTIVE | @@ -1111,8 +1111,8 @@ Notes: | `INV-SNAPK-CLAIM-ID-001` | A holder is its epoch, its server and the claim id its claim wrote into HEAD; every transition refuses the same server at the same epoch with another claim id. | M9 every transition | `core/frontend/chunkstore/layout` `head.go` `heldBy`; `claim.go` `Head.Claim` | `TestClaim_WritesItsClaimID`, `TestTransitions_RefuseAStaleHolder`, `TestHolderFunctions_RefuseAStaleHolder` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-DELETE-ORDER-001` | A volume delete runs in its order, each prefix safe and the whole re-runnable: HEAD deleting, this volume released from every source, its objects deleted, HEAD deleted. | M9 idle → deleting → deleted | `core/frontend/chunkstore/layout` `delete.go` `DeleteVolume` | `TestDeleteVolume`, `TestDeleteVolume_InterruptAtEveryStep`, `TestRunMarkDeleting_InterruptAtEveryStep`, `TestRunMarkDeleted_InterruptAtEveryStep` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-DELETE-OWNED-001` | Every object entry carries the id of its volume; a volume delete removes an object only if it carries that id, so a late delete of a finished run never removes the object of a volume created again under the name. | M9 deleting → deleted | `core/frontend/chunkstore/layout` `delete.go` `DeleteVolume`; `objects.go` `ObjectStore.DeleteOfVolume` | `TestDeleteVolume_ALateDeleteSparesTheNameReused`, `TestDeleteVolume` | — (the snapshot kernel model is not in this repository) | ACTIVE | -| `INV-SNAPK-DELETE-GATE-001` | HEAD becomes deleting only with no holder (checked immediately before), no open activity and no snapshot with dependents; from deleting on, no holder transition, claim or removal applies. | M9 idle → deleting | `core/frontend/chunkstore/layout` `delete.go` `Head.MarkDeleting`; `head.go` `holderErr` | `TestMarkDeleting_Closure`, `TestMarkDeleted_Closure`, `TestDeleting_RefusesEveryHolderStep`, `TestDeleteVolume` | — (the snapshot kernel model is not in this repository) | ACTIVE | -| `INV-SNAPK-DELETE-GUARD-001` | A source scan requires DeleteVolume to run no-holder check, deleting, release, object deletes and deleted in that order, and allows it as the only remover besides RemoveUnreachable. | M9 idle → deleting → deleted | `core/frontend/chunkstore/layout` (source scan of `delete.go`) | `TestGuard_WritersTransitionsAndRemovers`, `TestGuard_Controls` | — (the snapshot kernel model is not in this repository) | ACTIVE | +| `INV-SNAPK-DELETE-GATE-001` | HEAD becomes deleting only after the master reserved the volume (no grant after) and saw no live lease between the HEAD read and the update, with no open activity and no snapshot with dependents; then no holder transition, claim or removal applies. | M9 idle → deleting | `core/frontend/chunkstore/layout` `delete.go` `Head.MarkDeleting`; `head.go` `holderErr` | `TestMarkDeleting_Closure`, `TestMarkDeleted_Closure`, `TestDeleting_RefusesEveryHolderStep`, `TestDeleteVolume`, `TestDeleteVolume_AGrantRaceNeverDeletesALiveVolume` | — (the snapshot kernel model is not in this repository) | ACTIVE | +| `INV-SNAPK-DELETE-GUARD-001` | A source scan requires DeleteVolume to run reservation, deleting (whose transition checks live leases), release, object deletes and deleted in that order, and allows it as the only remover besides RemoveUnreachable. | M9 idle → deleting → deleted | `core/frontend/chunkstore/layout` (source scan of `delete.go`) | `TestGuard_WritersTransitionsAndRemovers`, `TestGuard_Controls` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-VOLUME-DIR-001` | A volume lives in the directory -, created exclusively and never reused; a foreign chunk is read from the directory its reference's owner name and id give, after that directory's VOLUME id is checked. | Content-named layout | `core/frontend/chunkstore/layout` `volume.go` `VolumeDir`; `read.go` `Image.Chunk` | `TestRead_ForeignChunkFromSourcePool`, `TestRead_ForeignChunkNeedsTheOwnersVolumeID` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-TOMBSTONE-001` | For a restore target without HEAD (never created, or a restore died between its two creates) the operator writes a deleted HEAD exclusively in its directory before releasing, so the restore cannot create it later. | M9 source HEAD, dependents | `core/frontend/chunkstore/layout` `delete.go` `OperatorReleaseDependent`, `TargetStore.CreateDeletedHead` | `TestOperatorReleaseDependent`, `TestOperatorReleaseDependent_TombstoneLosesToTheRestore`, `TestGuard_Controls` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-KEEP-HEAD-001` | Nothing removes a HEAD, a VOLUME or a volume directory: a volume delete removes only pool, segment and root objects; a source scan lists every delete and every directory-naming site in core/ and cmd/. | M9 deleting → deleted | `core/frontend/chunkstore/layout` `delete.go` `DeleteVolume`; (source scan) | `TestDeleteVolume_RemovesOnlyObjects`, `TestDeleteAndDirectorySites_Enumeration` | — (the snapshot kernel model is not in this repository) | ACTIVE | From a3ff2ce060ce4035b86ddd9a6d2d426f3bdba754 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 24 Nov 2026 19:19:20 -0800 Subject: [PATCH 6/7] docs: M9 names the tombstone create and the dependent release The M9 introduction names its one HEAD create (the deleted HEAD the operator's remove-dependent writes for a restore target without HEAD); the diagram and the transition table add absent -> deleted (tombstone) and the release of a target from a source's dependents. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/docs/design/invariants.md | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 5c6e262e8f..18c0119884 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -517,7 +517,7 @@ Tests: `TestSnapshotSchedule_SlotsAreOffsetPerVolume`, `_FailureIsTypedAndBacksO ### M9 Snapshot kernel: HEAD transactions over the content-named layout -A library, `core/frontend/chunkstore/layout`, with no production caller yet. A volume's HEAD holds its epoch and holder, one activity (`idle`, `snap(s)` or `clean(c)`), the current root and position, and the named snapshots with their dependents. Every transition is one conditional update of HEAD through `runTransition`; no transition creates a HEAD, and an absent HEAD is refused. Objects (chunks, segments, roots) are written first under content names; the commit is the only step that makes them reachable. +A library, `core/frontend/chunkstore/layout`, with no production caller yet. A volume's HEAD holds its epoch and holder, one activity (`idle`, `snap(s)` or `clean(c)`), the current root and position, and the named snapshots with their dependents. Every transition is one conditional update of HEAD through `runTransition`; no transition creates a HEAD, and an absent HEAD is refused. One exception: the remove-dependent command of the operator writes a deleted HEAD exclusively for a restore target without HEAD (a tombstone), before releasing it from the source. Objects (chunks, segments, roots) are written first under content names; the commit is the only step that makes them reachable. ```mermaid stateDiagram-v2 @@ -533,6 +533,8 @@ stateDiagram-v2 clean --> clean: RemoveUnreachable(shard) idle --> deleting: MarkDeleting (reserved, no live lease, no dependents) deleting --> deleted: MarkDeleted (after release and pool) + [*] --> deleted: tombstone (operator, target without HEAD; exclusive create) + idle --> idle: ReleaseDependent(target) on a source ``` | From | To | Guard | Enforced in | Protects | @@ -545,6 +547,8 @@ stateDiagram-v2 | clean(c) | idle | holder at HEAD's epoch (epoch, server and claim id); activity clean(c); over idle it succeeds without a write | clean.go `Head.EndClean` | `INV-SNAPK-CLEAN-EXCL-001` | | clean(c) | clean(c), names removed | holder at HEAD's epoch (epoch, server and claim id) with clean(c) open (HEAD read once, after BeginClean); a name is deleted only if no root in HEAD (current or snapshot) names it in this volume's pool; each removal is a mark conditional on the plan's metadata, then a delete conditional on that mark | remove.go `RemoveUnreachable` | `INV-SNAPK-REMOVE-MARK-001` | | idle (live) | deleting | the master reserved the volume for delete (no line granted after), then no line holds a live lease, checked between the HEAD read and the update; no open activity, no snapshot with dependents; deleting again is a replay | delete.go `Head.MarkDeleting`, `RunMarkDeleting` (`DeleteAuthority`) | `INV-SNAPK-DELETE-ORDER-001` | +| absent | deleted (tombstone) | the operator's remove-dependent, for a restore target without HEAD (never created, or a restore died between its two creates); one exclusive create, so a later HEAD create of the restore fails; a HEAD appearing first refuses | delete.go `OperatorReleaseDependent` (`TargetStore.CreateDeletedHead`) | `INV-SNAPK-TOMBSTONE-001`, `INV-SNAPK-HEAD-WRITE-001` | +| source: any live | source: target released | by the target's volume id, from every snapshot: from DeleteVolume once the target's HEAD is deleting, or from the operator's command once the target is deleted, of another id, no longer naming the source, or tombstoned; an absent target writes nothing | delete.go `Head.ReleaseDependent`, `RunReleaseDependent`, `OperatorReleaseDependent` | `INV-SNAPK-RELEASE-001`, `INV-SNAPK-RELEASE-CALLERS-001`, `INV-SNAPK-RELEASE-OPERATOR-001` | | deleting | deleted | after this volume is released from every source it names and its objects are deleted; deleted again is a replay; a live HEAD is refused | delete.go `Head.MarkDeleted`, `DeleteVolume` | `INV-SNAPK-DELETE-ORDER-001` | ## Part B. Invariant ledger From b81e0597d2d38ceb4450ba9cc4c0acf7bacc7341 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 24 Nov 2026 19:23:48 -0800 Subject: [PATCH 7/7] ci: run the spec trace check on a GitHub-hosted runner The check runs no PR code and needs no project host, but it queued behind the self-hosted test jobs; every PR's merge waited on that queue. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/.github/workflows/spec-trace.yml | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/seaweed-block/.github/workflows/spec-trace.yml b/seaweed-block/.github/workflows/spec-trace.yml index 7bd9bdaa40..25834070ec 100644 --- a/seaweed-block/.github/workflows/spec-trace.yml +++ b/seaweed-block/.github/workflows/spec-trace.yml @@ -22,10 +22,9 @@ concurrency: jobs: trace: name: spec trace - # Same-repository PRs use the project's self-hosted runners, as the test - # workflow does; fork PRs stay on a GitHub-hosted runner, whose shared queue - # can wait for hours. No PR code runs here either way. - runs-on: ${{ github.event.pull_request.head.repo.full_name == github.repository && 'tp04-seaweed-block' || 'ubuntu-latest' }} + # A GitHub-hosted runner: this check runs no PR code and needs no project + # host, so it does not queue behind the self-hosted test jobs. + runs-on: ubuntu-latest timeout-minutes: 5 steps: - name: Checkout base @@ -37,6 +36,12 @@ jobs: fetch-depth: 0 persist-credentials: false + - name: Set up Go + uses: actions/setup-go@924ae3a1cded613372ab5595356fb5720e22ba16 # v6.5.0 + with: + go-version-file: go.mod + cache: false + - name: Check spec trace env: BASE: ${{ github.event.pull_request.base.sha }}