Skip to content

The agent that grows with you

fix(cron): run POSIX .py job scripts on the selected venv interpreter

liuhao1024cb11c994f764
diff --git a/cron/scheduler_script.py b/cron/scheduler_script.py
index 589a4b8ee95..6b7ce22f80b 100644
--- a/cron/scheduler_script.py
+++ b/cron/scheduler_script.py
@@ -114,12 +114,39 @@ def _read_windows_pyvenv_cfg(venv_dir: Path) -> dict[str, str]:
}
+def _posix_cron_python_invocation(python_exe: str) -> tuple[str, dict[str, str]]:
+ """POSIX managed-store installs: cron ``.py`` scripts run on the selected dependency venv's
+ interpreter, not the bare store Python. The store Python only carries the repo and the
+ managed site-packages on its in-process ``sys.path``; a spawned child re-resolves imports
+ from scratch and dies with ``ModuleNotFoundError`` after the venv → PM runtime switch
+ (#123044). The venv interpreter finds its dependency site-packages through ``pyvenv.cfg``
+ (editable installs included), so no ``PYTHONPATH`` overlay is needed — and one must not be
+ used: it would be inherited by every child the script spawns, where a foreign interpreter
+ (another venv, system Python) would import the store's CPython-3.14 extension modules first
+ and crash (#123440). Lazy installs are disabled for script children so a script importing
+ ``hermes_bootstrap`` off the store-record venv cannot republish launchers (#123440).
+ Installs without a committed store (source checkouts, pre-PM venvs) keep the caller's
+ interpreter."""
+ from hermes_cli._launchers import resolve_store_python
+
+ repo = Path(__file__).resolve().parents[1]
+ if resolve_store_python(repo) is None:
+ return python_exe, {}
+
+ from pm.environments import selected_venv, venv_bin_dir
+
+ venv_python = venv_bin_dir(selected_venv(repo)) / "python"
+ if not venv_python.is_file():
+ return python_exe, {}
+ return str(venv_python), {"HERMES_DISABLE_LAZY_INSTALLS": "1"}
+
+
def _windows_cron_python_invocation(python_exe: str) -> tuple[str, dict[str, str]]:
"""Hidden, output-capable Python invocation for Windows cron scripts. ``pythonw.exe`` loses
captured output; uv venv launchers can re-exec the base console python and flash a window
even with CREATE_NO_WINDOW, so run the base python directly with venv paths overlaid in env."""
if sys.platform != "win32":
- return python_exe, {}
+ return _posix_cron_python_invocation(python_exe)
interpreter = _sched.Path(python_exe)
venv_dir = interpreter.parent.parent
@@ -320,7 +347,8 @@ def _resolve_script_path(script_path: str) -> tuple[Optional[Path], Optional[str
def _script_argv(path: Path) -> tuple[Optional[list[str]], dict[str, str], Optional[str]]:
"""``(argv, env_overlay, error)`` for a validated script. Interpreter by extension — the
shebang is deliberately NOT honoured (small, auditable surface): ``.sh``/``.bash`` → bash,
- else ``sys.executable`` (Windows uv-venv overlay gets the .pth bootstrap)."""
+ else ``sys.executable`` (Windows managed/uv overlays get the ``.pth`` bootstrap; POSIX
+ managed installs run on the selected venv's interpreter)."""
if path.suffix.lower() in {".sh", ".bash"}:
# which() finds Git Bash on Windows; None there → clear error instead of a "[WinError 2]".
_bash = shutil.which("bash") or ("/bin/bash" if os.path.isfile("/bin/bash") else None)
@@ -332,7 +360,9 @@ def _script_argv(path: Path) -> tuple[Optional[list[str]], dict[str, str], Optio
)
return [_bash, str(path)], {}, None
python_exe, env_overlay = _windows_cron_python_invocation(sys.executable)
- if env_overlay:
+ if env_overlay.get("PYTHONPATH"):
+ # The bootstrap exists to give PYTHONPATH overlays .pth processing (editable installs);
+ # non-PYTHONPATH overlays (the POSIX venv-interpreter path) pass through plain.
return _windows_cron_bootstrap_argv(python_exe, env_overlay, str(path)), env_overlay, None
return [python_exe, str(path)], env_overlay, None
diff --git a/tests/cron/test_cron_script.py b/tests/cron/test_cron_script.py
index 4e25a3df3d6..708738bfc99 100644
--- a/tests/cron/test_cron_script.py
+++ b/tests/cron/test_cron_script.py
@@ -305,8 +305,127 @@ class TestRunJobScript:
)
assert argv == [sys.executable, str(script)]
+ @pytest.mark.platforms("posix")
+ def test_posix_invocation_selects_venv_interpreter(self, tmp_path, monkeypatch):
+ """POSIX managed-store installs: cron ``.py`` scripts run on the selected dependency
+ venv's interpreter — the bare store Python carries the repo/dependencies only
+ in-process (#123044) — with lazy installs disabled and NO ``PYTHONPATH`` overlay: an
+ inherited overlay makes foreign-interpreter children import the store's 3.14 extension
+ modules first (#123440). No committed store → the caller's interpreter passes through
+ untouched (pre-PM venvs, source checkouts), as does a store whose venv python
+ vanished (half-migrated install must not crash the scheduler)."""
+ from cron import scheduler_script
+
+ venv = tmp_path / "selected-venv" / "bin"
+ venv.mkdir(parents=True)
+ venv_python = venv / "python"
+ venv_python.touch()
+ monkeypatch.setattr(
+ "hermes_cli._launchers.resolve_store_python", lambda repo: venv_python
+ )
+ monkeypatch.setattr("pm.environments.selected_venv", lambda repo: venv.parent)
+
+ assert scheduler_script._posix_cron_python_invocation(sys.executable) == (
+ str(venv_python),
+ {"HERMES_DISABLE_LAZY_INSTALLS": "1"},
+ )
+
+ venv_python.unlink()
+ assert scheduler_script._posix_cron_python_invocation(sys.executable) == (
+ sys.executable,
+ {},
+ )
+
+ monkeypatch.setattr(
+ "hermes_cli._launchers.resolve_store_python", lambda repo: None
+ )
+ assert scheduler_script._posix_cron_python_invocation(sys.executable) == (
+ sys.executable,
+ {},
+ )
+
+ @pytest.mark.platforms("posix")
+ def test_posix_managed_store_script_argv_stays_plain(
+ self, cron_env, tmp_path, monkeypatch
+ ):
+ """The POSIX venv-interpreter path must not go through the ``addsitedir`` bootstrap:
+ the venv interpreter processes its own ``.pth`` files through ``pyvenv.cfg``, and a
+ plain argv keeps the script's ``__file__``/``sys.path[0]`` semantics untouched."""
+ from cron.scheduler_script import _script_argv
+
+ venv = tmp_path / "selected-venv" / "bin"
+ venv.mkdir(parents=True)
+ venv_python = venv / "python"
+ venv_python.touch()
+ monkeypatch.setattr(
+ "hermes_cli._launchers.resolve_store_python", lambda repo: venv_python
+ )
+ monkeypatch.setattr("pm.environments.selected_venv", lambda repo: venv.parent)
+
+ script = cron_env / "scripts" / "probe.py"
+ script.write_text('print("ok")\n', encoding="utf-8")
+
+ argv, overlay, err = _script_argv(script)
+ assert err is None
+ assert argv == [str(venv_python), str(script)]
+ assert overlay == {"HERMES_DISABLE_LAZY_INSTALLS": "1"}
+
+ @pytest.mark.platforms("posix")
+ def test_posix_managed_store_script_imports_via_venv(
+ self, cron_env, tmp_path, monkeypatch
+ ):
+ """End-to-end #123044/#123440 shape: on a POSIX managed-store install a cron ``.py``
+ script must import managed dependencies and Hermes modules by running on the selected
+ venv's interpreter, and the environment it runs in must be clean — no ``PYTHONPATH``
+ pointing at the store's paths, so children the script spawns never import the store's
+ extension modules on a foreign interpreter."""
+ from cron.scheduler_script import _run_job_script
+ from pm.environments import site_packages as dependency_site
+
+ fake_venv = tmp_path / "selected-venv"
+ # Standard venv layout: bin/python symlink + pyvenv.cfg + lib/pythonX.Y/site-packages.
+ venv_bin = fake_venv / "bin"
+ venv_bin.mkdir(parents=True)
+ venv_python = venv_bin / "python"
+ venv_python.symlink_to(sys.executable)
+ (fake_venv / "pyvenv.cfg").write_text(
+ f"home = {Path(sys.base_prefix) / 'bin'}\n"
+ "include-system-site-packages = false\n",
+ encoding="utf-8",
+ )
+ deps = dependency_site(fake_venv)
+ deps.mkdir(parents=True)
+ (deps / "probe_pkg.py").write_text("VALUE = 42\n", encoding="utf-8")
+ # Editable-style repo exposure, as a real PM venv carries for the checkout.
+ repo = Path(__file__).resolve().parents[2]
+ (deps / "zz_repo.pth").write_text(f"{repo}\n", encoding="utf-8")
+
+ monkeypatch.setattr(
+ "hermes_cli._launchers.resolve_store_python",
+ lambda repo: Path(sys.executable),
+ )
+ monkeypatch.setattr("pm.environments.selected_venv", lambda repo: fake_venv)
+
+ script = cron_env / "scripts" / "probe.py"
+ script.write_text(
+ "import os\n"
+ "import probe_pkg\n"
+ "import hermes_constants\n"
+ "print(probe_pkg.VALUE)\n"
+ "print('PP=' + (os.environ.get('PYTHONPATH') or ''))\n",
+ encoding="utf-8",
+ )
+
+ success, output = _run_job_script("probe.py")
+ assert success is True, output
+ lines = output.strip().splitlines()
+ assert lines[0] == "42"
+ pp_line = next(line for line in lines if line.startswith("PP="))
+ # The #123440 contract: the store's repo/dependency paths never leak onto PYTHONPATH.
+ assert str(deps) not in pp_line
+ assert str(repo) not in pp_line
def test_emoji_stdout_round_trips_through_script_capture(self, cron_env):
"""Emoji in script stdout must reach the caller intact (#42384).