fix(tools): harden interpreter-environment probe for the strict-mode default

Follow-up to the salvaged #81201 commits:

- Short-circuit _uses_hermes_python_environment when the child IS the
  running interpreter (path or realpath match). The default strict-mode
  path no longer spawns a probe subprocess at all, and a flaky probe of
  sys.executable can never drop the hermes root from PYTHONPATH
  (protects the test_repo_root_modules_are_importable invariant). The
  realpath leg also covers uv-style venvs whose bin/python resolves to
  the same binary.
- Stop caching failed probes: _python_environment_prefix now uses a
  success-only dict cache instead of lru_cache, so one transient
  timeout under load no longer sticks for the process lifetime.
- Deduplicate the subprocess probe scaffolding shared with
  _is_usable_python into _probe_python().
- Log once when the hermes root is omitted so import-behavior changes
  are diagnosable from user reports.
- Tests: fail the composition tests loudly if execute_code never
  reaches Popen (was vacuously passing on exceptions); assert the
  staging dir is literally first in PYTHONPATH (was truthiness only);
  add guards for probe-failure retry and the no-probe short-circuit.
This commit is contained in:
kshitij
2026-08-12 17:13:03 +05:30
parent ec884fc655
commit 89556c63ac
2 changed files with 109 additions and 43 deletions
+52 -20
View File
@@ -39,6 +39,7 @@ from tools.code_execution_tool import (
_get_execution_mode,
_is_usable_python,
_python_environment_prefix,
_python_prefix_cache,
_resolve_child_cwd,
_resolve_child_python,
_uses_hermes_python_environment,
@@ -385,10 +386,10 @@ class TestPythonEnvironmentPrefix(unittest.TestCase):
"""Unit tests for the helper that queries sys.prefix of an interpreter."""
def setUp(self):
_python_environment_prefix.cache_clear()
_python_prefix_cache.clear()
def tearDown(self):
_python_environment_prefix.cache_clear()
_python_prefix_cache.clear()
def test_returns_realpath_of_current_interpreter_prefix(self):
"""Happy path: sys.executable reports its own prefix."""
@@ -431,20 +432,49 @@ class TestPythonEnvironmentPrefix(unittest.TestCase):
_python_environment_prefix("/cached/python")
self.assertEqual(mock_run.call_count, 1)
def test_failure_is_not_cached(self):
"""A transient probe failure must not stick — the next call retries.
A sticky cached failure would silently drop the hermes root from
every subsequent execute_code call in the process.
"""
with patch("subprocess.run",
side_effect=subprocess.TimeoutExpired(cmd=[], timeout=5)) as mock_run:
self.assertEqual(_python_environment_prefix("/flaky/python"), "")
self.assertEqual(mock_run.call_count, 1)
with patch("subprocess.run") as mock_run:
mock_run.return_value = unittest.mock.MagicMock(
returncode=0, stdout="/recovered/prefix\n"
)
result = _python_environment_prefix("/flaky/python")
self.assertEqual(mock_run.call_count, 1, "probe must be retried after a failure")
self.assertEqual(result, os.path.realpath("/recovered/prefix"))
class TestUsesHermesPythonEnvironment(unittest.TestCase):
"""Unit tests for _uses_hermes_python_environment."""
def setUp(self):
_python_environment_prefix.cache_clear()
_python_prefix_cache.clear()
def tearDown(self):
_python_environment_prefix.cache_clear()
_python_prefix_cache.clear()
def test_true_for_current_interpreter(self):
"""sys.executable always belongs to the current environment."""
self.assertTrue(_uses_hermes_python_environment(sys.executable))
def test_true_for_current_interpreter_without_probe(self):
"""sys.executable short-circuits — no subprocess probe on the default path.
Guards the strict-mode invariant: a flaky probe (timeout under load)
must never drop the hermes root for the interpreter Hermes itself runs.
"""
with patch("subprocess.run",
side_effect=subprocess.TimeoutExpired(cmd=[], timeout=5)) as mock_run:
self.assertTrue(_uses_hermes_python_environment(sys.executable))
mock_run.assert_not_called()
def test_false_for_different_prefix(self):
"""An interpreter reporting a different prefix is external."""
with patch("tools.code_execution_tool._python_environment_prefix",
@@ -476,13 +506,15 @@ class TestPythonPathComposition(unittest.TestCase):
cover the detection logic end-to-end.
"""
def _capture_pythonpath(self, same_env: bool) -> str:
"""Return the PYTHONPATH that execute_code would pass to the child."""
def _capture_pythonpath(self, same_env: bool) -> tuple:
"""Return (PYTHONPATH, staging_dir) that execute_code passes to the child."""
captured = {}
def _fake_popen(cmd, **kwargs):
env = kwargs.get("env") or {}
captured["PYTHONPATH"] = env.get("PYTHONPATH", "")
# cmd is [python, <staging_dir>/script.py]
captured["staging_dir"] = os.path.dirname(cmd[1])
mock_proc = unittest.mock.MagicMock()
mock_proc.stdout.read.return_value = b""
mock_proc.stderr.read.return_value = b""
@@ -496,41 +528,41 @@ class TestPythonPathComposition(unittest.TestCase):
patch("tools.code_execution_tool._uses_hermes_python_environment",
return_value=same_env), \
patch("subprocess.Popen", side_effect=_fake_popen):
try:
execute_code(code="pass", task_id="test-pp", enabled_tools=[])
except Exception:
pass
execute_code(code="pass", task_id="test-pp", enabled_tools=[])
return captured.get("PYTHONPATH", "")
# If execute_code never reached Popen, the capture is empty and any
# "X not in PYTHONPATH" assertion downstream would pass vacuously.
self.assertIn("PYTHONPATH", captured,
"execute_code never spawned the child process")
return captured["PYTHONPATH"], captured["staging_dir"]
def _hermes_root(self) -> str:
tools_dir = os.path.dirname(os.path.abspath(
__import__("tools.code_execution_tool", fromlist=["__file__"]).__file__
))
import tools.code_execution_tool as _cet
tools_dir = os.path.dirname(os.path.abspath(_cet.__file__))
return os.path.dirname(tools_dir)
def test_hermes_root_included_when_same_env(self):
"""When interpreter is in the Hermes env, hermes root is in PYTHONPATH."""
pythonpath = self._capture_pythonpath(same_env=True)
pythonpath, _ = self._capture_pythonpath(same_env=True)
parts = pythonpath.split(os.pathsep)
self.assertIn(self._hermes_root(), parts,
"hermes root must be in PYTHONPATH for same-env interpreters")
def test_hermes_root_excluded_when_external_env(self):
"""When interpreter is external, hermes root must NOT be in PYTHONPATH."""
pythonpath = self._capture_pythonpath(same_env=False)
pythonpath, _ = self._capture_pythonpath(same_env=False)
parts = pythonpath.split(os.pathsep)
self.assertNotIn(self._hermes_root(), parts,
"hermes root must not leak into an external interpreter's PYTHONPATH")
def test_staging_dir_always_present(self):
def test_staging_dir_always_first(self):
"""The staging tmpdir must always be the first PYTHONPATH entry."""
for same_env in (True, False):
with self.subTest(same_env=same_env):
pythonpath = self._capture_pythonpath(same_env=same_env)
pythonpath, staging_dir = self._capture_pythonpath(same_env=same_env)
parts = pythonpath.split(os.pathsep)
self.assertTrue(parts and parts[0],
"PYTHONPATH must start with the staging tmpdir")
self.assertEqual(parts[0], staging_dir,
"PYTHONPATH must start with the staging tmpdir")
if __name__ == "__main__":