carlos / platform Public

instancefs: purge any depth or width with three descriptors (F6)

RemoveAllBeneath refused trees nested more than 64 deep and read each
directory whole, holding one descriptor per level. It now walks with a
stack of names: every directory is opened one component at a time from
its parent's descriptor with openat2 RESOLVE_BENEATH|NO_SYMLINKS|
NO_MAGICLINKS, so no joined path reaches the kernel; entries are read 256
at a time with getdents; at most three directory descriptors are open,
dir's included. Backing up a level re-walks from an anchor kept every
256 levels, not from the top, so a 10,000-deep tree takes ~4 s here
rather than ~170 s. Past 65,536 levels it refuses with ErrTooDeep and
leaves the tree; the demo purge logs DEMO-PURGE-OPERATOR for it and fails
as any purge does, leaving the demo releasing for an operator.

Tests: 10,000 deep and a >64 KiB path both purge under RLIMIT_NOFILE 16;
100,000 entries purge with ~3 MiB heap growth (27 MiB before); at most
three descriptors across anchors; a directory swapped for a symlink
between batches is refused, not followed, and the retry finishes; an
injected mid-walk error resumes; the depth bound refuses and keeps.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 0d058b5ebe4203a4d407be4797dbec2d609b0131 parent f5b79fc
4 files changed, +606 −26
  • internal/instancectl/demo_cleanup.go +6 −0
  • internal/instancefs/dirs_linux.go +301 −26
  • internal/instancefs/instancefs.go +5 −0
  • internal/instancefs/removeall_linux_test.go +294 −0
diff --git a/internal/instancectl/demo_cleanup.go b/internal/instancectl/demo_cleanup.go
index ec5b89d5d..c5e84977b 100644
--- a/internal/instancectl/demo_cleanup.go
+++ b/internal/instancectl/demo_cleanup.go
@@ -133,6 +133,12 @@ func (s *Server) purgeDemoWithJobs(ctx context.Context, d demo.Descriptor, jobs
if errors.Is(err, os.ErrNotExist) {
return nil
}
+ if errors.Is(err, instancefs.ErrTooDeep) {
+ // No retry can finish this tree (F6). The purge fails as any other
+ // does: the demo stays releasing under its hold and the agent logs
+ // DEMO-EXPIRED with each retry. This line says why.
+ s.logf("instance-control: DEMO-PURGE-OPERATOR demo=%s host=%s: %v: remove it by hand, then the next retry completes the purge", d.ID, d.Host, err)
+ }
return err
}
// Delete the database before its local initialization proof.
diff --git a/internal/instancefs/dirs_linux.go b/internal/instancefs/dirs_linux.go
index 6e0334802..651acd7ca 100644
--- a/internal/instancefs/dirs_linux.go
+++ b/internal/instancefs/dirs_linux.go
@@ -5,6 +5,7 @@ package instancefs
import (
"errors"
"fmt"
+ "io"
"os"
"path/filepath"
@@ -164,55 +165,329 @@ func RenameBetweenNoReplace(srcDir, srcName, dstDir, dstName string) error {
// tenant sharing the agent's uid can plant links and directories in a run
// directory (run spec §5.2); this is the only way the agent deletes one.
// A missing name is not an error.
+//
+// Neither depth nor width costs descriptors or much memory (F6). The walk
+// holds at most three directory descriptors, dir's included, keeps a stack
+// of names rather than descriptors, and reads entries 256 at a time. A
+// tree deeper than 65,536 directories is refused with ErrTooDeep and what
+// remains is left for an operator. An interrupted removal leaves a smaller
+// tree that the next call finishes.
func RemoveAllBeneath(dir, name string) error {
if err := bareName(name); err != nil {
return err
}
- dfd, err := openDir(dir)
- if err != nil {
- return err
- }
- defer unix.Close(dfd)
- return removeAt(dfd, name, filepath.Join(dir, name), 0)
+ r := treeRemover{dir: dir, top: name, path: filepath.Join(dir, name), maxDepth: removeMaxDepth}
+ return r.remove()
+}
+
+const (
+ removeBatch = 256
+ removeMaxDepth = 65536
+ // removeAnchorEvery is how far apart the walk's one kept directory
+ // descriptor (its anchor) sits in a deep tree, so that backing up a
+ // level re-walks at most this many components rather than the whole
+ // depth.
+ removeAnchorEvery = 256
+)
+
+// treeRemover is one RemoveAllBeneath walk.
+//
+// The directory it works in is named by depth: -1 is dir, 0 is top, and n
+// is the n names of stack below top. It reaches one by walking down from
+// its anchor, one component at a time from the parent's descriptor,
+// closing each parent once the child is open. Nothing joined from the
+// tree's names ever reaches the kernel, so the depth of the tree and the
+// length of its paths do not matter. The anchor is dir's descriptor or a
+// directory on the current stack at a multiple of removeAnchorEvery; to
+// back up above it the walk reopens dir as RemoveAllBeneath first did and
+// checks that top is still the directory it started on. At most three
+// descriptors are open at once: the anchor, the one being walked from and
+// the one being opened.
+type treeRemover struct {
+ dir, top, path string
+ maxDepth int
+ // 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
+
+ stack []string
+ anchor int // a descriptor, or -1 for none
+ anchorDepth int
+ topDev uint64
+ topIno uint64
+ live, peak int // directory descriptors open now, and at most
+ buf []byte
+ off, end int
+ names []string
}
-// removeAt removes name under the directory fd parent; path is for errors.
-func removeAt(parent int, name, path string, depth int) error {
- if depth > 64 {
- return fmt.Errorf("instancefs: %s is nested more than 64 deep", path)
+func (r *treeRemover) remove() (err error) {
+ r.anchor = -1
+ defer r.dropAnchor()
+ if err = r.anchorAtDir(); err != nil {
+ return err
}
var st unix.Stat_t
- if err := unix.Fstatat(parent, name, &st, unix.AT_SYMLINK_NOFOLLOW); err != nil {
+ if err := unix.Fstatat(r.anchor, r.top, &st, unix.AT_SYMLINK_NOFOLLOW); err != nil {
if errors.Is(err, unix.ENOENT) {
return nil
}
- return &os.PathError{Op: "fstatat", Path: path, Err: err}
+ return &os.PathError{Op: "fstatat", Path: r.path, Err: err}
}
if st.Mode&unix.S_IFMT != unix.S_IFDIR {
- if err := unix.Unlinkat(parent, name, 0); err != nil && !errors.Is(err, unix.ENOENT) {
- return &os.PathError{Op: "unlinkat", Path: path, Err: err}
+ if err := unix.Unlinkat(r.anchor, r.top, 0); err != nil && !errors.Is(err, unix.ENOENT) {
+ return &os.PathError{Op: "unlinkat", Path: r.path, Err: err}
}
return nil
}
- fd, err := unix.Openat(parent, name, unix.O_RDONLY|unix.O_DIRECTORY|unix.O_NOFOLLOW|unix.O_CLOEXEC, 0)
+ r.topDev, r.topIno = uint64(st.Dev), uint64(st.Ino)
+ cur, err := r.at(0)
+ if errors.Is(err, unix.ENOENT) {
+ return nil
+ }
+ if err != nil {
+ return r.walkError(err)
+ }
+ for {
+ child, err := r.clear(cur)
+ if err != nil {
+ r.release(cur)
+ return err
+ }
+ if child != "" {
+ if len(r.stack) >= r.maxDepth {
+ r.release(cur)
+ return fmt.Errorf("%w: %s", ErrTooDeep, r.path)
+ }
+ next, err := r.open(cur, child)
+ r.release(cur)
+ if err != nil {
+ return &os.PathError{Op: "openat2", Path: r.where(child), Err: err}
+ }
+ r.stack = append(r.stack, child)
+ cur = next
+ if d := len(r.stack); d%removeAnchorEvery == 0 {
+ r.setAnchor(cur, d)
+ }
+ continue
+ }
+ // cur is empty: back up a level and remove it from its parent.
+ depth := len(r.stack)
+ if cur == r.anchor {
+ r.dropAnchor()
+ } else {
+ r.release(cur)
+ }
+ name := r.top
+ if depth > 0 {
+ name = r.stack[depth-1]
+ }
+ parent, err := r.at(depth - 1)
+ if err != nil {
+ return r.walkError(err)
+ }
+ if err := unix.Unlinkat(parent, name, unix.AT_REMOVEDIR); err != nil && !errors.Is(err, unix.ENOENT) {
+ r.release(parent)
+ return &os.PathError{Op: "unlinkat", Path: r.where(name), Err: err}
+ }
+ if depth == 0 {
+ r.release(parent)
+ return nil
+ }
+ r.stack = r.stack[:depth-1]
+ cur = parent
+ }
+}
+
+// where names an entry for errors only; it is never opened.
+func (r *treeRemover) where(name string) string {
+ if len(r.stack) == 0 {
+ return filepath.Join(r.path, name)
+ }
+ return fmt.Sprintf("%s/<%d levels>/%s", r.path, len(r.stack), name)
+}
+
+func (r *treeRemover) walkError(err error) error {
+ var pe *os.PathError
+ if errors.As(err, &pe) || errors.Is(err, ErrSymlink) {
+ return err
+ }
+ return &os.PathError{Op: "openat2", Path: r.where("."), Err: err}
+}
+
+// open opens the directory name under parent: exactly one component, never
+// through a symlink and never out of parent.
+func (r *treeRemover) open(parent int, name string) (int, error) {
+ how := unix.OpenHow{
+ Flags: unix.O_RDONLY | unix.O_DIRECTORY | unix.O_NOFOLLOW | unix.O_CLOEXEC,
+ Resolve: unix.RESOLVE_BENEATH | unix.RESOLVE_NO_SYMLINKS | unix.RESOLVE_NO_MAGICLINKS,
+ }
+ var fd int
+ var err error
+ for range 8 {
+ if fd, err = unix.Openat2(parent, name, &how); err != unix.EINTR && err != unix.EAGAIN {
+ break
+ }
+ }
if err != nil {
- return &os.PathError{Op: "openat", Path: path, Err: err}
+ return -1, err
}
- f := os.NewFile(uintptr(fd), path)
- names, err := f.Readdirnames(-1)
+ r.live++
+ r.peak = max(r.peak, r.live)
+ return fd, nil
+}
+
+// release closes fd unless it is the anchor.
+func (r *treeRemover) release(fd int) {
+ if fd >= 0 && fd != r.anchor {
+ unix.Close(fd)
+ r.live--
+ }
+}
+
+func (r *treeRemover) dropAnchor() {
+ if r.anchor >= 0 {
+ unix.Close(r.anchor)
+ r.live--
+ r.anchor = -1
+ }
+}
+
+func (r *treeRemover) setAnchor(fd, depth int) {
+ r.dropAnchor()
+ r.anchor, r.anchorDepth = fd, depth
+}
+
+// anchorAtDir opens dir exactly as RemoveAllBeneath's caller named it.
+func (r *treeRemover) anchorAtDir() error {
+ r.dropAnchor()
+ fd, err := openDir(r.dir)
if err != nil {
- f.Close()
return err
}
- for _, n := range names {
- if err := removeAt(fd, n, filepath.Join(path, n), depth+1); err != nil {
- f.Close()
- return err
+ r.live++
+ r.peak = max(r.peak, r.live)
+ r.anchor, r.anchorDepth = fd, -1
+ return nil
+}
+
+// at returns a descriptor for the directory at depth d, which may be the
+// anchor itself; the caller gives it back with release.
+func (r *treeRemover) at(d int) (int, error) {
+ if r.anchor >= 0 && r.anchorDepth > d {
+ r.dropAnchor()
+ }
+ if r.anchor < 0 {
+ if err := r.anchorAtDir(); err != nil {
+ return -1, err
+ }
+ }
+ keep := d / removeAnchorEvery * removeAnchorEvery
+ fd, depth := r.anchor, r.anchorDepth
+ for depth < d {
+ name := r.top
+ if depth >= 0 {
+ name = r.stack[depth]
+ }
+ next, err := r.open(fd, name)
+ if err == nil && depth == -1 {
+ err = r.sameTop(next)
+ }
+ r.release(fd)
+ if err != nil {
+ if next >= 0 {
+ r.release(next)
+ }
+ return -1, err
+ }
+ fd, depth = next, depth+1
+ if depth > 0 && depth == keep && depth > r.anchorDepth {
+ r.setAnchor(fd, depth)
}
}
- f.Close()
- if err := unix.Unlinkat(parent, name, unix.AT_REMOVEDIR); err != nil && !errors.Is(err, unix.ENOENT) {
- return &os.PathError{Op: "unlinkat", Path: path, Err: err}
+ return fd, nil
+}
+
+// sameTop refuses a top that is no longer the directory the walk began on.
+func (r *treeRemover) sameTop(fd int) error {
+ var st unix.Stat_t
+ if err := unix.Fstat(fd, &st); err != nil {
+ return err
+ }
+ if uint64(st.Dev) != r.topDev || uint64(st.Ino) != r.topIno {
+ return fmt.Errorf("instancefs: %s was replaced during removal", r.path)
}
return nil
}
+
+// clear removes what it can of the directory fd, reading it from the start
+// in batches: every non-directory, and every directory that is already
+// empty. It returns the first directory that is not, to descend into, or
+// "" once fd is empty.
+func (r *treeRemover) clear(fd int) (string, error) {
+ if _, err := unix.Seek(fd, 0, io.SeekStart); err != nil {
+ return "", &os.PathError{Op: "seek", Path: r.where("."), Err: err}
+ }
+ r.off, r.end = 0, 0
+ for {
+ names, err := r.batch(fd)
+ if err != nil {
+ return "", &os.PathError{Op: "getdents", Path: r.where("."), Err: err}
+ }
+ if len(names) == 0 {
+ return "", nil
+ }
+ for _, name := range names {
+ var st unix.Stat_t
+ if err := unix.Fstatat(fd, name, &st, unix.AT_SYMLINK_NOFOLLOW); err != nil {
+ if errors.Is(err, unix.ENOENT) {
+ continue
+ }
+ return "", &os.PathError{Op: "fstatat", Path: r.where(name), Err: err}
+ }
+ flags := 0
+ if st.Mode&unix.S_IFMT == unix.S_IFDIR {
+ flags = unix.AT_REMOVEDIR
+ }
+ err := unix.Unlinkat(fd, name, flags)
+ if flags != 0 && (errors.Is(err, unix.ENOTEMPTY) || errors.Is(err, unix.EEXIST)) {
+ return name, nil
+ }
+ if err != nil && !errors.Is(err, unix.ENOENT) {
+ return "", &os.PathError{Op: "unlinkat", Path: r.where(name), Err: err}
+ }
+ }
+ if r.afterBatch != nil {
+ if err := r.afterBatch(r.stack); err != nil {
+ return "", err
+ }
+ }
+ }
+}
+
+// batch returns up to removeBatch more names from fd, none at its end.
+func (r *treeRemover) batch(fd int) ([]string, error) {
+ if r.buf == nil {
+ r.buf = make([]byte, 8192)
+ }
+ r.names = r.names[:0]
+ for len(r.names) < removeBatch {
+ if r.off >= r.end {
+ n, err := unix.Getdents(fd, r.buf)
+ for err == unix.EINTR {
+ n, err = unix.Getdents(fd, r.buf)
+ }
+ if err != nil {
+ return nil, err
+ }
+ if n <= 0 {
+ break
+ }
+ r.off, r.end = 0, n
+ }
+ var consumed int
+ consumed, _, r.names = unix.ParseDirent(r.buf[r.off:r.end], removeBatch-len(r.names), r.names)
+ r.off += consumed
+ }
+ return r.names, nil
+}
diff --git a/internal/instancefs/instancefs.go b/internal/instancefs/instancefs.go
index aca341bd0..8a3360115 100644
--- a/internal/instancefs/instancefs.go
+++ b/internal/instancefs/instancefs.go
@@ -44,6 +44,11 @@ var ErrNotRegular = errors.New("instancefs: not a regular file")
// directory: never evidence that the name is absent.
var ErrDirUnopened = errors.New("instancefs: the directory could not be opened")
+// ErrTooDeep is returned when RemoveAllBeneath meets a tree nested deeper
+// than it will walk (65,536 directories). It stops and leaves what remains
+// in place for an operator.
+var ErrTooDeep = errors.New("instancefs: tree too deep to remove")
+
// ErrNotDir is returned when OpenDirBeneath resolves to anything other
// than a directory: a file, or a FIFO, which it never waits on.
var ErrNotDir = errors.New("instancefs: not a directory")
diff --git a/internal/instancefs/removeall_linux_test.go b/internal/instancefs/removeall_linux_test.go
new file mode 100644
index 000000000..7d8f797e9
--- /dev/null
+++ b/internal/instancefs/removeall_linux_test.go
@@ -0,0 +1,294 @@
+//go:build linux
+
+package instancefs
+
+import (
+ "errors"
+ "fmt"
+ "os"
+ "path/filepath"
+ "runtime"
+ "strings"
+ "testing"
+ "time"
+
+ "golang.org/x/sys/unix"
+)
+
+// chain makes depth nested directories named name under dir/top, one
+// component at a time from a parent descriptor, with a file at the bottom.
+// It returns the number of bytes the bottom file's full path would take.
+func chain(t *testing.T, dir string, depth int, name string) int {
+ t.Helper()
+ if err := os.Mkdir(filepath.Join(dir, "top"), 0o700); err != nil {
+ t.Fatal(err)
+ }
+ fd, err := unix.Open(filepath.Join(dir, "top"), unix.O_RDONLY|unix.O_DIRECTORY|unix.O_CLOEXEC, 0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ length := len(dir) + len("/top")
+ for range depth {
+ if err := unix.Mkdirat(fd, name, 0o700); err != nil {
+ unix.Close(fd)
+ t.Fatal(err)
+ }
+ next, err := unix.Openat(fd, name, unix.O_RDONLY|unix.O_DIRECTORY|unix.O_CLOEXEC|unix.O_NOFOLLOW, 0)
+ unix.Close(fd)
+ if err != nil {
+ t.Fatal(err)
+ }
+ fd = next
+ length += 1 + len(name)
+ }
+ defer unix.Close(fd)
+ file, err := unix.Openat(fd, "leaf", unix.O_CREAT|unix.O_WRONLY|unix.O_CLOEXEC, 0o600)
+ if err != nil {
+ t.Fatal(err)
+ }
+ unix.Close(file)
+ return length + len("/leaf")
+}
+
+// lowNofile caps this process's open descriptors at n for the rest of the
+// test, restoring the old limit before the temporary directory's cleanup.
+func lowNofile(t *testing.T, n uint64) {
+ t.Helper()
+ var old unix.Rlimit
+ if err := unix.Getrlimit(unix.RLIMIT_NOFILE, &old); err != nil {
+ t.Fatal(err)
+ }
+ if err := unix.Setrlimit(unix.RLIMIT_NOFILE, &unix.Rlimit{Cur: n, Max: old.Max}); err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { _ = unix.Setrlimit(unix.RLIMIT_NOFILE, &old) })
+}
+
+func gone(t *testing.T, path string) {
+ t.Helper()
+ if _, err := os.Lstat(path); !errors.Is(err, os.ErrNotExist) {
+ t.Fatalf("%s still there: %v", path, err)
+ }
+}
+
+// F6: a tree 10,000 directories deep purges with only 16 descriptors
+// allowed to the whole process.
+func TestRemoveAllBeneathTenThousandDeepLowNofile(t *testing.T) {
+ if testing.Short() {
+ t.Skip("walks a 10,000-deep tree")
+ }
+ dir := t.TempDir()
+ chain(t, dir, 10000, "d")
+ lowNofile(t, 16)
+ start := time.Now()
+ if err := RemoveAllBeneath(dir, "top"); err != nil {
+ t.Fatal(err)
+ }
+ t.Logf("10,000 deep: %s", time.Since(start))
+ gone(t, filepath.Join(dir, "top"))
+}
+
+// F6: a tree whose deepest path is longer than 64 KiB (well past PATH_MAX)
+// purges: no joined path ever reaches the kernel.
+func TestRemoveAllBeneathPathOver64KiBLowNofile(t *testing.T) {
+ dir := t.TempDir()
+ name := strings.Repeat("n", 255)
+ if n := chain(t, dir, 260, name); n <= 64<<10 {
+ t.Fatalf("fixture path is only %d bytes", n)
+ }
+ lowNofile(t, 16)
+ if err := RemoveAllBeneath(dir, "top"); err != nil {
+ t.Fatal(err)
+ }
+ gone(t, filepath.Join(dir, "top"))
+}
+
+// F6: a directory of 100,000 entries purges in batches: the names are
+// never all in memory at once.
+func TestRemoveAllBeneathHundredThousandEntriesBoundedMemory(t *testing.T) {
+ if testing.Short() {
+ t.Skip("creates 100,000 files")
+ }
+ dir := t.TempDir()
+ top := filepath.Join(dir, "top")
+ if err := os.Mkdir(top, 0o700); err != nil {
+ t.Fatal(err)
+ }
+ fd, err := unix.Open(top, unix.O_RDONLY|unix.O_DIRECTORY|unix.O_CLOEXEC, 0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ // 100,000 names of 120 bytes: about 13 MiB as Go strings if read whole.
+ pad := strings.Repeat("x", 113)
+ for i := range 100000 {
+ f, err := unix.Openat(fd, fmt.Sprintf("%06d-%s", i, pad), unix.O_CREAT|unix.O_WRONLY|unix.O_CLOEXEC, 0o600)
+ if err != nil {
+ unix.Close(fd)
+ t.Fatal(err)
+ }
+ unix.Close(f)
+ }
+ unix.Close(fd)
+ runtime.GC()
+ var base runtime.MemStats
+ runtime.ReadMemStats(&base)
+ peak := base.HeapAlloc
+ stop := make(chan struct{})
+ sampled := make(chan struct{})
+ go func() {
+ defer close(sampled)
+ var m runtime.MemStats
+ for {
+ runtime.ReadMemStats(&m)
+ peak = max(peak, m.HeapAlloc)
+ select {
+ case <-stop:
+ return
+ case <-time.After(time.Millisecond):
+ }
+ }
+ }()
+ err = RemoveAllBeneath(dir, "top")
+ close(stop)
+ <-sampled
+ if err != nil {
+ t.Fatal(err)
+ }
+ gone(t, top)
+ t.Logf("heap growth during purge: %d KiB", (peak-base.HeapAlloc)>>10)
+ if grew := peak - base.HeapAlloc; grew > 6<<20 {
+ t.Fatalf("heap grew %d KiB while purging", grew>>10)
+ }
+}
+
+func files(t *testing.T, dir string, n int) {
+ t.Helper()
+ if err := os.MkdirAll(dir, 0o700); err != nil {
+ t.Fatal(err)
+ }
+ for i := range n {
+ if err := os.WriteFile(filepath.Join(dir, fmt.Sprintf("f%04d", i)), nil, 0o600); err != nil {
+ t.Fatal(err)
+ }
+ }
+}
+
+// The walk never holds more than three directory descriptors, dir's
+// included, even across its anchors in a deep tree with side branches, and
+// gives every one back.
+func TestRemoveAllBeneathHoldsAtMostThreeDescriptors(t *testing.T) {
+ dir := t.TempDir()
+ chain(t, dir, 700, "d")
+ p := filepath.Join(dir, "top")
+ for depth := range 700 {
+ p = filepath.Join(p, "d")
+ if depth%97 == 0 {
+ files(t, filepath.Join(p, "side", "deeper"), 300)
+ }
+ }
+ lowNofile(t, 16)
+ r := treeRemover{dir: dir, top: "top", path: filepath.Join(dir, "top"), maxDepth: removeMaxDepth}
+ if err := r.remove(); err != nil {
+ t.Fatal(err)
+ }
+ gone(t, filepath.Join(dir, "top"))
+ if r.peak > 3 || r.live != 0 {
+ t.Fatalf("peak=%d live=%d directory descriptors", r.peak, r.live)
+ }
+}
+
+// A directory swapped for a symlink between batches is not followed: the
+// walk refuses the link, and the next removal unlinks it and finishes.
+func TestRemoveAllBeneathSwappedDirectoryNotFollowed(t *testing.T) {
+ dir := t.TempDir()
+ outside := t.TempDir()
+ files(t, filepath.Join(outside, "sub"), 1)
+ files(t, outside, 1)
+ top := filepath.Join(dir, "top")
+ files(t, filepath.Join(top, "D"), 600)
+ files(t, filepath.Join(top, "D", "sub"), 1)
+ swapped := false
+ r := treeRemover{dir: dir, top: "top", path: top, maxDepth: removeMaxDepth, afterBatch: func(stack []string) error {
+ if !swapped && len(stack) > 0 && stack[0] == "D" {
+ swapped = true
+ if err := os.Rename(filepath.Join(top, "D"), filepath.Join(top, "D2")); err != nil {
+ return err
+ }
+ return os.Symlink(outside, filepath.Join(top, "D"))
+ }
+ return nil
+ }}
+ err := r.remove()
+ if !swapped {
+ t.Fatal("never swapped")
+ }
+ if !errors.Is(err, unix.ELOOP) && !errors.Is(err, unix.ENOTDIR) {
+ t.Fatalf("walked through the swapped-in symlink: %v", err)
+ }
+ t.Logf("refused: %v", err)
+ for _, f := range []string{"f0000", "sub/f0000"} {
+ if _, e := os.Stat(filepath.Join(outside, f)); e != nil {
+ t.Fatalf("followed the symlink: %s: %v (removal said %v)", f, e, err)
+ }
+ }
+ if err := RemoveAllBeneath(dir, "top"); err != nil {
+ t.Fatal(err)
+ }
+ gone(t, top)
+ for _, f := range []string{"f0000", "sub/f0000"} {
+ if _, e := os.Stat(filepath.Join(outside, f)); e != nil {
+ t.Fatalf("retry followed the symlink: %s: %v", f, e)
+ }
+ }
+}
+
+// An error mid-walk leaves a smaller tree; the next removal finishes it.
+func TestRemoveAllBeneathInterruptedResumes(t *testing.T) {
+ dir := t.TempDir()
+ top := filepath.Join(dir, "top")
+ files(t, top, 300)
+ files(t, filepath.Join(top, "a"), 300)
+ files(t, filepath.Join(top, "b", "c"), 300)
+ injected := errors.New("injected")
+ batches := 0
+ r := treeRemover{dir: dir, top: "top", path: top, maxDepth: removeMaxDepth, afterBatch: func([]string) error {
+ if batches++; batches == 3 {
+ return injected
+ }
+ return nil
+ }}
+ if err := r.remove(); !errors.Is(err, injected) {
+ t.Fatalf("err=%v", err)
+ }
+ if r.live != 0 {
+ t.Fatalf("%d directory descriptors left open", r.live)
+ }
+ if _, err := os.Lstat(top); err != nil {
+ t.Fatal("interrupted removal already finished")
+ }
+ if err := RemoveAllBeneath(dir, "top"); err != nil {
+ t.Fatal(err)
+ }
+ gone(t, top)
+}
+
+// Past the depth bound the walk refuses with ErrTooDeep and leaves the
+// tree; within it, it removes everything.
+func TestRemoveAllBeneathTooDeep(t *testing.T) {
+ dir := t.TempDir()
+ chain(t, dir, 12, "d")
+ r := treeRemover{dir: dir, top: "top", path: filepath.Join(dir, "top"), maxDepth: 8}
+ if err := r.remove(); !errors.Is(err, ErrTooDeep) {
+ t.Fatalf("err=%v", err)
+ }
+ if r.live != 0 {
+ t.Fatalf("%d directory descriptors left open", r.live)
+ }
+ if _, err := os.Lstat(filepath.Join(dir, "top", "d", "d", "d", "d", "d", "d", "d", "d", "d")); err != nil {
+ t.Fatal("refused removal did not leave the tree", err)
+ }
+ if err := RemoveAllBeneath(dir, "top"); err != nil {
+ t.Fatal(err)
+ }
+ gone(t, filepath.Join(dir, "top"))
+}