Skip to content

The agent that grows with you

prune(scratch): rescue entries touched mid-prune (C1/F1, #132401)

Viiy6189904aafa5
diff --git a/hermes_constants.py b/hermes_constants.py
index 98507d5fdb0..b2aad521b26 100644
--- a/hermes_constants.py
+++ b/hermes_constants.py
@@ -967,8 +967,9 @@ def get_scratch_dir(home: str | Path | None = None, *, prune: bool = True) -> Pa
def prune_scratch_dir(scratch: Path | None = None, max_idle_hours: float = SCRATCH_MAX_IDLE_HOURS) -> int:
"""Delete top-level scratch entries with no write anywhere in their subtree for
*max_idle_hours*, reaping processes and git worktree registrations rooted in them
- first (``hermes_constants_scratch``); return the count removed. Each removal and kill is
- recorded in ``<home>/logs/scratch-prune.log`` (*scratch* is ``<home>/cache/scratch``)."""
+ first (``hermes_constants_scratch``); return the count removed. Each removal, each
+ kill and each entry rescued mid-prune is recorded in ``<home>/logs/scratch-prune.log``
+ (*scratch* is ``<home>/cache/scratch``)."""
from hermes_constants_scratch import prune_idle_entries
root = scratch if scratch is not None else get_scratch_dir(prune=False)
diff --git a/hermes_constants_scratch.py b/hermes_constants_scratch.py
index ec14a164ec4..2adfd867f4c 100644
--- a/hermes_constants_scratch.py
+++ b/hermes_constants_scratch.py
@@ -22,8 +22,8 @@ logger = logging.getLogger(__name__)
_REAP_GRACE_SECONDS = 3.0
# ``.git`` files (linked worktrees) are looked for this deep; lanes nest repo/tree/subtree.
_GIT_FILE_MAX_DEPTH = 4
-# logs/scratch-prune.log: one line per entry deleted and per process signalled (#132401). Same
-# fixed rotation as tool_calls.log.
+# logs/scratch-prune.log: one line per entry deleted, per process signalled, and per
+# entry rescued or vanished mid-prune (#132401). Same fixed rotation as tool_calls.log.
_PRUNE_LOG_MAX_BYTES = 5 * 1024 * 1024
_PRUNE_LOG_BACKUPS = 3
# Paths and process names go in with %r: a control character (a newline in a legal POSIX name)
@@ -245,8 +245,9 @@ def prune_idle_entries(
) -> int:
"""Delete top-level entries of *root* with no write anywhere in their subtree for
*max_idle_hours*, reaping processes and worktree registrations rooted in them first.
- Each removal and each signalled process is recorded in *log_file*. Returns the count
- actually removed."""
+ Each removal, each signalled process and each entry rescued mid-prune (touched
+ again after selection) is recorded in *log_file*. Returns the count actually
+ removed."""
audit = _open_prune_log(log_file)
try:
return _prune_idle_entries(root, max_idle_hours, skip_names, audit)
@@ -276,10 +277,28 @@ def _prune_idle_entries(
repos: set[str] = set()
removed = 0
for entry in doomed:
+ # Worktree scan first: a registration whose tree an earlier pass (or hand)
+ # removed is stale even in a rescued entry, and the re-check below sits as
+ # close to the delete as the loop allows.
+ if entry.is_dir() and not entry.is_symlink():
+ repos |= _linked_worktree_repos(entry)
+ # Last-moment re-validation (#132401 C1/F1): ``doomed`` is a snapshot from
+ # before the reap ran, and a writer whose cwd is outside scratch — invisible
+ # to the reap — can land fresh work in that window. The snapshot is a
+ # candidate list, never a verdict: anything touched since selection is
+ # rescued here, not deleted; an unreadable entry is kept, as in selection.
+ if subtree_touched_since(entry, cutoff):
+ if os.path.lexists(entry):
+ audit.info(
+ "scratch prune: rescued %r — touched since selection, kept",
+ os.fspath(entry),
+ )
+ else:
+ audit.info("scratch prune: entry %r vanished since selection", os.fspath(entry))
+ continue
size = _tree_bytes(entry)
try:
if entry.is_dir() and not entry.is_symlink():
- repos |= _linked_worktree_repos(entry)
shutil.rmtree(entry, ignore_errors=True)
else:
entry.unlink()
diff --git a/tests/test_scratch_dir.py b/tests/test_scratch_dir.py
index d4596a75d0d..c66c3d8678f 100644
--- a/tests/test_scratch_dir.py
+++ b/tests/test_scratch_dir.py
@@ -387,3 +387,34 @@ def test_prune_releases_git_worktree_registration_of_idle_entry(tmp_path):
listing = subprocess.run(["git", "worktree", "list", "--porcelain"], cwd=repo, capture_output=True,
text=True, stdin=subprocess.DEVNULL, check=True).stdout
assert str(tree) not in listing and not tree.exists()
+
+
+def test_midprune_resumed_write_is_rescued(tmp_path: Path) -> None:
+ """F1 on #132401, ported from 3f72fd9c8e (#132455): a writer whose cwd is outside
+ scratch — invisible to the reap — resumes during the prune's own reap window and
+ lands a fresh file in a doomed entry. The doomed list is a candidate list, never a
+ verdict: the entry is re-validated with the same idleness walk immediately before
+ deletion, rescued, recorded in ``scratch-prune.log``, and never counted as removed.
+ Red on pre-fix code: the entry is destroyed with the fresh write inside."""
+ scratch = get_scratch_dir(tmp_path, prune=False)
+ entry = scratch / "resumed-lane"
+ entry.mkdir()
+ (entry / "old-output.md").write_text("stale content\n", encoding="utf-8")
+ ancient = time.time() - 30 * 3600
+ for path in (entry / "old-output.md", entry):
+ os.utime(path, (ancient, ancient))
+ fresh = entry / "resumed-work.md"
+
+ def write_during_reap(root, doomed, *args, **kwargs):
+ # The resumed writer lands its fresh write mid-prune: selection is done,
+ # the deletion loop has not started. This is the F1 window.
+ fresh.write_text("FRESH RESUMED WORK\n", encoding="utf-8")
+ return 0
+
+ with patch("hermes_constants_scratch.reap_processes_rooted_in", write_during_reap):
+ assert prune_scratch_dir(scratch) == 0 # rescued — not counted as removed
+ assert fresh.exists(), "fresh mid-prune write was destroyed"
+ assert entry.exists()
+ log = (tmp_path / "logs" / "scratch-prune.log").read_text(encoding="utf-8-sig")
+ assert f"rescued {str(entry)!r} " in log, log
+ assert f"removed {str(entry)!r} (" not in log, log