The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(scratch): a failed re-scan is not activity — tri-state mid-prune audit (P3 on #134173)
Viiy491c50fed8d0
diff --git a/hermes_constants_scratch.py b/hermes_constants_scratch.pyindex 2adfd867f4c..68831dc7cd0 100644--- a/hermes_constants_scratch.py+++ b/hermes_constants_scratch.py@@ -92,21 +92,23 @@ def _tree_bytes(path: Path) -> int:return total-def subtree_touched_since(path: Path, cutoff: float) -> bool:- """True when *path* or anything beneath it has an mtime at or after *cutoff*.+_TOUCHED = "touched"+_SCAN_FAILED = "scan-failed"+_IDLE = "idle"- Stops at the first recent entry, so a live tree costs one hit and only a truly idle- tree pays for the full walk (once, right before it is deleted). Symlinks are never- followed: a link into the repo would make the target's activity keep the entry alive.- An unreadable entry is kept: an incomplete scan cannot establish that it is idle.- """++def subtree_touch_state(path: Path, cutoff: float) -> str:+ """Tri-state form of :func:`subtree_touched_since`: ``touched`` (recent write seen),+ ``scan-failed`` (unreadable — idle cannot be established, so the entry is kept, but+ a failed scan is not activity and is never reported as such), or ``idle``.+ Same walk, same stop-at-first-recent shortcut, same symlink rules."""try:if os.lstat(path).st_mtime >= cutoff:- return True+ return _TOUCHEDif not path.is_dir() or path.is_symlink():- return False+ return _IDLEexcept OSError:- return True+ return _SCAN_FAILEDstack = [str(path)]while stack:try:@@ -114,14 +116,27 @@ def subtree_touched_since(path: Path, cutoff: float) -> bool:for child in it:try:if child.stat(follow_symlinks=False).st_mtime >= cutoff:- return True+ return _TOUCHEDexcept OSError:- return True+ return _SCAN_FAILEDif child.is_dir(follow_symlinks=False):stack.append(child.path)except OSError:- return True- return False+ return _SCAN_FAILED+ return _IDLE+++def subtree_touched_since(path: Path, cutoff: float) -> bool:+ """True when *path* or anything beneath it has an mtime at or after *cutoff*.++ Stops at the first recent entry, so a live tree costs one hit and only a truly idle+ tree pays for the full walk (once, right before it is deleted). Symlinks are never+ followed: a link into the repo would make the target's activity keep the entry alive.+ An unreadable entry is kept: an incomplete scan cannot establish that it is idle —+ so True here means "touched **or** uninspectable", and callers that need to tell the+ two apart (the mid-prune audit) use :func:`subtree_touch_state` instead.+ """+ return subtree_touch_state(path, cutoff) != _IDLEdef _under(path: str, root: str) -> bool:@@ -286,15 +301,35 @@ def _prune_idle_entries(# 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):+ # rescued here, not deleted. A re-scan that cannot read the entry is also+ # fail-closed (the entry is kept), but a failed scan is not activity — the+ # audit names the failed re-scan instead of inventing a touch that did not+ # happen, so operators can tell an uninspectable candidate from verified+ # recent activity (P3 on #134173).+ state = subtree_touch_state(entry, cutoff)+ if state != _IDLE:+ # Only a missing path is a vanish: a stat that raises PermissionError means+ # the entry is there but unreadable, and reporting it as vanished would be+ # the same invented reason the audit exists to prevent.+ try:+ os.lstat(entry)+ entry_gone = False+ except FileNotFoundError:+ entry_gone = True+ except OSError:+ entry_gone = False+ if entry_gone:+ audit.info("scratch prune: entry %r vanished since selection", os.fspath(entry))+ elif state == _TOUCHED: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))+ audit.info(+ "scratch prune: kept %r — activity re-scan failed, left untouched",+ os.fspath(entry),+ )continuesize = _tree_bytes(entry)try:diff --git a/tests/test_scratch_dir.py b/tests/test_scratch_dir.pyindex c66c3d8678f..6f1776bccb1 100644--- a/tests/test_scratch_dir.py+++ b/tests/test_scratch_dir.py@@ -418,3 +418,30 @@ def test_midprune_resumed_write_is_rescued(tmp_path: Path) -> None:log = (tmp_path / "logs" / "scratch-prune.log").read_text(encoding="utf-8-sig")assert f"rescued {str(entry)!r} " in log, logassert f"removed {str(entry)!r} (" not in log, log+++def test_midprune_vanished_entry_is_recorded_not_counted(tmp_path: Path) -> None:+ """The third state beside rescued and kept: an entry deleted by an outside actor+ during the reap window is recorded as vanished — not a rescue (no touch happened),+ not a scan failure (nothing is unreadable), and never counted as removed (we did+ not remove it). Pins the tri-state audit born in the P3 review of #134173."""+ scratch = get_scratch_dir(tmp_path, prune=False)+ entry = scratch / "doomed-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))++ def remove_during_reap(root, doomed, *args, **kwargs):+ # An outside actor (a lane's own cleanup) deletes the entry mid-prune.+ shutil.rmtree(entry)+ return 0++ with patch("hermes_constants_scratch.reap_processes_rooted_in", remove_during_reap):+ assert prune_scratch_dir(scratch) == 0 # gone, but not by our hand+ assert not entry.exists()+ log = (tmp_path / "logs" / "scratch-prune.log").read_text(encoding="utf-8-sig")+ assert f"entry {str(entry)!r} vanished" in log, log+ assert f"rescued {str(entry)!r} " not in log, log+ assert "re-scan failed" not in log, logdiff --git a/tests/test_scratch_scan_failures.py b/tests/test_scratch_scan_failures.pyindex 7850a7226a3..1de9596fbb4 100644--- a/tests/test_scratch_scan_failures.py+++ b/tests/test_scratch_scan_failures.py@@ -58,3 +58,77 @@ def test_unreadable_subtree_is_preserved_until_it_can_be_scanned(tmp_path, monke# Once observation succeeds, the same genuinely idle tree is reclaimable.assert scratch.prune_idle_entries(root, 24, frozenset()) == 1assert not entry.exists()++[email protected]("failed_probe", ["root-stat", "directory-scan", "child-stat"])+def test_post_selection_scan_failure_keeps_entry_with_honest_audit(+ tmp_path, monkeypatch, failed_probe+):+ """P3 on #134173: the mid-prune re-validation is a fail-closed keep, and its record+ must not dress a failed re-scan up as observed activity. Selection completes on a+ genuinely idle entry, then the re-validation scan fails: the entry is kept with its+ bytes and mtime intact, and the audit names the failed re-scan — it never claims+ the entry was touched. Once the scan works again, the entry is reclaimable."""+ root = tmp_path / "scratch"+ entry = root / "lane"+ entry.mkdir(parents=True)+ result = entry / "result.txt"+ result.write_text("keep until activity can be checked", encoding="utf-8")+ old = time.time() - 48 * 3600+ os.utime(result, (old, old))+ os.utime(entry, (old, old))+ log_file = tmp_path / "logs" / "scratch-prune.log"++ state = {"selected": False}++ def reap_after_selection(*_args, **_kwargs):+ # The doomed list is built; every scan past this point is the re-validation walk.+ state["selected"] = True+ return 0++ monkeypatch.setattr(scratch, "reap_processes_rooted_in", reap_after_selection)+ real_lstat, real_scandir = os.lstat, os.scandir+ with monkeypatch.context() as probe:+ if failed_probe == "root-stat":+ def lstat(path, *args, **kwargs):+ if state["selected"] and path == entry:+ raise PermissionError("cannot inspect entry")+ return real_lstat(path, *args, **kwargs)+ probe.setattr(scratch.os, "lstat", lstat)+ else:+ def scandir(path):+ if state["selected"] and path == str(entry):+ if failed_probe == "directory-scan":+ raise PermissionError("cannot inspect subtree")++ class UnreadableChild:+ name = "result.txt"++ def stat(self, **_kwargs):+ raise OSError("cannot inspect child activity")++ def is_dir(self, **_kwargs):+ return False++ class Scan:+ def __enter__(self):+ return iter([UnreadableChild()])++ def __exit__(self, *_args):+ pass++ return Scan()+ return real_scandir(path)+ probe.setattr(scratch.os, "scandir", scandir)+ # Kept, never counted as removed, original bytes and mtime intact: no payload+ # write occurred, and none may be invented by the audit.+ assert scratch.prune_idle_entries(root, 24, frozenset(), log_file) == 0+ assert result.read_text(encoding="utf-8") == "keep until activity can be checked"+ assert result.stat().st_mtime == old+ log = log_file.read_text(encoding="utf-8-sig")+ assert "touched since selection" not in log, log+ assert f"kept {str(entry)!r} " in log, log+ assert "activity re-scan failed, left untouched" in log, log+ # A later prune that can scan the entry reclaims it: fail-closed, not fail-forever.+ assert scratch.prune_idle_entries(root, 24, frozenset(), log_file) == 1+ assert not entry.exists()