Skip to content

The agent that grows with you

fix(pm): an interrupted orphan reclaim leaves a dir the next pass still finds

Teknium121eb0c4cd96
diff --git a/pm/install_states.py b/pm/install_states.py
index 1ae35054c6c..ffa363ae764 100644
--- a/pm/install_states.py
+++ b/pm/install_states.py
@@ -18,6 +18,7 @@ lock, or a dependency / PM runtime generation lease.
from __future__ import annotations
+import contextlib
import logging
import os
import shutil
@@ -83,6 +84,20 @@ def collect_orphan_install_states(installs: Path) -> list[Path]:
if _held(state):
logger.debug("orphan install state %s is still held; skipped", state.name)
continue
+ # The record goes last, and only once everything else is gone: the startup prune runs on
+ # a daemon thread and a removal can fail part-way (an open file on Windows, a read-only
+ # dir), and a dir that lost its record first would never be recognised again.
+ for child in state.iterdir():
+ if child.name == "inputs":
+ continue
+ if child.is_dir() and not child.is_symlink():
+ shutil.rmtree(child, ignore_errors=True)
+ else:
+ with contextlib.suppress(OSError):
+ child.unlink()
+ if any(child.name != "inputs" for child in state.iterdir()):
+ logger.debug("orphan install state %s only partly removed; retried next pass", state.name)
+ continue
shutil.rmtree(state, ignore_errors=True)
if not state.exists():
removed.append(state)
diff --git a/tests/pm/test_install_states_gc.py b/tests/pm/test_install_states_gc.py
index 3ed517e2005..ea9f3a3b3a2 100644
--- a/tests/pm/test_install_states_gc.py
+++ b/tests/pm/test_install_states_gc.py
@@ -7,6 +7,7 @@ import os
import subprocess
import pm.environments
+import pytest
from hermes_cli.worktree_ops import _prune_stale_worktrees
from pm.filesystem import lock_fd
from pm.install_states import collect_orphan_install_states, orphan_install_states
@@ -66,3 +67,19 @@ def test_held_orphan_is_kept(tmp_path):
os.close(fd)
# Locks released (owner exited): all are reclaimed on the next pass.
assert sorted(p.name for p in collect_orphan_install_states(installs)) == ["dddd", "eeee", "ffff"]
+
+
[email protected](getattr(os, "geteuid", lambda: 1)() == 0, reason="root ignores directory modes")
+def test_partly_removed_orphan_keeps_its_record_until_retried(tmp_path):
+ installs = tmp_path / "installs"
+ state = _state(installs, "aaaa", tmp_path / "gone")
+ stuck = state / "environments" / "gen" / "venv"
+ (stuck / "pyvenv.cfg").write_text("", encoding="utf-8")
+ stuck.chmod(0o500) # its entries cannot be unlinked: the removal stops part-way
+ try:
+ assert collect_orphan_install_states(installs) == []
+ assert orphan_install_states(installs) == [state]
+ finally:
+ stuck.chmod(0o700)
+ assert collect_orphan_install_states(installs) == [state] and not state.exists()