The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(cron): stop the external worker when PM refuses its dependency boot
kshitijk4poor744f05e2204d
diff --git a/cron/AGENTS.md b/cron/AGENTS.mdindex dc62aff75cb..522e712141f 100644--- a/cron/AGENTS.md+++ b/cron/AGENTS.md@@ -76,8 +76,9 @@ Hardening invariants — each guards a real failure; don't weaken without answer(`cron/__init__.py` → `cron/worker_bootstrap.py`, ahead of the `cron.jobs` import — `-mcron.scheduler` runs the package first) then runs PM's `activate_dependencies`, whichleases the committed generation for the worker's lifetime, runs its `.pth` files and- activates it before the first third-party import. The pin is the fallback the worker still- imports through if that boot fails; the gateway never re-runs the boot — `hermes_bootstrap`+ activates it before the first third-party import. A failed activation is fatal: the worker+ exits before its ownership ack (a reported dispatch failure) rather than run on an unleased+ generation the collector may delete. The gateway never re-runs the boot — `hermes_bootstrap`already did at its own launch (#122222).- Cron sessions pass `skip_memory=True`; memory providers intentionally do not run during cron.- Cron execution has its own session. Eligible continuable deliveries may mirror or seed thediff --git a/cron/scheduler_worker_env.py b/cron/scheduler_worker_env.pyindex 5f470df367e..79bfc6031d2 100644--- a/cron/scheduler_worker_env.py+++ b/cron/scheduler_worker_env.py@@ -39,18 +39,18 @@ def _committed_dependency_site_packages(project_root: Path) -> Path | None:Asked of PM's own committed selection -- the record ``activate_dependencies`` resolvesat process boot -- rather than re-derived from this process's ``sys.path``: the record- is scoped to this home, so the lookup cannot walk a path under the *real* home when a- test runs against an isolated one. A runner that owns its dependencies (wheel / pipx /- developer venv / Nix: no committed generation) has nothing to restore, so ``None``- means "pin the tree only" and nothing is invented.+ belongs to this install (``install_state_dir``, shared by every profile it serves). A+ runner that owns its dependencies (wheel / pipx / developer venv / Nix: no committed+ generation) has nothing to restore, so ``None`` means "pin the tree only" and nothing+ is invented."""try:from pm.environments import committed_venv, site_packagesenvironment = committed_venv(project_root)except Exception as exc:- # No PM on this tree, or a record naming a generation PM already removed: keep the- # previous behaviour (tree only) rather than failing the handoff.+ # An unreadable record: pin the tree only. The cron worker's own boot re-reads it and+ # fails the dispatch with PM's error.logger.warning("cron worker: could not read the committed dependency environment: %s", exc)@@ -71,9 +71,9 @@ def pin_hermes_tree_on_pythonpath(worker_env: dict, repo_root: Path) -> dict:and pinning it would move site-packages ahead of the stdlib on ``sys.path``.Order (checkout, generation, sanitizer-kept) mirrors ``activate_dependencies``' own- ``sys.path``. The worker's boot (``cron/worker_bootstrap.py``) re-selects and leases the- committed generation before any third-party import; this pin is what the worker still- imports through if that boot fails.+ ``sys.path``. For the cron worker, its boot (``cron/worker_bootstrap.py``) then re-selects+ and leases the committed generation before any third-party import, and exits the worker+ if it cannot."""root = str(repo_root)if _installed_purelib() == Path(root).resolve():diff --git a/cron/worker_bootstrap.py b/cron/worker_bootstrap.pyindex 0a74ece6c9e..4f3e944470e 100644--- a/cron/worker_bootstrap.py+++ b/cron/worker_bootstrap.py@@ -18,18 +18,18 @@ dependency -- and does nothing unless ``_launch_external_cron_worker`` marked thgateway already booted through ``hermes_bootstrap``, and every other importer of``cron.scheduler`` is an interpreter that owns its own dependencies.-Failure degrades to a log line: the worker still has the pinned dependency path, and a-dependency problem must not be reported as a lost job.+A genuine activation failure propagates: continuing on the inherited, unleased path lets the+collector delete the generation under a live worker. The worker then exits before its ownership+acknowledgement, which ``_launch_external_cron_worker`` already reports as a failed dispatch with+the worker's stderr. PM's legitimate no-ops (no committed generation under a venv, wheel, Nix)+return normally."""from __future__ import annotations-import loggingimport osfrom pathlib import Path-logger = logging.getLogger(__name__)-# Set by ``_launch_external_cron_worker`` in the child's env and consumed here, so it never# reaches the worker's own children -- they inherit the activated PYTHONPATH instead.# Distinct from ``_HERMES_CRON_EXTERNAL_WORKER`` (the owning execution id) in scheduler.py.@@ -37,12 +37,9 @@ WORKER_MARKER = "_HERMES_CRON_WORKER_BOOT"def worker_bootstrap() -> None:- """Run PM's dependency boot in the marked external worker; idempotent, never raises."""+ """Run PM's dependency boot in the marked external worker, once."""if not os.environ.pop(WORKER_MARKER, None):return- try:- from pm.environments import activate_dependencies+ from pm.environments import activate_dependencies- activate_dependencies(Path(__file__).resolve().parent.parent)- except Exception as exc:- logger.warning("cron external worker dependency activation failed: %s", exc)+ activate_dependencies(Path(__file__).resolve().parent.parent)diff --git a/tests/cron/test_restart_safe_worker.py b/tests/cron/test_restart_safe_worker.pyindex d150a418d38..961453aacaa 100644--- a/tests/cron/test_restart_safe_worker.py+++ b/tests/cron/test_restart_safe_worker.py@@ -648,6 +648,32 @@ 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 _commit_generation(repo_root: Path, name: str, *, with_site_packages: bool) -> Path:+ """Commit a PM generation for ``repo_root`` in the sandboxed home; return its venv."""+ import pm.environments++ version = f"{sys.version_info[0]}.{sys.version_info[1]}"+ venv = pm.environments.install_state_dir(repo_root) / "environments" / name / "venv"+ (venv / "lib" / f"python{version}").mkdir(parents=True)+ (venv / "pyvenv.cfg").write_text(f"version = {version}\n", encoding="utf-8")+ (venv.parent / ".lease-managed").write_text("", encoding="utf-8")+ if with_site_packages:+ # The generation's .pth hands back this interpreter's own packages, so the+ # activated worker can still import its dependencies after PM rewrites sys.path.+ selected = pm.environments.site_packages(venv)+ selected.mkdir()+ (selected / "test_deps.pth").write_text(+ "\n".join(p for p in sys.path+ if Path(p).name in ("site-packages", "dist-packages")) + "\n",+ encoding="utf-8")+ # Importable only through this generation, so the worker proves it activated it.+ (selected / "_generation_sentinel.py").write_text(f"NAME = {name!r}\n", encoding="utf-8")+ pm.environments.runtime_facts_path(repo_root).write_text(+ json.dumps({"packages": {"venv": {"environment": str(venv)}}, "schema": 1}),+ encoding="utf-8")+ return venv++def test_pin_restores_the_committed_generation_site_packages(tmp_path):"""#122222: the sanitizer drops the generation ``activate_dependencies`` put on our``sys.path``, and the worker inherits the store Python, which owns no dependencies. The@@ -658,16 +684,8 @@ def test_pin_restores_the_committed_generation_site_packages(tmp_path):repo_root = tmp_path / "hermes-agent"repo_root.mkdir()- version = f"{sys.version_info[0]}.{sys.version_info[1]}"- venv = pm.environments.install_state_dir(repo_root) / "environments" / "gen1" / "venv"- (venv / "lib" / f"python{version}").mkdir(parents=True)- (venv / "pyvenv.cfg").write_text(f"version = {version}\n", encoding="utf-8")+ venv = _commit_generation(repo_root, "gen1", with_site_packages=True)selected = pm.environments.site_packages(venv)- selected.mkdir()- pm.environments.runtime_facts_path(repo_root).write_text(- json.dumps({"packages": {"venv": {"environment": str(venv)}}, "schema": 1}),- encoding="utf-8",- )env = worker_env_mod.pin_hermes_tree_on_pythonpath({"PYTHONPATH": str(tmp_path / "kept")}, repo_root@@ -717,6 +735,79 @@ def test_marked_worker_boots_dependencies_before_cron_jobs(marked):assert result == {"boots": [False] if marked else [], "marker": None}+_REAL_BOOT_PROBE = """+import json, sys+try:+ import cron+except RuntimeError as exc:+ print(json.dumps({"error": str(exc), "jobs": "cron.jobs" in sys.modules}))+ sys.exit(3)+import _generation_sentinel+print(json.dumps({"sentinel": _generation_sentinel.NAME, "path": sys.path,+ "jobs": "cron.jobs" in sys.modules}), flush=True)+sys.stdin.read()+"""+++def _marked_worker(repo_root: Path, stderr) -> subprocess.Popen:+ import cron.worker_bootstrap as worker_bootstrap++ env = dict(os.environ, PYTHONPATH=str(repo_root))+ env[worker_bootstrap.WORKER_MARKER] = "1"+ return subprocess.Popen(+ [sys.executable, "-c", _REAL_BOOT_PROBE], cwd=repo_root, env=env,+ stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=stderr, text=True)+++def test_marked_worker_keeps_its_generation_through_a_rotation(tmp_path):+ """#122222 / #122936 review: the real PM boot activates the committed generation before+ ``cron.jobs`` loads and leases it for the worker's lifetime. When an update commits a+ newer generation mid-job, the collector must not delete the one the live worker imports+ from; it becomes collectable once the worker exits."""+ import cron.worker_bootstrap as worker_bootstrap+ import pm.environments+ from hermes_cli.runtime_state import collect_generations++ repo_root = Path(worker_bootstrap.__file__).resolve().parent.parent+ generation = _commit_generation(repo_root, "g1", with_site_packages=True).parent+ stderr_path = tmp_path / "worker.stderr"+ with stderr_path.open("w") as stderr:+ child = _marked_worker(repo_root, stderr)+ try:+ result = json.loads(child.stdout.readline())+ assert result["sentinel"] == "g1" and result["jobs"] is True+ first_site = next(p for p in result["path"] if Path(p).name == "site-packages")+ assert first_site == str(pm.environments.site_packages(generation / "venv"))++ _commit_generation(repo_root, "g2", with_site_packages=True)+ assert collect_generations(repo_root, min_age_seconds=0) == []+ assert generation.is_dir()+ finally:+ try:+ child.communicate(timeout=60)+ except subprocess.TimeoutExpired:+ child.kill()+ raise+ assert child.returncode == 0, stderr_path.read_text()+ assert collect_generations(repo_root, min_age_seconds=0) == [generation]+++def test_marked_worker_exits_before_cron_jobs_when_activation_fails():+ """#122936 review: a genuine PM refusal (committed generation without site-packages) must+ stop the worker before its first dependency import -- the spawn site reports the pre-ack+ exit -- rather than run on an inherited path nothing leases."""+ import cron.worker_bootstrap as worker_bootstrap++ repo_root = Path(worker_bootstrap.__file__).resolve().parent.parent+ _commit_generation(repo_root, "damaged", with_site_packages=False)+ child = _marked_worker(repo_root, subprocess.PIPE)+ out, err = child.communicate(timeout=60)+ assert child.returncode == 3, err+ result = json.loads(out.strip().splitlines()[-1])+ assert "has no site-packages" in result["error"]+ assert result["jobs"] is False++def test_shared_run_path_hands_gateway_fire_to_external_worker(monkeypatch):import cron.scheduler as scheduler