Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 42 additions & 5 deletions infra/worktree-reaper/bin/worktree_reaper.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,9 @@
= newest working-tree file mtime excluding the tree's root
.git entry, max()ed with the HEAD reflog timestamp.
4. UNOCCUPIED a fresh /proc cwd scan shows no process inside the tree
(re-scanned immediately before each removal).
(re-scanned immediately before each removal). A scan that
fails (e.g. /proc cannot be listed) proves nothing: the
tree is treated as occupied and retained (#5740).
5. NOT DENIED the tree is not on the config denylist, is not a primary,
is not under ~/backups or ~/atlas, and does not contain
this running script.
Expand Down Expand Up @@ -375,12 +377,20 @@ def walk_activity(tree, cutoff):


def proc_cwds():
"""Cwds of every other live process, from /proc.

Returns None when /proc cannot be listed at all: a failed scan is
NOT a successful scan with zero matches, and callers must fail
closed (treat occupancy as unknown) rather than as unoccupied
(#5740). Per-process readlink failures still skip just that
process — the scan itself succeeded.
"""
cwds = []
me = str(os.getpid())
try:
pids = os.listdir("/proc")
except OSError:
return cwds
return None
for pid in pids:
if not pid.isdigit() or pid == me:
continue
Expand All @@ -394,9 +404,22 @@ def proc_cwds():
return cwds


def tree_occupied(tree, cwds=None):
_FRESH_SCAN = object()


def tree_occupied(tree, cwds=_FRESH_SCAN):
"""True when a process cwd is inside `tree`.

`cwds` is a proc_cwds() result; omit it to scan fresh. A None
result (the /proc scan failed) means occupancy is UNKNOWN, which
fails closed: the tree counts as occupied (#5740).
"""
if cwds is _FRESH_SCAN:
cwds = proc_cwds()
if cwds is None:
return True
rp = os.path.realpath(tree)
for cwd in (proc_cwds() if cwds is None else cwds):
for cwd in cwds:
c = os.path.realpath(cwd)
if c == rp or c.startswith(rp + os.sep):
return True
Expand Down Expand Up @@ -467,6 +490,10 @@ def evaluate_tree(primary, wt, cfg, now, cwds):
if not gates["quiet"]["ok"]:
rec["reason"] = "active"
return rec
if cwds is None:
gates["occupied"] = {"ok": False, "error": "proc-scan-failed"}
rec["reason"] = "occupied-unknown"
return rec
occupied = tree_occupied(tree, cwds)
gates["occupied"] = {"ok": not occupied}
if occupied:
Expand All @@ -482,7 +509,12 @@ def reap_tree(primary, rec, cfg):
# Re-verify in the same run, immediately before the irreversible step:
# fresh /proc scan and a fresh dirt check (spec: --force only when the
# sole blocker is allowlisted dirt, re-verified in the same run).
if tree_occupied(tree):
fresh_cwds = proc_cwds()
if fresh_cwds is None:
rec["action"] = "keep"
rec["reason"] = "occupied-unknown-at-removal"
return False
if tree_occupied(tree, fresh_cwds):
rec["action"] = "keep"
rec["reason"] = "occupied-at-removal"
return False
Expand Down Expand Up @@ -549,6 +581,11 @@ def main(argv=None):

primaries = [expand(p) for p in args.primary] or discover_primaries(cfg)
cwds = proc_cwds()
if cwds is None:
msg = ("proc scan failed: occupancy unknown for every tree; "
"all trees retained (fail closed, #5740)")
print(f"worktree-reaper: {msg}", file=sys.stderr)
summary["errors"].append(msg)
reaped_count = 0
cap = int(cfg["max_removals"])

Expand Down
92 changes: 92 additions & 0 deletions infra/worktree-reaper/tests/test_worktree_reaper.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
detached HEAD -> kept (detached, v1 rule)
denylisted tree -> kept (denied)
process cwd inside tree -> kept (occupied)
/proc scan failure at evaluation -> kept (occupied-unknown)
/proc scan failure at removal re-scan -> kept (occupied-unknown-at-removal)
fresh tree with huge quiet_hours -> kept (active)
--dry-run -> would-reap listed, tree intact
DISABLED kill switch -> exit 0, nothing touched
Expand All @@ -37,6 +39,7 @@
import tempfile
import time
import unittest
from unittest import mock

HERE = os.path.dirname(os.path.abspath(__file__))
BIN = os.path.join(HERE, "..", "bin", "worktree_reaper.py")
Expand Down Expand Up @@ -255,6 +258,77 @@ def test_04_quiet_gate(self):
self.assertFalse(os.path.isdir(tree))



class ProcScanFailureTests(unittest.TestCase):
"""#5740: a /proc scan failure must fail closed at BOTH occupancy
consumers — evaluation and the pre-removal re-scan. Oracle: the
candidate tree and its branch survive on disk (so `git worktree
remove` and `git branch -d` demonstrably never ran); the decision
records are checked only for the named reason."""

def _repo_and_tree(self, tmp):
repo = SyntheticRepo(tmp)
runner = ReaperRun(repo, os.path.join(tmp, "state"))
tree = repo.branch_tree("t/victim", push=True)
return repo, runner, tree

@staticmethod
def _fail_proc(fail_first):
"""os.listdir wrapper: listing /proc raises OSError — from the
first call, or from the second (the run-wide evaluation scan
consumes the first; the pre-removal re-scan is the second).
Every other path delegates to the real listdir."""
real_listdir = os.listdir
calls = {"n": 0}

def fake(path="."):
if path == "/proc":
calls["n"] += 1
if fail_first or calls["n"] > 1:
raise OSError("injected /proc failure")
return real_listdir(path)

return fake

def test_scan_failure_at_evaluation_retains_candidate(self):
tmp = tempfile.mkdtemp(prefix="wtreaper-procfail-eval-")
try:
repo, runner, tree = self._repo_and_tree(tmp)
with mock.patch("os.listdir",
side_effect=self._fail_proc(fail_first=True)):
decisions = runner.run()
self.assertTrue(os.path.isdir(tree), "candidate must be retained")
self.assertTrue(repo.branch_exists("t/victim"),
"branch must survive")
self.assertEqual(decisions[tree]["action"], "keep")
self.assertEqual(decisions[tree]["reason"], "occupied-unknown")
self.assertEqual(
decisions[tree]["gates"]["occupied"]["error"],
"proc-scan-failed")
finally:
shutil.rmtree(tmp, ignore_errors=True)

def test_scan_failure_at_removal_rescan_retains_candidate(self):
tmp = tempfile.mkdtemp(prefix="wtreaper-procfail-reap-")
try:
repo, runner, tree = self._repo_and_tree(tmp)
with mock.patch("os.listdir",
side_effect=self._fail_proc(fail_first=False)):
decisions = runner.run()
self.assertTrue(
os.path.isdir(tree),
"tree must survive a failed removal re-scan "
"(git worktree remove must not run)")
self.assertTrue(
repo.branch_exists("t/victim"),
"branch must survive (git branch -d must not run)")
self.assertEqual(decisions[tree]["action"], "keep")
self.assertEqual(decisions[tree]["reason"],
"occupied-unknown-at-removal")
finally:
shutil.rmtree(tmp, ignore_errors=True)


class RunLogCollisionTests(unittest.TestCase):
"""#5716: two runs in the same second must not share a run log."""

Expand Down Expand Up @@ -298,6 +372,24 @@ def test_dirt_allowlisted(self):
self.assertEqual(len(allow), 3)
self.assertEqual(other, ["src/real.py"])

def test_proc_cwds_scan_failure_is_unknown_not_empty(self):
# Oracle: the /proc listing is the failure point — a failed scan
# must be distinguishable from a successful scan with no matches.
with mock.patch("os.listdir", side_effect=OSError("no /proc")):
self.assertIsNone(wr.proc_cwds())

def test_tree_occupied_unknown_scan_fails_closed(self):
root = tempfile.mkdtemp(prefix="wtreaper-occ-")
try:
self.assertTrue(wr.tree_occupied(root, None),
"unknown occupancy must count as occupied")
self.assertFalse(wr.tree_occupied(root, []),
"successful empty scan still means unoccupied")
self.assertTrue(wr.tree_occupied(root, [root]),
"confirmed matching cwd still means occupied")
finally:
shutil.rmtree(root, ignore_errors=True)

def test_walk_activity(self):
root = tempfile.mkdtemp(prefix="wtreaper-walk-")
try:
Expand Down
Loading