Skip to content

The agent that grows with you

fix(execute-code): preserve PM runtime dependencies for own kernel

funky-xamarin7a09408e7c3c
diff --git a/tests/tools/test_code_execution_pm_runtime.py b/tests/tools/test_code_execution_pm_runtime.py
new file mode 100644
index 00000000000..efea68d13a4
--- /dev/null
+++ b/tests/tools/test_code_execution_pm_runtime.py
@@ -0,0 +1,69 @@
+"""PM runtime dependencies survive the kernel child boundary (#124049)."""
+
+import json
+import os
+import sys
+import venv
+from pathlib import Path
+
+import pytest
+
+from pm.environments import install_state_dir, runtime_facts_path, site_packages, venv_python
+from tools import code_execution_env, code_execution_tool
+from tools.code_kernel import shutdown_all_kernels
+
+
+def runtime_dependency(tmp_path, monkeypatch):
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "h"))
+ root = Path(code_execution_env.__file__).resolve().parents[1]
+ generation = install_state_dir(root) / "environments" / "fixture" / "venv"
+ generation.mkdir(parents=True)
+ (generation / "pyvenv.cfg").write_text(
+ f"version = {sys.version_info.major}.{sys.version_info.minor}.0\n", encoding="utf-8"
+ )
+ packages = site_packages(generation)
+ packages.mkdir(parents=True)
+ (packages / "pm_fixture_dependency.py").write_text("VALUE = 'runtime-dependency'\n", encoding="utf-8")
+ facts = runtime_facts_path(root)
+ facts.write_text(json.dumps({"packages": {"venv": {"environment": str(generation)}}}), encoding="utf-8")
+ user_lib = tmp_path / "user-lib"
+ user_lib.mkdir()
+ (user_lib / "user_fixture_dependency.py").write_text("VALUE = 'user-dependency'\n", encoding="utf-8")
+ monkeypatch.setenv("PYTHONPATH", os.pathsep.join(map(str, (root, packages, user_lib))))
+ monkeypatch.setenv("TERMINAL_ENV", "local")
+ monkeypatch.delenv("VIRTUAL_ENV", raising=False)
+ monkeypatch.delenv("CONDA_PREFIX", raising=False)
+ shutdown_all_kernels()
+ yield packages
+ shutdown_all_kernels()
+
+
[email protected]("mode", ["strict", "project"])
+def test_runtime_dependencies_import_in_persistent_kernel(runtime_dependency, monkeypatch, mode):
+ monkeypatch.setattr(code_execution_tool, "_load_config", lambda: {"mode": mode, "timeout": 15})
+ first = json.loads(code_execution_tool.execute_code(
+ "import pm_fixture_dependency as dep\nimport user_fixture_dependency as user\nprint(dep.VALUE, user.VALUE)",
+ task_id="pm-runtime-import",
+ ))
+ assert first["status"] == "success", first
+ assert "runtime-dependency user-dependency" in first["output"]
+ second = json.loads(code_execution_tool.execute_code("print(dep.VALUE)", task_id="pm-runtime-import"))
+ assert second["status"] == "success", second
+ assert second["kernel"]["reused"] is True
+ assert "runtime-dependency" in second["output"]
+
+
+def test_project_interpreter_keeps_runtime_dependencies_out(runtime_dependency, tmp_path, monkeypatch):
+ project = tmp_path / "project-env"
+ venv.EnvBuilder(with_pip=False).create(project)
+ monkeypatch.setenv("VIRTUAL_ENV", str(project))
+ monkeypatch.setattr(code_execution_tool, "_load_config", lambda: {"mode": "project", "timeout": 15})
+ assert code_execution_env._resolve_child_python("project") == str(venv_python(project))
+ result = json.loads(code_execution_tool.execute_code(
+ "import importlib.util\nimport user_fixture_dependency as user\n"
+ "print(importlib.util.find_spec('pm_fixture_dependency') is None, user.VALUE)",
+ task_id="pm-project-isolation",
+ ))
+ assert result["status"] == "success", result
+ assert "True user-dependency" in result["output"]
diff --git a/tools/code_execution_env.py b/tools/code_execution_env.py
index 34d90c36c43..403350cb415 100644
--- a/tools/code_execution_env.py
+++ b/tools/code_execution_env.py
@@ -150,13 +150,29 @@ def _build_child_env(*, rpc_endpoint: str, rpc_token: str, tmpdir: str,
# exposing Hermes's site-packages to an external interpreter can mix incompatible compiled
# extensions (3.12 NumPy under a 3.9 venv). Inherited Hermes-owned entries are stripped first.
# Before re-injecting PYTHONPATH, strip Hermes-owned entries that leaked through _scrub_child_env
- # (PYTHONPATH is in _SAFE_ENV_PREFIXES so it passes the scrub). They are redundant for same-Hermes-
- # environment children and may be incompatible with external interpreters (project mode can select a
- # different venv), so they must not shadow or poison the child's sys.path (#74817).
- from tools.environments.local_pythonpath import _strip_hermes_owned_pythonpath
+ # (PYTHONPATH is in _SAFE_ENV_PREFIXES so it passes the scrub). External project interpreters
+ # must not inherit Hermes dependencies (#74817). PM's own interpreter, however, can be a
+ # bare bundled Python whose dependencies live in the selected generation, not sys.prefix.
+ from tools.environments.local_pythonpath import (
+ _strip_hermes_owned_pythonpath, _validated_runtime_venv, _same_path,
+ )
+ _runtime_path = None
+ if child_python == sys.executable:
+ runtime_venv = _validated_runtime_venv(child_env)
+ if runtime_venv is not None:
+ from pathlib import Path
+ from pm.environments import site_packages
+ candidate = site_packages(runtime_venv)
+ # Restore only a dependency path the launcher actually supplied, not a newly
+ # selected generation that this still-running interpreter has never loaded.
+ if any(_same_path(Path(entry), candidate)
+ for entry in child_env.get("PYTHONPATH", "").split(os.pathsep) if entry):
+ _runtime_path = str(candidate)
_strip_hermes_owned_pythonpath(child_env)
_existing_pp = child_env.get("PYTHONPATH", "")
_pp_parts = [tmpdir]
+ if _runtime_path is not None:
+ _pp_parts.append(_runtime_path)
if _uses_hermes_python_environment(child_python):
_pp_parts.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
elif child_python not in _external_env_logged: