Skip to content

The agent that grows with you

fix(cron): restore activated dependency site-packages for the external worker

123456hyuf57d2357485f
diff --git a/cron/scheduler_worker_env.py b/cron/scheduler_worker_env.py
index ef13355fcac..026c3209bb1 100644
--- a/cron/scheduler_worker_env.py
+++ b/cron/scheduler_worker_env.py
@@ -9,13 +9,18 @@ editable install maps a moved/deleted checkout -- the worker then dies with
The shared subprocess sanitizer strips Hermes-owned PYTHONPATH entries because user
children must not see our tree. This child IS Hermes, so the pin is applied *after* the
-env is built, on the sanitized env -- the sanitizer's other decisions (dropped runtime
-site-packages, dropped venv markers) stand.
+env is built, on the sanitized env. On a self-managed (shell-installer / PM) install the
+sanitizer's drop of the runtime site-packages cannot stand this time: the worker's
+interpreter is the store Python, which owns no third-party dependencies, so the activated
+dependency environment's site-packages must be restored here too or the child dies at its
+first import (``No module named 'ruamel'``, #122222) before it can publish its ownership
+acknowledgement.
"""
from __future__ import annotations
import os
+import sys
import sysconfig
from pathlib import Path
@@ -27,8 +32,68 @@ def _installed_purelib() -> Path | None:
return None
+def _in_real_venv(path: Path) -> bool:
+ """True when *path* sits under a directory carrying ``pyvenv.cfg``.
+
+ ``activate_dependencies`` exposes the selected generation by path (no ``sys.prefix``
+ switch), so the only proof that a ``site-packages`` entry is a dependency environment
+ rather than a directory that merely happens to be named that is the venv marker in an
+ ancestor.
+ """
+ current = path
+ while current != current.parent:
+ try:
+ if (current / "pyvenv.cfg").is_file():
+ return True
+ except OSError:
+ return False
+ current = current.parent
+ return False
+
+
+def _activated_dependency_site_packages() -> Path | None:
+ """The site-packages this process imports Hermes's dependencies from, or ``None``.
+
+ On a self-managed install the gateway runs on the store Python and
+ ``activate_dependencies`` puts the dependency generation on ``sys.path`` -- the same
+ signal ``pm.environments.running_from_selected_environment`` reads. Derived from
+ ``sys.path`` (never via ``selected_venv()``/``site_packages()``) so the child-spawn
+ path performs no home-scoped filesystem reads. The interpreter's own ``purelib`` is
+ excluded: a runner that owns its dependencies (wheel / pipx / test / developer venv)
+ hands the child its own interpreter and needs nothing added. ``None`` therefore means
+ "pin the tree only", and nothing is invented.
+ """
+ purelib = _installed_purelib()
+ purelib_key = os.path.normcase(str(purelib)) if purelib is not None else None
+ seen: set[str] = set()
+ for entry in sys.path:
+ if not entry:
+ continue
+ path = Path(entry)
+ if path.name not in ("site-packages", "dist-packages"):
+ continue
+ try:
+ resolved = path.resolve()
+ except OSError:
+ continue
+ key = os.path.normcase(str(resolved))
+ if key in seen:
+ continue
+ seen.add(key)
+ if purelib_key is not None and key == purelib_key:
+ continue
+ if not resolved.is_dir():
+ continue
+ if not _in_real_venv(resolved):
+ continue
+ return resolved
+ return None
+
+
def pin_hermes_tree_on_pythonpath(worker_env: dict, repo_root: Path) -> dict:
- """Prepend ``repo_root`` to the worker env's own PYTHONPATH (never ``os.environ``'s).
+ """Prepend ``repo_root`` -- and, when the worker's interpreter cannot import Hermes's
+ dependencies otherwise, the activated environment's ``site-packages`` -- to the worker
+ env's own PYTHONPATH (never ``os.environ``'s).
Skipped when ``repo_root`` is the interpreter's ``purelib``: under a wheel / pipx /
uv-tool install ``cron/`` lives in site-packages itself, which is already importable,
@@ -38,5 +103,9 @@ def pin_hermes_tree_on_pythonpath(worker_env: dict, repo_root: Path) -> dict:
if _installed_purelib() == Path(root).resolve():
return worker_env
existing = [e for e in worker_env.get("PYTHONPATH", "").split(os.pathsep) if e]
- worker_env["PYTHONPATH"] = os.pathsep.join(dict.fromkeys([root, *existing]))
- return worker_env
+ pinned = [root]
+ dependency = _activated_dependency_site_packages()
+ if dependency is not None:
+ pinned.append(str(dependency))
+ worker_env["PYTHONPATH"] = os.pathsep.join(dict.fromkeys([*pinned, *existing]))
+ return worker_env
\ No newline at end of file
diff --git a/tests/cron/test_restart_safe_worker.py b/tests/cron/test_restart_safe_worker.py
index ef5c607fcdf..8ceb6e9ffca 100644
--- a/tests/cron/test_restart_safe_worker.py
+++ b/tests/cron/test_restart_safe_worker.py
@@ -639,7 +639,10 @@ def test_launch_external_worker_pin_extends_the_sanitized_env_not_os_environ(
assert scheduler._launch_external_cron_worker(job) is True
entries = spawned[0][1]["env"]["PYTHONPATH"].split(os.pathsep)
- assert entries == [str(repo_root), str(tmp_path / "kept-by-sanitizer")]
+ # Relationship, not an exact list: on a self-managed install the pin also restores the
+ # activated dependency site-packages (#122222), so the entry count is runner-dependent.
+ assert entries[0] == str(repo_root)
+ assert str(tmp_path / "kept-by-sanitizer") in entries
# Wheel / pipx layout: repo_root == purelib -> untouched.
monkeypatch.setattr(worker_env_mod, "_installed_purelib", lambda: repo_root)
@@ -648,6 +651,82 @@ def test_launch_external_worker_pin_extends_the_sanitized_env_not_os_environ(
assert "PYTHONPATH" not in worker_env_mod.pin_hermes_tree_on_pythonpath({}, repo_root)
+def test_pin_restores_activated_dependency_site_packages(monkeypatch, tmp_path):
+ """#122222: on a self-managed install the sanitizer drops the activated dependency
+ site-packages and the store-Python worker cannot import them; the pin restores them
+ next to the tree, in activation order, after the tree and before the kept entries."""
+ import cron.scheduler_worker_env as worker_env_mod
+
+ venv = tmp_path / "installs" / "env"
+ dependency = venv / "lib" / "python3.14" / "site-packages"
+ dependency.mkdir(parents=True)
+ (venv / "pyvenv.cfg").write_text("version = 3.14\n")
+ repo_root = tmp_path / "hermes-agent"
+ repo_root.mkdir()
+ monkeypatch.setattr(
+ worker_env_mod, "_activated_dependency_site_packages", lambda: dependency.resolve()
+ )
+
+ env = worker_env_mod.pin_hermes_tree_on_pythonpath(
+ {"PYTHONPATH": str(tmp_path / "kept")}, repo_root
+ )
+ entries = env["PYTHONPATH"].split(os.pathsep)
+ assert entries == [
+ str(repo_root.resolve()),
+ str(dependency.resolve()),
+ str(tmp_path / "kept"),
+ ]
+
+
+def test_activated_dependency_site_packages_derives_from_sys_path(monkeypatch, tmp_path):
+ import cron.scheduler_worker_env as worker_env_mod
+
+ venv = tmp_path / "env"
+ dependency = venv / "lib" / "python3.14" / "site-packages"
+ dependency.mkdir(parents=True)
+ (venv / "pyvenv.cfg").write_text("version = 3.14\n")
+ purelib = tmp_path / "purelib"
+ purelib.mkdir()
+
+ monkeypatch.setattr(worker_env_mod, "_installed_purelib", lambda: purelib.resolve())
+ monkeypatch.setattr(
+ worker_env_mod.sys,
+ "path",
+ [str(purelib), str(dependency), str(tmp_path / "user-libs")],
+ )
+
+ assert worker_env_mod._activated_dependency_site_packages() == dependency.resolve()
+
+
+def test_activated_dependency_site_packages_excludes_own_purelib(monkeypatch, tmp_path):
+ """A runner that owns its dependencies (here its only venv site-packages IS its own
+ purelib) needs nothing added, so nothing is invented."""
+ import cron.scheduler_worker_env as worker_env_mod
+
+ purelib = tmp_path / "venv" / "lib" / "python3.11" / "site-packages"
+ purelib.mkdir(parents=True)
+ (tmp_path / "venv" / "pyvenv.cfg").write_text("version = 3.11\n")
+ monkeypatch.setattr(worker_env_mod, "_installed_purelib", lambda: purelib.resolve())
+ monkeypatch.setattr(worker_env_mod.sys, "path", [str(purelib)])
+
+ assert worker_env_mod._activated_dependency_site_packages() is None
+
+
+def test_activated_dependency_site_packages_requires_real_venv(monkeypatch, tmp_path):
+ """A directory that merely happens to be named site-packages, outside any venv, is
+ never pinned."""
+ import cron.scheduler_worker_env as worker_env_mod
+
+ not_a_venv = tmp_path / "site-packages"
+ not_a_venv.mkdir()
+ purelib = tmp_path / "purelib"
+ purelib.mkdir()
+ monkeypatch.setattr(worker_env_mod, "_installed_purelib", lambda: purelib.resolve())
+ monkeypatch.setattr(worker_env_mod.sys, "path", [str(not_a_venv)])
+
+ assert worker_env_mod._activated_dependency_site_packages() is None
+
+
def test_shared_run_path_hands_gateway_fire_to_external_worker(monkeypatch):
import cron.scheduler as scheduler