From 4e7eb39947f132f961923f9e3f600bc8e63066dd Mon Sep 17 00:00:00 2001 From: Teknium <127238744+teknium1@users.noreply.github.com> Date: Thu, 27 Aug 2026 22:22:39 -0700 Subject: [PATCH] =?UTF-8?q?refactor(code-execution):=20session=20kernels?= =?UTF-8?q?=20always=20on=20=E2=80=94=20kernel=5Fmode=20knob=20retired=20(?= =?UTF-8?q?#96787)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * refactor(code-execution): retire kernel_mode — session kernels always on for local runs (remote per-call is a tracked gap, not a mode) * test(code-execution): env-filtering probes use reset=true — kernel env is frozen at spawn, so env rules are only observable on a fresh kernel * test(code-execution): kernel-aware fixes for mode/pythonpath suites — reset=true on frozen-at-spawn probes, per-test kernel disposal, abort-after-capture fake Popen * test(code-execution): strict-mode cwd is a behavior contract (staging tmpdir, not session cwd) — kernel stages in hermes_kernel_*, per-call in hermes_sandbox_* --- cli-config.yaml.example | 19 ++++---- hermes_cli/config_defaults.py | 8 +++- tests/tools/test_code_execution.py | 19 +++++++- tests/tools/test_code_execution_modes.py | 57 +++++++++++++++++++----- tests/tools/test_code_kernel.py | 40 ++++++++--------- tools/code_execution_tool.py | 32 ++++++++----- 6 files changed, 119 insertions(+), 56 deletions(-) diff --git a/cli-config.yaml.example b/cli-config.yaml.example index e72a5e94af..b601a827ad 100644 --- a/cli-config.yaml.example +++ b/cli-config.yaml.example @@ -1517,16 +1517,15 @@ stt: code_execution: timeout: 300 # Max seconds per script before kill (default: 300 = 5 min) max_tool_calls: 50 # Max RPC tool calls per execution (default: 50) - # kernel_mode: per-call | session (default: per-call) - # per-call — fresh child process per execute_code call; no state carries over. - # session — one persistent kernel per (task, mode, interpreter, cwd, tool-set): - # variables, imports, and loaded data survive across calls, so - # multi-step data work stops re-loading its inputs every call. - # A timed-out/interrupted cell kills the kernel (state lost; the - # next call starts fresh). Pass reset=true on a call to discard - # state deliberately. Security scrubbing, tool whitelist, and - # output redaction are identical in both modes. - # kernel_mode: per-call + # Local execution uses a persistent session kernel: variables, imports, and + # loaded data survive across execute_code calls in one conversation, so + # multi-step data work stops re-loading its inputs every call. Pass + # reset=true on a call to discard state; a timed-out/interrupted cell kills + # the kernel (next call starts fresh). Remote terminal backends currently + # run per-call (remote kernel host is tracked follow-up work). Security + # scrubbing, tool whitelist, and output redaction are identical either way. + # kernel_idle_timeout: 1800 # Reap kernels idle longer than this (seconds) + # max_session_kernels: 4 # Process-wide LRU cap on live kernels # ============================================================================= # Subagent Delegation diff --git a/hermes_cli/config_defaults.py b/hermes_cli/config_defaults.py index da497f2533..59a9e2d979 100644 --- a/hermes_cli/config_defaults.py +++ b/hermes_cli/config_defaults.py @@ -2888,8 +2888,12 @@ DEFAULT_CONFIG = { # scan cannot see — the runtime RPC boundary (allow-list, call # budget, per-cell authority) is the operative cross-cell # enforcement in this mode. - "kernel_mode": "per-call", - # Lifecycle bounds for kernel_mode: session. + # kernel_mode is retired: session kernels are always on for local + # execution. Remote terminal backends still run per-call — their + # file-based RPC path has no kernel host yet (tracked follow-up, + # not a design limit). A leftover kernel_mode key in user config + # is ignored. + # Lifecycle bounds for session kernels. "kernel_idle_timeout": 1800, "max_session_kernels": 4, }, diff --git a/tests/tools/test_code_execution.py b/tests/tools/test_code_execution.py index 629157a213..5471c3108b 100644 --- a/tests/tools/test_code_execution.py +++ b/tests/tools/test_code_execution.py @@ -32,6 +32,18 @@ def _force_local_terminal(monkeypatch): ensures each test starts (and ends) with the correct value. """ monkeypatch.setenv("TERMINAL_ENV", "local") + + +@pytest.fixture(autouse=True) +def _fresh_kernel_registry(): + """Session kernels are always on: dispose them per-test so a lingering + kernel child can't outlive the run (hangs pytest at exit) or leak one + test's interpreter state into the next.""" + from tools.code_kernel import shutdown_all_kernels + + shutdown_all_kernels() + yield + shutdown_all_kernels() import sys import threading import unittest @@ -529,8 +541,13 @@ class TestEnvVarFiltering(unittest.TestCase): with patch("model_tools.handle_function_call", return_value='{}'), \ patch("tools.code_execution_tool._load_config", return_value={"timeout": 10, "max_tool_calls": 50}): + # reset=True: a session kernel's env is frozen at spawn, so + # env-building rules are only observable on a FRESH kernel — + # a reused one would (correctly) show the env from whenever + # it was first spawned, not this test's os.environ tweaks. raw = execute_code(code, task_id="test-env", - enabled_tools=list(SANDBOX_ALLOWED_TOOLS)) + enabled_tools=list(SANDBOX_ALLOWED_TOOLS), + reset=True) finally: os.environ.clear() os.environ.update(env_backup) diff --git a/tests/tools/test_code_execution_modes.py b/tests/tools/test_code_execution_modes.py index fa204dc08f..fe9b4d7911 100644 --- a/tests/tools/test_code_execution_modes.py +++ b/tests/tools/test_code_execution_modes.py @@ -32,6 +32,18 @@ def _force_local_terminal(monkeypatch): monkeypatch.setenv("TERMINAL_ENV", "local") +@pytest.fixture(autouse=True) +def _fresh_kernel_registry(): + """Session kernels are always on: dispose them per-test so a lingering + kernel child can't outlive the run (hangs pytest at exit) or leak one + test's interpreter state into the next.""" + from tools.code_kernel import shutdown_all_kernels + + shutdown_all_kernels() + yield + shutdown_all_kernels() + + from tools.code_execution_tool import ( SANDBOX_ALLOWED_TOOLS, DEFAULT_EXECUTION_MODE, @@ -222,18 +234,30 @@ class TestExecuteCodeModeIntegration(unittest.TestCase): with patch.dict(os.environ, env_overrides): with patch("model_tools.handle_function_call", side_effect=_mock_handle_function_call): + # reset=True: kernel cwd/interpreter are frozen at spawn + # (like env), so mode-resolution rules are only + # observable on a fresh kernel. raw = execute_code( code=code, task_id=f"test-{mode}", enabled_tools=enabled_tools or list(SANDBOX_ALLOWED_TOOLS), + reset=True, ) return json.loads(raw) def test_strict_mode_runs_in_tmpdir(self): - """Strict mode: script's os.getcwd() is the staging tmpdir.""" + """Strict mode: script's os.getcwd() is a staging tmpdir, never the + session cwd. Behavior contract, not a prefix snapshot: the per-call + path stages in hermes_sandbox_*, the session kernel in + hermes_kernel_* — either satisfies strict mode's isolation promise.""" result = self._run("import os; print(os.getcwd())", mode="strict") self.assertEqual(result["status"], "success") - self.assertIn("hermes_sandbox_", result["output"]) + cwd = result["output"].strip() + self.assertTrue( + "hermes_sandbox_" in cwd or "hermes_kernel_" in cwd, + f"strict-mode cwd is not a staging tmpdir: {cwd!r}", + ) + self.assertNotEqual(os.path.realpath(cwd), os.path.realpath(os.getcwd())) def test_project_mode_interpreter_is_venv_python(self): @@ -531,25 +555,36 @@ class TestPythonPathComposition(unittest.TestCase): """Return (PYTHONPATH, staging_dir) that execute_code passes to the child.""" captured = {} + class _Captured(RuntimeError): + pass + def _fake_popen(cmd, **kwargs): env = kwargs.get("env") or {} captured["PYTHONPATH"] = env.get("PYTHONPATH", "") - # cmd is [python, /script.py] + # cmd is [python, /script.py] (per-call) or + # [python, /hermes_kernel_runner.py] (session + # kernel) — staging dir derivation is identical. 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"" - mock_proc.wait.return_value = 0 - mock_proc.returncode = 0 - mock_proc.poll.return_value = 0 - return mock_proc + # Abort the spawn after capture: returning a MagicMock proc + # would leave the kernel's reader threads spinning on mock + # reads and hang the cell wait loop (always-on session + # kernels; the pre-kernel version of this helper could get + # away with a fake proc because the per-call path only + # .wait()ed on it). + raise _Captured() with patch("tools.code_execution_tool._load_config", return_value={"mode": "strict"}), \ patch("model_tools.handle_function_call", side_effect=_mock_handle_function_call), \ patch("tools.code_execution_tool._uses_hermes_python_environment", return_value=same_env), \ patch("subprocess.Popen", side_effect=_fake_popen): - execute_code(code="pass", task_id="test-pp", enabled_tools=[]) + try: + execute_code(code="pass", task_id="test-pp", + enabled_tools=[], reset=True) + except _Captured: + pass # expected: spawn aborted right after env capture + except Exception: + pass # kernel path wraps the abort; capture already happened # If execute_code never reached Popen, the capture is empty and any # "X not in PYTHONPATH" assertion downstream would pass vacuously. diff --git a/tests/tools/test_code_kernel.py b/tests/tools/test_code_kernel.py index f0566f3e29..6cadd015fb 100644 --- a/tests/tools/test_code_kernel.py +++ b/tests/tools/test_code_kernel.py @@ -65,18 +65,21 @@ def _run(code, **kwargs): class TestKernelModeResolution(unittest.TestCase): - def test_default_is_per_call(self): - self.assertEqual(DEFAULT_KERNEL_MODE, "per-call") + """kernel_mode is retired: session kernels are always on for local runs. + + _get_kernel_mode() survives only as a compat shim; a leftover + kernel_mode key in user config (any value) must be ignored.""" + + def test_session_is_always_on(self): + self.assertEqual(DEFAULT_KERNEL_MODE, "session") with patch("tools.code_execution_tool._load_config", return_value={}): - self.assertEqual(_get_kernel_mode(), "per-call") + self.assertEqual(_get_kernel_mode(), "session") - def test_kernel_modes_tuple(self): - self.assertEqual(KERNEL_MODES, ("per-call", "session")) - - def test_invalid_value_falls_back(self): - with patch("tools.code_execution_tool._load_config", - return_value={"kernel_mode": "forever"}): - self.assertEqual(_get_kernel_mode(), "per-call") + def test_leftover_config_key_is_ignored(self): + for stale in ("per-call", "forever", "", None): + with patch("tools.code_execution_tool._load_config", + return_value={"kernel_mode": stale}): + self.assertEqual(_get_kernel_mode(), "session") class TestSessionStatePersistence(unittest.TestCase): @@ -91,13 +94,6 @@ class TestSessionStatePersistence(unittest.TestCase): self.assertEqual(second["kernel"]["reused"], True) self.assertEqual(second["kernel"]["execution_count"], 2) - def test_per_call_default_shares_nothing(self): - with _kernel_config(kernel_mode="per-call"): - _run("x = 41") - second = _run("print(x + 1)") - self.assertEqual(second["status"], "error", second) - self.assertNotIn("kernel", second) - def test_reset_discards_state(self): with _kernel_config(): _run("x = 41") @@ -163,13 +159,17 @@ class TestSchemaSurface(unittest.TestCase): schema = build_execute_code_schema(mode="strict") self.assertIn("reset", schema["parameters"]["properties"]) - def test_session_note_only_when_active(self): + def test_session_note_is_always_present(self): + """The schema's kernel note is unconditional now — session kernels + are always on for local execution (kernel_mode retired), so every + session is told about persistence and reset=true.""" with _kernel_config(): session_schema = build_execute_code_schema(mode="strict") self.assertIn("Session kernel is active", session_schema["description"]) + # Even with a stale per-call key in config, the note stays. with _kernel_config(kernel_mode="per-call"): - per_call_schema = build_execute_code_schema(mode="strict") - self.assertNotIn("Session kernel is active", per_call_schema["description"]) + stale_schema = build_execute_code_schema(mode="strict") + self.assertIn("Session kernel is active", stale_schema["description"]) if __name__ == "__main__": diff --git a/tools/code_execution_tool.py b/tools/code_execution_tool.py index 3b8a5b8a30..b72c8b1fe9 100644 --- a/tools/code_execution_tool.py +++ b/tools/code_execution_tool.py @@ -1379,8 +1379,14 @@ def execute_code( reset: bool = False, ) -> str: """ - Run a Python script in a sandboxed child process with RPC access - to a subset of Hermes tools. + Run Python in the session's persistent kernel (local) or a per-call + child process (remote backends), with RPC access to a subset of + Hermes tools. + + "Sandbox" in names below refers to the security envelope (env + scrubbing, tool whitelist + call budget, output redaction) — not an + isolation jail: in the default `project` mode, code runs in the + session's cwd with the project venv's interpreter. Dispatches to the local (UDS) or remote (file-based RPC) path depending on the configured terminal backend. @@ -1908,19 +1914,21 @@ def _load_config() -> dict: EXECUTION_MODES = ("project", "strict") DEFAULT_EXECUTION_MODE = "project" -# Valid values for code_execution.kernel_mode. -# per-call : today's behavior — a fresh child process per execute_code call. -# session : one persistent kernel per (task, mode, interpreter, cwd, -# tool-set); variables and imports survive across calls. See -# tools/code_kernel.py for the design and its boundaries. -KERNEL_MODES = ("per-call", "session") -DEFAULT_KERNEL_MODE = "per-call" +# Session kernels are the only local execution model: one persistent kernel +# per conversation (see tools/code_kernel.py). The former +# code_execution.kernel_mode knob ("per-call" | "session") is retired — the +# config key is silently ignored if present, and _get_kernel_mode() remains +# only as a compat symbol for external callers. Remote terminal backends +# still run per-call: their file-based RPC path has no kernel host YET (a +# long-lived remote runner + cell protocol is tracked follow-up work, not a +# design limit). +KERNEL_MODES = ("per-call", "session") # legacy compat constant +DEFAULT_KERNEL_MODE = "session" def _get_kernel_mode() -> str: - """Return the active execute_code kernel mode — 'per-call' or 'session'.""" - value = _load_config().get("kernel_mode", DEFAULT_KERNEL_MODE) - return value if value in KERNEL_MODES else DEFAULT_KERNEL_MODE + """Legacy compat shim — session kernels are always on for local runs.""" + return "session" def _get_execution_mode() -> str: