The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(code-execution): reap idle and cap remote session kernels
nftpoetristd4126c6f492e
diff --git a/tests/tools/test_code_kernel_remote.py b/tests/tools/test_code_kernel_remote.pyindex 9b2a1343d21..12e618baa88 100644--- a/tests/tools/test_code_kernel_remote.py+++ b/tests/tools/test_code_kernel_remote.py@@ -200,6 +200,51 @@ class TestOwnershipIsolation(RemoteKernelBase):self.assertEqual(remaining_owner, "owner-b")+class TestIdleReapAndCapEviction(RemoteKernelBase):+ """Unlike local session kernels, remote kernels had no idle-reap or+ process-wide cap: _REMOTE_KERNELS grew one entry per distinct+ (owner, env_type, task_env_id) that was never revisited, for the life+ of the gateway process."""++ def test_idle_expired_kernel_is_reaped_on_next_call(self):+ env = ScriptedEnv(_spawn_ok_handlers([_cell(), _cell()]))+ execute_in_remote_kernel(+ "print(1)", env=env, env_type="ssh", task_env_id="stale",+ sandbox_tools=frozenset(), timeout=10, max_tool_calls=5,+ reset=False, idle_exit=1800,+ )+ self.assertEqual(len(_REMOTE_KERNELS), 1)+ # Backdate the kernel's last_used past the idle window — simulates+ # a key that is never revisited again.+ for kernel in _REMOTE_KERNELS.values():+ kernel.last_used -= 2000+ # A call for a DIFFERENT key must reap the stale entry on entry,+ # without ever touching or reviving it.+ execute_in_remote_kernel(+ "print(1)", env=env, env_type="ssh", task_env_id="fresh",+ sandbox_tools=frozenset(), timeout=10, max_tool_calls=5,+ reset=False, idle_exit=1800,+ )+ owners = {key[0] for key in _REMOTE_KERNELS}+ self.assertNotIn("stale", owners)+ self.assertIn("fresh", owners)++ def test_over_cap_evicts_least_recently_used(self):+ with patch("tools.code_kernel._lifecycle_limits", return_value=(2, 1800)):+ env = ScriptedEnv(_spawn_ok_handlers([_cell() for _ in range(10)]))+ for i in range(3):+ execute_in_remote_kernel(+ "print(1)", env=env, env_type="ssh", task_env_id=f"owner-{i}",+ sandbox_tools=frozenset(), timeout=10, max_tool_calls=5,+ reset=False, idle_exit=1800,+ )+ self.assertEqual(len(_REMOTE_KERNELS), 2)+ owners = {key[0] for key in _REMOTE_KERNELS}+ self.assertNotIn("owner-0", owners)+ self.assertIn("owner-1", owners)+ self.assertIn("owner-2", owners)++class TestDispatchIntegration(unittest.TestCase):"""_execute_remote prefers the kernel and falls open to per-call."""diff --git a/tools/code_kernel_remote.py b/tools/code_kernel_remote.pyindex 3b3e9a22934..92f514535a4 100644--- a/tools/code_kernel_remote.py+++ b/tools/code_kernel_remote.py@@ -219,6 +219,44 @@ def shutdown_remote_kernels_for_owner(owner: str) -> None:_kill(kernel)+def _reap_unlocked(idle_timeout: int) -> List["RemoteKernel"]:+ """Pop idle-expired remote kernels; caller tears them down outside the lock.++ Mirrors tools.code_kernel._reap_unlocked. The remote runner itself+ self-exits after the same idle window (REMOTE_KERNEL_RUNNER_SOURCE's+ IDLE_EXIT_SECONDS), so this only needs to clear the HOST-side+ bookkeeping entry — without it, _REMOTE_KERNELS grows one entry per+ distinct (owner, env_type, task_env_id) that is never revisited, for+ the life of the gateway process.+ """+ now = time.monotonic()+ doomed = [+ key+ for key, kernel in _REMOTE_KERNELS.items()+ if now - kernel.last_used > idle_timeout+ ]+ return [_REMOTE_KERNELS.pop(key) for key in doomed]+++def _evict_over_cap_unlocked(keep: Tuple) -> List["RemoteKernel"]:+ """Pop least-recently-used remote kernels beyond the process-wide cap.++ Mirrors tools.code_kernel._evict_over_cap_unlocked, reusing the same+ max_session_kernels config as an independent bound on _REMOTE_KERNELS.+ """+ from tools.code_kernel import _lifecycle_limits++ cap, _ = _lifecycle_limits()+ if len(_REMOTE_KERNELS) <= cap:+ return []+ by_age = sorted(+ (key for key in _REMOTE_KERNELS if key != keep),+ key=lambda key: _REMOTE_KERNELS[key].last_used,+ )+ doomed = by_age[: len(_REMOTE_KERNELS) - cap]+ return [_REMOTE_KERNELS.pop(key) for key in doomed]++atexit.register(shutdown_all_remote_kernels)@@ -329,7 +367,10 @@ def execute_in_remote_kernel(state_reset = Falsewith _REMOTE_KERNELS_LOCK:+ expired = _reap_unlocked(idle_exit)kernel = _REMOTE_KERNELS.get(key)+ for doomed in expired:+ _kill(doomed)if kernel is not None and reset:with _REMOTE_KERNELS_LOCK:@@ -359,6 +400,10 @@ def execute_in_remote_kernel(_REMOTE_KERNELS[key] = kernelkernel.last_used = time.monotonic()+ with _REMOTE_KERNELS_LOCK:+ evicted = _evict_over_cap_unlocked(keep=key)+ for doomed in evicted:+ _kill(doomed)kernel.cell_seq += 1seq = f"{kernel.cell_seq:06d}"q_cells = shlex.quote(f"{kernel.kernel_dir}/cells")