Skip to content

The agent that grows with you

fix(cron): boot the external worker's PM dependencies before cron.jobs

kshitijk4poor308072df899e
diff --git a/cron/AGENTS.md b/cron/AGENTS.md
index 17391d699c4..05c2b3aaed8 100644
--- a/cron/AGENTS.md
+++ b/cron/AGENTS.md
@@ -73,7 +73,7 @@ Hardening invariants — each guards a real failure; don't weaken without answer
- **The restart-safe external worker boots itself.** `_launch_external_cron_worker` pins the
checkout — and, on a PM install, the committed generation's `site-packages` — on the child's
`PYTHONPATH` and marks it `HERMES_CRON_EXTERNAL_WORKER`; the child's own entry
- (`cron/scheduler.py` → `cron/worker_bootstrap.py`) then runs PM's `activate_dependencies`,
+ (`cron/__init__.py` → `cron/worker_bootstrap.py`, ahead of the `cron.jobs` import) then runs PM's `activate_dependencies`,
which leases that generation for the worker's lifetime and activates it before the first
application import. Neither half is redundant (the pin is what the child can import through,
the boot is what keeps the generation alive and its `.pth` files executed) and the gateway
diff --git a/cron/__init__.py b/cron/__init__.py
index 9d12ef02d57..d79625d8d12 100644
--- a/cron/__init__.py
+++ b/cron/__init__.py
@@ -3,7 +3,14 @@ self-scheduled reminders, isolated sessions. The gateway daemon (``hermes gatewa
the scheduler every 60 seconds; a file lock prevents duplicate execution across processes.
"""
-from cron.jobs import (
+# The restart-safe external worker runs as ``-m cron.scheduler``, which executes this package
+# first: boot PM dependencies before ``cron.jobs`` reaches a third-party import. A no-op
+# unless ``_launch_external_cron_worker`` marked this process. See cron/worker_bootstrap.py.
+from cron.worker_bootstrap import worker_bootstrap as _boot_external_worker
+
+_boot_external_worker()
+
+from cron.jobs import ( # noqa: E402
create_job,
get_job,
list_jobs,
@@ -15,7 +22,7 @@ from cron.jobs import (
rearm_oneshot,
JOBS_FILE,
)
-from cron.scheduler import tick
+from cron.scheduler import tick # noqa: E402
__all__ = [
"create_job",
diff --git a/cron/scheduler.py b/cron/scheduler.py
index f2ef48f53a1..7816ea45692 100644
--- a/cron/scheduler.py
+++ b/cron/scheduler.py
@@ -35,12 +35,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))
-# Cron external worker: run PM's dependency boot (lease the committed generation, activate
-# its site-packages) at this process's own entry, *before* any Hermes package import. A
-# no-op unless this process was spawned as the external worker. See cron/worker_bootstrap.py.
-from cron.worker_bootstrap import WORKER_MARKER, worker_bootstrap
-worker_bootstrap()
-
+from cron.worker_bootstrap import WORKER_MARKER
from hermes_constants import get_hermes_home, hermes_home_key
from hermes_cli.observability.shared_metrics_gateway import note_cron_execution, note_cron_skipped
from cron.env_settings import cron_env_setting
diff --git a/cron/scheduler_worker_env.py b/cron/scheduler_worker_env.py
index 62d43bcdfbd..d74327b1a7c 100644
--- a/cron/scheduler_worker_env.py
+++ b/cron/scheduler_worker_env.py
@@ -80,4 +80,4 @@ def pin_hermes_tree_on_pythonpath(worker_env: dict, repo_root: Path) -> dict:
dependency = _committed_dependency_site_packages(Path(root))
pinned = [root, *([str(dependency)] if dependency is not None else [])]
worker_env["PYTHONPATH"] = os.pathsep.join(dict.fromkeys([*pinned, *existing]))
- return worker_env
\ No newline at end of file
+ return worker_env
diff --git a/cron/worker_bootstrap.py b/cron/worker_bootstrap.py
index 5334f655dc1..9ef63a9b535 100644
--- a/cron/worker_bootstrap.py
+++ b/cron/worker_bootstrap.py
@@ -12,8 +12,9 @@ between the gateway's exit and the worker's next import (#122290 review), and it
``pm.environments.activate_dependencies`` is exactly that boot -- the same call
``hermes_bootstrap`` makes for every other entry point -- and it leases the generation it
selects for the life of the process. ``worker_bootstrap()`` runs it at the top of
-``cron/scheduler.py`` (after the stdlib-only ``sys.path`` pin, before any Hermes package
-import) and does nothing unless ``_launch_external_cron_worker`` marked this child: the
+``cron/__init__.py`` -- ``-m cron.scheduler`` executes the package before the module, and the
+package's first import (``cron.jobs`` -> ``hermes_yaml`` -> ``ruamel``) is already a
+dependency -- and does nothing unless ``_launch_external_cron_worker`` marked this child: the
gateway already booted through ``hermes_bootstrap``, and every other importer of
``cron.scheduler`` is an interpreter that owns its own dependencies.
@@ -45,4 +46,4 @@ def worker_bootstrap() -> None:
activate_dependencies(_root)
except Exception as exc:
- logger.warning("cron external worker dependency activation failed: %s", exc)
\ No newline at end of file
+ logger.warning("cron external worker dependency activation failed: %s", exc)
diff --git a/tests/cron/test_restart_safe_worker.py b/tests/cron/test_restart_safe_worker.py
index e7097d0e8f6..1fb04780ed9 100644
--- a/tests/cron/test_restart_safe_worker.py
+++ b/tests/cron/test_restart_safe_worker.py
@@ -684,31 +684,38 @@ def test_pin_restores_the_committed_generation_site_packages(tmp_path):
}
-def test_worker_bootstrap_boots_only_the_marked_worker(tmp_path, monkeypatch):
- """The PM dependency boot runs in the process ``_launch_external_cron_worker`` marked --
- and only there: the gateway already booted through ``hermes_bootstrap``, and activation
- rewrites ``sys.path``, so an unmarked importer of ``cron.scheduler`` keeps its launch
- contract. The marker is consumed, so the worker's own children do not inherit it."""
+_BOOT_ORDER_PROBE = """
+import json, os, sys
+import pm.environments
+
+boots = []
+pm.environments.activate_dependencies = lambda root: boots.append("cron.jobs" in sys.modules)
+import cron
+print(json.dumps({"boots": boots, "marker": os.environ.get("HERMES_CRON_EXTERNAL_WORKER")}))
+"""
+
+
[email protected]("marked", [True, False])
+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."""
import cron.worker_bootstrap as worker_bootstrap
- import pm.environments
- monkeypatch.setattr(worker_bootstrap, "_root", tmp_path)
- booted = []
- monkeypatch.setattr(
- pm.environments,
- "activate_dependencies",
- lambda project_root: booted.append(project_root),
+ repo_root = Path(worker_bootstrap.__file__).resolve().parent.parent
+ env = {k: v for k, v in os.environ.items() if k != worker_bootstrap.WORKER_MARKER}
+ env["PYTHONPATH"] = str(repo_root)
+ if marked:
+ env[worker_bootstrap.WORKER_MARKER] = "1"
+ child = subprocess.run(
+ [sys.executable, "-c", _BOOT_ORDER_PROBE],
+ cwd=repo_root, env=env, capture_output=True, text=True, timeout=60,
)
-
- monkeypatch.delenv(worker_bootstrap.WORKER_MARKER, raising=False)
- worker_bootstrap.worker_bootstrap()
- assert booted == []
-
- monkeypatch.setenv(worker_bootstrap.WORKER_MARKER, "1")
- worker_bootstrap.worker_bootstrap()
- worker_bootstrap.worker_bootstrap()
- assert booted == [tmp_path]
- assert worker_bootstrap.WORKER_MARKER not in os.environ
+ assert child.returncode == 0, child.stderr
+ result = json.loads(child.stdout.strip().splitlines()[-1])
+ assert result == {"boots": [False] if marked else [], "marker": None}
def test_shared_run_path_hands_gateway_fire_to_external_worker(monkeypatch):