instancefs: random hoist names; one post-start ENOENT policy
A hoist named its directory .carlos-removing-0 to -63 in turn, so 64 planted (or leftover) names made every retry fail. It now uses 128 random bits from crypto/rand with RENAME_NOREPLACE and retries only a freak collision, so a finite tree always makes progress. remove now passes every error from the walk through changed, so no ENOENT after removal began (hoist reopening dir included) reads as "already absent". A child gone at the hoist counts against the same retry budget as one gone before a descent.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2 files changed,
+278
−23
internal/instancefs/dirs_linux.go+75 −23internal/instancefs/removeall_linux_test.go+203 −0
diff --git a/internal/instancefs/dirs_linux.go b/internal/instancefs/dirs_linux.go| index f541352f4..47684d0f3 100644 |
| --- a/internal/instancefs/dirs_linux.go |
| +++ b/internal/instancefs/dirs_linux.go |
| @@ -3,6 +3,7 @@ |
| package instancefs |
| import ( |
| + "crypto/rand" |
| "errors" |
| "fmt" |
| "io" |
| @@ -176,7 +177,7 @@ func RemoveAllBeneath(dir, name string) error { |
| if err := bareName(name); err != nil { |
| return err |
| } |
| - r := treeRemover{dir: dir, top: name, path: filepath.Join(dir, name), maxDepth: removeMaxDepth} |
| + r := newTreeRemover(treeRemover{dir: dir, top: name, path: filepath.Join(dir, name)}) |
| return r.remove() |
| } |
| @@ -188,10 +189,22 @@ func removeAllAt(parent int, name, path string) error { |
| if err := bareName(name); err != nil { |
| return err |
| } |
| - r := treeRemover{dir: filepath.Dir(path), top: name, path: path, maxDepth: removeMaxDepth, held: parent, holdsDir: true} |
| + r := newTreeRemover(treeRemover{dir: filepath.Dir(path), top: name, path: path, held: parent, holdsDir: true}) |
| return r.remove() |
| } |
| +// configureRemover, when set, adjusts every walk RemoveAllBeneath and |
| +// removeAllAt start (a smaller depth bound, hooks). Tests only. |
| +var configureRemover func(*treeRemover) |
| + |
| +func newTreeRemover(r treeRemover) *treeRemover { |
| + r.maxDepth = removeMaxDepth |
| + if configureRemover != nil { |
| + configureRemover(&r) |
| + } |
| + return &r |
| +} |
| + |
| const ( |
| removeBatch = 256 |
| removeMaxDepth = 65536 |
| @@ -203,6 +216,10 @@ const ( |
| // level re-walks at most this many components rather than the whole |
| // depth. |
| removeAnchorEvery = 256 |
| + // removeHoistTries is how many fresh random names a hoist tries before |
| + // it gives up. Each is 128 bits from crypto/rand, so a second try means |
| + // a freak collision, not a name anyone planted. |
| + removeHoistTries = 4 |
| ) |
| // treeRemover is one RemoveAllBeneath walk. |
| @@ -229,9 +246,14 @@ type treeRemover struct { |
| // afterBatch runs after each batch of entries is handled, with the |
| // stack of names below top. Tests only; nil in production. |
| afterBatch func(stack []string) error |
| - // beforeOpen runs just before the walk descends into child. Tests |
| - // only; nil in production. |
| - beforeOpen func(stack []string, child string) |
| + // beforeOpen runs just before the walk descends into child, and |
| + // beforeHoist just before it hoists child. Tests only; nil in |
| + // production. |
| + beforeOpen func(stack []string, child string) |
| + beforeHoist func(stack []string, child string) |
| + // hoistName names a hoisted directory; nil means a random name. |
| + // Tests only. |
| + hoistName func() string |
| stack []string |
| anchor int // a descriptor, or -1 for none |
| @@ -267,11 +289,21 @@ func (r *treeRemover) remove() (err error) { |
| r.topDev, r.topIno = uint64(st.Dev), uint64(st.Ino) |
| cur, err := r.at(0) |
| if errors.Is(err, unix.ENOENT) { |
| + // top went between the stat and the open: nothing of it has been |
| + // touched, so this is still "not there". |
| return nil |
| } |
| if err != nil { |
| return r.walkError(err) |
| } |
| + // From here on removal has begun, and every error goes through |
| + // changed: none of them may read as "already absent". |
| + return r.changed(r.walk(cur)) |
| +} |
| + |
| +// walk removes the tree from cur, top's descriptor, down. Its errors are |
| +// mid-walk errors; remove passes them through changed. |
| +func (r *treeRemover) walk(cur int) error { |
| vanished := 0 |
| for { |
| child, err := r.clear(cur) |
| @@ -281,10 +313,19 @@ func (r *treeRemover) remove() (err error) { |
| } |
| if child != "" { |
| if len(r.stack) >= r.maxDepth { |
| - if err := r.hoist(cur, child); err != nil { |
| + if r.beforeHoist != nil { |
| + r.beforeHoist(r.stack, child) |
| + } |
| + err := r.hoist(cur, child) |
| + if errors.Is(err, errHoistGone) && vanished < removeVanishedRetries { |
| + vanished++ // as for a descent: list cur again |
| + continue |
| + } |
| + if err != nil { |
| r.release(cur) |
| return err |
| } |
| + vanished = 0 |
| continue |
| } |
| if r.beforeOpen != nil { |
| @@ -299,7 +340,7 @@ func (r *treeRemover) remove() (err error) { |
| } |
| r.release(cur) |
| if err != nil { |
| - return r.changed(&os.PathError{Op: "openat2", Path: r.where(child), Err: err}) |
| + return &os.PathError{Op: "openat2", Path: r.where(child), Err: err} |
| } |
| vanished = 0 |
| r.stack = append(r.stack, child) |
| @@ -322,7 +363,7 @@ func (r *treeRemover) remove() (err error) { |
| } |
| parent, err := r.at(depth - 1) |
| if err != nil { |
| - return r.changed(r.walkError(err)) |
| + return r.walkError(err) |
| } |
| if err := unix.Unlinkat(parent, name, unix.AT_REMOVEDIR); err != nil && !errors.Is(err, unix.ENOENT) { |
| r.release(parent) |
| @@ -353,10 +394,12 @@ func (r *treeRemover) walkError(err error) error { |
| return &os.PathError{Op: "openat2", Path: r.where("."), Err: err} |
| } |
| -// changed is a mid-walk error. A directory the walk already stood in that |
| -// is now missing was moved, perhaps out of the tree with what it holds, so |
| -// "no such file" here is never evidence that the tree is gone: callers map |
| -// that to success. Other errors pass unchanged. |
| +// changed is the one policy for errors once removal has begun: remove |
| +// passes everything walk returns through it. A directory the walk already |
| +// stood in (or dir, or top) that is now missing was moved, perhaps out of |
| +// the tree with what it holds, so "no such file" here is never evidence |
| +// that the tree is gone: callers map that to success. It keeps the text |
| +// but drops ENOENT from the chain. Other errors pass unchanged. |
| func (r *treeRemover) changed(err error) error { |
| if errors.Is(err, unix.ENOENT) { |
| return fmt.Errorf("instancefs: %s changed during removal: %v", r.path, err) |
| @@ -364,12 +407,18 @@ func (r *treeRemover) changed(err error) error { |
| return err |
| } |
| +// errHoistGone is hoist's answer when child went before it could be moved. |
| +var errHoistGone = errors.New("instancefs: hoisted directory went first") |
| + |
| // hoist moves child, a directory in cur at the depth bound, up into top |
| // under a fresh name, so the walk meets it again near the top instead of |
| // keeping more names. Both directories are inside the tree being removed; |
| // top is reopened from dir as at does, checked to be the directory the walk |
| -// began on, and renameat2 follows no link and replaces nothing. cur stays |
| -// open. The anchor is dropped unless it is cur, so at most three |
| +// began on, and renameat2 follows no link and replaces nothing. The name is |
| +// 128 random bits, so nothing already in top (a tenant's planted names, an |
| +// interrupted walk's leftovers) can make the move fail every time: each |
| +// hoist strictly shortens the deepest path and a retry always finds a name. |
| +// cur stays open. The anchor is dropped unless it is cur, so at most three |
| // descriptors are open: cur, dir and top. |
| func (r *treeRemover) hoist(cur int, child string) error { |
| if r.anchor != cur { |
| @@ -387,24 +436,27 @@ func (r *treeRemover) hoist(cur int, child string) error { |
| } |
| } |
| if err != nil { |
| - return r.changed(r.walkError(err)) |
| + return r.walkError(err) |
| } |
| defer r.release(top) |
| - for range removeVanishedRetries { |
| - name := fmt.Sprintf(".carlos-removing-%d", r.hoisted) |
| - r.hoisted++ |
| + for range removeHoistTries { |
| + name := ".carlos-removing-" + rand.Text() |
| + if r.hoistName != nil { |
| + name = r.hoistName() |
| + } |
| err = unix.Renameat2(cur, child, top, name, unix.RENAME_NOREPLACE) |
| + if err == nil { |
| + r.hoisted++ |
| + return nil |
| + } |
| if errors.Is(err, unix.ENOENT) { |
| - return nil // child went meanwhile: cur is listed again |
| + return errHoistGone |
| } |
| if !errors.Is(err, unix.EEXIST) { |
| break |
| } |
| } |
| - if err != nil { |
| - return &os.PathError{Op: "renameat2", Path: r.where(child), Err: err} |
| - } |
| - return nil |
| + return &os.PathError{Op: "renameat2", Path: r.where(child), Err: err} |
| } |
| // open opens the directory name under parent: exactly one component, never |
diff --git a/internal/instancefs/removeall_linux_test.go b/internal/instancefs/removeall_linux_test.go| index 44de64dec..55e1e2299 100644 |
| --- a/internal/instancefs/removeall_linux_test.go |
| +++ b/internal/instancefs/removeall_linux_test.go |
| @@ -359,3 +359,206 @@ func TestRemoveAllBeneathChildVanishedBeforeDescent(t *testing.T) { |
| } |
| gone(t, top) |
| } |
| + |
| +// hoistDepth is the reduced depth bound the hoist tests use; deep is a |
| +// chain comfortably past it. |
| +const hoistDepth, deep = 4, "a/b/c/d/e/f/g/h/i/j" |
| + |
| +// Names already in top cannot stall a hoist. Here the 64 names the walk |
| +// once used in turn (.carlos-removing-0 to -63) are planted, each holding a |
| +// chain past the bound, beside one more chain: whichever the listing meets |
| +// first, its hoist needs a name, and every retry of a predictable sequence |
| +// would meet the same planted ones. |
| +func TestRemoveAllBeneathHoistPastPlantedNames(t *testing.T) { |
| + dir := t.TempDir() |
| + top := filepath.Join(dir, "top") |
| + for i := range 64 { |
| + files(t, filepath.Join(top, fmt.Sprintf(".carlos-removing-%d", i), deep), 1) |
| + } |
| + files(t, filepath.Join(top, "d", deep), 1) |
| + lowNofile(t, 16) |
| + r := treeRemover{dir: dir, top: "top", path: top, maxDepth: hoistDepth} |
| + if err := r.remove(); err != nil { |
| + t.Fatal(err) |
| + } |
| + gone(t, top) |
| + if r.hoisted == 0 || r.live != 0 || r.peak > 3 { |
| + t.Fatalf("hoisted=%d live=%d peak=%d", r.hoisted, r.live, r.peak) |
| + } |
| +} |
| + |
| +// A hoist whose name is taken by the time it renames tries a fresh one; |
| +// RENAME_NOREPLACE still replaces nothing. If every try collides the walk |
| +// stops with an error that is not "no such file", having moved nothing |
| +// over anything, and the next removal finishes. |
| +func TestRemoveAllBeneathHoistCollisionRetries(t *testing.T) { |
| + collide := func(top string, n *int) func() string { |
| + return func() string { |
| + *n++ |
| + name := fmt.Sprintf("taken-%d", *n) |
| + files(t, filepath.Join(top, name), 1) |
| + return name |
| + } |
| + } |
| + t.Run("once", func(t *testing.T) { |
| + dir := t.TempDir() |
| + top := filepath.Join(dir, "top") |
| + files(t, filepath.Join(top, "d", deep), 1) |
| + calls := 0 |
| + taken := collide(top, &calls) |
| + r := treeRemover{dir: dir, top: "top", path: top, maxDepth: hoistDepth, hoistName: func() string { |
| + if calls == 0 { |
| + return taken() |
| + } |
| + calls++ |
| + return fmt.Sprintf("fresh-%d", calls) |
| + }} |
| + if err := r.remove(); err != nil { |
| + t.Fatal(err) |
| + } |
| + gone(t, top) |
| + if r.hoisted == 0 || calls != r.hoisted+1 { |
| + t.Fatalf("hoisted=%d names=%d: the collision was not retried", r.hoisted, calls) |
| + } |
| + }) |
| + t.Run("always", func(t *testing.T) { |
| + dir := t.TempDir() |
| + top := filepath.Join(dir, "top") |
| + files(t, filepath.Join(top, "d", deep), 1) |
| + calls := 0 |
| + r := treeRemover{dir: dir, top: "top", path: top, maxDepth: hoistDepth, hoistName: collide(top, &calls)} |
| + err := r.remove() |
| + if !errors.Is(err, unix.EEXIST) || errors.Is(err, os.ErrNotExist) { |
| + t.Fatalf("err=%v", err) |
| + } |
| + if calls != removeHoistTries || r.live != 0 { |
| + t.Fatalf("names=%d live=%d", calls, r.live) |
| + } |
| + if _, err := os.Lstat(filepath.Join(top, "d", deep, "f0000")); err != nil { |
| + t.Fatal(err) |
| + } |
| + r = treeRemover{dir: dir, top: "top", path: top, maxDepth: hoistDepth} |
| + if err := r.remove(); err != nil { |
| + t.Fatal(err) |
| + } |
| + gone(t, top) |
| + }) |
| +} |
| + |
| +// A walk stopped just after a hoist leaves the hoisted directory in top |
| +// under its random name; the next walk removes it like any other entry. |
| +func TestRemoveAllBeneathResumesAfterInterruptedHoist(t *testing.T) { |
| + dir := t.TempDir() |
| + top := filepath.Join(dir, "top") |
| + chain(t, dir, 30, "d") |
| + injected := errors.New("injected") |
| + r := &treeRemover{dir: dir, top: "top", path: top, maxDepth: hoistDepth} |
| + r.afterBatch = func([]string) error { |
| + if r.hoisted > 0 { |
| + return injected |
| + } |
| + return nil |
| + } |
| + if err := r.remove(); !errors.Is(err, injected) { |
| + t.Fatalf("err=%v", err) |
| + } |
| + left := 0 |
| + for _, n := range entries(t, top) { |
| + if strings.HasPrefix(n, ".carlos-removing-") { |
| + left++ |
| + } |
| + } |
| + if left == 0 || r.live != 0 { |
| + t.Fatalf("hoisted names left=%d live=%d", left, r.live) |
| + } |
| + r = &treeRemover{dir: dir, top: "top", path: top, maxDepth: hoistDepth} |
| + if err := r.remove(); err != nil { |
| + t.Fatal(err) |
| + } |
| + gone(t, top) |
| +} |
| + |
| +// dir itself going at the moment of a hoist (the walk must reopen it to |
| +// reach top) is a tree moved mid-walk, not a tree already gone. |
| +func TestRemoveAllBeneathParentGoneAtHoistIsNotGone(t *testing.T) { |
| + base := t.TempDir() |
| + dir := filepath.Join(base, "p") |
| + if err := os.Mkdir(dir, 0o700); err != nil { |
| + t.Fatal(err) |
| + } |
| + chain(t, dir, 30, "d") |
| + moved := false |
| + r := treeRemover{dir: dir, top: "top", path: filepath.Join(dir, "top"), maxDepth: hoistDepth, beforeHoist: func([]string, string) { |
| + if !moved { |
| + moved = true |
| + if err := os.Rename(dir, filepath.Join(base, "q")); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + }} |
| + err := r.remove() |
| + if !moved { |
| + t.Fatal("the walk never hoisted") |
| + } |
| + if err == nil || errors.Is(err, os.ErrNotExist) { |
| + t.Fatalf("err=%v: a parent gone at the hoist reads as removed", err) |
| + } |
| + if r.live != 0 { |
| + t.Fatalf("%d directory descriptors left open", r.live) |
| + } |
| + if _, err := os.Lstat(filepath.Join(base, "q", "top", "d")); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +// hoistBound makes every RemoveAllBeneath and removeAllAt walk in this |
| +// test use the hoist tests' depth bound, and returns them. |
| +func hoistBound(t *testing.T) *[]*treeRemover { |
| + t.Helper() |
| + var walks []*treeRemover |
| + configureRemover = func(r *treeRemover) { |
| + r.maxDepth = hoistDepth |
| + walks = append(walks, r) |
| + } |
| + t.Cleanup(func() { configureRemover = nil }) |
| + return &walks |
| +} |
| + |
| +// The production entry points hoist too: RemoveAllBeneath by path, and |
| +// removeAllAt from the descriptor PurgeProven holds. |
| +func TestRemoveAllBeneathEntryPointsHoist(t *testing.T) { |
| + t.Run("RemoveAllBeneath", func(t *testing.T) { |
| + walks := hoistBound(t) |
| + dir := t.TempDir() |
| + chain(t, dir, 30, "d") |
| + if err := RemoveAllBeneath(dir, "top"); err != nil { |
| + t.Fatal(err) |
| + } |
| + gone(t, filepath.Join(dir, "top")) |
| + if len(*walks) != 1 || (*walks)[0].hoisted == 0 { |
| + t.Fatal("the walk never hoisted") |
| + } |
| + }) |
| + t.Run("PurgeProven", func(t *testing.T) { |
| + walks := hoistBound(t) |
| + _, root, inst := purgeRig(t) |
| + chain(t, inst, 30, "d") |
| + files(t, filepath.Join(inst, "top", ".carlos-removing-0", deep), 1) |
| + if err := PurgeProven(root, "instances/abc", func(n string) bool { return n == "top" || seedish(n) }); err != nil { |
| + t.Fatal(err) |
| + } |
| + if got := strings.Join(entries(t, inst), ","); got != "uploads" { |
| + t.Fatalf("left %s", got) |
| + } |
| + hoisted := 0 |
| + for _, w := range *walks { |
| + if !w.holdsDir { |
| + t.Fatal("PurgeProven walked by path") |
| + } |
| + hoisted += w.hoisted |
| + } |
| + if hoisted == 0 { |
| + t.Fatal("no walk hoisted") |
| + } |
| + }) |
| +} |