Skip to content

The agent that grows with you

fix(cron): boot the external worker through PM's committed selection

ethernet9ec6b94eca45
diff --git a/cron/scheduler.py b/cron/scheduler.py
index dc5a834f5b4..f2ef48f53a1 100644
--- a/cron/scheduler.py
+++ b/cron/scheduler.py
@@ -35,12 +35,10 @@ 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: acquire the committed dependency generation's lifetime lease and
-# activate its site-packages on this process's path, *before* any Hermes package import.
-# Without this the collector may delete an unselected generation between the gateway's
-# exit and the worker's next import; without site-packages the first dependency import
-# fails (`No module named 'ruamel'`). No-op when the runner owns its dependencies.
-from cron.worker_bootstrap import worker_bootstrap
+# 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 hermes_constants import get_hermes_home, hermes_home_key
@@ -3571,10 +3569,13 @@ def _launch_external_cron_worker(job: dict) -> bool:
):
worker_env.pop(_presence_var, None)
# `-m cron.scheduler` has no hermes_cli.main bootstrap; pin this checkout explicitly
- # (PYTHONSAFEPATH / stale editable mapping, #112729). See cron/scheduler_worker_env.py.
+ # (PYTHONSAFEPATH / stale editable mapping, #112729), hand the child the committed
+ # dependency generation (#122222), and mark it so its own entry runs the PM dependency
+ # boot. See cron/scheduler_worker_env.py and cron/worker_bootstrap.py.
from cron.scheduler_worker_env import pin_hermes_tree_on_pythonpath
repo_root = Path(__file__).resolve().parent.parent
worker_env = pin_hermes_tree_on_pythonpath(worker_env, repo_root)
+ worker_env[WORKER_MARKER] = "1"
try:
stderr_fd = os.open(stderr_path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
try:
diff --git a/cron/scheduler_worker_env.py b/cron/scheduler_worker_env.py
index 026c3209bb1..62d43bcdfbd 100644
--- a/cron/scheduler_worker_env.py
+++ b/cron/scheduler_worker_env.py
@@ -10,20 +10,22 @@ 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. 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.
+sanitizer's drop of the runtime site-packages cannot stand this time: the worker inherits
+this process's interpreter, which is PM's store Python and owns no third-party
+dependencies, so the committed generation's site-packages is restored here too or the
+child dies at its first dependency import (``No module named 'ruamel'``, #122222) before
+it can publish its ownership acknowledgement.
"""
from __future__ import annotations
+import logging
import os
-import sys
import sysconfig
from pathlib import Path
+logger = logging.getLogger(__name__)
+
def _installed_purelib() -> Path | None:
try:
@@ -32,80 +34,50 @@ def _installed_purelib() -> Path | None:
return None
-def _in_real_venv(path: Path) -> bool:
- """True when *path* sits under a directory carrying ``pyvenv.cfg``.
+def _committed_dependency_site_packages(project_root: Path) -> Path | None:
+ """The dependency ``site-packages`` PM committed for this install, or ``None``.
- ``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.
+ Asked of PM's own committed selection -- the record ``activate_dependencies`` resolves
+ at 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.
"""
- 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``.
+ try:
+ from pm.environments import committed_venv, site_packages
- 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
+ environment = 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.
+ logger.warning(
+ "cron worker: could not read the committed dependency environment: %s", exc
+ )
+ return None
+ if environment is None:
+ return None
+ selected = site_packages(environment)
+ return selected if selected.is_dir() else None
def pin_hermes_tree_on_pythonpath(worker_env: dict, repo_root: Path) -> dict:
- """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).
+ """Prepend ``repo_root`` -- and, when this runner has one, the committed dependency
+ generation'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,
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``, so the worker resolves every module exactly as the gateway did.
"""
root = str(repo_root)
if _installed_purelib() == Path(root).resolve():
return worker_env
existing = [e for e in worker_env.get("PYTHONPATH", "").split(os.pathsep) if e]
- pinned = [root]
- dependency = _activated_dependency_site_packages()
- if dependency is not None:
- pinned.append(str(dependency))
+ 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
diff --git a/cron/worker_bootstrap.py b/cron/worker_bootstrap.py
index a72f4a9e43b..5334f655dc1 100644
--- a/cron/worker_bootstrap.py
+++ b/cron/worker_bootstrap.py
@@ -1,151 +1,48 @@
-"""Cron external worker: lifetime protection and dependency activation at spawn.
-
-The restart-safe external worker (``sys.executable -m cron.scheduler``) is a fresh
-process. Its own ``sys.path`` is the store Python's, which owns no third-party
-dependencies; the gateway's dependency generation is not on that path.
-
-``pin_hermes_tree_on_pythonpath`` (``cron/scheduler_worker_env.py``) restores the
-site-packages directory into the child's ``PYTHONPATH`` so the worker can import
-Hermes dependencies. That directory alone, however, is not a retention
-permit: the PM collector removes an unselected, lease-managed generation once it
-is old enough and no process holds its lease. The gateway holds a lease on the
-generation it is running; the freshly spawned worker does not, so between the
-gateway's exit and the worker's next import the collector may delete the very
-generation the worker needs (``#122290`` P2, ``andrexibiza`` review).
-
-This module closes that gap at the worker entry, *before* the first
-application/dependency import:
-
-* ``lease_dependencies()`` acquires the generation's kernel lease (the same
- primitive ``pm.environments.activate_dependencies`` uses) so the collector
- cannot remove it while the worker imports or runs.
-* ``activate_worker_dependencies()`` puts the committed generation's
- ``site-packages`` on this process's ``sys.path`` (``site.addsitedir``), so
- dependency imports resolve without waiting for the gateway's handoff.
-
-Both are no-ops (or degrade to a warning) when no dependency generation is
-committed — a runner that owns its dependencies (wheel / pipx / test /
-developer venv) needs nothing added.
+"""Cron external worker: the PM dependency boot its own entry point never gets.
+
+``sys.executable -m cron.scheduler --external-worker-file ...``
+(``cron/scheduler.py::_launch_external_cron_worker``) is a full Hermes entry point that
+does not go through ``hermes_bootstrap``, and it imports Hermes packages the moment it
+starts. ``cron/scheduler_worker_env.py`` restores the committed generation's
+``site-packages`` on its ``PYTHONPATH`` so those imports resolve, but a pinned path is not a
+boot: the worker holds no lease on the generation, so the PM collector may remove it
+between the gateway's exit and the worker's next import (#122290 review), and its
+``sys.path`` never ran the generation's ``.pth`` files.
+
+``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
+gateway 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.
"""
from __future__ import annotations
import logging
import os
-import sys
from pathlib import Path
logger = logging.getLogger(__name__)
-_root = Path(__file__).resolve().parent.parent
-_LEASE_ACQUIRED = False
-_ACTIVATED = False
-
-
-def _activate_generation() -> Path | None:
- """Locate the committed dependency venv, or ``None`` when there is none.
-
- Uses the same resolution ``pm.environments.activate_dependencies`` uses
- (``committed_venv`` — never the in-tree ``venv``/``.venv``). Returns the
- *venv* directory (the one containing ``pyvenv.cfg``) that
- ``lease_generation`` expects; the function's ``.parent`` is the
- lease-managed generation.
- Stdlib-only reads: a missing facts file means "nothing committed", not an
- error.
- """
- try:
- from pm.environments import committed_venv
- except Exception:
- # pm is not yet importable (pre-PM tree / sealed payload); nothing to lease.
- return None
- try:
- venv = committed_venv(_root)
- except Exception:
- # Corrupt facts file: degrade to a warning, never brick the worker.
- return None
- if venv is None:
- return None
- # A committed venv must carry the marker; a directory that merely happens to
- # be named like one is not a retention target.
- if not (venv / "pyvenv.cfg").is_file():
- return None
- return venv
-
-
-def lease_dependencies() -> None:
- """Hold the committed dependency generation's kernel lease for this worker's lifetime.
-
- Must be called *before* any application or dependency import, because the
- collector's safety condition is "no process holds the lease"; a late lease
- only protects imports that happen after it. ``lease_generation`` takes the
- committed venv path and leases its parent (the generation directory), so a
- generation that is no longer the selected one still survives the collector
- while the worker holds the lease. The lease is released by ``atexit``
- (``hermes_cli.runtime_state.lease_directory``), so an early crash still
- releases it on exit. Idempotent within a process.
- """
- global _LEASE_ACQUIRED
- if _LEASE_ACQUIRED:
- return
- venv = _activate_generation()
- if venv is None:
- return
- try:
- from hermes_cli.runtime_state import lease_generation
- lease_generation(venv)
- _LEASE_ACQUIRED = True
- except Exception as exc: # pragma: no cover - degradation path
- logger.warning("cron worker could not lease dependency generation: %s", exc)
+# 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.
+WORKER_MARKER = "HERMES_CRON_EXTERNAL_WORKER"
+_root = Path(__file__).resolve().parent.parent
-def activate_worker_dependencies() -> None:
- """Put the committed generation's ``site-packages`` on this process's path.
- Delegates to ``pm.environments.activate_dependencies`` — the same
- resolution, ``site.addsitedir`` and ``sys.path`` reordering the gateway's
- boot uses — so the worker imports exactly what the gateway was running.
- No-op when there is no committed generation. Idempotent within a process.
- """
- global _ACTIVATED
- if _ACTIVATED:
+def worker_bootstrap() -> None:
+ """Run PM's dependency boot in the marked external worker; idempotent, never raises."""
+ if not os.environ.pop(WORKER_MARKER, None):
return
try:
from pm.environments import activate_dependencies
- activate_dependencies(_root)
- _ACTIVATED = True
- except Exception as exc: # pragma: no cover - degradation path
- logger.warning("cron worker dependency activation failed: %s", exc)
-
-def worker_bootstrap() -> None:
- """Entry-point hook: lease then activate, in that order.
-
- Leasing first guarantees the generation survives even if activation is
- later skipped; activating second puts ``site-packages`` on the path so the
- first dependency import succeeds. Call this at the very top of
- ``cron/scheduler.py`` (after the stdlib-only ``sys.path`` pin, before any
- Hermes package import).
-
- Activation is gated on the process being a *restart-safe external worker*
- (one spawned as ``python -m cron.scheduler --external-worker-file ...``):
- such a worker is a fresh interpreter whose own ``sys.path`` is the store
- Python's and carries no dependency packages, so it must activate. A
- gateway process already runs on its activated dependency graph (booted
- through ``hermes_bootstrap`` → ``activate_dependencies``); re-activating
- there is a harmless no-op but is skipped so the gateway keeps its exact
- launch contract. Leasing is unconditional: it is idempotent and protects
- the generation the worker (or the gateway) will use regardless.
- """
- lease_dependencies()
- if _is_restart_safe_worker():
- activate_worker_dependencies()
-
-
-def _is_restart_safe_worker() -> bool:
- """True only when this process is the externally spawned restart-safe worker.
-
- The spawn site (``_launch_external_cron_worker``) passes
- ``--external-worker-file``; the gateway runs in-process with no such flag,
- and other CLI invocations of ``cron/scheduler`` do not use it either.
- """
- return "--external-worker-file" in sys.argv
+ activate_dependencies(_root)
+ except Exception as exc:
+ logger.warning("cron external worker dependency activation failed: %s", exc)
\ 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 0af1197c9dc..e7097d0e8f6 100644
--- a/tests/cron/test_restart_safe_worker.py
+++ b/tests/cron/test_restart_safe_worker.py
@@ -639,10 +639,7 @@ 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)
- # 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
+ assert entries == [str(repo_root), str(tmp_path / "kept-by-sanitizer")]
# Wheel / pipx layout: repo_root == purelib -> untouched.
monkeypatch.setattr(worker_env_mod, "_installed_purelib", lambda: repo_root)
@@ -652,277 +649,66 @@ def test_launch_external_worker_pin_extends_the_sanitized_env_not_os_environ(
-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."""
+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
+ pin hands the child PM's committed generation -- after the checkout, before the entries
+ the sanitizer kept -- and invents nothing when no generation is committed."""
import cron.scheduler_worker_env as worker_env_mod
+ import pm.environments
- 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()
+ 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")
+ 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
)
- entries = env["PYTHONPATH"].split(os.pathsep)
- assert entries == [
- str(repo_root.resolve()),
- str(dependency.resolve()),
- str(tmp_path / "kept"),
+ assert env["PYTHONPATH"].split(os.pathsep) == [
+ str(repo_root), str(selected), str(tmp_path / "kept"),
]
+ # A runner that owns its dependencies has no committed generation: tree only.
+ pm.environments.runtime_facts_path(repo_root).unlink()
+ assert worker_env_mod.pin_hermes_tree_on_pythonpath({}, repo_root) == {
+ "PYTHONPATH": str(repo_root)
+ }
-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()
+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."""
+ import cron.worker_bootstrap as worker_bootstrap
+ import pm.environments
- monkeypatch.setattr(worker_env_mod, "_installed_purelib", lambda: purelib.resolve())
+ monkeypatch.setattr(worker_bootstrap, "_root", tmp_path)
+ booted = []
monkeypatch.setattr(
- worker_env_mod.sys,
- "path",
- [str(purelib), str(dependency), str(tmp_path / "user-libs")],
+ pm.environments,
+ "activate_dependencies",
+ lambda project_root: booted.append(project_root),
)
- 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_worker_bootstrap_lease_and_activation(tmp_path, monkeypatch):
- """#122290 P2 (andrexibiza review): the externally spawned worker must hold the
- committed generation's kernel lease *and* activate its site-packages on its own
- sys.path, both *before* the first application/dependency import. Without the lease
- the PM collector may delete an unselected generation between the gateway's exit and
- the worker's next import; without activation the first import fails
- (``No module named 'ruamel'``).
-
- The fixture arranges:
- * a committed venv whose ``.parent`` carries ``.lease-managed`` (so
- ``lease_directory`` takes a real kernel lock),
- * a fake ``lease_generation`` that records the call,
- * a fake ``activate_dependencies`` that records the call,
- * the worker flag on ``sys.argv`` so ``worker_bootstrap`` performs activation.
- """
- import cron.worker_bootstrap as wb
- from pathlib import Path
-
- # Reset module-level idempotency flags so the assertions see fresh state.
- wb._LEASE_ACQUIRED = False
- wb._ACTIVATED = False
- try:
- # Build a committed venv layout under tmp_path:
- # tmp_path/install/environments/<gen>/venv -> pyvenv.cfg
- # tmp_path/install/environments/<gen>/.lease-managed
- install_state = tmp_path / "install_state"
- generation = install_state / "environments" / "g1"
- venv = generation / "venv"
- venv.mkdir(parents=True)
- (venv / "pyvenv.cfg").write_text("home = /usr/bin\n", encoding="utf-8")
- (generation / ".lease-managed").write_text("", encoding="utf-8")
-
- # Point _activate_generation at our fixture layout.
- monkeypatch.setattr(wb, "_root", tmp_path)
-
- # Stub _activate_generation to return the venv path (the fixture).
- monkeypatch.setattr(wb, "_activate_generation", lambda: venv)
-
- # Stub lease_generation to record the call without touching the real lock.
- lease_calls = []
- def _fake_lease_generation(environment):
- lease_calls.append(environment)
- return lambda: None
- monkeypatch.setattr(
- "hermes_cli.runtime_state.lease_generation", _fake_lease_generation,
- raising=False,
- )
- # The real lease_generation is imported inside lease_dependencies via
- # "from hermes_cli.runtime_state import lease_generation", so we must patch
- # the module attribute before the import runs.
- import hermes_cli.runtime_state as _rs
- monkeypatch.setattr(_rs, "lease_generation", _fake_lease_generation)
-
- # Stub activate_dependencies to record the call.
- activate_calls = []
- def _fake_activate(project_root):
- activate_calls.append(project_root)
- monkeypatch.setattr(
- "pm.environments.activate_dependencies", _fake_activate,
- raising=False,
- )
- import pm.environments as _env
- monkeypatch.setattr(_env, "activate_dependencies", _fake_activate)
-
- # Simulate the restart-safe worker flag.
- old_argv = list(sys.argv)
- sys.argv = old_argv + ["--external-worker-file", "x.json", "--ack-file", "a.ready"]
- try:
- wb.worker_bootstrap()
- finally:
- sys.argv = old_argv
-
- # Lease was taken on the venv path (lease_generation internally does .parent).
- assert len(lease_calls) == 1
- assert lease_calls[0] == venv
- # Activation was performed (worker flag was present).
- assert len(activate_calls) == 1
- assert activate_calls[0] == tmp_path # _root passed to activate_dependencies
- # Idempotency flags set.
- assert wb._LEASE_ACQUIRED is True
- assert wb._ACTIVATED is True
- finally:
- wb._LEASE_ACQUIRED = False
- wb._ACTIVATED = False
-
-
-def test_worker_bootstrap_leases_but_skips_activation_in_gateway(tmp_path, monkeypatch):
- """The gateway process (no ``--external-worker-file`` flag) leases the generation
- (unconditionally, idempotently) but does *not* re-activate dependencies, so the
- gateway keeps its exact launch contract (already booted through hermes_bootstrap).
- """
- import cron.worker_bootstrap as wb
-
- wb._LEASE_ACQUIRED = False
- wb._ACTIVATED = False
- try:
- venv = tmp_path / "install" / "environments" / "g1" / "venv"
- venv.mkdir(parents=True)
- (venv / "pyvenv.cfg").write_text("home = /usr/bin\n", encoding="utf-8")
- monkeypatch.setattr(wb, "_root", tmp_path)
- monkeypatch.setattr(wb, "_activate_generation", lambda: venv)
-
- lease_calls = []
- def _fake_lease_generation(environment):
- lease_calls.append(environment)
- return lambda: None
- import hermes_cli.runtime_state as _rs
- monkeypatch.setattr(_rs, "lease_generation", _fake_lease_generation)
-
- activate_calls = []
- def _fake_activate(project_root):
- activate_calls.append(project_root)
- import pm.environments as _env
- monkeypatch.setattr(_env, "activate_dependencies", _fake_activate)
-
- old_argv = list(sys.argv)
- sys.argv = old_argv # no --external-worker-file flag
- try:
- wb.worker_bootstrap()
- finally:
- sys.argv = old_argv
-
- # Lease still taken (unconditional).
- assert len(lease_calls) == 1
- # Activation NOT performed (gateway path).
- assert activate_calls == []
- assert wb._ACTIVATED is False
- finally:
- wb._LEASE_ACQUIRED = False
- wb._ACTIVATED = False
-
-
-def test_worker_bootstrap_no_committed_venv_is_noop(tmp_path, monkeypatch):
- """When there is no committed dependency generation (pre-PM install, wheel/pipx
- runner that owns its own deps), both lease and activation are no-ops; the worker
- proceeds on whatever its interpreter already carries."""
- import cron.worker_bootstrap as wb
-
- wb._LEASE_ACQUIRED = False
- wb._ACTIVATED = False
- try:
- monkeypatch.setattr(wb, "_root", tmp_path)
- # _activate_generation returns None -> no committed venv.
- monkeypatch.setattr(wb, "_activate_generation", lambda: None)
-
- # Stub the real lease/activate to *fail* if called (they should not be).
- def _boom_lease(environment):
- raise AssertionError("lease_generation called with no committed venv")
- import hermes_cli.runtime_state as _rs
- monkeypatch.setattr(_rs, "lease_generation", _boom_lease)
-
- def _boom_activate(project_root):
- raise AssertionError("activate_dependencies called with no committed venv")
- import pm.environments as _env
- monkeypatch.setattr(_env, "activate_dependencies", _boom_activate)
-
- old_argv = list(sys.argv)
- sys.argv = old_argv + ["--external-worker-file", "x.json", "--ack-file", "a.ready"]
- try:
- wb.worker_bootstrap() # must not raise
- finally:
- sys.argv = old_argv
-
- assert wb._LEASE_ACQUIRED is False
- assert wb._ACTIVATED is False
- finally:
- wb._LEASE_ACQUIRED = False
- wb._ACTIVATED = False
-
-
-def test_cron_scheduler_module_hooks_worker_bootstrap(tmp_path, monkeypatch):
- """The scheduler module-level hook (``from cron.worker_bootstrap import
- worker_bootstrap; worker_bootstrap()``) must run *before* the first Hermes
- package import. Assert that importing ``cron.scheduler`` with the worker
- flag set does not raise (the bootstrap is idempotent and degrades
- gracefully when pm/environments is not yet reachable on a dev checkout)."""
- import importlib
- import sys
-
- # Remove any cached module so the import re-runs top-level code.
- for mod in list(sys.modules):
- if mod.startswith("cron.scheduler") or mod == "cron.worker_bootstrap":
- del sys.modules[mod]
-
- old_argv = list(sys.argv)
- sys.argv = old_argv + ["--external-worker-file", "x.json", "--ack-file", "a.ready"]
- try:
- # This import must succeed: worker_bootstrap degrades to a warning when
- # pm.environments / hermes_cli.runtime_state are not importable in the
- # dev checkout, and when _activate_generation returns None.
- mod = importlib.import_module("cron.scheduler")
- assert mod is not None
- finally:
- sys.argv = old_argv
+ 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
def test_shared_run_path_hands_gateway_fire_to_external_worker(monkeypatch):