Merge 7', identity and owned deletes; start: fresh across a crash, deleting refused, cure named

A root counts as fresh from its creation until its restore's base is
durable, across any crash in between, so a restart continues the
restore (tested); a deleting volume does not start at the holder's own
epoch or above (the claim refuses it; tested now that both are on one
branch); a stale-root refusal names its cure: after a clean stop the old
directory holds nothing the published image lacks, clear it and start on
a fresh root (a planned move away and back).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
pingqiuandClaude Opus 5.5 committed 2026-11-24 18:21:33 -08:00
commit d32af23cae
17 files changed
+913 -367

No files matched your search

@@ -42,7 +42,7 @@ var headReaders = map[string]string{
"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/start.go Start -> ReadHead": "refuses ErrHeadAbsent and creates nothing (probe LayoutStart)",
"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)",
@@ -273,11 +273,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("LayoutOperatorRelease", func(t *testing.T) {
@@ -347,13 +347,27 @@ 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 }
func (p *countingPool) DeleteOfVolume(context.Context, string, layout.VolumeID) error {
p.writes++
return nil
}
// presentLayoutHead is a layout HEAD store whose HEAD is present (a live,
// idle volume); it counts updates.
@@ -361,7 +375,7 @@ 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
return layout.Head{Gen: 1, VolumeID: id, Epoch: 1, Holder: "h", ClaimID: "k", Activity: layout.Activity{Kind: layout.ActIdle}}, true, nil
}
func (p *presentLayoutHead) UpdateHead(context.Context, uint64, layout.Head) error {
@@ -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
}
@@ -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", ClaimID: "k-a", VolumeID: idFor("v1"), 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", ClaimID: "k-a", VolumeID: idFor("v1"), 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)
}
}
}
@@ -123,12 +123,14 @@ func RunReleaseDependent(ctx context.Context, source HeadStore, target VolumeID)
// 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
// 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, pool Pool, objects []string) error {
if gone == nil || pool == nil {
return errors.New("layout: delete needs a holder check and a pool")
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")
}
if err := gone.NoHolder(ctx); err != nil {
return fmt.Errorf("%w: %v", ErrHolderActive, err)
@@ -142,7 +144,10 @@ func DeleteVolume(ctx context.Context, st HeadStore, gone HolderGone, id VolumeI
}
}
for _, rel := range objects {
if err := pool.DeleteObject(ctx, rel); err != nil {
if err := os.DeleteOfVolume(ctx, rel, id); err != nil {
if errors.Is(err, ErrPrecondition) {
continue // the name holds another volume's object now
}
return fmt.Errorf("layout: delete %s: %w", rel, err)
}
}
@@ -93,8 +93,8 @@ func TestDeleting_RefusesEveryHolderStep(t *testing.T) {
}
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))
if _, err := removeShard0(t, &memHead{h: rh}, o, "c1", orphans); !errors.Is(err, ErrVolumeDeleting) || len(o.writes) != 0 {
t.Fatalf("removal over a deleting HEAD: %v, %d writes", err, len(o.writes))
}
}
@@ -158,13 +158,45 @@ func newDeleteWorld() *deleteWorld {
return &deleteWorld{t: &memHead{h: &tgt}, src: &memHead{h: &src}, objs: objs, rels: rels}
}
// objects returns the target's objects as an object store of volume t.
func (w *deleteWorld) objects() *memObjects {
o := newMemObjects(volRoot)
o.volume = idFor("t")
for p, b := range w.objs {
o.objs[p] = &memObject{data: b, meta: ObjectMeta{Session: "s0", Volume: o.volume}}
}
return o
}
// A late delete of a finished volume delete never removes the object of a
// volume created again under the name: the delete is conditional on the
// entry's volume id, and the new volume's entry carries another.
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 {
t.Fatal(err)
}
o.volume = idFor("t again") // the name holds a new volume, which writes the same content name
if err := o.Create(ctx, w.rels[0], []byte("o"), "n1"); err != nil {
t.Fatal(err)
}
if err := o.DeleteOfVolume(ctx, w.rels[0], idFor("t")); !errors.Is(err, ErrPrecondition) {
t.Fatalf("the old run's late delete: %v; want ErrPrecondition", err)
}
if !o.has(w.rels[0]) {
t.Fatal("the old run's late delete removed the new volume's object")
}
}
// 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}
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 {
t.Fatalf("delete while held: %v (%d HEAD writes)", err, w.t.updates)
}
@@ -195,7 +227,7 @@ func TestDeleteVolume_InterruptAtEveryStep(t *testing.T) {
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}
o := w.objects()
nth := 0
for _, kind := range order[:k+1] {
if kind == order[k] {
@@ -129,10 +129,10 @@ func owners(m map[string]bool) []string {
// 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
// DeleteVolume, whose steps run in the delete's order: no holder, HEAD
// deleting, the dependents released, the objects deleted, HEAD
// RemoveUnreachable, whose only removal is DeleteMarked, each right
// after a gate on its Mark's error, and in DeleteVolume, whose steps run
// in the delete's order: no holder, HEAD deleting, the dependents
// released, the objects deleted (conditional on the volume id), HEAD
// deleted; see removerOrderFindings and deleteOrderFindings.
//
// These are syntactic checks of this package's own files: they see any
@@ -190,7 +190,7 @@ func guardFindings(code map[string]map[string]bool, decl, tests map[string]bool)
if strings.HasPrefix(name, "Delete") || strings.HasPrefix(name, "Remove") {
for _, fn := range owners(by) {
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")
bad = append(bad, fn+" uses "+name+": only RemoveUnreachable (mark-gated) and DeleteVolume (after HEAD deleting and the dependents released) remove")
}
}
}
@@ -199,27 +199,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
@@ -233,7 +234,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)
@@ -244,12 +245,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 {
@@ -273,12 +281,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
@@ -294,10 +308,10 @@ 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,
// DeleteObject, RunMarkDeleted.
// DeleteOfVolume, RunMarkDeleted.
func deleteOrderFindings(t *testing.T, srcs map[string]string) []string {
t.Helper()
steps := []string{"NoHolder", "RunMarkDeleting", "RunReleaseDependent", "DeleteObject", "RunMarkDeleted"}
steps := []string{"NoHolder", "RunMarkDeleting", "RunReleaseDependent", "DeleteOfVolume", "RunMarkDeleted"}
var bad []string
for fname, src := range srcs {
file, err := parser.ParseFile(token.NewFileSet(), fname, src, 0)
@@ -401,48 +415,12 @@ 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 (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 {
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"},
func w(ctx context.Context, x p) error { return x.DeleteObject(ctx, "o") }`, want: "only RemoveUnreachable (mark-gated) and DeleteVolume"},
"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"},
"delete removes the pool before releasing dependents": {file: "delete.go", src: `type p interface{ DeleteObject(context.Context, string) error }
"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) }
func RunMarkDeleted(ctx context.Context, st HeadStore) (Head, error) { return runTransition(ctx, st, nil) }
@@ -451,15 +429,15 @@ func DeleteVolume(ctx context.Context, st HeadStore, x g, id VolumeID, srcs []He
_ = x.NoHolder(ctx)
_, _ = RunMarkDeleting(ctx, st)
for _, o := range objs {
_ = pool.DeleteObject(ctx, o)
_ = pool.DeleteOfVolume(ctx, o, id)
}
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 }
}`, 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) }
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) }
@@ -469,7 +447,7 @@ func DeleteVolume(ctx context.Context, st HeadStore, id VolumeID, srcs []HeadSto
_, _ = RunReleaseDependent(ctx, s, id)
}
for _, o := range objs {
_ = pool.DeleteObject(ctx, o)
_ = pool.DeleteOfVolume(ctx, o, id)
}
_, _ = RunMarkDeleted(ctx, st)
return nil
@@ -478,12 +456,13 @@ 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"},
"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"},
"claim outside Start": {src: `func w(ctx context.Context, st HeadStore, l LeaseWait, me HolderID) { _, _ = RunClaim(ctx, st, l, me) }`, want: "a claim is made only by Start"},
"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"},
func w(x p) { f := x.RemoveName; f("o") }`, want: "only RemoveUnreachable (mark-gated) and DeleteVolume"},
} {
srcs := packageSources(t, false)
file := c.file
@@ -507,17 +486,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:]
@@ -128,6 +128,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)
}
@@ -181,9 +184,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()
@@ -231,6 +240,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
}
@@ -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)
}
}
@@ -0,0 +1,94 @@
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, a removal mark (the session
// of a cleaning that planned to remove it; empty when unmarked) and the id
// of the volume it belongs to (content names repeat across volumes and
// across a volume's re-creation under its name).
type ObjectMeta struct {
Session string
Mark string
Volume VolumeID // the volume the entry belongs to, stamped by the store at Create
}
// 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 and the store's volume id; 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
// DeleteOfVolume deletes the entry only if it belongs to volume
// (ErrPrecondition otherwise); a missing entry succeeds.
DeleteOfVolume(ctx context.Context, rel string, volume VolumeID) 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
}
@@ -0,0 +1,204 @@
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
volume VolumeID // stamped on every entry the store creates
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, Volume: m.volume}}
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, Volume: o.meta.Volume}
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
})
}
func (m *memObjects) DeleteOfVolume(_ context.Context, rel string, volume VolumeID) error {
return m.write("delete-of-volume", rel, func() error {
o, ok := m.objs[m.full(rel)]
if !ok {
return nil
}
if o.meta.Volume != volume {
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, Volume: m.volume}}
}
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")
}
}
@@ -7,38 +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. 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 (a
// dependent is added before its target exists, and a target never becomes
// a restore source while it names foreign chunks). 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 {
@@ -64,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)
@@ -10,102 +10,58 @@ 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, 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))
data[path.Join(volRoot, c.Path())] = []byte(d)
orphans = append(orphans, c)
}
vb, err := Volume{ID: idFor("v1"), Name: "v1", Format: VolumeFormat}.Encode()
if err != nil {
t.Fatal(err)
}
objs[path.Join(volRoot, VolumeName)] = vb
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")})
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)
orphans = append(orphans, c)
data[path.Join(volRoot, VolumeName)] = vb
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", ClaimID: "k-a", VolumeID: idFor("v1"), 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)
}
@@ -117,10 +73,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 {
@@ -144,41 +101,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
}
@@ -186,86 +216,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)
}
})
@@ -278,7 +305,7 @@ func TestCleaningPass_InterruptAtEveryStep(t *testing.T) {
func TestRemoveUnreachable_NeedsItsOwnVolumeID(t *testing.T) {
o, h, _, orphans := removeFixture(t)
delete(o.objs, path.Join(volRoot, VolumeName))
if _, err := removeShard0(t, &memHead{h: h}, o, &fakeHeld{}, "c1", orphans); !errors.Is(err, ErrMissing) || len(o.deletes) != 0 {
t.Fatalf("removal without VOLUME: %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("removal without VOLUME: %v, %d writes; want ErrMissing and none", err, len(o.writes))
}
}
@@ -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,106 @@ 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) DeleteOfVolume(_ context.Context, rel string, volume VolumeID) error {
p := path.Join(volRoot, rel)
return v.objWrite("delete-of-volume "+rel, func() error {
if _, ok := v.objects[p]; !ok {
return nil
}
if v.meta(p).Volume != volume {
return ErrPrecondition
}
delete(v.objects, p)
delete(v.metas, p)
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 +187,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 +196,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 +204,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 +234,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", ClaimID: "k-a", VolumeID: idFor("v1"), 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"}
}
@@ -76,9 +76,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))
}
}
// Start: an older line, another server at HEAD's epoch and another claim
@@ -15,13 +15,20 @@ var (
ErrStaleLocalRoot = errors.New("layout: local root is from an earlier claim")
)
// StaleLocalRootCure is the way back a stale-root refusal names: after a
// clean stop the published image holds everything the old directory does.
const StaleLocalRootCure = "another root claimed this volume since this directory's last claim (for example a planned move away and back); after a clean stop the directory holds nothing the published image lacks: clear it and start again on a fresh root"
// MissingLocalRootCure is the way back the refusal names.
const MissingLocalRootCure = "check for a wrong or unmounted data directory; if the local data is gone, a forced move (also to the same host) records the lost range and restarts from the published image"
// LocalRoot is what a starting holder knows of its local data: the claim
// id its local root's marker carries (written before any claim, so it is
// durable before HEAD can name it), whether the root is fresh (just
// created, holding no data), and the position it holds synced.
// durable before HEAD can name it), whether the root is fresh, and the
// position it holds synced. A root is fresh from its creation until the
// base of its restore from HEAD is durable, across any crash in between:
// reported non-fresh before that, its position below HEAD's would be
// refused as an old copy.
type LocalRoot struct {
ClaimID string
Fresh bool
@@ -62,11 +69,11 @@ func Start(ctx context.Context, st HeadStore, lease LeaseWait, line HolderID, lo
case local.Fresh:
return Head{}, fmt.Errorf("%w at epoch %d: %s", ErrMissingLocalRoot, h.Epoch, MissingLocalRootCure)
default:
return Head{}, fmt.Errorf("%w (%w): HEAD holds claim %q at epoch %d, the local root carries %q", ErrStaleLocalRoot, ErrNotHolder, h.ClaimID, h.Epoch, local.ClaimID)
return Head{}, fmt.Errorf("%w (%w): HEAD holds claim %q at epoch %d, the local root carries %q: %s", ErrStaleLocalRoot, ErrNotHolder, h.ClaimID, h.Epoch, local.ClaimID, StaleLocalRootCure)
}
}
if line.Epoch > h.Epoch && !local.Fresh && local.ClaimID != h.ClaimID {
return Head{}, fmt.Errorf("%w (%w): the local root carries claim %q, HEAD's lineage is %q; a root that is not the continuing lineage starts fresh", ErrStaleLocalRoot, ErrNotHolder, local.ClaimID, h.ClaimID)
return Head{}, fmt.Errorf("%w (%w): the local root carries claim %q, HEAD's lineage is %q: %s", ErrStaleLocalRoot, ErrNotHolder, local.ClaimID, h.ClaimID, StaleLocalRootCure)
}
return RunClaim(ctx, st, lease, me)
}
@@ -180,3 +180,49 @@ func TestStart_InterruptAtTheClaim(t *testing.T) {
}
}
}
// A fresh root stays fresh until its restore's base is durable: claimed at
// a higher epoch, crashed before the base is down, restarted at the same
// epoch with the same marker and still fresh, it continues the restore.
// Reported as non-fresh at position 0 under HEAD's published position, the
// same root would be refused as an old copy; the caller reports Fresh until
// the base is durable.
func TestStart_FreshAcrossACrashContinuesTheRestore(t *testing.T) {
h := startHead(3, "s1/r1", "k-prev")
h.Position = 50
st := &memHead{h: &h}
line := HolderID{Epoch: 4, Holder: "s1/r1"}
if _, err := Start(context.Background(), st, &fakeLease{ended: true}, line, LocalRoot{ClaimID: "k4", Fresh: true}); err != nil {
t.Fatal(err)
}
got, err := Start(context.Background(), st, &fakeLease{ended: true}, line, LocalRoot{ClaimID: "k4", Fresh: true})
if err != nil || got.ClaimID != "k4" || got.Epoch != 4 {
t.Fatalf("restart of a still-fresh root: %+v %v; want continue", got, err)
}
if _, err := Start(context.Background(), st, &fakeLease{ended: true}, line, LocalRoot{ClaimID: "k4", Position: 0}); !errors.Is(err, ErrStaleLocalRoot) {
t.Fatalf("the same root reported non-fresh at 0 under 50: %v; want ErrStaleLocalRoot", err)
}
}
// A deleting volume does not start: at the holder's own epoch Start falls
// through to the claim, which refuses a deleting HEAD.
func TestStart_DeletingVolumeRefused(t *testing.T) {
h := startHead(3, "s1/r1", "k3")
h.State = StateDeleting
for _, line := range []HolderID{{Epoch: 3, Holder: "s1/r1"}, {Epoch: 4, Holder: "s1/r1"}} {
st, _, err := start(t, h, line, LocalRoot{ClaimID: "k3"})
if !errors.Is(err, ErrVolumeDeleting) || st.updates != 0 {
t.Fatalf("start at epoch %d of a deleting volume: %v (%d writes); want ErrVolumeDeleting", line.Epoch, err, st.updates)
}
}
}
// A planned move away and back finds the old directory on the first host:
// another root claimed in between, so it is refused as stale, and the
// error names the cure.
func TestStart_StaleRootNamesTheCure(t *testing.T) {
_, _, err := start(t, startHead(5, "s2/r1", "k5"), HolderID{Epoch: 6, Holder: "s1/r1"}, LocalRoot{ClaimID: "k3"})
if !errors.Is(err, ErrStaleLocalRoot) || !strings.Contains(err.Error(), StaleLocalRootCure) {
t.Fatalf("old directory after a move away and back: %v; want ErrStaleLocalRoot naming %q", err, StaleLocalRootCure)
}
}
+11 -8
View File
@@ -543,13 +543,13 @@ 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` |
| 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
357 rows: 286 ACTIVE, 67 STUB, 4 ARCHIVED; 15 kept from the internal ledger, 342 new.
360 rows: 289 ACTIVE, 67 STUB, 4 ARCHIVED; 15 kept from the internal ledger, 345 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.
@@ -1090,7 +1090,7 @@ Notes:
|---|---|---|---|---|---|---|
| `INV-SNAPK-NAME-CANONICAL-001` | A chunk is named by its index and the SHA-256 of its bytes under `pool/<index/10000>/`; 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 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-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 |
| `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 |
@@ -1099,14 +1099,17 @@ 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-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 |
| `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-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 |
@@ -1114,8 +1117,8 @@ Notes:
| `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-START-ROOT-001` | At its own epoch a holder continues only on the local root whose claim id HEAD holds; a fresh root with another id is refused as a missing local root naming the cure, an older one as stale and fenced; neither writes HEAD. | M9 start (before any transition) | `core/frontend/chunkstore/layout` `start.go` `Start` | `TestStart_OwnEpochFreshRootRefusedBeforeClaim`, `TestStart_OwnEpochSameRootContinues`, `TestStart_LostClaimReplyContinues`, `TestStart_SameHostForcedSuccessorRefusesTheRemountedOldRoot` | — (the snapshot kernel model is not in this repository) | ACTIVE |
| `INV-SNAPK-START-LINEAGE-001` | At an epoch above HEAD's a holder claims only with a fresh root (it restores from HEAD) or the root whose claim id HEAD holds; any other root holds older data and is refused as stale, HEAD unchanged. | M9 any → idle (Claim) | `core/frontend/chunkstore/layout` `start.go` `Start` | `TestStart_HigherEpochRefusesAnOlderLineage`, `TestStart_FreshRootAtHigherEpochClaims` | — (the snapshot kernel model is not in this repository) | ACTIVE |
| `INV-SNAPK-START-POSITION-001` | A root carrying HEAD's claim id but synced below HEAD's published position is an old copy of that lineage and is refused as stale, at its own epoch and above, HEAD unchanged. | M9 start (before any transition) | `core/frontend/chunkstore/layout` `start.go` `Start` | `TestStart_OldCopyOfTheRightRootRefused` | — (the snapshot kernel model is not in this repository) | ACTIVE |
| `INV-SNAPK-START-LINEAGE-001` | At an epoch above HEAD's a holder claims only with a fresh root (it restores from HEAD) or the root whose claim id HEAD holds; any other root holds older data and is refused as stale, HEAD unchanged. | M9 any → idle (Claim) | `core/frontend/chunkstore/layout` `start.go` `Start` | `TestStart_HigherEpochRefusesAnOlderLineage`, `TestStart_FreshRootAtHigherEpochClaims`, `TestStart_StaleRootNamesTheCure`, `TestStart_DeletingVolumeRefused` | — (the snapshot kernel model is not in this repository) | ACTIVE |
| `INV-SNAPK-START-POSITION-001` | A root carrying HEAD's claim id but synced below HEAD's published position is an old copy of that lineage and is refused as stale, at its own epoch and above, HEAD unchanged. | M9 start (before any transition) | `core/frontend/chunkstore/layout` `start.go` `Start` | `TestStart_OldCopyOfTheRightRootRefused`, `TestStart_FreshAcrossACrashContinuesTheRestore` | — (the snapshot kernel model is not in this repository) | ACTIVE |
| `INV-SNAPK-START-CLAIM-001` | A claim is made only by Start, at an epoch above HEAD's, with the local root's claim id; a source scan refuses any other caller of RunClaim. | M9 any → idle (Claim) | `core/frontend/chunkstore/layout` `start.go` `Start`; (source scan) | `TestStart_FreshRootAtHigherEpochClaims`, `TestStart_Refusals`, `TestStart_InterruptAtTheClaim`, `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 |