The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(cron): a source-update relaunch replays the external worker before its ack
mzyas2d3dc08ba7c3
diff --git a/cron/AGENTS.md b/cron/AGENTS.mdindex f9ec35d4574..761d1203075 100644--- a/cron/AGENTS.md+++ b/cron/AGENTS.md@@ -79,7 +79,10 @@ Hardening invariants — each guards a real failure; don't weaken without answeractivates it before the first third-party import. A failed activation is fatal: the workerexits before its ownership ack (a reported dispatch failure) rather than run on an unleasedgeneration the collector may delete. The gateway never re-runs the boot — `hermes_bootstrap`- already did at its own launch (#122222).+ already did at its own launch (#122222). The worker's `__main__` imports `hermes_bootstrap`+ (`finish_worker_boot`) before it reads the payload, and only then drops the marker: a+ source-update relaunch (`-I`, no `PYTHONPATH`) must replay the whole worker, never land after+ the ack with the payload gone and no dependency boot.- 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 thereply-facing conversation: origin, origin-less home fallback, user-written bare-platform home,diff --git a/cron/scheduler.py b/cron/scheduler.pyindex 4b852e5973f..175cc28cf8b 100644--- a/cron/scheduler.py+++ b/cron/scheduler.py@@ -36,7 +36,7 @@ from typing import Any, Callable, Dict, List, Optional, Protocol, Union# `hermes update`) otherwise fail with ModuleNotFoundError for hermes_time et al.sys.path.insert(0, str(Path(__file__).parent.parent))-from cron.worker_bootstrap import WORKER_MARKER+from cron.worker_bootstrap import WORKER_MARKER, finish_worker_bootfrom hermes_constants import get_hermes_home, hermes_home_keyfrom hermes_cli.observability.shared_metrics_gateway import note_cron_execution, note_cron_skippedfrom cron.env_settings import cron_env_setting@@ -4435,16 +4435,16 @@ from cron.scheduler_preflight import ( # noqa: E402# tick paths see every name they need.if __name__ == "__main__":if "--external-worker-file" in sys.argv:+ finish_worker_boot() # may relaunch: before the payload is read and the ack publishedimport argparseparser = argparse.ArgumentParser(add_help=False)parser.add_argument("--external-worker-file", type=Path, required=True)parser.add_argument("--ack-file", type=Path, required=True)args = parser.parse_args()- # The gateway spawns this worker with stdout on DEVNULL and stderr on a- # capture file it only reads back if we die before the ack; without a- # log handler every adoption/ack failure below would otherwise be- # invisible to the persistent log.+ # The gateway spawns this worker with stdout on DEVNULL and stderr on a capture file it+ # only reads back if we die before the ack; without a log handler every adoption/ack+ # failure below would otherwise be invisible to the persistent log.try:from hermes_logging import setup_loggingdiff --git a/cron/worker_bootstrap.py b/cron/worker_bootstrap.pyindex 4f3e944470e..255f8c30ad4 100644--- a/cron/worker_bootstrap.py+++ b/cron/worker_bootstrap.py@@ -23,6 +23,15 @@ collector delete the generation under a live worker. The worker then exits beforacknowledgement, which ``_launch_external_cron_worker`` already reports as a failed dispatch withthe worker's stderr. PM's legitimate no-ops (no committed generation under a venv, wheel, Nix)return normally.++That boot covers dependencies only. ``hermes_bootstrap`` also finishes a pending source update+and may relaunch the process into a fresh one (``hermes_cli/venv_sync.py::relaunch_command``, an+``-I`` interpreter that ignores the pinned ``PYTHONPATH``). ``finish_worker_boot()`` runs it from+the worker's ``__main__`` before the payload is read, so a relaunch replays the whole worker: the+payload is still on disk and the marker still set, and the new process boots its dependencies+again. Left to ``run_agent``'s import inside ``run_one_job``, the relaunch came after the ack, with+the payload deleted and the marker consumed: the new process died on ``ruamel`` and the adopted+run was left ``unknown``."""from __future__ import annotations@@ -30,16 +39,29 @@ from __future__ import annotationsimport osfrom pathlib import Path-# 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.+# Set by ``_launch_external_cron_worker`` in the child's env and consumed by+# ``finish_worker_boot()`` -- after any relaunch, before the ack -- 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.WORKER_MARKER = "_HERMES_CRON_WORKER_BOOT"def worker_bootstrap() -> None:- """Run PM's dependency boot in the marked external worker, once."""- if not os.environ.pop(WORKER_MARKER, None):+ """Run PM's dependency boot in the marked external worker (again after a relaunch)."""+ if not os.environ.get(WORKER_MARKER):returnfrom pm.environments import activate_dependenciesactivate_dependencies(Path(__file__).resolve().parent.parent)+++def finish_worker_boot() -> None:+ """Run ``hermes_bootstrap`` before the worker reads its payload; may relaunch the worker.++ Not from ``worker_bootstrap()``: while ``-m cron.scheduler`` executes ``cron/__init__.py``,+ ``sys.argv[0]`` is still ``-m`` and ``__main__`` has no spec, so the relaunch command could+ not name the module to re-run. In ``__main__`` both are set.+ """+ import hermes_bootstrap # noqa: F401++ os.environ.pop(WORKER_MARKER, None)diff --git a/tests/cron/test_restart_safe_worker.py b/tests/cron/test_restart_safe_worker.pyindex 32b3c5c63c9..7d73b7e6ed3 100644--- a/tests/cron/test_restart_safe_worker.py+++ b/tests/cron/test_restart_safe_worker.py@@ -757,9 +757,9 @@ print(json.dumps({"boots": boots, "marker": os.environ.get(sys.argv[1])}))def test_marked_worker_boots_dependencies_before_cron_jobs(marked):"""#122222: ``-m cron.scheduler`` executes ``cron/__init__.py`` first, whose first import(``cron.jobs`` -> ``hermes_yaml`` -> ``ruamel``) is already a dependency, so the marked- worker must boot before it -- exactly once, consuming the marker so the worker's own- children do not inherit it. An unmarked importer (the gateway already booted through- ``hermes_bootstrap``) is never re-booted."""+ worker must boot before it -- exactly once. The marker survives the package import so a+ relaunched worker boots again (``finish_worker_boot`` consumes it). An unmarked importer+ (the gateway already booted through ``hermes_bootstrap``) is never re-booted."""import cron.worker_bootstrap as worker_bootstraprepo_root = Path(worker_bootstrap.__file__).resolve().parent.parent@@ -773,7 +773,63 @@ def test_marked_worker_boots_dependencies_before_cron_jobs(marked):)assert child.returncode == 0, child.stderrresult = json.loads(child.stdout.strip().splitlines()[-1])- assert result == {"boots": [False] if marked else [], "marker": None}+ assert result == {"boots": [False] if marked else [], "marker": "1" if marked else None}+++_RELAUNCH_PROBE = """+import json, os, runpy, subprocess, sys+from pathlib import Path++import pm.environments+pm.environments.activate_dependencies = lambda root: None+import hermes_cli.venv_sync as venv_sync++payload, ack, record, marker = Path(sys.argv[1]), Path(sys.argv[2]), Path(sys.argv[3]), sys.argv[4]+venv_sync.prepare_launch = lambda root, argv: Path(sys.executable)+++def relaunch(*args):+ record.write_text(json.dumps({+ "payload": payload.exists(), "ack": ack.exists(),+ "marker": os.environ.get(marker), "command": args[-1],+ }))+ raise SystemExit(0)+++os.execv = relaunch+subprocess.call = relaunch+sys.argv = ["cron.scheduler", "--external-worker-file", str(payload), "--ack-file", str(ack)]+runpy.run_module("cron.scheduler", run_name="__main__", alter_sys=True)+"""+++def test_source_update_relaunch_replays_the_worker_before_its_ack(tmp_path):+ """A worker whose ``hermes_bootstrap`` finishes a source update relaunches into an ``-I``+ interpreter that ignores the pinned PYTHONPATH. Reached through ``run_agent`` inside+ ``run_one_job``, that relaunch came after the ack: the payload was deleted, the marker+ consumed, and the new process died on ``ruamel`` with the adopted run left ``unknown``.+ The relaunch must instead replay the whole worker: payload unread, no ack, marker set,+ re-running ``cron.scheduler`` as ``__main__``."""+ import cron.worker_bootstrap as worker_bootstrap++ repo_root = Path(worker_bootstrap.__file__).resolve().parent.parent+ payload = tmp_path / "exec-1.json"+ payload.write_text(json.dumps({+ "job": {"id": "job-1", "execution_id": "exec-1"},+ "profile_home": str(tmp_path / "profile"),+ }), encoding="utf-8")+ ack, record = tmp_path / "exec-1.ready", tmp_path / "relaunch.json"+ env = dict(os.environ, PYTHONPATH=str(repo_root))+ env[worker_bootstrap.WORKER_MARKER] = "1"+ child = subprocess.run(+ [sys.executable, "-c", _RELAUNCH_PROBE, str(payload), str(ack), str(record),+ worker_bootstrap.WORKER_MARKER],+ cwd=repo_root, env=env, capture_output=True, text=True, timeout=120,+ )+ assert record.exists(), f"worker never relaunched (exit {child.returncode}): {child.stderr}"+ seen = json.loads(record.read_text())+ assert (seen["payload"], seen["ack"], seen["marker"]) == (True, False, "1")+ assert "runpy.run_module('cron.scheduler', run_name='__main__'" in seen["command"][-1]_REAL_BOOT_PROBE = """