The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(pm): collect superseded and aborted PM runtime generations
ethernet15335df680ed
diff --git a/hermes_cli/runtime_state.py b/hermes_cli/runtime_state.pyindex e48923b7ad0..813c7bd233e 100644--- a/hermes_cli/runtime_state.py+++ b/hermes_cli/runtime_state.py@@ -190,7 +190,11 @@ def lease_generation(environment: Path) -> Callable[[], None]:caller must re-read the selection after leasing: an installer may have moved it in between,and an unselected, unleased generation is exactly what the collector removes."""- generation = environment.parent+ return lease_directory(environment.parent)+++def lease_directory(generation: Path) -> Callable[[], None]:+ """Pin a lease-managed generation directory for this process's lifetime."""if not (generation / ".lease-managed").is_file():return lambda: None # Generations produced before leases stay conservatively retained.leases = generation / ".leases"@@ -236,16 +240,19 @@ def collect_generations(project: Path, *, min_age_seconds: float = 86400) -> lismarker = generation / ".lease-managed"if not marker.is_file() or time.time() - marker.stat().st_mtime < min_age_seconds:continue- active = False- for lease in (generation / ".leases").glob("*"):- fd = os.open(lease, os.O_RDWR)- try:- if not _lock(fd, wait=False):- active = True- break- finally:- os.close(fd)- if not active:+ if not leases_held(generation):shutil.rmtree(generation)removed.append(generation)return removed+++def leases_held(generation: Path) -> bool:+ """True while any process still holds a lease taken by ``lease_directory``."""+ for lease in (generation / ".leases").glob("*"):+ fd = os.open(lease, os.O_RDWR)+ try:+ if not _lock(fd, wait=False):+ return True+ finally:+ os.close(fd)+ return Falsediff --git a/pm/cli.py b/pm/cli.pyindex 7faaf6f5848..883b1feadf5 100644--- a/pm/cli.py+++ b/pm/cli.py@@ -288,9 +288,13 @@ def cmd_gc(args) -> int:facts = _facts() if store.root == _store().root else Facts(store.root / "facts.json")removed, kept = _gc_store(store, facts)from hermes_cli.runtime_state import collect_generations+ from pm.environments import install_state_dirfrom pm.paths import repo_root+ from pm.runtime import collect_runtime_generationsgenerations = collect_generations(repo_root())- print(f"gc: removed {removed}, kept {kept}; removed {len(generations)} dependency generations")+ runtimes = collect_runtime_generations(install_state_dir(repo_root()) / "pm-runtime")+ print(f"gc: removed {removed}, kept {kept}; removed {len(generations)} dependency generations, "+ f"{len(runtimes)} PM runtime generations")return 0diff --git a/pm/launch.py b/pm/launch.pyindex 96aa6bd7c29..ce4dcee3acf 100644--- a/pm/launch.py+++ b/pm/launch.py@@ -9,6 +9,8 @@ truststore.inject_into_ssl()sys.path.insert(0, str(Path(__file__).resolve().parents[1]))from pm.cli import main+from pm.runtime import lease_current_runtimeif __name__ == "__main__":+ lease_current_runtime()raise SystemExit(main())diff --git a/pm/runtime.py b/pm/runtime.pyindex f6d7af7c36c..0b92d80c6c7 100644--- a/pm/runtime.py+++ b/pm/runtime.py@@ -137,6 +137,7 @@ def prepare_runtime(uv: Path, python: Path, root: Path, *, offline: bool = Falsetry:print("Preparing the isolated PM runtime…", file=sys.stderr, flush=True)executable = stage_runtime(uv, python, environment, project=project, offline=offline, cache=cache)+ (environment / ".lease-managed").touch()_write(environment / "pm-runtime.json", {"inputs": identity})_write(selected, {"inputs": identity, "generation": generation.as_posix()})return executable@@ -145,6 +146,46 @@ def prepare_runtime(uv: Path, python: Path, root: Path, *, offline: bool = Falseraise+def lease_current_runtime() -> None:+ """Pin the PM runtime this process runs from so the collector leaves it alone."""+ if (Path(sys.prefix) / "pm-runtime.json").is_file():+ from hermes_cli.runtime_state import lease_directory++ lease_directory(Path(sys.prefix))+++def collect_runtime_generations(root: Path) -> list[Path]:+ """Remove PM runtime generations nothing can run from any more.++ Staging happens under ``.prepare.lock``, so with it held an unpublished generation+ (no ``pm-runtime.json``) is an aborted stage. A superseded published generation goes+ once every worker launched from it has exited; generations published before leases+ existed stay, as the application collector keeps its own.+ """+ from hermes_cli.runtime_state import _lock, leases_held++ generations = root / "generations"+ removed: list[Path] = []+ if not generations.is_dir():+ return removed+ with (root / ".prepare.lock").open("a+b") as lock:+ if not _lock(lock.fileno(), wait=False):+ return removed # a stage is in flight; maintenance skips rather than queues+ try:+ selected = json.loads((root / "selected.json").read_text(encoding="utf-8-sig")).get("generation", "")+ except FileNotFoundError:+ selected = ""+ for generation in sorted(generations.iterdir()):+ if not generation.is_dir() or generation.is_symlink() or generation == root / selected:+ continue+ published = (generation / "pm-runtime.json").is_file()+ if published and (not (generation / ".lease-managed").is_file() or leases_held(generation)):+ continue+ shutil.rmtree(generation)+ removed.append(generation)+ return removed++def runtime_python(*, bootstrap: bool = True, cache: Path | None = None) -> Path:"""Resolve PM without selecting, repairing, or importing the app environment."""diff --git a/pm/worker.py b/pm/worker.pyindex 83d42775d59..6d56f05dddb 100644--- a/pm/worker.py+++ b/pm/worker.py@@ -73,7 +73,9 @@ def main():from pm import paths, receiptfrom pm.package import InstallErrorfrom pm.registry import load_package_definitions+ from pm.runtime import lease_current_runtimefrom pm.worker_operations import OPERATIONS+ lease_current_runtime()context = request["context"]paths.repo_root = lambda: Path(context["repo"])paths.lockfile_path = lambda: Path(context["lockfile"])diff --git a/tests/pm/test_runtime_gc.py b/tests/pm/test_runtime_gc.pynew file mode 100644index 00000000000..4851a1f719a--- /dev/null+++ b/tests/pm/test_runtime_gc.py@@ -0,0 +1,49 @@+"""Superseded and aborted PM runtime generations are collected; running workers are not."""+import json+from pathlib import Path++from pm.runtime import collect_runtime_generations+++def _generation(root: Path, name: str, *, published: bool = True, leased: bool = True) -> Path:+ generation = root / "generations" / name+ generation.mkdir(parents=True)+ if leased:+ (generation / ".lease-managed").touch()+ if published:+ (generation / "pm-runtime.json").write_text(json.dumps({"inputs": name}), encoding="utf-8")+ return generation+++def test_collector_keeps_selected_leased_and_pre_lease_generations(tmp_path):+ from hermes_cli.runtime_state import lease_directory++ root = tmp_path / "pm-runtime"+ selected = _generation(root, "selected")+ busy = _generation(root, "busy")+ idle = _generation(root, "idle")+ legacy = _generation(root, "legacy", leased=False)+ aborted = _generation(root, "aborted", published=False)+ (root / "selected.json").write_text(json.dumps({"generation": "generations/selected"}), encoding="utf-8")+ release = lease_directory(busy)+ lease_directory(idle)()++ removed = collect_runtime_generations(root)++ assert set(removed) == {idle, aborted}+ assert selected.is_dir() and busy.is_dir() and legacy.is_dir()+ release()+ assert collect_runtime_generations(root) == [busy]+++def test_collector_yields_to_an_in_flight_stage(tmp_path):+ from hermes_cli.runtime_state import _lock++ root = tmp_path / "pm-runtime"+ aborted = _generation(root, "aborted", published=False)+ root.mkdir(exist_ok=True)+ with (root / ".prepare.lock").open("a+b") as lock:+ assert _lock(lock.fileno(), wait=False)+ assert collect_runtime_generations(root) == []+ assert aborted.is_dir()+ assert collect_runtime_generations(root) == [aborted]