From 249afe303aa2fa02a4c6a093dc2df6765143ee75 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 24 Nov 2026 18:14:22 -0800 Subject: [PATCH 1/2] layout: removal by mark and conditional delete (7') The removal no longer rests on a lease check before an unconditional delete, which a delete landing after the lease and a successor's commit defeated. Every object entry carries the session of its last writer and a mark. RemoveUnreachable plans after BeginClean, then for each unreachable candidate MARKs it (conditional on the metadata read for the plan, unmarked) and DELETEs it (conditional on that mark). Writing an object for a session (EnsureObject) creates it, or reuses an existing one by a conditional update that sets the session and clears any mark, so a reuse after the plan or after the mark makes the remover's write fail its own condition, however late it lands. A commit names only objects its own session wrote or reused, unmarked. The source guard now requires DeleteMarked as the remover's only removal, each immediately after a gate on its mark's error. Tests cover both reuse windows (after the plan, after the mark), another session's mark, the commit's session rule and the cleaning killed at each of its six writes. Co-Authored-By: Claude Opus 5.5 --- .../frontend/chunkstore/head_readers_test.go | 30 +- .../core/frontend/chunkstore/layout/commit.go | 53 ++-- .../frontend/chunkstore/layout/commit_test.go | 58 ++-- .../frontend/chunkstore/layout/guard_test.go | 117 ++++---- .../frontend/chunkstore/layout/objects.go | 87 ++++++ .../chunkstore/layout/objects_test.go | 189 ++++++++++++ .../core/frontend/chunkstore/layout/remove.go | 63 ++-- .../frontend/chunkstore/layout/remove_test.go | 271 ++++++++++-------- .../chunkstore/layout/session_test.go | 97 +++++-- .../frontend/chunkstore/layout/stale_test.go | 6 +- seaweed-block/docs/design/invariants.md | 13 +- 11 files changed, 680 insertions(+), 304 deletions(-) create mode 100644 seaweed-block/core/frontend/chunkstore/layout/objects.go create mode 100644 seaweed-block/core/frontend/chunkstore/layout/objects_test.go diff --git a/seaweed-block/core/frontend/chunkstore/head_readers_test.go b/seaweed-block/core/frontend/chunkstore/head_readers_test.go index 434da26d5c..05e5a59161 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/remove.go RemoveUnreachable -> ReadHead": "refuses ErrHeadAbsent and deletes nothing (probe LayoutRemoval)", + "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)", "core/frontend/chunkstore/volume_delete.go DeleteVolume -> ReadHead": "operator delete writes a deleting HEAD from nothing and completes (probe DeleteVolume)", @@ -271,11 +271,11 @@ func TestHeadReaders_AbsentHeadProbes(t *testing.T) { t.Fatal(err) } pool := &countingPool{} - if _, err := layout.RemoveUnreachable(ctx, &absentLayoutHead{}, r, pool, okLease{}, layout.HolderID{Epoch: 1, Holder: "h"}, "c", 0, []layout.ChunkName{layout.NameChunk(1, []byte("x"))}); !errors.Is(err, layout.ErrHeadAbsent) { + if _, err := layout.RemoveUnreachable(ctx, &absentLayoutHead{}, r, pool, layout.HolderID{Epoch: 1, Holder: "h"}, "c", 0, []layout.ChunkName{layout.NameChunk(1, []byte("x"))}); !errors.Is(err, layout.ErrHeadAbsent) { t.Fatalf("layout removal over an absent HEAD: %v; want ErrHeadAbsent", err) } - if pool.deletes != 0 { - t.Fatalf("layout removal over an absent HEAD deleted %d objects", pool.deletes) + if pool.writes != 0 { + t.Fatalf("layout removal over an absent HEAD wrote %d times to the objects", pool.writes) } }) t.Run("ForkReplay", func(t *testing.T) { @@ -312,10 +312,20 @@ func (a *absentLayoutHead) UpdateHead(context.Context, uint64, layout.Head) erro return nil } -type countingPool struct{ deletes int } +// countingPool is a layout object store that counts writes and holds +// nothing. +type countingPool struct{ writes int } -func (p *countingPool) DeleteObject(context.Context, string) error { p.deletes++; return nil } - -type okLease struct{} - -func (okLease) StillHeld(context.Context) error { return nil } +func (p *countingPool) Stat(context.Context, string) (layout.ObjectMeta, bool, error) { + return layout.ObjectMeta{}, false, nil +} +func (p *countingPool) Create(context.Context, string, []byte, string) error { p.writes++; return nil } +func (p *countingPool) Reuse(context.Context, string, layout.ObjectMeta, string) error { + p.writes++ + return nil +} +func (p *countingPool) Mark(context.Context, string, layout.ObjectMeta, string) error { + p.writes++ + return nil +} +func (p *countingPool) DeleteMarked(context.Context, string, string) error { p.writes++; return nil } diff --git a/seaweed-block/core/frontend/chunkstore/layout/commit.go b/seaweed-block/core/frontend/chunkstore/layout/commit.go index 3afbc378a1..ca60b41a95 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/commit.go +++ b/seaweed-block/core/frontend/chunkstore/layout/commit.go @@ -100,12 +100,14 @@ func (h Head) Commit(me HolderID, session string, root RootName, position uint64 return next, true, nil } -// RunCommit checks that every object the new root reaches is written (the -// new chunks of this volume against HEAD's current root, every segment, -// the root), then commits by one conditional update. Prev must build to -// HEAD's current root; a re-run after a lost reply finds the commit -// applied and writes nothing. -func RunCommit(ctx context.Context, st HeadStore, look Lookup, volRoot, vol string, me HolderID, req CommitRequest) (Head, error) { +// RunCommit checks that every object the new root reaches is written by +// this session and unmarked (the new chunks of this volume against HEAD's +// current root, every segment, the root: see EnsureObject), then commits +// by one conditional update. An object present but written by another +// session, or marked for removal, is not prepared: EnsureObject reuses it +// first. Prev must build to HEAD's current root; a re-run after a lost +// reply finds the commit applied and writes nothing. +func RunCommit(ctx context.Context, st HeadStore, os ObjectStore, vol string, me HolderID, req CommitRequest) (Head, error) { root, segs, err := rootOf(req.Next) if err != nil { return Head{}, err @@ -131,12 +133,15 @@ func RunCommit(ctx context.Context, st HeadStore, look Lookup, volRoot, vol stri return Head{}, false, ErrStaleBase } } - missing, err := MissingOwn(ctx, look, volRoot, vol, newOwn(vol, req.Prev, req.Next)) - if err != nil { - return Head{}, false, err + var rels []string + chunks := newOwn(vol, req.Prev, req.Next) + idx := make([]uint64, 0, len(chunks)) + for i := range chunks { + idx = append(idx, i) } - if len(missing) > 0 { - return Head{}, false, fmt.Errorf("%w: %d chunks, first %s", ErrNotPrepared, len(missing), missing[0]) + sort.Slice(idx, func(a, b int) bool { return idx[a] < idx[b] }) + for _, i := range idx { + rels = append(rels, chunks[i].Chunk.Path()) } names := make([]SegName, 0, len(segs)) for n := range segs { @@ -144,24 +149,18 @@ func RunCommit(ctx context.Context, st HeadStore, look Lookup, volRoot, vol stri } sort.Slice(names, func(a, b int) bool { return names[a].Shard < names[b].Shard }) for _, n := range names { - if err := present(ctx, look, volRoot, n.Path()); err != nil { - return Head{}, false, err - } + rels = append(rels, n.Path()) } - if err := present(ctx, look, volRoot, root.Path()); err != nil { - return Head{}, false, err + rels = append(rels, root.Path()) + for _, rel := range rels { + ok, err := ownedBySession(ctx, os, rel, req.Session) + if err != nil { + return Head{}, false, fmt.Errorf("layout: look up %s: %w", rel, err) + } + if !ok { + return Head{}, false, fmt.Errorf("%w: %s (absent, written by another session, or marked)", ErrNotPrepared, rel) + } } return h.Commit(me, req.Session, root, req.Position, req.Snapshot) }) } - -func present(ctx context.Context, look Lookup, volRoot, rel string) error { - ok, err := Present(ctx, look, volRoot, rel) - if err != nil { - return fmt.Errorf("layout: look up %s: %w", rel, err) - } - if !ok { - return fmt.Errorf("%w: %s", ErrNotPrepared, rel) - } - return nil -} diff --git a/seaweed-block/core/frontend/chunkstore/layout/commit_test.go b/seaweed-block/core/frontend/chunkstore/layout/commit_test.go index 5a2119b002..79044c537a 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/commit_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout/commit_test.go @@ -11,9 +11,9 @@ import ( const volRoot = "/swblock/chunks/v1" -// prepared writes (in the fake store) every object a commit of next needs: -// next's own chunks, its segments and its root. -func prepared(t *testing.T, f *fakeStore, next map[uint64]Ref) RootName { +// prepared writes (in the object store, as session) every object a commit +// of next needs: next's own chunks, its segments and its root. +func prepared(t *testing.T, f *memObjects, next map[uint64]Ref, session string) RootName { t.Helper() root, segs, err := Build(next) if err != nil { @@ -21,17 +21,17 @@ func prepared(t *testing.T, f *fakeStore, next map[uint64]Ref) RootName { } for i, r := range next { if r.Owner == "v1" { - f.have[path.Join(volRoot, next[i].Chunk.Path())] = true + f.put(next[i].Chunk.Path(), []byte("c"), session) } } for n := range segs { - f.have[path.Join(volRoot, n.Path())] = true + f.put(n.Path(), []byte("s"), session) } rn, _, err := NameRoot(root) if err != nil { t.Fatal(err) } - f.have[path.Join(volRoot, rn.Path())] = true + f.put(rn.Path(), []byte("r"), session) return rn } @@ -89,19 +89,19 @@ func TestCommit_Closure(t *testing.T) { // commitFixture: HEAD is snap(s1) at current root = prev's root; prev and // next share chunk 0 (unchanged), next changes chunk 3, adds chunk 10004 // and names chunk 7 of volume "src". -func commitFixture(t *testing.T) (*fakeStore, Head, CommitRequest) { +func commitFixture(t *testing.T) (*memObjects, Head, CommitRequest) { t.Helper() - f := &fakeStore{have: map[string]bool{}} + f := newMemObjects(volRoot) prev := manifest(ref("v1", 0, "a"), ref("v1", 3, "b")) - prevRoot := prepared(t, f, prev) + prevRoot := prepared(t, f, prev, "s0") next := manifest(ref("v1", 0, "a"), ref("v1", 3, "b2"), ref("v1", 10004, "c"), ref("src", 7, "d")) - prepared(t, f, next) + prepared(t, f, next, "s1") h := Head{Gen: 7, Epoch: 3, Holder: "srv-a", Activity: Activity{Kind: ActSnap, Session: "s1"}, Current: &prevRoot, Position: 40} return f, h, CommitRequest{Session: "s1", Prev: prev, Next: next, Position: 50, Snapshot: "hourly"} } -func runCommit(st HeadStore, f *fakeStore, req CommitRequest) (Head, error) { - return RunCommit(context.Background(), st, f.look, volRoot, "v1", me, req) +func runCommit(st HeadStore, f *memObjects, req CommitRequest) (Head, error) { + return RunCommit(context.Background(), st, f, "v1", me, req) } func TestRunCommit_LooksUpOnlyWhatIsNew(t *testing.T) { @@ -146,7 +146,7 @@ func TestRunCommit_RefusesUnwrittenObjects(t *testing.T) { case "root": p = root.Path() } - delete(f.have, path.Join(volRoot, p)) + delete(f.objs, path.Join(volRoot, p)) st := &memHead{h: &h} if _, err := runCommit(st, f, req); !errors.Is(err, ErrNotPrepared) { t.Fatalf("commit with its %s missing: %v; want ErrNotPrepared", what, err) @@ -179,9 +179,9 @@ func TestRunCommit_StaleBaseAndLookupFailure(t *testing.T) { t.Fatal("HEAD written by a refused commit") } // The first commit of a volume: no current root, no previous manifest. - f2 := &fakeStore{have: map[string]bool{}} + f2 := newMemObjects(volRoot) next := manifest(ref("v1", 1, "x")) - prepared(t, f2, next) + prepared(t, f2, next, "s1") h2 := Head{Gen: 1, Epoch: 3, Holder: "srv-a", Activity: Activity{Kind: ActSnap, Session: "s1"}} if got, err := runCommit(&memHead{h: &h2}, f2, CommitRequest{Session: "s1", Next: next, Position: 5}); err != nil || got.Current == nil { t.Fatalf("first commit: %+v %v", got, err) @@ -207,8 +207,8 @@ func TestRunCommit_InterruptAtEveryStep(t *testing.T) { // refused. func TestRunCommit_AfterAnEmptyPublishedRoot(t *testing.T) { ctx := context.Background() - f := &fakeStore{have: map[string]bool{}} - prepared(t, f, nil) + f := newMemObjects(volRoot) + prepared(t, f, nil, "s0") h := idleHead() st := &memHead{h: &h} if _, err := RunBegin(ctx, st, me, "s0"); err != nil { @@ -223,11 +223,12 @@ func TestRunCommit_AfterAnEmptyPublishedRoot(t *testing.T) { if _, err := RunBegin(ctx, st, me, "s1"); err != nil { t.Fatal(err) } + prepared(t, f, nil, "s1") // each session writes (reuses) what it commits if _, err := runCommit(st, f, CommitRequest{Session: "s1", Prev: map[uint64]Ref{}, Position: 1}); err != nil { t.Fatalf("empty -> empty: %v", err) } next := manifest(ref("v1", 1, "x")) - prepared(t, f, next) + prepared(t, f, next, "s2") if _, err := RunBegin(ctx, st, me, "s2"); err != nil { t.Fatal(err) } @@ -266,3 +267,24 @@ func TestAbort_AfterCommitLeavesTheCommit(t *testing.T) { t.Fatalf("Abort after the commit wrote or changed HEAD: %+v", st.h) } } + +// A commit names only objects its own session wrote or reused, unmarked: +// one written by another session, or marked by a cleaning, is not +// prepared until EnsureObject reuses it. +func TestRunCommit_NeedsObjectsOfItsOwnSession(t *testing.T) { + for _, meta := range []ObjectMeta{{Session: "s0"}, {Session: "s1", Mark: "c9"}} { + f, h, req := commitFixture(t) + rel := req.Next[10004].Chunk.Path() + f.objs[path.Join(volRoot, rel)].meta = meta + st := &memHead{h: &h} + if _, err := runCommit(st, f, req); !errors.Is(err, ErrNotPrepared) || st.updates != 0 { + t.Fatalf("object %+v: %v (%d writes); want ErrNotPrepared, nothing written", meta, err, st.updates) + } + if err := EnsureObject(context.Background(), f, rel, []byte("c"), "s1"); err != nil { + t.Fatal(err) + } + if _, err := runCommit(st, f, req); err != nil { + t.Fatalf("after EnsureObject reused it: %v", err) + } + } +} diff --git a/seaweed-block/core/frontend/chunkstore/layout/guard_test.go b/seaweed-block/core/frontend/chunkstore/layout/guard_test.go index 540797002a..ca861ff2be 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/guard_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout/guard_test.go @@ -179,27 +179,28 @@ func guardFindings(code map[string]map[string]bool, decl, tests map[string]bool) return bad } -// removerOrderFindings checks the removal half of the time premise in the -// sources: in RemoveUnreachable, every statement that calls a method named -// Delete* or Remove* is IMMEDIATELY preceded, in the same block, by a lease -// gate: an if statement whose init calls StillHeld and whose body returns -// on its error. A check whose result is ignored, one check reused for a -// second removal, and a removal method the scan does not list each fail. +// removerOrderFindings checks the removal rule (7') in the sources: in +// RemoveUnreachable the only removal call is DeleteMarked (a delete +// conditional on the remover's own mark), and each is IMMEDIATELY +// preceded, in the same block, by a mark gate: an if statement whose init +// calls Mark and whose body leaves on its error (return or continue). An +// unconditional delete, an ignored mark, one mark reused for a second +// delete and an unlisted removal method each fail. func removerOrderFindings(t *testing.T, srcs map[string]string) []string { t.Helper() - removes := func(n ast.Node) bool { - found := false + removals := func(n ast.Node) []string { + var names []string ast.Inspect(n, func(n ast.Node) bool { if c, ok := n.(*ast.CallExpr); ok { if sel, ok := c.Fun.(*ast.SelectorExpr); ok && (strings.HasPrefix(sel.Sel.Name, "Delete") || strings.HasPrefix(sel.Sel.Name, "Remove")) { - found = true + names = append(names, sel.Sel.Name) } } - return !found + return true }) - return found + return names } - leaseGate := func(st ast.Stmt) bool { + markGate := func(st ast.Stmt) bool { is, ok := st.(*ast.IfStmt) if !ok || is.Init == nil { return false @@ -213,7 +214,7 @@ func removerOrderFindings(t *testing.T, srcs map[string]string) []string { return false } sel, ok := call.Fun.(*ast.SelectorExpr) - if !ok || sel.Sel.Name != "StillHeld" { + if !ok || sel.Sel.Name != "Mark" { return false } errName, ok := as.Lhs[0].(*ast.Ident) @@ -224,12 +225,19 @@ func removerOrderFindings(t *testing.T, srcs map[string]string) []string { if x, ok := cond.X.(*ast.Ident); !ok || x.Name != errName.Name { return false } - for _, b := range is.Body.List { - if _, ok := b.(*ast.ReturnStmt); ok { - return true + leaves := false + ast.Inspect(is.Body, func(n ast.Node) bool { + switch x := n.(type) { + case *ast.ReturnStmt: + leaves = true + case *ast.BranchStmt: + if x.Tok == token.CONTINUE { + leaves = true + } } - } - return false + return !leaves + }) + return leaves } var bad []string for fname, src := range srcs { @@ -253,12 +261,18 @@ func removerOrderFindings(t *testing.T, srcs map[string]string) []string { case *ast.BlockStmt, *ast.RangeStmt, *ast.ForStmt: continue // their bodies are checked as their own blocks } - if !removes(st) { + names := removals(st) + if len(names) == 0 { continue } deletes++ - if i == 0 || !leaseGate(blk.List[i-1]) { - bad = append(bad, "RemoveUnreachable removes without a lease gate immediately before it (an if on StillHeld's error that returns)") + for _, name := range names { + if name != "DeleteMarked" { + bad = append(bad, "RemoveUnreachable calls "+name+": its only removal is DeleteMarked, conditional on its own mark") + } + } + if i == 0 || !markGate(blk.List[i-1]) { + bad = append(bad, "RemoveUnreachable removes without a mark gate immediately before it (an if on Mark's error that leaves)") } } return true @@ -328,49 +342,14 @@ func TestGuard_Controls(t *testing.T) { "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"}, - "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 { - for _, n := range names { - if err := x.DeleteObject(ctx, n); err != nil { - return err - } - } - return nil -}`, want: "without a lease gate immediately before it"}, - "lease check after the delete": {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 { - for _, n := range names { - if err := x.DeleteObject(ctx, n); err != nil { - return err - } - if err := h.StillHeld(ctx); err != nil { - return err - } - } - return nil -}`, want: "without a lease gate immediately before it"}, - "lease check once before the loop": {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 { - if err := h.StillHeld(ctx); err != nil { - return err - } - for _, n := range names { - if err := x.DeleteObject(ctx, n); err != nil { - return err - } - } - return nil -}`, want: "without a lease gate immediately before it"}, "claim without lease wait": {src: `func RunClaim(ctx context.Context, st HeadStore, lease LeaseWait, me HolderID) (Head, 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"}, - "ignored lease check": {file: "remove.go", src: removeVariant(t, "ignored"), want: "without a lease gate immediately before it"}, - "one check, two deletes": {file: "remove.go", src: removeVariant(t, "second"), want: "without a lease gate immediately before it"}, - "unlisted removal method": {file: "remove.go", src: removeVariant(t, "other"), want: "without a lease 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"}, "remover method value": {src: `type p interface{ RemoveName(string) } func w(x p) { f := x.RemoveName; f("o") }`, want: "only RemoveUnreachable removes"}, } { @@ -396,17 +375,21 @@ func removeVariant(t *testing.T, mode string) string { t.Fatal(err) } src := strings.ReplaceAll(string(b), "\r\n", "\n") - gate := "if err := lease.StillHeld(ctx); err != nil {\n\t\t\treturn removed, fmt.Errorf(\"%w: %v\", ErrLeaseLost, err)\n\t\t}" + gate := "if err := os.Mark(ctx, c.Path(), plan, session); err != nil {" + if !strings.Contains(src, gate) { + t.Fatal("remove.go mark gate not found") + } switch mode { case "ignored": - if !strings.Contains(src, gate) { - t.Fatal("remove.go lease gate not found") - } - src = strings.Replace(src, gate, "_ = lease.StillHeld(ctx)", 1) + i := strings.Index(src, gate) + j := strings.Index(src[i:], "\n\t\t}\n") + i + len("\n\t\t}\n") + src = src[:i] + "_ = os.Mark(ctx, c.Path(), plan, session)\n" + src[j:] case "second": - src = strings.Replace(src, "removed = append(removed, c)", "_ = pool.DeleteObject(ctx, c.Path())\n\t\tremoved = append(removed, c)", 1) + src = strings.Replace(src, "removed = append(removed, c)", "_ = os.DeleteMarked(ctx, c.Path(), session)\n\t\tremoved = append(removed, c)", 1) case "other": - src = strings.Replace(src, "removed = append(removed, c)", "_ = pool.RemoveOther(ctx, c.Path())\n\t\tremoved = append(removed, c)", 1) + src = strings.Replace(src, "removed = append(removed, c)", "_ = os.RemoveOther(ctx, c.Path())\n\t\tremoved = append(removed, c)", 1) + case "unconditional": + src = strings.Replace(src, "if err := os.DeleteMarked(ctx, c.Path(), session); err != nil {", "if err := os.DeleteObject(ctx, c.Path()); err != nil {", 1) } i := strings.Index(src, ")\n") return src[i+2:] diff --git a/seaweed-block/core/frontend/chunkstore/layout/objects.go b/seaweed-block/core/frontend/chunkstore/layout/objects.go new file mode 100644 index 0000000000..1a63a9995b --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout/objects.go @@ -0,0 +1,87 @@ +package layout + +import ( + "context" + "errors" + "fmt" +) + +// ObjectMeta is what an object entry (chunk, segment, root) carries besides +// its bytes: the session of its last writer and a removal mark (the +// session of a cleaning that planned to remove it; empty when unmarked). +type ObjectMeta struct { + Session string + Mark string +} + +// ErrExists is returned by ObjectStore.Create when the entry exists. +var ErrExists = errors.New("layout: object exists") + +// ObjectStore holds a volume's objects by path relative to the volume +// root. Every change of an existing entry is conditional on its metadata, +// so a late write fails its own condition instead of undoing a newer one. +type ObjectStore interface { + // Stat returns an entry's metadata; a missing entry is found=false. + Stat(ctx context.Context, rel string) (meta ObjectMeta, found bool, err error) + // Create writes a new entry exclusively (data first, entry after), + // with session as its writer; ErrExists if the entry exists. + Create(ctx context.Context, rel string, data []byte, session string) error + // Reuse sets session as the writer and clears the mark, only if the + // entry's metadata is still expect (ErrPrecondition otherwise). + Reuse(ctx context.Context, rel string, expect ObjectMeta, session string) error + // Mark sets mark, only if the entry's metadata is still expect + // (ErrPrecondition otherwise). + Mark(ctx context.Context, rel string, expect ObjectMeta, mark string) error + // DeleteMarked deletes the entry only if it carries mark + // (ErrPrecondition otherwise); a missing entry succeeds. + DeleteMarked(ctx context.Context, rel string, mark string) error +} + +// maxEnsureRounds bounds EnsureObject's retries when another writer moves +// the entry between its read and its conditional write. +const maxEnsureRounds = 8 + +// EnsureObject is transition 3, the write of one object for a session: an +// absent entry is created with the session as writer; an existing one +// (content-named, so already complete) is reused by a conditional update +// that sets the session and clears any mark, so a cleaning's planned mark +// or delete of it fails its own condition from then on. An entry already +// written by this session and unmarked needs nothing. +func EnsureObject(ctx context.Context, os ObjectStore, rel string, data []byte, session string) error { + if session == "" { + return errors.New("layout: EnsureObject needs a session") + } + for round := 0; round < maxEnsureRounds; round++ { + meta, found, err := os.Stat(ctx, rel) + if err != nil { + return err + } + switch { + case !found: + err = os.Create(ctx, rel, data, session) + if errors.Is(err, ErrExists) { + continue + } + return err + case meta.Session == session && meta.Mark == "": + return nil + default: + err = os.Reuse(ctx, rel, meta, session) + if errors.Is(err, ErrPrecondition) { + continue + } + return err + } + } + return fmt.Errorf("layout: %s kept moving under %d attempts", rel, maxEnsureRounds) +} + +// ownedBySession reports whether rel exists, carries session as its writer +// and is unmarked: an object a commit of that session may name. +func ownedBySession(ctx context.Context, os ObjectStore, rel, session string) (bool, error) { + meta, found, err := os.Stat(ctx, rel) + if err != nil { + return false, err + } + return found && meta.Session == session && meta.Mark == "", nil +} diff --git a/seaweed-block/core/frontend/chunkstore/layout/objects_test.go b/seaweed-block/core/frontend/chunkstore/layout/objects_test.go new file mode 100644 index 0000000000..19bae22a9f --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout/objects_test.go @@ -0,0 +1,189 @@ +package layout + +import ( + "context" + "errors" + "path" + "testing" +) + +// memObject is one entry: its bytes and metadata. +type memObject struct { + data []byte + meta ObjectMeta +} + +// memObjects is an ObjectStore of one volume, keyed by full path under +// root, with an optional failing path, a record of every Stat, and a kill +// point counted over its writes (Create, Reuse, Mark, DeleteMarked). +type memObjects struct { + root string + objs map[string]*memObject + fail string + asked []string + writes []string + killAt int + after bool + dead bool + hook func(op, rel string) // runs before a write applies + // afterStat runs after a Stat of rel returned (a writer acting between + // a read and the conditional write that follows it). + afterStat func(rel string) +} + +func newMemObjects(root string) *memObjects { + return &memObjects{root: root, objs: map[string]*memObject{}} +} + +func (m *memObjects) full(rel string) string { return path.Join(m.root, rel) } + +func (m *memObjects) Stat(_ context.Context, rel string) (ObjectMeta, bool, error) { + if m.dead { + return ObjectMeta{}, false, errKilled + } + p := m.full(rel) + m.asked = append(m.asked, p) + if p == m.fail { + return ObjectMeta{}, false, errors.New("filer unavailable") + } + o, ok := m.objs[p] + if m.afterStat != nil { + defer m.afterStat(rel) + } + if !ok { + return ObjectMeta{}, false, nil + } + return o.meta, true, nil +} + +// write runs op's effect under the kill point: before it applies, or +// applied with its reply lost. +func (m *memObjects) write(op, rel string, apply func() error) error { + if m.dead { + return errKilled + } + if m.hook != nil { + m.hook(op, rel) + } + m.writes = append(m.writes, op+" "+rel) + kill := len(m.writes) == m.killAt + if kill && !m.after { + m.dead = true + return errKilled + } + err := apply() + if kill { + m.dead = true + return errKilled + } + return err +} + +func (m *memObjects) Create(_ context.Context, rel string, data []byte, session string) error { + return m.write("create", rel, func() error { + if _, ok := m.objs[m.full(rel)]; ok { + return ErrExists + } + m.objs[m.full(rel)] = &memObject{data: append([]byte(nil), data...), meta: ObjectMeta{Session: session}} + return nil + }) +} + +func (m *memObjects) Reuse(_ context.Context, rel string, expect ObjectMeta, session string) error { + return m.write("reuse", rel, func() error { + o, ok := m.objs[m.full(rel)] + if !ok || o.meta != expect { + return ErrPrecondition + } + o.meta = ObjectMeta{Session: session} + return nil + }) +} + +func (m *memObjects) Mark(_ context.Context, rel string, expect ObjectMeta, mark string) error { + return m.write("mark", rel, func() error { + o, ok := m.objs[m.full(rel)] + if !ok || o.meta != expect { + return ErrPrecondition + } + o.meta.Mark = mark + return nil + }) +} + +func (m *memObjects) DeleteMarked(_ context.Context, rel string, mark string) error { + return m.write("delete", rel, func() error { + o, ok := m.objs[m.full(rel)] + if !ok { + return nil + } + if o.meta.Mark != mark { + return ErrPrecondition + } + delete(m.objs, m.full(rel)) + return nil + }) +} + +// put stores an object directly (fixture setup, no kill point). +func (m *memObjects) put(rel string, data []byte, session string) { + m.objs[m.full(rel)] = &memObject{data: append([]byte(nil), data...), meta: ObjectMeta{Session: session}} +} + +func (m *memObjects) has(rel string) bool { _, ok := m.objs[m.full(rel)]; return ok } + +// data returns every object's bytes by full path (for the reachability +// walk and the reader). +func (m *memObjects) data() map[string][]byte { + out := map[string][]byte{} + for p, o := range m.objs { + out[p] = o.data + } + return out +} + +func (m *memObjects) fetch(_ context.Context, p string) ([]byte, bool, error) { + if m.dead { + return nil, false, errKilled + } + o, ok := m.objs[p] + if !ok { + return nil, false, nil + } + return o.data, true, nil +} + +func (m *memObjects) restart() { m.dead, m.killAt = false, 0 } + +// EnsureObject: an absent object is created by the session; an existing +// one, written by another session or marked, is reused (session set, mark +// cleared); one already the session's and unmarked is left; a racing +// writer between the read and the conditional write is retried. +func TestEnsureObject(t *testing.T) { + ctx := context.Background() + o := newMemObjects("/v") + if err := EnsureObject(ctx, o, "pool/0/a", []byte("x"), "s1"); err != nil || o.objs["/v/pool/0/a"].meta != (ObjectMeta{Session: "s1"}) { + t.Fatalf("create: %v %+v", err, o.objs["/v/pool/0/a"]) + } + writes := len(o.writes) + if err := EnsureObject(ctx, o, "pool/0/a", []byte("x"), "s1"); err != nil || len(o.writes) != writes { + t.Fatalf("own unmarked object rewritten: %v (%d writes)", err, len(o.writes)-writes) + } + o.objs["/v/pool/0/a"].meta = ObjectMeta{Session: "c9", Mark: "c9"} + if err := EnsureObject(ctx, o, "pool/0/a", []byte("x"), "s2"); err != nil || o.objs["/v/pool/0/a"].meta != (ObjectMeta{Session: "s2"}) { + t.Fatalf("reuse of a marked object: %v %+v; want session s2, mark cleared", err, o.objs["/v/pool/0/a"].meta) + } + raced := false + o.hook = func(op, rel string) { + if op == "reuse" && !raced { + raced = true + o.objs["/v/pool/0/a"].meta = ObjectMeta{Session: "other"} + } + } + if err := EnsureObject(ctx, o, "pool/0/a", []byte("x"), "s3"); err != nil || o.objs["/v/pool/0/a"].meta.Session != "s3" { + t.Fatalf("reuse racing another writer: %v %+v; want retried and s3", err, o.objs["/v/pool/0/a"].meta) + } + if err := EnsureObject(ctx, o, "pool/0/b", nil, ""); err == nil { + t.Fatal("EnsureObject without a session accepted") + } +} diff --git a/seaweed-block/core/frontend/chunkstore/layout/remove.go b/seaweed-block/core/frontend/chunkstore/layout/remove.go index b3ce03db59..8f656dfa23 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/remove.go +++ b/seaweed-block/core/frontend/chunkstore/layout/remove.go @@ -7,34 +7,22 @@ import ( "sort" ) -// ErrLeaseLost: the remover's own lease is no longer valid; nothing more -// is removed. -var ErrLeaseLost = errors.New("layout: remover's lease is not valid") - -// LeaseHeld is the remover's half of the time premise: it returns nil only -// while the caller's own lease is valid. Remove calls it immediately before -// every delete. -type LeaseHeld interface { - StillHeld(ctx context.Context) error -} - -// Pool deletes one object of the volume by its path relative to the volume -// root; deleting an absent object succeeds. -type Pool interface { - DeleteObject(ctx context.Context, rel string) error -} - -// RemoveUnreachable is transition 7 for one pool shard: for the holder -// with clean(session) open at HEAD's epoch, every candidate chunk of shard -// that no root in HEAD (current and every snapshot) names in this -// volume's pool is deleted, each delete preceded by a check of the -// remover's own lease. HEAD is read once, after BeginClean: while clean is -// open no commit can add a root, and a claim that voids the cleaning waits -// for this lease to end, which the check before every delete sees. It -// returns the names it deleted, in index order. -func RemoveUnreachable(ctx context.Context, st HeadStore, r *Reader, pool Pool, lease LeaseHeld, me HolderID, session string, shard uint64, candidates []ChunkName) ([]ChunkName, error) { - if lease == nil || pool == nil || r == nil { - return nil, errors.New("layout: removal needs a reader, a pool and a lease check") +// RemoveUnreachable is the cleaning's removal (transition 7') for one pool +// shard: for the holder with its own clean(session) open at HEAD's epoch, +// each candidate chunk that no root in HEAD (current or any snapshot) +// names in this volume's pool is removed in two conditional writes on its +// own entry: MARK, expected the metadata read when the plan was made and +// unmarked, sets the mark to this session; DELETE, expected that mark, +// deletes it. A writer that reuses the object in between (EnsureObject: +// new session, mark cleared) makes the mark or the delete fail its own +// condition, however late it lands; no lease reasoning is needed. A +// candidate already marked by another session, or moved, is left alone. +// Chunks a restore target names stay live here: the source's snapshot +// root names them, and that snapshot stays in HEAD while it has dependents. +// It returns the names it deleted, in index order. +func RemoveUnreachable(ctx context.Context, st HeadStore, r *Reader, os ObjectStore, me HolderID, session string, shard uint64, candidates []ChunkName) ([]ChunkName, error) { + if os == nil || r == nil { + return nil, errors.New("layout: removal needs a reader and an object store") } h, found, err := st.ReadHead(ctx) if err != nil { @@ -60,10 +48,23 @@ func RemoveUnreachable(ctx context.Context, st HeadStore, r *Reader, pool Pool, if Shard(c.Index) != shard || live[c] { continue } - if err := lease.StillHeld(ctx); err != nil { - return removed, fmt.Errorf("%w: %v", ErrLeaseLost, err) + plan, found, err := os.Stat(ctx, c.Path()) + if err != nil { + return removed, err } - if err := pool.DeleteObject(ctx, c.Path()); err != nil { + if !found || plan.Mark != "" { + continue + } + if err := os.Mark(ctx, c.Path(), plan, session); err != nil { + if errors.Is(err, ErrPrecondition) { + continue // reused or marked since the plan + } + return removed, fmt.Errorf("layout: mark %s: %w", c, err) + } + if err := os.DeleteMarked(ctx, c.Path(), session); err != nil { + if errors.Is(err, ErrPrecondition) { + continue // reused since the mark + } return removed, fmt.Errorf("layout: delete %s: %w", c, err) } removed = append(removed, c) diff --git a/seaweed-block/core/frontend/chunkstore/layout/remove_test.go b/seaweed-block/core/frontend/chunkstore/layout/remove_test.go index 31a901b9d3..696950f90f 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/remove_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout/remove_test.go @@ -10,97 +10,53 @@ import ( const removeBase = "/swblock/chunks" // volRoot = removeBase/v1 -// objPool is a volume's objects for removal tests: Fetch reads them, Pool -// deletes them, with an optional kill point counted over deletes. -type objPool struct { - objs map[string][]byte - deletes []string - killAt int - after bool - dead bool -} - -func (o *objPool) fetch(_ context.Context, p string) ([]byte, bool, error) { - if o.dead { - return nil, false, errKilled - } - b, ok := o.objs[p] - return b, ok, nil -} - -func (o *objPool) DeleteObject(_ context.Context, rel string) error { - if o.dead { - return errKilled - } - o.deletes = append(o.deletes, rel) - kill := len(o.deletes) == o.killAt - if kill && !o.after { - o.dead = true - return errKilled - } - delete(o.objs, path.Join(volRoot, rel)) - if kill { - o.dead = true - return errKilled - } - return nil -} - -type fakeHeld struct { - calls int - lostAt int // the n-th call (1-based) and later fail; 0 = never -} - -func (l *fakeHeld) StillHeld(context.Context) error { - l.calls++ - if l.lostAt > 0 && l.calls >= l.lostAt { - return errors.New("lease lapsed") - } - return nil -} - // removeFixture: HEAD clean(c1) at epoch 3; the current root names chunks // 0 and 3, the snapshot "daily" an older image naming chunks 0 and 2 (all // in shard 0); chunks 5 and 7 are in the pool but no root names them, and -// chunk 10001 (shard 1) is unreferenced too. -func removeFixture(t *testing.T) (*objPool, *Head, []ChunkName, []ChunkName) { +// chunk 10001 (shard 1) is unreferenced too. Every object was written by +// session s0. +func removeFixture(t *testing.T) (*memObjects, *Head, []ChunkName, []ChunkName) { t.Helper() - objs := map[string][]byte{} + data := map[string][]byte{} cur := manifest(ref("v1", 0, "a"), ref("v1", 3, "b")) old := manifest(ref("v1", 0, "a"), ref("v1", 2, "c")) - curRoot := writeImage(t, objs, cur, map[uint64][]byte{0: []byte("a"), 3: []byte("b")}) - oldRoot := writeImage(t, objs, old, map[uint64][]byte{0: []byte("a"), 2: []byte("c")}) + curRoot := writeImage(t, data, cur, map[uint64][]byte{0: []byte("a"), 3: []byte("b")}) + oldRoot := writeImage(t, data, old, map[uint64][]byte{0: []byte("a"), 2: []byte("c")}) var orphans []ChunkName for i, d := range map[uint64]string{5: "e", 7: "f", 10001: "g"} { c := NameChunk(i, []byte(d)) - objs[path.Join(volRoot, c.Path())] = []byte(d) + data[path.Join(volRoot, c.Path())] = []byte(d) orphans = append(orphans, c) } + o := newMemObjects(volRoot) + for p, b := range data { + o.objs[p] = &memObject{data: b, meta: ObjectMeta{Session: "s0"}} + } h := &Head{Gen: 7, Epoch: 3, Holder: "srv-a", Activity: Activity{Kind: ActClean, Session: "c1"}, Current: &curRoot, Snapshots: map[string]Snapshot{"daily": {Root: oldRoot}}} live := []ChunkName{cur[0].Chunk, cur[3].Chunk, old[2].Chunk} - return &objPool{objs: objs}, h, live, orphans + return o, h, live, orphans } -func removeShard0(t *testing.T, st HeadStore, o *objPool, l LeaseHeld, session string, cands []ChunkName) ([]ChunkName, error) { +func removeShard0(t *testing.T, st HeadStore, o *memObjects, session string, cands []ChunkName) ([]ChunkName, error) { t.Helper() r, err := NewReader(removeBase, "v1", o.fetch) if err != nil { t.Fatal(err) } - return RemoveUnreachable(context.Background(), st, r, o, l, me, session, 0, cands) + return RemoveUnreachable(context.Background(), st, r, o, me, session, 0, cands) } -func inPool(o *objPool, c ChunkName) bool { _, ok := o.objs[path.Join(volRoot, c.Path())]; return ok } +func inPool(o *memObjects, c ChunkName) bool { return o.has(c.Path()) } -// Only names no root in HEAD reaches are removed: the current root's and -// a snapshot's chunks stay, shard 0's orphans go, the shard-1 orphan is -// not touched by a shard-0 pass; the lease is checked before every delete. +// Only names no root in HEAD reaches are removed, each by a mark then a +// delete conditional on that mark: the current root's and a snapshot's +// chunks stay, shard 0's orphans go, the shard-1 orphan is not touched by +// a shard-0 pass. func TestRemoveUnreachable_RemovesOnlyWhatNoRootNames(t *testing.T) { o, h, live, orphans := removeFixture(t) - l := &fakeHeld{} cands := append(append([]ChunkName(nil), live...), orphans...) - removed, err := removeShard0(t, &memHead{h: h}, o, l, "c1", cands) + removed, err := removeShard0(t, &memHead{h: h}, o, "c1", cands) if err != nil { t.Fatal(err) } @@ -112,10 +68,11 @@ func TestRemoveUnreachable_RemovesOnlyWhatNoRootNames(t *testing.T) { t.Fatalf("reachable chunk %s was removed", c) } } - if l.calls != len(o.deletes) { - t.Fatalf("lease checks %d for %d deletes; want one before each", l.calls, len(o.deletes)) + want := []string{"mark " + removed[0].Path(), "delete " + removed[0].Path(), "mark " + removed[1].Path(), "delete " + removed[1].Path()} + if fmt.Sprint(o.writes) != fmt.Sprint(want) { + t.Fatalf("writes %v; want each removal as a mark then its conditional delete: %v", o.writes, want) } - if err := reachableMissing(h, o.objs); err != nil { + if err := reachableMissing(h, o.data()); err != nil { t.Fatalf("after removal HEAD reaches a missing object: %v", err) } for _, c := range orphans { @@ -139,41 +96,114 @@ func TestRemoveUnreachable_RefusedOutsideItsCleaning(t *testing.T) { } { o, h, _, orphans := removeFixture(t) tc.edit(h) - if _, err := removeShard0(t, &memHead{h: h}, o, &fakeHeld{}, "c1", orphans); !errors.Is(err, tc.want) || len(o.deletes) != 0 { - t.Errorf("%s: %v, %d deletes; want %v and none", name, err, len(o.deletes), tc.want) + if _, err := removeShard0(t, &memHead{h: h}, o, "c1", orphans); !errors.Is(err, tc.want) || len(o.writes) != 0 { + t.Errorf("%s: %v, %d writes; want %v and none", name, err, len(o.writes), tc.want) } } o, _, _, orphans := removeFixture(t) - if _, err := removeShard0(t, &memHead{}, o, &fakeHeld{}, "c1", orphans); !errors.Is(err, ErrHeadAbsent) || len(o.deletes) != 0 { - t.Errorf("absent HEAD: %v, %d deletes", err, len(o.deletes)) + if _, err := removeShard0(t, &memHead{}, o, "c1", orphans); !errors.Is(err, ErrHeadAbsent) || len(o.writes) != 0 { + t.Errorf("absent HEAD: %v, %d writes", err, len(o.writes)) } } -// A lease that lapses mid-pass stops the removal before the next delete. -func TestRemoveUnreachable_StopsWhenTheLeaseLapses(t *testing.T) { +// The race the conditional writes close: a successor (after a claim that +// voided this cleaning) reuses an orphan the old remover planned to remove, +// between the old plan and its mark, or between its mark and its delete, +// and commits a root naming it. The old mark or the old delete fails its +// condition; the object stays. +func TestRemoveUnreachable_AReuseDefeatsALateMarkOrDelete(t *testing.T) { + for _, between := range []string{"mark", "delete"} { + t.Run("reuse before the old "+between, func(t *testing.T) { + o, h, _, orphans := removeFixture(t) + var target ChunkName + for _, c := range orphans { + if c.Index == 5 { + target = c + } + } + o.hook = func(op, rel string) { + if op == between && rel == target.Path() { + o.hook = nil + if err := EnsureObject(context.Background(), o, rel, []byte("e"), "successor"); err != nil { + t.Fatal(err) + } + } + } + if _, err := removeShard0(t, &memHead{h: h}, o, "c1", orphans); err != nil { + t.Fatal(err) + } + if !inPool(o, target) || o.objs[path.Join(volRoot, target.Path())].meta != (ObjectMeta{Session: "successor"}) { + t.Fatalf("chunk %s after a reuse before the old %s: present %t meta %+v; want kept, the successor's", target, between, inPool(o, target), o.objs[path.Join(volRoot, target.Path())]) + } + }) + } +} + +// The window the mark's condition is for: a successor reuses an orphan +// right after the remover read it for its plan. The mark, conditional on +// the metadata of the plan (not a fresh read), fails; the object stays. +func TestRemoveUnreachable_AReuseAfterThePlanDefeatsTheMark(t *testing.T) { o, h, _, orphans := removeFixture(t) - removed, err := removeShard0(t, &memHead{h: h}, o, &fakeHeld{lostAt: 2}, "c1", orphans) - if !errors.Is(err, ErrLeaseLost) || len(removed) != 1 || len(o.deletes) != 1 { - t.Fatalf("lease lapsing before the second delete: removed %v, %v; want one delete then ErrLeaseLost", removed, err) + var target ChunkName + for _, c := range orphans { + if c.Index == 5 { + target = c + } + } + o.afterStat = func(rel string) { + if rel == target.Path() { + o.afterStat = nil + if err := EnsureObject(context.Background(), o, rel, []byte("e"), "successor"); err != nil { + t.Fatal(err) + } + } + } + if _, err := removeShard0(t, &memHead{h: h}, o, "c1", orphans); err != nil { + t.Fatal(err) + } + if !inPool(o, target) { + t.Fatalf("chunk %s reused after the plan was removed", target) + } +} + +// A candidate already marked by another session is left alone. +func TestRemoveUnreachable_LeavesAnotherSessionsMark(t *testing.T) { + o, h, _, orphans := removeFixture(t) + for _, c := range orphans { + if c.Index == 5 { + o.objs[path.Join(volRoot, c.Path())].meta.Mark = "c0" + } + } + removed, err := removeShard0(t, &memHead{h: h}, o, "c1", orphans) + if err != nil || len(removed) != 1 || removed[0].Index != 7 { + t.Fatalf("removed %v %v; want only chunk 7 (5 carries another session's mark)", removed, err) } } // A root or segment HEAD names that cannot be read stops the pass before -// any delete: nothing is removed on a partial view. +// any write: nothing is removed on a partial view. func TestRemoveUnreachable_NothingRemovedOnAPartialView(t *testing.T) { o, h, _, orphans := removeFixture(t) delete(o.objs, path.Join(volRoot, h.Snapshots["daily"].Root.Path())) - if _, err := removeShard0(t, &memHead{h: h}, o, &fakeHeld{}, "c1", orphans); !errors.Is(err, ErrMissing) || len(o.deletes) != 0 { - t.Fatalf("unreadable snapshot root: %v, %d deletes; want ErrMissing and none", err, len(o.deletes)) + if _, err := removeShard0(t, &memHead{h: h}, o, "c1", orphans); !errors.Is(err, ErrMissing) || len(o.writes) != 0 { + t.Fatalf("unreadable snapshot root: %v, %d writes; want ErrMissing and none", err, len(o.writes)) } } +func (v *memVolume) fetch(_ context.Context, p string) ([]byte, bool, error) { + if v.dead { + return nil, false, errKilled + } + b, ok := v.objects[p] + return b, ok, nil +} + // cleaningPass is the whole cleaning operation as the holder runs it after // a (re)start: a cleaning of its own left open is ended first, then // BeginClean, the removal of shard 0, EndClean. -func cleaningPass(st *memVolume, o *objPool, session string, cands []ChunkName) error { +func cleaningPass(v *memVolume, session string, cands []ChunkName) error { ctx := context.Background() - h, found, err := st.ReadHead(ctx) + h, found, err := v.ReadHead(ctx) if err != nil { return err } @@ -181,86 +211,83 @@ func cleaningPass(st *memVolume, o *objPool, session string, cands []ChunkName) return ErrHeadAbsent } if h.Activity.Kind == ActClean && h.heldBy(me) { - if _, err := RunEndClean(ctx, st, me, h.Activity.Session); err != nil { + if _, err := RunEndClean(ctx, v, me, h.Activity.Session); err != nil { return err } } - if _, err := RunBeginClean(ctx, st, me, session); err != nil { + if _, err := RunBeginClean(ctx, v, me, session); err != nil { return err } - r, err := NewReader(removeBase, "v1", o.fetch) + r, err := NewReader(removeBase, "v1", v.fetch) if err != nil { return err } - if _, err := RemoveUnreachable(ctx, st, r, o, &fakeHeld{}, me, session, 0, cands); err != nil { + if _, err := RemoveUnreachable(ctx, v, r, v, me, session, 0, cands); err != nil { return err } - _, err = RunEndClean(ctx, st, me, session) + _, err = RunEndClean(ctx, v, me, session) return err } // Interrupt at every step of the cleaning operation: killed at each of its -// writes (BeginClean, every delete, EndClean), before the write applies -// and after it applied with its reply lost; at no point does HEAD reach a -// missing object, and the restarted holder ends idle with every orphan of -// shard 0 removed and every reachable object present. +// writes (BeginClean, each mark, each conditional delete, EndClean), before +// the write applies and after it applied with its reply lost; at no point +// does HEAD reach a missing object, and the restarted holder (a new +// session) ends idle with every orphan of shard 0 removed and every +// reachable object present. A mark left by the killed session is cleared +// by nothing but a reuse, so a marked orphan stays until then. func TestCleaningPass_InterruptAtEveryStep(t *testing.T) { - fresh := func() (*memVolume, *objPool, []ChunkName, []ChunkName) { + fresh := func() (*memVolume, []ChunkName, []ChunkName) { o, h, live, orphans := removeFixture(t) h.Activity = Activity{Kind: ActIdle} - return &memVolume{head: &memHead{h: h}, objects: o.objs}, o, live, orphans + v := &memVolume{head: &memHead{h: h}, objects: map[string][]byte{}, metas: map[string]ObjectMeta{}} + for p, ob := range o.objs { + v.objects[p] = ob.data + v.metas[p] = ob.meta + } + return v, live, orphans } - v, o, live, orphans := fresh() + v, live, orphans := fresh() cands := append(append([]ChunkName(nil), live...), orphans...) - if err := cleaningPass(v, o, "c1", cands); err != nil { + if err := cleaningPass(v, "c1", cands); err != nil { t.Fatal(err) } - steps := len(v.writes) + len(o.deletes) - if steps != 4 { - t.Fatalf("the cleaning made %d writes; want 4 (BeginClean, two deletes, EndClean)", steps) + steps := append([]string(nil), v.writes...) + if len(steps) != 6 { + t.Fatalf("the cleaning made %d writes: %v; want 6 (BeginClean, mark and delete twice, EndClean)", len(steps), steps) } - // Kill points: HEAD writes are counted by memVolume, deletes by objPool; - // step k is the k-th write of either kind in run order. - order := []string{"head", "delete", "delete", "head"} - for k := range order { + for k := range steps { for _, after := range []bool{false, true} { - t.Run(fmt.Sprintf("step%d %s/after=%t", k+1, order[k], after), func(t *testing.T) { - v, o, live, orphans := fresh() - nth := 0 - for _, kind := range order[:k+1] { - if kind == order[k] { - nth++ - } - } - if order[k] == "head" { - v.killAt, v.after = nth, after - } else { - o.killAt, o.after = nth, after - } - if err := cleaningPass(v, o, "c1", cands); !errors.Is(err, errKilled) { + t.Run(fmt.Sprintf("step%d %s/after=%t", k+1, steps[k], after), func(t *testing.T) { + v, live, orphans := fresh() + v.killAt, v.after = k+1, after + if err := cleaningPass(v, "c1", cands); !errors.Is(err, errKilled) { t.Fatalf("killed run: %v", err) } - if err := reachableMissing(v.head.h, o.objs); err != nil { + if err := reachableMissing(v.head.h, v.objects); err != nil { t.Fatalf("after the kill HEAD reaches a missing object: %v", err) } - v.dead, v.killAt, o.dead, o.killAt = false, 0, false, 0 - if err := cleaningPass(v, o, "c2", cands); err != nil { + v.dead, v.killAt = false, 0 + v.head.restart() + if err := cleaningPass(v, "c2", cands); err != nil { t.Fatalf("re-run: %v", err) } if v.head.h.Activity.Kind != ActIdle { t.Fatalf("activity after the re-run: %+v", v.head.h.Activity) } for _, c := range orphans { - if c.Index != 10001 && inPool(o, c) { - t.Fatalf("orphan %s still present", c) + p := path.Join(volRoot, c.Path()) + _, present := v.objects[p] + if c.Index != 10001 && present && v.meta(p).Mark != "c1" { + t.Fatalf("orphan %s still present and not held by the killed session's mark", c) } } for _, c := range live { - if !inPool(o, c) { + if _, ok := v.objects[path.Join(volRoot, c.Path())]; !ok { t.Fatalf("reachable %s removed", c) } } - if err := reachableMissing(v.head.h, o.objs); err != nil { + if err := reachableMissing(v.head.h, v.objects); err != nil { t.Fatal(err) } }) diff --git a/seaweed-block/core/frontend/chunkstore/layout/session_test.go b/seaweed-block/core/frontend/chunkstore/layout/session_test.go index c8e89926de..129b7e48cb 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/session_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout/session_test.go @@ -13,6 +13,7 @@ import ( type memVolume struct { head *memHead objects map[string][]byte + metas map[string]ObjectMeta writes []string // every write, in order killAt int after bool @@ -54,35 +55,91 @@ func (v *memVolume) UpdateHead(ctx context.Context, gen uint64, next Head) error return nil } -func (v *memVolume) look(_ context.Context, dir, name string) (bool, error) { - if v.dead { - return false, errKilled +// memVolume is also the volume's ObjectStore: every object write counts +// toward the same kill point as HEAD's. An object a fixture stored without +// metadata reads as written by session "s0". +func (v *memVolume) meta(p string) ObjectMeta { + if m, ok := v.metas[p]; ok { + return m } - _, ok := v.objects[path.Join(dir, name)] - return ok, nil + return ObjectMeta{Session: "s0"} } -// put writes an object if absent (a content name that exists is complete, -// so a present one is skipped). -func (v *memVolume) put(rel string, b []byte) error { - p := path.Join(volRoot, rel) +func (v *memVolume) Stat(_ context.Context, rel string) (ObjectMeta, bool, error) { if v.dead { - return errKilled + return ObjectMeta{}, false, errKilled } - if _, ok := v.objects[p]; ok { - return nil + p := path.Join(volRoot, rel) + if _, ok := v.objects[p]; !ok { + return ObjectMeta{}, false, nil } - apply, die, err := v.write("create " + rel) + return v.meta(p), true, nil +} + +// objWrite applies f under the shared kill point. +func (v *memVolume) objWrite(what string, f func() error) error { + apply, die, err := v.write(what) if err != nil { return err } if apply { - v.objects[p] = append([]byte(nil), b...) + err = f() } if die { return errKilled } - return nil + return err +} + +func (v *memVolume) Create(_ context.Context, rel string, data []byte, session string) error { + p := path.Join(volRoot, rel) + return v.objWrite("create "+rel, func() error { + if _, ok := v.objects[p]; ok { + return ErrExists + } + v.objects[p] = append([]byte(nil), data...) + v.metas[p] = ObjectMeta{Session: session} + return nil + }) +} + +func (v *memVolume) Reuse(_ context.Context, rel string, expect ObjectMeta, session string) error { + p := path.Join(volRoot, rel) + return v.objWrite("reuse "+rel, func() error { + if _, ok := v.objects[p]; !ok || v.meta(p) != expect { + return ErrPrecondition + } + v.metas[p] = ObjectMeta{Session: session} + return nil + }) +} + +func (v *memVolume) Mark(_ context.Context, rel string, expect ObjectMeta, mark string) error { + p := path.Join(volRoot, rel) + return v.objWrite("mark "+rel, func() error { + if _, ok := v.objects[p]; !ok || v.meta(p) != expect { + return ErrPrecondition + } + m := v.meta(p) + m.Mark = mark + v.metas[p] = m + return nil + }) +} + +func (v *memVolume) DeleteMarked(_ context.Context, rel string, mark string) error { + p := path.Join(volRoot, rel) + return v.objWrite("delete "+rel, func() error { + if _, ok := v.objects[p]; !ok { + return nil + } + if v.meta(p).Mark != mark { + return ErrPrecondition + } + delete(v.objects, p) + delete(v.metas, p) + return nil + }) } // snapshotSession is the whole snapshot transaction as the holder runs it @@ -115,7 +172,7 @@ func snapshotSession(v *memVolume, session string, data map[uint64][]byte, req C return fmt.Errorf("unexpected current root %s", cur) } for i, r := range newOwn("v1", req.Prev, req.Next) { - if err := v.put(r.Chunk.Path(), data[i]); err != nil { + if err := EnsureObject(ctx, v, r.Chunk.Path(), data[i], session); err != nil { return err } } @@ -124,7 +181,7 @@ func snapshotSession(v *memVolume, session string, data map[uint64][]byte, req C return err } for n, b := range segs { - if err := v.put(n.Path(), b); err != nil { + if err := EnsureObject(ctx, v, n.Path(), b, session); err != nil { return err } } @@ -132,11 +189,11 @@ func snapshotSession(v *memVolume, session string, data map[uint64][]byte, req C if err != nil { return err } - if err := v.put(rn.Path(), rb); err != nil { + if err := EnsureObject(ctx, v, rn.Path(), rb, session); err != nil { return err } req.Session = session - _, err = RunCommit(ctx, v, v.look, volRoot, "v1", me, req) + _, err = RunCommit(ctx, v, v, "v1", me, req) return err } @@ -162,7 +219,7 @@ func sessionFixture(t *testing.T) (func() *memVolume, map[uint64][]byte, CommitR prevRoot := writeImage(t, objs, prev, prevData) h := Head{Gen: 7, Epoch: 3, Holder: "srv-a", Activity: Activity{Kind: ActIdle}, Current: &prevRoot, Position: 40, Snapshots: map[string]Snapshot{"daily": {Root: prevRoot}}} - return &memVolume{head: &memHead{h: &h}, objects: objs} + return &memVolume{head: &memHead{h: &h}, objects: objs, metas: map[string]ObjectMeta{}} } return fresh, data, CommitRequest{Prev: prev, Next: next, Position: 50, Snapshot: "hourly"} } diff --git a/seaweed-block/core/frontend/chunkstore/layout/stale_test.go b/seaweed-block/core/frontend/chunkstore/layout/stale_test.go index 69e0d9a518..dcb7ee16b6 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/stale_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout/stale_test.go @@ -73,9 +73,9 @@ func TestHolderFunctions_RefuseAStaleHolder(t *testing.T) { if err != nil { t.Fatal(err) } - _, err = RemoveUnreachable(context.Background(), &memHead{h: h}, r, o, &fakeHeld{}, c, "c1", 0, orphans) - if !errors.Is(err, ErrNotHolder) || len(o.deletes) != 0 { - t.Errorf("RemoveUnreachable by %s: %v, %d deletes; want ErrNotHolder and none", who, err, len(o.deletes)) + _, err = RemoveUnreachable(context.Background(), &memHead{h: h}, r, o, c, "c1", 0, orphans) + if !errors.Is(err, ErrNotHolder) || len(o.writes) != 0 { + t.Errorf("RemoveUnreachable by %s: %v, %d writes; want ErrNotHolder and none", who, err, len(o.writes)) } } covered := map[string]bool{"RemoveUnreachable": true} diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 5f3c99c8bf..918edde458 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -541,11 +541,11 @@ stateDiagram-v2 | any | idle at epoch e | e above HEAD's epoch (the same epoch and server is a replay); every older holder's lease has ended, checked after the read and before the update | claim.go `Head.Claim`, `RunClaim` (`LeaseWait.OldLeaseEnded`) | `INV-SNAPK-CLAIM-LEASE-001` | | 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` | +| 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; 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` | ## Part B. Invariant ledger -342 rows: 271 ACTIVE, 67 STUB, 4 ARCHIVED; 15 kept from the internal ledger, 327 new. +343 rows: 272 ACTIVE, 67 STUB, 4 ARCHIVED; 15 kept from the internal ledger, 328 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. @@ -1086,7 +1086,7 @@ Notes: |---|---|---|---|---|---|---| | `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-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 lease-gated RemoveUnreachable. | 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-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. | 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 | | `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 | @@ -1095,9 +1095,10 @@ Notes: | `INV-SNAPK-CLAIM-LEASE-001` | A claim takes HEAD only at a newer epoch and only after every older holder's lease has ended (checked after the read, before the update); it voids any open session or cleaning, so the old holder's commit, abort and begin are refused. | M9 any → idle (Claim) | `core/frontend/chunkstore/layout` `claim.go` `RunClaim`, `Head.Claim` | `TestClaim_Closure`, `TestRunClaim_WaitsForTheOldLease`, `TestRunClaim_VoidsTheOldSession`, `TestRunClaim_InterruptAtEveryStep` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-CLEAN-EXCL-001` | A cleaning and a snapshot exclude each other through HEAD's one activity field, so no name is removed while a snapshot is open; a claim voids an open cleaning. | M9 idle → clean → idle | `core/frontend/chunkstore/layout` `clean.go` `Head.BeginClean`, `Head.EndClean` | `TestBeginClean_Closure`, `TestEndClean_Closure`, `TestEndClean_IdleMeansNoActivityRemains`, `TestClean_ExcludesSnapshot`, `TestRunBeginClean_InterruptAtEveryStep`, `TestRunEndClean_InterruptAtEveryStep` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `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 (current or snapshot) names it, and only after the remover's own lease is checked immediately before that delete. | M9 clean → clean (RemoveUnreachable) | `core/frontend/chunkstore/layout` `remove.go` `RemoveUnreachable` | `TestRemoveUnreachable_RemovesOnlyWhatNoRootNames`, `TestCleaningPass_InterruptAtEveryStep`, `TestHolderFunctions_RefuseAStaleHolder` | — (the snapshot kernel model is not in this repository) | ACTIVE | -| `INV-SNAPK-REMOVE-STOP-001` | A lapsed lease stops a removal pass before the next delete; an unreadable root or segment stops it before any delete; a snapshot open on the volume, another cleaning or idle refuses it. | M9 clean → clean (RemoveUnreachable) | `core/frontend/chunkstore/layout` `remove.go` `RemoveUnreachable` | `TestRemoveUnreachable_StopsWhenTheLeaseLapses`, `TestRemoveUnreachable_NothingRemovedOnAPartialView`, `TestRemoveUnreachable_RefusedOutsideItsCleaning` | — (the snapshot kernel model is not in this repository) | ACTIVE | -| `INV-SNAPK-REMOVE-GUARD-001` | A source scan requires, immediately before every Delete or Remove call in RemoveUnreachable, an if on StillHeld's error that returns: an ignored check, a reused check or an unlisted removal method fails. | M9 clean → clean (RemoveUnreachable) | `core/frontend/chunkstore/layout` (source scan of `remove.go`) | `TestGuard_WritersTransitionsAndRemovers`, `TestGuard_Controls` | — (the snapshot kernel model is not in this repository) | ACTIVE | +| `INV-SNAPK-REMOVE-MARK-001` | A pool name is removed only inside the holder's own cleaning, only when no root in HEAD names it, by a mark conditional on the metadata read for the plan and then a delete conditional on that mark. | M9 clean → clean (RemoveUnreachable) | `core/frontend/chunkstore/layout` `remove.go` `RemoveUnreachable` | `TestRemoveUnreachable_RemovesOnlyWhatNoRootNames`, `TestCleaningPass_InterruptAtEveryStep`, `TestHolderFunctions_RefuseAStaleHolder` | — (the snapshot kernel model is not in this repository) | ACTIVE | +| `INV-SNAPK-REMOVE-STOP-001` | A reuse of an object after the plan, or after the mark, makes the remover's mark or delete fail its condition, however late it lands; an unreadable root stops the pass before any write; an open snapshot refuses it. | M9 clean → clean (RemoveUnreachable) | `core/frontend/chunkstore/layout` `remove.go` `RemoveUnreachable` | `TestRemoveUnreachable_AReuseAfterThePlanDefeatsTheMark`, `TestRemoveUnreachable_AReuseDefeatsALateMarkOrDelete`, `TestRemoveUnreachable_NothingRemovedOnAPartialView`, `TestRemoveUnreachable_RefusedOutsideItsCleaning` | — (the snapshot kernel model is not in this repository) | ACTIVE | +| `INV-SNAPK-REMOVE-GUARD-001` | A source scan requires DeleteMarked as RemoveUnreachable's only removal, each immediately after an if on its Mark's error that leaves: an unconditional delete, an ignored mark, a reused mark or another method fails. | M9 clean → clean (RemoveUnreachable) | `core/frontend/chunkstore/layout` (source scan of `remove.go`) | `TestGuard_WritersTransitionsAndRemovers`, `TestGuard_Controls` | — (the snapshot kernel model is not in this repository) | ACTIVE | +| `INV-SNAPK-REUSE-001` | Writing an object for a session creates it, or reuses an existing one by a conditional update that sets the session and clears any mark; a commit names only objects its session wrote or reused, unmarked. | M9 snap → idle (Upload, Commit) | `core/frontend/chunkstore/layout` `objects.go` `EnsureObject`; `commit.go` `RunCommit` | `TestEnsureObject`, `TestRunCommit_NeedsObjectsOfItsOwnSession`, `TestSnapshotSession_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 f5f25c1639be9336565d08a6e76fdcc93f708421 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 24 Nov 2026 18:17:04 -0800 Subject: [PATCH 2/2] layout: a HEAD is read only for its own volume; holders name a claim id DecodeHead now takes the id from the same directory's VOLUME and refuses a HEAD carrying another volume id (ErrIdentity): a HEAD left by an interrupted delete, or created late by an old restore, under a name since given to another volume, is never read as this volume's. HEAD's check refuses a holder without a claim id. Co-Authored-By: Claude Opus 5.5 --- .../core/frontend/chunkstore/layout/head.go | 18 +++++- .../frontend/chunkstore/layout/head_test.go | 63 ++++++++++++++----- seaweed-block/docs/design/invariants.md | 3 +- 3 files changed, 63 insertions(+), 21 deletions(-) diff --git a/seaweed-block/core/frontend/chunkstore/layout/head.go b/seaweed-block/core/frontend/chunkstore/layout/head.go index fd8b71024d..ffa9035721 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/head.go +++ b/seaweed-block/core/frontend/chunkstore/layout/head.go @@ -121,6 +121,9 @@ func (h Head) check() error { 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) } @@ -174,9 +177,15 @@ func (h Head) Encode() ([]byte, error) { return json.Marshal(d) } -// DecodeHead parses canonical HEAD bytes; unknown fields and non-canonical -// bytes are refused. -func DecodeHead(b []byte, gen uint64) (Head, error) { +// DecodeHead parses canonical HEAD bytes for the volume whose VOLUME +// record carries volume; unknown fields and non-canonical bytes are +// refused, and so is a HEAD of another volume id (ErrIdentity): one left +// by an interrupted delete, or created late by an old restore, under a +// name since given to another volume. Every reader of HEAD decodes here. +func DecodeHead(b []byte, gen uint64, volume VolumeID) (Head, error) { + if volume.IsZero() { + return Head{}, errors.New("layout: DecodeHead needs the volume's id from its VOLUME") + } var d headDoc dec := json.NewDecoder(bytes.NewReader(b)) dec.DisallowUnknownFields() @@ -224,6 +233,9 @@ func DecodeHead(b []byte, gen uint64) (Head, error) { if !bytes.Equal(again, b) { return Head{}, fmt.Errorf("%w: HEAD bytes are not canonical", ErrMalformed) } + if h.VolumeID != volume { + return Head{}, fmt.Errorf("%w: HEAD carries volume id %s, VOLUME has %s", ErrIdentity, h.VolumeID, volume) + } return h, nil } diff --git a/seaweed-block/core/frontend/chunkstore/layout/head_test.go b/seaweed-block/core/frontend/chunkstore/layout/head_test.go index 372ac5f82f..3db4af07e9 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/head_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout/head_test.go @@ -46,7 +46,7 @@ func TestHead_GoldenEncodingRoundTrip(t *testing.T) { if string(b) != want { t.Fatalf("encoding\n got %s\nwant %s", b, want) } - back, err := DecodeHead(b, 9) + back, err := DecodeHead(b, 9, idFor("v1")) if err != nil { t.Fatal(err) } @@ -70,18 +70,18 @@ func TestHead_Refusals(t *testing.T) { snap := func(ds []Dependent) map[string]Snapshot { return map[string]Snapshot{"n": {Root: rn, Dependents: ds}} } ab := deps(rn, "a", "b") for name, h := range map[string]Head{ - "no volume id": {Epoch: 1, Holder: "a", Activity: Activity{Kind: ActIdle}}, - "idle with a session": {VolumeID: v, Epoch: 1, Holder: "a", Activity: Activity{Kind: ActIdle, Session: "s"}}, - "snap without a session": {VolumeID: v, Epoch: 1, Holder: "a", Activity: Activity{Kind: ActSnap}}, - "unknown activity": {VolumeID: v, Epoch: 1, Holder: "a", Activity: Activity{Kind: "open"}}, - "epoch zero": {VolumeID: v, Holder: "a", Activity: Activity{Kind: ActIdle}}, + "no volume id": {Epoch: 1, Holder: "a", ClaimID: "k", Activity: Activity{Kind: ActIdle}}, + "idle with a session": {VolumeID: v, Epoch: 1, Holder: "a", ClaimID: "k", Activity: Activity{Kind: ActIdle, Session: "s"}}, + "snap without a session": {VolumeID: v, Epoch: 1, Holder: "a", ClaimID: "k", Activity: Activity{Kind: ActSnap}}, + "unknown activity": {VolumeID: v, Epoch: 1, Holder: "a", ClaimID: "k", Activity: Activity{Kind: "open"}}, + "epoch zero": {VolumeID: v, Holder: "a", ClaimID: "k", Activity: Activity{Kind: ActIdle}}, "no holder": {VolumeID: v, Epoch: 1, Activity: Activity{Kind: ActIdle}}, - "dependents unordered": {VolumeID: v, Epoch: 1, Holder: "a", Activity: Activity{Kind: ActIdle}, Snapshots: snap([]Dependent{ab[1], ab[0]})}, - "dependent twice": {VolumeID: v, Epoch: 1, Holder: "a", Activity: Activity{Kind: ActIdle}, Snapshots: snap([]Dependent{ab[0], ab[0]})}, - "bad dependent name": {VolumeID: v, Epoch: 1, Holder: "a", Activity: Activity{Kind: ActIdle}, Snapshots: snap([]Dependent{{Target: "a/b", TargetID: idFor("x"), Root: rn}})}, - "dependent without id": {VolumeID: v, Epoch: 1, Holder: "a", Activity: Activity{Kind: ActIdle}, Snapshots: snap([]Dependent{{Target: "a", Root: rn}})}, - "dependent of another root": {VolumeID: v, Epoch: 1, Holder: "a", Activity: Activity{Kind: ActIdle}, Snapshots: snap([]Dependent{{Target: "a", TargetID: idFor("a"), Root: other}})}, - "too many snapshots": {VolumeID: v, Epoch: 1, Holder: "a", Activity: Activity{Kind: ActIdle}, Snapshots: many}, + "dependents unordered": {VolumeID: v, Epoch: 1, Holder: "a", ClaimID: "k", Activity: Activity{Kind: ActIdle}, Snapshots: snap([]Dependent{ab[1], ab[0]})}, + "dependent twice": {VolumeID: v, Epoch: 1, Holder: "a", ClaimID: "k", Activity: Activity{Kind: ActIdle}, Snapshots: snap([]Dependent{ab[0], ab[0]})}, + "bad dependent name": {VolumeID: v, Epoch: 1, Holder: "a", ClaimID: "k", Activity: Activity{Kind: ActIdle}, Snapshots: snap([]Dependent{{Target: "a/b", TargetID: idFor("x"), Root: rn}})}, + "dependent without id": {VolumeID: v, Epoch: 1, Holder: "a", ClaimID: "k", Activity: Activity{Kind: ActIdle}, Snapshots: snap([]Dependent{{Target: "a", Root: rn}})}, + "dependent of another root": {VolumeID: v, Epoch: 1, Holder: "a", ClaimID: "k", Activity: Activity{Kind: ActIdle}, Snapshots: snap([]Dependent{{Target: "a", TargetID: idFor("a"), Root: other}})}, + "too many snapshots": {VolumeID: v, Epoch: 1, Holder: "a", ClaimID: "k", Activity: Activity{Kind: ActIdle}, Snapshots: many}, } { if _, err := h.Encode(); !errors.Is(err, ErrMalformed) { t.Errorf("%s: %v; want ErrMalformed", name, err) @@ -96,7 +96,7 @@ func TestHead_Refusals(t *testing.T) { "short volume id": strings.Replace(string(good), idFor("v1").String(), "abc", 1), "not json": "HEAD", } { - if _, err := DecodeHead([]byte(b), 1); !errors.Is(err, ErrMalformed) { + if _, err := DecodeHead([]byte(b), 1, idFor("v1")); !errors.Is(err, ErrMalformed) { t.Errorf("decode %s: %v; want ErrMalformed", name, err) } } @@ -162,7 +162,7 @@ func (m *memHead) ReadHead(context.Context) (Head, bool, error) { return Head{}, false, nil } b, _ := m.h.Encode() - h, err := DecodeHead(b, m.h.Gen) + h, err := DecodeHead(b, m.h.Gen, m.h.VolumeID) return h, true, err } @@ -385,9 +385,9 @@ func TestHead_RefusesInvalidUTF8(t *testing.T) { bad := "a\xff" for name, h := range map[string]Head{ "holder": {Epoch: 1, Holder: bad, Activity: Activity{Kind: ActIdle}}, - "session": {Epoch: 1, Holder: "a", VolumeID: idFor("v1"), Activity: Activity{Kind: ActSnap, Session: bad}}, - "snapshot": {Epoch: 1, Holder: "a", VolumeID: idFor("v1"), Activity: Activity{Kind: ActIdle}, Snapshots: map[string]Snapshot{bad: {Root: rn}}}, - "dependent": {Epoch: 1, Holder: "a", VolumeID: idFor("v1"), Activity: Activity{Kind: ActIdle}, Snapshots: map[string]Snapshot{"n": {Root: rn, Dependents: []Dependent{{Target: bad, TargetID: idFor("x"), Root: rn}}}}}, + "session": {Epoch: 1, Holder: "a", ClaimID: "k", VolumeID: idFor("v1"), Activity: Activity{Kind: ActSnap, Session: bad}}, + "snapshot": {Epoch: 1, Holder: "a", ClaimID: "k", VolumeID: idFor("v1"), Activity: Activity{Kind: ActIdle}, Snapshots: map[string]Snapshot{bad: {Root: rn}}}, + "dependent": {Epoch: 1, Holder: "a", ClaimID: "k", VolumeID: idFor("v1"), Activity: Activity{Kind: ActIdle}, Snapshots: map[string]Snapshot{"n": {Root: rn, Dependents: []Dependent{{Target: bad, TargetID: idFor("x"), Root: rn}}}}}, "claim id": {Epoch: 1, Holder: "a", ClaimID: bad, VolumeID: idFor("v1"), Activity: Activity{Kind: ActIdle}}, } { if _, err := h.Encode(); !errors.Is(err, ErrMalformed) { @@ -400,3 +400,32 @@ func TestHead_RefusesInvalidUTF8(t *testing.T) { t.Fatalf("Begin with an invalid UTF-8 session: %v, HEAD %+v; want refused, nothing written", err, st.h.Activity) } } + +// A HEAD is read only for the volume whose VOLUME carries its volume id: a +// HEAD left by an interrupted delete, or created late by an old restore, +// under a name since given to another volume, is refused (ErrIdentity). +func TestDecodeHead_RefusesAnotherVolumesHead(t *testing.T) { + b, err := idleHead().Encode() + if err != nil { + t.Fatal(err) + } + if _, err := DecodeHead(b, 1, idFor("v1")); err != nil { + t.Fatalf("HEAD of this volume: %v", err) + } + if _, err := DecodeHead(b, 1, idFor("v1 again")); !errors.Is(err, ErrIdentity) { + t.Fatalf("HEAD under a name now holding another volume: %v; want ErrIdentity", err) + } + if _, err := DecodeHead(b, 1, VolumeID{}); err == nil { + t.Fatal("DecodeHead without the volume's id accepted") + } +} + +// A HEAD naming a holder names its claim id too: a holder without one +// would fail closed only at its next claim. +func TestHead_HolderNeedsAClaimID(t *testing.T) { + h := idleHead() + h.ClaimID = "" + if _, err := h.Encode(); !errors.Is(err, ErrMalformed) { + t.Fatalf("HEAD with a holder and no claim id: %v; want ErrMalformed", err) + } +} diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index cdb0d53efa..d9b9361a9a 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -545,7 +545,7 @@ stateDiagram-v2 ## Part B. Invariant ledger -347 rows: 276 ACTIVE, 67 STUB, 4 ARCHIVED; 15 kept from the internal ledger, 332 new. +348 rows: 277 ACTIVE, 67 STUB, 4 ARCHIVED; 15 kept from the internal ledger, 333 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. @@ -1100,6 +1100,7 @@ Notes: | `INV-SNAPK-REMOVE-GUARD-001` | A source scan requires DeleteMarked as RemoveUnreachable's only removal, each immediately after an if on its Mark's error that leaves: an unconditional delete, an ignored mark, a reused mark or another method fails. | M9 clean → clean (RemoveUnreachable) | `core/frontend/chunkstore/layout` (source scan of `remove.go`) | `TestGuard_WritersTransitionsAndRemovers`, `TestGuard_Controls` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-REUSE-001` | Writing an object for a session creates it, or reuses an existing one by a conditional update that sets the session and clears any mark; a commit names only objects its session wrote or reused, unmarked. | M9 snap → idle (Upload, Commit) | `core/frontend/chunkstore/layout` `objects.go` `EnsureObject`; `commit.go` `RunCommit` | `TestEnsureObject`, `TestRunCommit_NeedsObjectsOfItsOwnSession`, `TestSnapshotSession_InterruptAtEveryStep` | — (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 and refuses to encode without it. | Content-named layout; M9 every transition | `core/frontend/chunkstore/layout` `volume.go` `Volume`, `VolumeID`; `head.go` `Head.check` | `TestVolumeID_RandomAndParsed`, `TestVolume_GoldenEncodingRoundTrip`, `TestHead_GoldenEncodingRoundTrip`, `TestHead_Refusals` | — (the snapshot kernel model is not in this repository) | ACTIVE | +| `INV-SNAPK-HEAD-ID-001` | HEAD is decoded only for the volume whose VOLUME carries its volume id; a HEAD of another id, left by an interrupted delete or an old restore under a reused name, is ErrIdentity; a holder without a claim id is malformed. | M9 every transition | `core/frontend/chunkstore/layout` `head.go` `DecodeHead`, `Head.check` | `TestDecodeHead_RefusesAnotherVolumesHead`, `TestHead_HolderNeedsAClaimID` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-REF-ID-001` | Every chunk reference in a segment carries its owner's volume id; a read checks it against the owner's VOLUME before fetching (another id is ErrIdentity), and the remover tells its own chunks by its VOLUME id. | Content-named layout | `core/frontend/chunkstore/layout` `layout.go` `Segment.Encode`; `read.go` `Image.Chunk`; `remove.go` | `TestSegment_EncodeRefusals`, `TestRead_ForeignChunkNeedsTheOwnersVolumeID`, `TestRemoveUnreachable_NeedsItsOwnVolumeID` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-DEP-ID-001` | Every dependent records the target's volume id and the root of the snapshot it depends on; a dependent without the id, or of another root, is refused. | M9 snapshots and dependents | `core/frontend/chunkstore/layout` `head.go` `Head.check` | `TestHead_Refusals`, `TestHead_GoldenEncodingRoundTrip` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `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 |