Skip to content

The agent that grows with you

fix(pm): canonicalize the store only in the PM runtime identity

teknium16a17705227cb
diff --git a/pm/environments.py b/pm/environments.py
index a09ebd7621d..95e874f7c36 100644
--- a/pm/environments.py
+++ b/pm/environments.py
@@ -120,13 +120,10 @@ def store_root(project_root: Path) -> Path:
try:
data = json.loads(stamp.read_text(encoding="utf-8-sig"))
except (OSError, ValueError):
- break
+ return get_default_hermes_root() / "tools"
value = data.get("runtimeDir") if isinstance(data, dict) else None
- if value:
- return Path(value).resolve()
- break
- # PM hashes the interpreter path: aliases of one store must share an identity.
- return (get_default_hermes_root() / "tools").resolve()
+ return Path(value).resolve() if value else get_default_hermes_root() / "tools"
+ return get_default_hermes_root() / "tools"
def flush_before_selecting() -> None:
diff --git a/pm/runtime.py b/pm/runtime.py
index 18fd49001c3..ec8205d07f8 100644
--- a/pm/runtime.py
+++ b/pm/runtime.py
@@ -37,13 +37,17 @@ def _python(environment: Path) -> Path:
return venv_python(environment)
-def _inputs(project: Path, python: Path) -> str:
+def _inputs(project: Path, python: Path, *, as_spelled: bool = False) -> str:
digest = hashlib.sha256()
for name in ("pyproject.toml", "uv.lock"):
digest.update((project / name).read_bytes())
digest.update(b"\0")
- # A different interpreter must not reuse a venv pointing at the old one.
- digest.update(str(python.absolute()).encode())
+ # A different interpreter must not reuse a venv pointing at the old one, but
+ # the same one reached through a symlinked store (a per-task HERMES_HOME whose
+ # tools/ links back) must. Only the directories resolve: the pinned
+ # bin/python3 is itself a symlink, so resolving it would re-key every install.
+ python = python.absolute()
+ digest.update(str(python if as_spelled else python.parent.resolve() / python.name).encode())
return digest.hexdigest()
@@ -142,7 +146,9 @@ def prepare_runtime(uv: Path, python: Path, root: Path, *, offline: bool = False
fact = json.loads(selected.read_text(encoding="utf-8"))
except FileNotFoundError:
fact = {}
- if fact.get("inputs") == identity:
+ # Records from before canonicalization spell the path as launched; for a
+ # home under a symlink (/home -> /var/home) that is still this interpreter.
+ if fact.get("inputs") in (identity, _inputs(project, python, as_spelled=True)):
environment = root / fact["generation"]
if (environment / "pm-runtime.json").is_file() and not _validate(_python(environment), env):
_hold_for_children(environment)
diff --git a/tests/pm/test_runtime.py b/tests/pm/test_runtime.py
index 23c8ce7fd3d..1fc3164d500 100644
--- a/tests/pm/test_runtime.py
+++ b/tests/pm/test_runtime.py
@@ -1,4 +1,5 @@
"""PM's resolver must not depend on the application it is repairing."""
+import hashlib
import json
import os
from pathlib import Path
@@ -135,3 +136,60 @@ def test_sealed_worker_command_uses_only_its_recorded_site(tmp_path, monkeypatch
entries = json.loads(result.stdout)
assert str(site) in entries
assert not any(Path(entry).name in {"site-packages", "dist-packages"} for entry in entries)
+
+
+def test_one_store_through_symlinked_homes_keeps_one_pm_runtime(tmp_path, monkeypatch):
+ """#123798: a store reached through symlinks (a per-task HERMES_HOME whose tools/ links back,
+ a home under /home -> /var/home) is ONE PM runtime: every spelling reuses the selected
+ generation, and a record written before canonicalization is not re-staged."""
+ from pm import runtime
+
+ project = tmp_path / "project"
+ project.mkdir()
+ (project / "pyproject.toml").write_text("[project]\nname = 'fixture'\n")
+ (project / "uv.lock").write_text("version = 1\n")
+ real = tmp_path / "volume" / "tools"
+ (real / "python" / "bin").mkdir(parents=True)
+ (real / "python" / "bin" / "python3.14").touch()
+ home, task = tmp_path / "home", tmp_path / "task"
+ try:
+ (real / "python" / "bin" / "python3").symlink_to("python3.14") # as the pinned CPython ships
+ for linked in (home, task):
+ linked.mkdir()
+ (linked / "tools").symlink_to(real, target_is_directory=True)
+ except OSError as exc:
+ pytest.skip(f"symlinks unavailable: {exc}")
+
+ def pre_fix_identity(python: Path) -> str: # the selected.json format earlier releases wrote
+ digest = hashlib.sha256()
+ for name in ("pyproject.toml", "uv.lock"):
+ digest.update((project / name).read_bytes() + b"\0")
+ digest.update(str(python).encode())
+ return digest.hexdigest()
+
+ staged = []
+
+ def stage(uv, python, environment, **_):
+ staged.append(python)
+ environment.mkdir(parents=True)
+ return runtime._python(environment)
+
+ monkeypatch.setattr("pm.runtime_stage.stage_runtime", stage)
+ monkeypatch.setattr(runtime, "_validate", lambda python, env: "")
+ monkeypatch.setattr(runtime, "_hold_for_children", lambda environment: None)
+ root = tmp_path / "pm-runtime"
+ old = root / "generations" / "old"
+ old.mkdir(parents=True)
+ (old / "pm-runtime.json").write_text("{}")
+ (root / "selected.json").write_text(json.dumps(
+ {"inputs": pre_fix_identity(home / "tools" / "python" / "bin" / "python3"), "generation": "generations/old"}))
+
+ def launch(tools: Path, bootstrap: bool = False) -> Path:
+ return runtime.prepare_runtime(tools / "uv", tools / "python" / "bin" / "python3", root,
+ project=project, bootstrap=bootstrap)
+
+ assert launch(home / "tools") == runtime._python(old)
+ current = launch(task / "tools", bootstrap=True) # a per-task home that was already churning re-stages once
+ for tools in (home / "tools", task / "tools", real, home / "tools"):
+ assert launch(tools) == current
+ assert len(staged) == 1
diff --git a/tests/pm/test_store_alias_identity.py b/tests/pm/test_store_alias_identity.py
deleted file mode 100644
index e8f72289d4a..00000000000
--- a/tests/pm/test_store_alias_identity.py
+++ /dev/null
@@ -1,110 +0,0 @@
-"""Regression for #123798: aliases of one store must reuse its PM generation."""
-import json
-from pathlib import Path
-
-import pytest
-
-
[email protected]("stamp", [None, {}, [], "malformed", "unreadable"])
-def test_home_store_alias_reuses_selected_runtime(tmp_path, monkeypatch, request, stamp):
- from pm import paths, runtime
-
- project = tmp_path / "project"
- project.mkdir()
- (project / "pyproject.toml").write_text("[project]\nname='fixture'\n")
- (project / "uv.lock").write_text("version = 1\n")
- stamp_path = project / "install-stamp.json"
- if stamp is not None:
- stamp_path.write_text(stamp if isinstance(stamp, str) else json.dumps(stamp))
- if stamp == "unreadable":
- read_text = Path.read_text
-
- def read(path, *args, **kwargs):
- if path == stamp_path:
- raise PermissionError("fixture stamp cannot be read")
- return read_text(path, *args, **kwargs)
-
- monkeypatch.setattr(Path, "read_text", read)
- monkeypatch.setattr(paths, "repo_root", lambda: project)
- monkeypatch.delenv("HERMES_RUNTIME_DIR", raising=False)
- monkeypatch.delenv("HERMES_INSTALL_ROOT", raising=False)
- home = tmp_path / "owner"
- store = home / "tools"
- store.mkdir(parents=True)
- alias = tmp_path / "alternate"
- alias.mkdir()
- try:
- (alias / "tools").symlink_to(store, target_is_directory=True)
- except OSError as exc:
- pytest.skip(f"directory symlinks unavailable: {exc}")
- (store / "python").touch()
- selected = tmp_path / "pm-runtime"
- generation = selected / "generations" / "existing"
- generation.mkdir(parents=True)
- (generation / "pm-runtime.json").write_text("{}")
- (generation / ".lease-managed").touch()
-
- def release():
- held = runtime._HELD.pop(generation, None)
- if held is not None:
- held()
-
- request.addfinalizer(release)
- record = {"inputs": runtime._inputs(project, store.resolve() / "python"),
- "generation": "generations/existing"}
- (selected / "selected.json").write_text(json.dumps(record))
- before = (selected / "selected.json").read_bytes()
- validated = []
- # Dependency validation is outside this path-identity contract; staging is
- # forbidden, so no interpreter/dependency installation can mask a mismatch.
- monkeypatch.setattr(runtime, "_validate", lambda python, env: validated.append(python) or "")
- monkeypatch.setattr("pm.runtime_stage.stage_runtime", lambda *a, **kw: pytest.fail("rebuilt current runtime"))
-
- for active in (home, alias, home):
- monkeypatch.setenv("HERMES_HOME", str(active))
- result = runtime.prepare_runtime(
- store / "uv", paths.store_root() / "python", selected,
- project=project, bootstrap=False,
- )
- assert result == runtime._python(generation)
- assert paths.store_root() == store.resolve()
- assert (selected / "selected.json").read_bytes() == before
- assert validated == [runtime._python(generation)] * 3
- from hermes_cli.runtime_state import leases_held
-
- assert leases_held(generation)
- assert len(list((generation / ".leases").iterdir())) == 1
- release()
- assert not leases_held(generation)
- assert list((selected / "generations").iterdir()) == [generation]
-
-
[email protected]("source", ["override", "stamp", "payload", "missing-default"])
-def test_store_resolution_keeps_caller_precedence(tmp_path, monkeypatch, source):
- from pm import environments
-
- project = tmp_path / "payload" / "project"
- project.mkdir(parents=True)
- home = tmp_path / "home"
- monkeypatch.setenv("HERMES_HOME", str(home))
- monkeypatch.delenv("HERMES_RUNTIME_DIR", raising=False)
- monkeypatch.delenv("HERMES_INSTALL_ROOT", raising=False)
- expected = home / "tools"
- if source != "missing-default":
- expected = project.parent / "chosen"
- expected.mkdir()
- alias = project.parent / "alias"
- try:
- alias.symlink_to(expected, target_is_directory=True)
- except OSError as exc:
- pytest.skip(f"directory symlinks unavailable: {exc}")
- if source == "override":
- monkeypatch.setenv("HERMES_RUNTIME_DIR", str(alias))
- (project.parent / "manifest.json").write_text("invalid, overridden")
- elif source == "stamp":
- (project / "install-stamp.json").write_text(json.dumps({"runtimeDir": str(alias)}))
- else:
- (project.parent / "manifest.json").write_text(json.dumps({"repo": "project", "store": "alias"}))
- assert environments.store_root(project) == expected.resolve()
- if source == "missing-default":
- assert not expected.exists(), "resolving a missing store must not create it"