fix(shell): separate wait, idle, and runtime limits (#6228)

* fix(shell): separate wait, idle, and runtime limits

* fix(shell): separate wait, idle, and runtime limits

* fix(exec): preserve settings aliases and reclaim completed sessions

* fix(webui): make shell runtime limits explicit
This commit is contained in:
chengyongru authored and GitHub committed 2026-10-16 13:44:15 +08:00
1 parent 70ac000ad9
commit 6310a39bac
36 files changed
+2392 -564

No files matched your search

+213
View File
@@ -0,0 +1,213 @@
import json
from unittest.mock import MagicMock
import pytest
from pydantic import ValidationError
from nanobot.agent.tools.shell_config import ExecToolConfig
from nanobot.config.errors import ConfigLoadError
from nanobot.config.loader import load_config, save_config
from nanobot.config.schema import Config
def test_exec_timing_defaults() -> None:
config = Config().tools.exec
assert config.max_runtime == 3600
assert config.max_runtime_limit == 86400
assert config.idle_timeout == 300
assert config.idle_action == "report"
assert config.timeout == config.max_runtime
@pytest.mark.parametrize("values", [
{"maxRuntime": 172800, "maxRuntimeLimit": 14400, "idleTimeout": 90, "idleAction": "terminate"},
{"max_runtime": 172800, "max_runtime_limit": 14400, "idle_timeout": 90, "idle_action": "terminate"},
{"timeout": 172800, "maxRuntimeLimit": 14400, "idleTimeout": 90, "idleAction": "terminate"},
])
def test_exec_timing_aliases_and_serialization(values) -> None:
config = ExecToolConfig.model_validate(values)
dumped = config.model_dump(by_alias=True)
assert config.max_runtime == 172800
assert config.max_runtime_limit == 14400
assert config.idle_timeout == 90
assert config.idle_action == "terminate"
assert dumped["maxRuntime"] == 172800
assert dumped["maxRuntimeLimit"] == 14400
assert dumped["idleTimeout"] == 90
assert dumped["idleAction"] == "terminate"
assert not {"timeout", "max_runtime", "max_runtime_limit", "idle_timeout", "idle_action"} & dumped.keys()
assert ExecToolConfig.model_validate_json(config.model_dump_json(by_alias=True)) == config
@pytest.mark.parametrize("name", ["timeout", "maxRuntime", "max_runtime"])
@pytest.mark.parametrize("runtime", [0, 60, 3600, 172800])
def test_exec_runtime_does_not_raise_default_model_limit(name: str, runtime: int) -> None:
config = ExecToolConfig.model_validate({name: runtime})
assert config.max_runtime == runtime
assert config.timeout == runtime
assert config.max_runtime_limit == 86400
@pytest.mark.parametrize("name", ["maxRuntime", "max_runtime"])
def test_exec_rejects_simultaneous_legacy_and_canonical_runtime(name: str) -> None:
with pytest.raises(ValidationError, match="not both"):
Config.model_validate({"tools": {"exec": {"timeout": 60, name: 60}}})
@pytest.mark.parametrize("values", [
{"maxRuntime": -1},
{"timeout": -1},
{"idleTimeout": -1},
{"maxRuntime": 1.5},
{"idleTimeout": 1.5},
{"maxRuntimeLimit": 0},
{"maxRuntimeLimit": -1},
{"idleAction": "ignore"},
])
def test_exec_rejects_invalid_timing_configuration(values) -> None:
with pytest.raises(ValidationError):
Config.model_validate({"tools": {"exec": values}})
def test_exec_unlimited_default_keeps_a_positive_model_limit() -> None:
config = ExecToolConfig(max_runtime=0, max_runtime_limit=1, idle_timeout=0)
assert config.max_runtime == 0
assert config.max_runtime_limit == 1
assert config.idle_timeout == 0
assert ExecToolConfig(max_runtime=1, max_runtime_limit=1).max_runtime == 1
def test_legacy_timeout_property_writes_canonical_runtime() -> None:
config = ExecToolConfig()
config.timeout = 42
assert config.max_runtime == 42
assert config.model_dump(by_alias=True)["maxRuntime"] == 42
config.max_runtime = 0
assert config.timeout == 0
assert "timeout" not in config.model_dump()
def test_legacy_exec_config_loads_and_saves_canonical_fields(tmp_path) -> None:
path = tmp_path / "config.json"
path.write_text(json.dumps({"tools": {"exec": {"timeout": 172800}}}), encoding="utf-8")
config = load_config(path)
save_config(config, path)
restored = load_config(path).tools.exec
saved = json.loads(path.read_text(encoding="utf-8"))["tools"]["exec"]
assert restored.max_runtime == 172800
assert restored.max_runtime_limit == 86400
assert saved["maxRuntime"] == 172800
assert saved["maxRuntimeLimit"] == 86400
assert saved["idleTimeout"] == 300
assert saved["idleAction"] == "report"
assert "timeout" not in saved
@pytest.mark.parametrize("runtime", [0, 42, 14400])
def test_legacy_webui_timeout_editor_updates_canonical_runtime(tmp_path, runtime: int) -> None:
from nanobot.webui.settings_api import update_runtime_config_settings
path = tmp_path / "config.json"
save_config(Config.model_validate({"tools": {"exec": {
"maxRuntime": 7200, "maxRuntimeLimit": 14400,
"idleTimeout": 90, "idleAction": "terminate",
}}}), path)
result = update_runtime_config_settings(
{"tools.exec.timeout": runtime}, local_browser=True, config_path=path,
)
config = load_config(path).tools.exec
assert config.max_runtime == runtime
assert config.timeout == runtime
assert config.max_runtime_limit == 14400
assert config.idle_timeout == 90
assert config.idle_action == "terminate"
assert result["runtime_config"]["tools.exec.timeout"] == runtime
assert result["requires_restart"]
assert json.loads(path.read_text(encoding="utf-8"))["tools"]["exec"]["maxRuntime"] == runtime
@pytest.mark.parametrize(("file_name", "env_name"), [
("timeout", "TIMEOUT"),
("timeout", "MAX_RUNTIME"),
("maxRuntime", "TIMEOUT"),
])
def test_exec_runtime_source_precedence_survives_settings_saves(
tmp_path, monkeypatch, file_name: str, env_name: str,
) -> None:
from nanobot.webui.settings_api import update_agent_settings, update_runtime_config_settings
path = tmp_path / "config.json"
path.write_text(json.dumps({"tools": {"exec": {file_name: 60}}}), encoding="utf-8")
monkeypatch.setenv(f"NANOBOT_TOOLS__EXEC__{env_name}", "90")
assert load_config(path).tools.exec.max_runtime == 60
result = update_runtime_config_settings(
{"tools.exec.timeout": 42}, local_browser=True, config_path=path,
)
assert result["runtime_config"]["tools.exec.timeout"] == 42
result = update_agent_settings({"timezone": ["Asia/Shanghai"]}, config_path=path)
assert result["runtime_config"]["tools.exec.timeout"] == 42
assert load_config(path).tools.exec.max_runtime == 42
saved = json.loads(path.read_text(encoding="utf-8"))["tools"]["exec"]
assert saved["maxRuntime"] == 42
assert "timeout" not in saved
@pytest.mark.parametrize("source", ["file", "environment"])
def test_exec_load_rejects_runtime_aliases_from_the_same_source(tmp_path, monkeypatch, source):
path = tmp_path / "config.json"
data = {"tools": {"exec": {"timeout": 60, "maxRuntime": 90}}}
if source == "file":
path.write_text(json.dumps(data), encoding="utf-8")
else:
monkeypatch.setenv("NANOBOT_TOOLS", json.dumps(data["tools"]))
with pytest.raises(ConfigLoadError):
load_config(path)
def test_exec_runtime_source_precedence_covers_both_canonical_spellings(monkeypatch):
monkeypatch.setenv("NANOBOT_TOOLS__EXEC", json.dumps({
"maxRuntime": 90, "max_runtime": 120,
}))
config = Config.model_validate({"tools": {"exec": {"timeout": 60}}})
assert config.tools.exec.max_runtime == 60
@pytest.mark.asyncio
async def test_my_exec_config_reports_configured_timing(tmp_path) -> None:
from nanobot.agent.loop import AgentLoop
from nanobot.agent.tools.self import MyTool
from nanobot.bus.queue import MessageBus
config = Config.model_validate({"tools": {"exec": {
"timeout": 172800, "idleTimeout": 0, "idleAction": "terminate",
}}})
provider = MagicMock()
provider.get_default_model.return_value = "test-model"
loop = AgentLoop(
bus=MessageBus(), provider=provider, workspace=tmp_path,
tools_config=config.tools, model="test-model",
)
tool = loop.tools.get("my")
assert isinstance(tool, MyTool)
expected = {
"max_runtime": 172800, "max_runtime_limit": 86400,
"idle_timeout": 0, "idle_action": "terminate", "timeout": 172800,
}
for key, value in expected.items():
result = await tool.execute(action="check", key=f"exec_config.{key}")
assert result == f"exec_config.{key}: {value!r}"
+58 -60
View File
@@ -22,6 +22,25 @@ _WINDOWS_ENV_KEYS = {
}
class _CompletedProcess:
"""A finished subprocess with the stream/wait protocol used by the collector."""
def __init__(self, stdout: bytes, stderr: bytes = b"", returncode: int = 0) -> None:
self.pid = 12345
self.returncode = returncode
self.stdin = None
self.stdout = asyncio.StreamReader()
self.stderr = asyncio.StreamReader()
self.stdout.feed_data(stdout)
self.stdout.feed_eof()
self.stderr.feed_data(stderr)
self.stderr.feed_eof()
async def wait(self) -> int:
await asyncio.sleep(0)
return self.returncode
class _FakeWindowsJob:
creation_flags = 0
@@ -373,15 +392,13 @@ class TestPathAppendPlatform:
@pytest.mark.asyncio
async def test_unix_uses_env_var_in_fixed_export(self):
"""On Unix, path_append must not be interpolated into shell source."""
mock_proc = AsyncMock()
mock_proc.communicate.return_value = (b"ok", b"")
mock_proc.returncode = 0
mock_proc = _CompletedProcess(b"ok")
captured_cmd = None
captured_env = {}
async def capture_spawn(
cmd, cwd, env, shell_program=None, login=True, *, process_tree=False,
cmd, cwd, env, shell_program=None, login=True, *, stdin=None, process_tree=False,
):
nonlocal captured_cmd
captured_cmd = cmd
@@ -404,9 +421,7 @@ class TestPathAppendPlatform:
@pytest.mark.asyncio
async def test_unix_path_prepend_uses_env_var_in_fixed_export(self):
"""On Unix, path_prepend must not be interpolated into shell source."""
mock_proc = AsyncMock()
mock_proc.communicate.return_value = (b"ok", b"")
mock_proc.returncode = 0
mock_proc = _CompletedProcess(b"ok")
captured_cmd = None
captured_env = {}
@@ -434,9 +449,7 @@ class TestPathAppendPlatform:
@pytest.mark.asyncio
async def test_unix_path_prepend_and_append_order(self):
mock_proc = AsyncMock()
mock_proc.communicate.return_value = (b"ok", b"")
mock_proc.returncode = 0
mock_proc = _CompletedProcess(b"ok")
captured_cmd = None
captured_env = {}
@@ -467,14 +480,12 @@ class TestPathAppendPlatform:
@pytest.mark.asyncio
async def test_windows_modifies_env(self):
"""On Windows, path_append is appended to PATH in the env dict."""
mock_proc = AsyncMock()
mock_proc.communicate.return_value = (b"ok", b"")
mock_proc.returncode = 0
mock_proc = _CompletedProcess(b"ok")
captured_env = {}
async def capture_spawn(
cmd, cwd, env, shell_program=None, login=True, *, process_tree=False,
cmd, cwd, env, shell_program=None, login=True, *, stdin=None, process_tree=False,
):
captured_env.update(env)
return mock_proc
@@ -492,9 +503,7 @@ class TestPathAppendPlatform:
@pytest.mark.asyncio
async def test_windows_path_prepend_and_append_order(self):
mock_proc = AsyncMock()
mock_proc.communicate.return_value = (b"ok", b"")
mock_proc.returncode = 0
mock_proc = _CompletedProcess(b"ok")
captured_env = {}
@@ -529,9 +538,7 @@ class TestSandboxPlatform:
@pytest.mark.parametrize("backend", ["bwrap", "seatbelt"])
async def test_sandbox_skipped_on_windows(self, backend):
"""Configured Unix backends preserve the Windows native fallback."""
mock_proc = AsyncMock()
mock_proc.communicate.return_value = (b"ok", b"")
mock_proc.returncode = 0
mock_proc = _CompletedProcess(b"ok")
with (
patch("nanobot.agent.tools.shell._IS_WINDOWS", True),
@@ -549,9 +556,7 @@ class TestSandboxPlatform:
@pytest.mark.parametrize("backend", ["bwrap", "seatbelt"])
async def test_sandbox_applied_on_unix(self, backend):
"""On Unix, sandbox wrapping should still happen normally."""
mock_proc = AsyncMock()
mock_proc.communicate.return_value = (b"sandboxed", b"")
mock_proc.returncode = 0
mock_proc = _CompletedProcess(b"sandboxed")
with (
patch("nanobot.agent.tools.shell._IS_WINDOWS", False),
@@ -570,9 +575,7 @@ class TestSandboxPlatform:
@pytest.mark.parametrize("backend", ["bwrap", "seatbelt"])
async def test_sandbox_receives_configured_bind_roots(self, tmp_path, backend):
"""Configured bind roots should be forwarded to the sandbox wrapper."""
mock_proc = AsyncMock()
mock_proc.communicate.return_value = (b"sandboxed", b"")
mock_proc.returncode = 0
mock_proc = _CompletedProcess(b"sandboxed")
tool_bin = tmp_path / "tool-bin"
tool_cache = tmp_path / "tool-cache"
@@ -606,54 +609,61 @@ class TestSandboxPlatform:
class TestExecuteEndToEnd:
@pytest.mark.asyncio
async def test_windows_full_path(self):
@pytest.mark.parametrize(
"yield_time_ms, stdin",
[(None, asyncio.subprocess.DEVNULL), (1000, asyncio.subprocess.PIPE)],
)
async def test_windows_full_path(self, yield_time_ms, stdin):
"""Full execute() flow on Windows: env, spawn, output formatting."""
mock_proc = AsyncMock()
mock_proc.communicate.return_value = (b"hello world\r\n", b"")
mock_proc.returncode = 0
mock_proc = _CompletedProcess(b"hello world\r\n")
with (
patch("nanobot.agent.tools.shell._IS_WINDOWS", True),
patch.object(ExecTool, "_spawn", return_value=mock_proc),
patch.object(ExecTool, "_spawn", return_value=mock_proc) as mock_spawn,
patch.object(ExecTool, "_guard_command", return_value=None),
):
tool = ExecTool()
result = await tool.execute(command="echo hello world")
result = await tool.execute(command="echo hello world", yield_time_ms=yield_time_ms)
assert "hello world" in result
assert "Exit code: 0" in result
assert "session_id:" not in result
assert mock_spawn.call_args.kwargs.get("stdin", asyncio.subprocess.DEVNULL) == stdin
assert mock_spawn.call_args.kwargs["process_tree"] is True
@pytest.mark.asyncio
async def test_unix_full_path(self):
@pytest.mark.parametrize(
"yield_time_ms, stdin",
[(None, asyncio.subprocess.DEVNULL), (1000, asyncio.subprocess.PIPE)],
)
async def test_unix_full_path(self, yield_time_ms, stdin):
"""Full execute() flow on Unix: env, spawn, output formatting."""
mock_proc = AsyncMock()
mock_proc.communicate.return_value = (b"hello world\n", b"")
mock_proc.returncode = 0
mock_proc = _CompletedProcess(b"hello world\n")
with (
patch("nanobot.agent.tools.shell._IS_WINDOWS", False),
patch.object(ExecTool, "_spawn", return_value=mock_proc),
patch.object(ExecTool, "_spawn", return_value=mock_proc) as mock_spawn,
patch.object(ExecTool, "_guard_command", return_value=None),
):
tool = ExecTool()
result = await tool.execute(command="echo hello world")
result = await tool.execute(command="echo hello world", yield_time_ms=yield_time_ms)
assert "hello world" in result
assert "Exit code: 0" in result
assert "session_id:" not in result
assert mock_spawn.call_args.kwargs.get("stdin", asyncio.subprocess.DEVNULL) == stdin
assert mock_spawn.call_args.kwargs["process_tree"] is True
@pytest.mark.asyncio
async def test_execute_defaults_to_non_login_shell(self):
"""The public execute path must not silently request a login shell."""
mock_proc = AsyncMock()
mock_proc.communicate.return_value = (b"ok\n", b"")
mock_proc.returncode = 0
captured_login = []
async def capture_spawn(
cmd, cwd, env, shell_program=None, login=None, *, stdin=None, process_tree=False,
):
captured_login.append(login)
return mock_proc
return _CompletedProcess(b"ok\n")
with (
patch("nanobot.agent.tools.shell._IS_WINDOWS", False),
@@ -735,9 +745,7 @@ class TestWindowsMultilineExec:
@pytest.mark.asyncio
async def test_multiline_python_uses_powershell(self):
mock_proc = AsyncMock()
mock_proc.communicate.return_value = (b"1\n2\n", b"")
mock_proc.returncode = 0
mock_proc = _CompletedProcess(b"1\n2\n")
with (
patch("nanobot.agent.tools.shell._IS_WINDOWS", True),
@@ -757,9 +765,7 @@ class TestWindowsMultilineExec:
@pytest.mark.asyncio
async def test_multiline_node_uses_powershell(self):
mock_proc = AsyncMock()
mock_proc.communicate.return_value = (b"1\n", b"")
mock_proc.returncode = 0
mock_proc = _CompletedProcess(b"1\n")
with (
patch("nanobot.agent.tools.shell._IS_WINDOWS", True),
@@ -778,9 +784,7 @@ class TestWindowsMultilineExec:
@pytest.mark.asyncio
async def test_single_line_uses_powershell(self):
"""Single-line commands also route through PowerShell now."""
mock_proc = AsyncMock()
mock_proc.communicate.return_value = (b"1\n", b"")
mock_proc.returncode = 0
mock_proc = _CompletedProcess(b"1\n")
with (
patch("nanobot.agent.tools.shell._IS_WINDOWS", True),
@@ -795,9 +799,7 @@ class TestWindowsMultilineExec:
@pytest.mark.asyncio
async def test_unix_unchanged(self):
mock_proc = AsyncMock()
mock_proc.communicate.return_value = (b"1\n2\n", b"")
mock_proc.returncode = 0
mock_proc = _CompletedProcess(b"1\n2\n")
with (
patch("nanobot.agent.tools.shell._IS_WINDOWS", False),
@@ -821,9 +823,7 @@ class TestResolveShellWindows:
@pytest.mark.asyncio
async def test_shell_powershell_accepted(self):
"""shell='powershell' should resolve and route through PowerShell."""
mock_proc = AsyncMock()
mock_proc.communicate.return_value = (b"hello\n", b"")
mock_proc.returncode = 0
mock_proc = _CompletedProcess(b"hello\n")
with (
patch("nanobot.agent.tools.shell._IS_WINDOWS", True),
@@ -843,9 +843,7 @@ class TestResolveShellWindows:
@pytest.mark.asyncio
async def test_shell_cmd_accepted(self):
"""shell='cmd' should preserve the command string for cmd.exe parsing."""
mock_proc = AsyncMock()
mock_proc.communicate.return_value = (b'"a & b"\n', b"")
mock_proc.returncode = 0
mock_proc = _CompletedProcess(b'"a & b"\n')
with (
patch("nanobot.agent.tools.shell._IS_WINDOWS", True),
+105
View File
@@ -0,0 +1,105 @@
from __future__ import annotations
import asyncio
import re
import shutil
import sys
import time
from pathlib import Path
import pytest
from nanobot.agent.tools.context import RequestContext, request_context
from nanobot.agent.tools.exec_session import (
ExecSessionManager,
ExecSessionTool,
ListExecSessionsTool,
)
from nanobot.agent.tools.registry import is_tool_error_result
from nanobot.agent.tools.rg import RgTool
from nanobot.agent.tools.shell import ExecTool
async def _start_gated(tool: ExecTool, gate: Path) -> str:
code = (
"import time; from pathlib import Path; "
f"gate=Path({str(gate)!r})\n"
"while not gate.exists(): time.sleep(0.01)\n"
"print('retained result')"
)
result = await tool.execute(command=[sys.executable, "-u", "-c", code], yield_time_ms=0)
match = re.search(r"session_id:\s*([0-9a-f]+)", result)
assert match, result
return match.group(1)
async def _wait_finished(manager: ExecSessionManager, owner: str | None, session_id: str) -> None:
deadline = time.monotonic() + 10
while time.monotonic() < deadline:
sessions = await manager.list(owner_session_key=owner)
if any(info.session_id == session_id and info.finish_reason == "exit" for info in sessions):
return
await asyncio.sleep(0.01)
raise AssertionError(f"session {session_id} did not finish")
@pytest.mark.parametrize("tool_name", [
"exec",
pytest.param("rg", marks=pytest.mark.skipif(shutil.which("rg") is None, reason="ripgrep not installed")),
])
async def test_finished_results_do_not_block_other_owner_tools(tmp_path, tool_name):
manager = ExecSessionManager(max_sessions=2)
tool = ExecTool(working_dir=str(tmp_path), session_manager=manager)
session_tool = ExecSessionTool(manager=manager)
owner_a = RequestContext(channel="cli", chat_id="a", session_key="cli:a")
owner_b = RequestContext(channel="cli", chat_id="b", session_key="cli:b")
try:
with request_context(owner_a):
oldest = await _start_gated(tool, tmp_path / "first")
newest = await _start_gated(tool, tmp_path / "second")
for gate, sid in [("first", oldest), ("second", newest)]:
(tmp_path / gate).touch()
await _wait_finished(manager, owner_a.session_key, sid)
with request_context(owner_b):
assert await ListExecSessionsTool(manager=manager).execute() == "No active exec sessions."
assert is_tool_error_result(await session_tool.execute(session_id=newest, timeout_ms=0))
if tool_name == "rg":
result = await RgTool(working_dir=str(tmp_path), session_manager=manager).execute(
args=["--version"],
)
assert "ripgrep" in result
else:
result = await tool.execute(command=[sys.executable, "-c", "print('other owner')"])
assert "other owner" in result
assert not is_tool_error_result(result), result
assert "Exit code: 0" in result
with request_context(owner_a):
remaining = await manager.list(owner_session_key=owner_a.session_key)
assert [info.session_id for info in remaining] == [newest]
result = await session_tool.execute(session_id=newest, timeout_ms=0)
assert "retained result" in result
assert "Exit code: 0" in result
finally:
await manager.close_all()
async def test_capacity_preserves_running_work_and_bounds_completed_results(tmp_path):
manager = ExecSessionManager(max_sessions=2)
tool = ExecTool(working_dir=str(tmp_path), session_manager=manager)
try:
running = await _start_gated(tool, tmp_path / "running")
latest = await _start_gated(tool, tmp_path / "finished-0")
rejected = await tool.execute(command=[sys.executable, "-c", "print('over capacity')"])
assert is_tool_error_result(rejected)
assert "maximum exec sessions reached (2)" in rejected
for index in range(4):
(tmp_path / f"finished-{index}").touch()
await _wait_finished(manager, None, latest)
latest = await _start_gated(tool, tmp_path / f"finished-{index + 1}")
sessions = await manager.list()
assert {info.session_id for info in sessions} == {running, latest}
assert all(info.finish_reason is None for info in sessions)
finally:
await manager.close_all()
+54
View File
@@ -0,0 +1,54 @@
from __future__ import annotations
import asyncio
import sys
import pytest
from nanobot.agent.tools.context import RequestContext, bind_request_context, reset_request_context
from nanobot.agent.tools.exec_session import ExecSessionManager
from nanobot.agent.tools.shell import ExecTool
async def test_owner_cancellation_during_startup_preserves_other_execution(tmp_path, monkeypatch):
manager = ExecSessionManager(max_sessions=2)
tool = ExecTool(working_dir=str(tmp_path), session_manager=manager)
blocked_command = [sys.executable, "-u", "-c", "print('blocked launch')"]
entered = asyncio.Event()
release = asyncio.Event()
spawn = manager._spawn
async def gated_spawn(command, cwd, env, shell_program, login, *, stdin):
if command == blocked_command:
entered.set()
await release.wait()
return await spawn(command, cwd, env, shell_program, login, stdin=stdin)
monkeypatch.setattr(manager, "_spawn", gated_spawn)
token = bind_request_context(RequestContext(channel="cli", chat_id="a", session_key="cli:a"))
try:
blocked = asyncio.create_task(tool.execute(command=blocked_command, yield_time_ms=0))
finally:
reset_request_context(token)
try:
await asyncio.wait_for(entered.wait(), timeout=5)
token = bind_request_context(RequestContext(channel="cli", chat_id="b", session_key="cli:b"))
try:
other = await asyncio.wait_for(
tool.execute(command=[sys.executable, "-u", "-c", "print('other completed')"]),
timeout=10,
)
finally:
reset_request_context(token)
assert "other completed" in other
assert "Exit code: 0" in other
assert await asyncio.wait_for(manager.terminate_by_owner("cli:a"), timeout=5) == 1
with pytest.raises(asyncio.CancelledError):
await blocked
continued = await tool.execute(command=[sys.executable, "-u", "-c", "print('slot released')"])
assert "slot released" in continued
assert "Exit code: 0" in continued
finally:
release.set()
await asyncio.gather(blocked, return_exceptions=True)
await manager.close_all()
+2 -2
View File
@@ -51,7 +51,7 @@ async def test_exec_session_hard_timeout_kills_process_tree_without_polling(tmp_
assert not late_write.exists(), "the descendant wrote after the hard timeout"
assert session.process.returncode != 0
final = await session_tool.execute(session_id=sid, timeout_ms=0)
final = await session_tool.execute(session_id=sid, until_exit=True, timeout_ms=2000)
assert is_tool_error_result(final)
assert "Command timed out; session was terminated." in final
assert "parent started" in initial + final
@@ -105,7 +105,7 @@ async def test_exec_session_zero_config_timeout_allows_unpolled_longer_process(t
sid = _session_id(initial)
await asyncio.wait_for(manager._sessions[sid].process.wait(), timeout=5)
final = await session_tool.execute(session_id=sid, timeout_ms=0)
final = await session_tool.execute(session_id=sid, until_exit=True, timeout_ms=2000)
assert not is_tool_error_result(final)
assert "completed without deadline" in initial + final
assert "Exit code: 0" in final
+112 -46
View File
@@ -65,6 +65,31 @@ def _session_id(output: str) -> str:
return match.group(1)
def _session_process(
*,
stdout: asyncio.StreamReader | None = None,
stderr: asyncio.StreamReader | None = None,
) -> tuple[SimpleNamespace, asyncio.Event]:
exited = asyncio.Event()
process = SimpleNamespace(pid=12345, stdout=stdout, stderr=stderr, returncode=None)
async def wait() -> int:
await exited.wait()
assert process.returncode is not None
return process.returncode
process.wait = wait
return process, exited
async def _cancel_session_tasks(session: _ExecSession) -> None:
tasks = [session._stdout_task, session._stderr_task, session._completion_task]
tasks.extend(task for task in (session._timeout_task, session._kill_task) if task is not None)
for task in tasks:
task.cancel()
await asyncio.gather(*tasks, return_exceptions=True)
async def _poll_if_running(
initial: str,
tool: ExecSessionTool,
@@ -160,23 +185,29 @@ async def test_exec_session_preserves_utf8_across_stdout_and_stderr_chunks():
stderr_bytes = b"b" * 4094 + "🙂é".encode() + b"\xff"
stdout.feed_data(stdout_bytes[:4096])
stderr.feed_data(stderr_bytes[:4096])
process, exited = _session_process(stdout=stdout, stderr=stderr)
session = _ExecSession(
session_id="utf8-output",
process=SimpleNamespace(stdout=stdout, stderr=stderr),
process=process,
command="test",
cwd=".",
timeout=None,
)
await asyncio.sleep(0)
stdout.feed_data(stdout_bytes[4096:])
stderr.feed_data(stderr_bytes[4096:])
stdout.feed_eof()
stderr.feed_eof()
await asyncio.gather(session._stdout_task, session._stderr_task)
try:
await asyncio.sleep(0)
stdout.feed_data(stdout_bytes[4096:])
stderr.feed_data(stderr_bytes[4096:])
stdout.feed_eof()
stderr.feed_eof()
process.returncode = 0
exited.set()
await asyncio.wait_for(session._completion_task, timeout=2)
assert session._stdout.drain() == ("a" * 4095 + "你好🙂\ufffd", 0)
assert session._stderr.drain() == ("b" * 4094 + "🙂é\ufffd", 0)
assert session._stdout.drain() == ("a" * 4095 + "你好🙂\ufffd", 0)
assert session._stderr.drain() == ("b" * 4094 + "🙂é\ufffd", 0)
finally:
await _cancel_session_tasks(session)
def test_exec_session_bounds_unpolled_stdout_and_stderr(tmp_path):
@@ -196,11 +227,9 @@ def test_exec_session_bounds_unpolled_stdout_and_stderr(tmp_path):
)
sid = _session_id(initial)
session = manager._sessions[sid]
await asyncio.wait_for(session.process.wait(), timeout=15)
await asyncio.wait_for(
asyncio.gather(session._stdout_task, session._stderr_task),
timeout=15,
)
await asyncio.wait_for(session._completion_task, timeout=15)
assert session.finish_reason == "exit"
assert session.finished_at is not None
retained_stdout = session._stdout.retained_chars
retained_stderr = session._stderr.retained_chars
poll = await manager.write(
@@ -246,7 +275,7 @@ def test_exec_session_wait_for_keeps_aggregate_within_output_budget():
assert result.startswith("HEAD")
assert "Wait target not observed" not in result
assert "(8,000 chars truncated from output)" in result
assert len(result) < 10100
assert len(result.partition("\n")[0]) == 10_000
def test_exec_session_wait_for_searches_before_response_truncation():
@@ -291,7 +320,7 @@ def test_exec_session_wait_for_searches_before_response_truncation():
assert observed_limits == [MAX_OUTPUT_CHARS]
assert "Wait target not observed" not in result
assert "(20,006 chars truncated from output)" in result
assert len(result) < 10100
assert len(result.partition("\n")[0]) == 10_000
def test_exec_one_shot_accepts_max_output_tokens_alias(tmp_path):
@@ -424,7 +453,10 @@ def test_exec_session_preserves_completed_session_output_until_polled(tmp_path):
initial = await exec_tool.execute(command=command, yield_time_ms=50)
sid = _session_id(initial)
await asyncio.wait_for(manager._sessions[sid].process.wait(), timeout=2)
session = manager._sessions[sid]
await asyncio.wait_for(session._completion_task, timeout=2)
assert session.finish_reason == "exit"
assert session.finished_at is not None
final = await stdin_tool.execute(session_id=sid, input="", timeout_ms=0)
return initial, final
@@ -832,8 +864,8 @@ def test_exec_session_manager_retains_and_aggregates_failed_cleanup():
assert len(exc_info.value.exceptions) == 2
assert manager._sessions == {first.session_id: first, second.session_id: second}
first.kill.assert_awaited_once()
second.kill.assert_awaited_once()
first.kill.assert_awaited_once_with("shutdown")
second.kill.assert_awaited_once_with("shutdown")
first.kill.side_effect = None
second.kill.side_effect = None
@@ -979,7 +1011,7 @@ def test_terminate_by_owner_retains_failed_sessions():
await manager.terminate_by_owner("cli:a")
assert manager._sessions == {session.session_id: session}
session.kill.assert_awaited_once()
session.kill.assert_awaited_once_with("owner_closed")
session.kill.side_effect = None
assert await manager.terminate_by_owner("cli:a") == 1
@@ -988,26 +1020,48 @@ def test_terminate_by_owner_retains_failed_sessions():
asyncio.run(run())
def test_stale_cleanup_retains_session_when_kill_fails():
def test_result_retention_only_cleans_completed_sessions(tmp_path, monkeypatch):
async def run() -> None:
manager = ExecSessionManager(idle_timeout=1)
session = SimpleNamespace(
session_id="stale-failed",
owner_session_key="cli:a",
last_access=time.monotonic() - 10,
kill=AsyncMock(side_effect=OSError("termination failed")),
now = time.monotonic()
monkeypatch.setattr(
"nanobot.agent.tools.exec_session.time",
SimpleNamespace(monotonic=lambda: now),
)
manager = ExecSessionManager(result_retention=10)
tool = ExecTool(working_dir=str(tmp_path), max_runtime=0, session_manager=manager)
command = _python_command(
"import sys; print('ready', flush=True); "
"sys.stdin.read(); print('done', flush=True)"
)
manager._sessions[session.session_id] = session
with pytest.raises(OSError, match="termination failed"):
await manager.list(owner_session_key="cli:a")
try:
initial = await tool.execute(command=command, yield_time_ms=0)
sid = _session_id(initial)
session = manager._sessions[sid]
assert manager._sessions == {session.session_id: session}
session.kill.assert_awaited_once()
now += 100
listing = await manager.list()
assert [info.session_id for info in listing] == [sid]
assert session.process.returncode is None
assert session.finished_at is None
session.kill.side_effect = None
assert await manager.list(owner_session_key="cli:a") == []
assert manager._sessions == {}
assert await session.close_stdin() is None
await asyncio.wait_for(session._completion_task, timeout=10)
assert session.finish_reason == "exit"
assert session.finished_at == now
assert session._stdout.has_output
now += 9
listing = await manager.list()
assert [info.session_id for info in listing] == [sid]
assert listing[0].finish_reason == "exit"
assert listing[0].returncode == 0
now += 2
assert await manager.list() == []
assert manager._sessions == {}
finally:
await manager.close_all()
asyncio.run(run())
@@ -1055,7 +1109,7 @@ def test_agent_loop_shutdown_preserves_single_cleanup_error():
async def test_exec_session_shared_kill_survives_cancelled_caller(monkeypatch):
process = SimpleNamespace(stdout=None, stderr=None, returncode=None)
process, exited = _session_process()
session = _ExecSession(
session_id="shared-kill", process=process, command="test", cwd=".",
timeout=None, process_tree=True,
@@ -1069,6 +1123,7 @@ async def test_exec_session_shared_kill_survives_cancelled_caller(monkeypatch):
kill_started.set()
await release_kill.wait()
process.returncode = -9
exited.set()
kill_tree = AsyncMock(side_effect=kill_process_tree)
monkeypatch.setattr(ExecTool, "_kill_process_tree", kill_tree)
@@ -1092,16 +1147,18 @@ async def test_exec_session_shared_kill_survives_cancelled_caller(monkeypatch):
release_kill.set()
await asyncio.wait_for(second, timeout=2)
assert process.returncode == -9
assert session.finish_reason == "cancelled"
assert session.finished_at is not None
kill_tree.assert_awaited_once_with(process)
finally:
release_kill.set()
await asyncio.gather(first, *([second] if second is not None else []), return_exceptions=True)
await asyncio.gather(session._stdout_task, session._stderr_task, return_exceptions=True)
await _cancel_session_tasks(session)
@pytest.mark.parametrize("log_content", [True, False])
async def test_exec_session_failed_kill_can_be_retried(monkeypatch, log_content):
process = SimpleNamespace(stdout=None, stderr=None, returncode=None)
process, exited = _session_process()
session = _ExecSession(
session_id="retry-kill", process=process, command="test", cwd=".",
timeout=None, process_tree=True,
@@ -1115,6 +1172,7 @@ async def test_exec_session_failed_kill_can_be_retried(monkeypatch, log_content)
if attempts == 1:
raise OSError("temporary process-tree cleanup failure")
process.returncode = -9
exited.set()
monkeypatch.setattr(ExecTool, "_kill_process_tree", kill_process_tree)
records = []
@@ -1126,8 +1184,12 @@ async def test_exec_session_failed_kill_can_be_retried(monkeypatch, log_content)
with pytest.raises(OSError, match="temporary process-tree cleanup failure"):
await session.kill()
assert process.returncode is None
assert session.finished_at is None
await session.kill()
assert process.returncode == -9
assert session.finish_reason == "cancelled"
assert session.finished_at is not None
assert session.cleanup_error is None
assert attempts == 2
assert len(records) == 1
assert (records[0]["exception"] is not None) is log_content
@@ -1135,12 +1197,11 @@ async def test_exec_session_failed_kill_can_be_retried(monkeypatch, log_content)
finally:
reset_request_context(token)
logger.remove(sink)
await asyncio.gather(session._stdout_task, session._stderr_task, return_exceptions=True)
await _cancel_session_tasks(session)
async def test_exec_session_deadline_during_explicit_kill_is_not_timeout(monkeypatch):
exited = asyncio.Event()
process = SimpleNamespace(stdout=None, stderr=None, returncode=None, wait=exited.wait)
process, exited = _session_process()
session = _ExecSession(
session_id="explicit-kill", process=process, command="test", cwd=".",
timeout=None, process_tree=True,
@@ -1164,25 +1225,30 @@ async def test_exec_session_deadline_during_explicit_kill_is_not_timeout(monkeyp
await asyncio.wait_for(kill_started.wait(), timeout=2)
original_kill = session.kill
async def join_existing_kill():
async def join_existing_kill(reason="cancelled"):
assert reason == "max_runtime"
watcher_joined.set()
await original_kill()
await original_kill(reason)
monkeypatch.setattr(session, "kill", join_existing_kill)
session.deadline = time.monotonic() - 1
watcher = asyncio.create_task(session._watch_timeout())
await asyncio.wait_for(watcher_joined.wait(), timeout=2)
assert not session._timed_out
assert session.finish_reason is None
assert session.stopping
assert not watcher.done()
kill_tree.assert_awaited_once_with(process)
release_kill.set()
await asyncio.wait_for(asyncio.gather(explicit_kill, watcher), timeout=2)
assert process.returncode == -9
assert not session._timed_out
assert session.finish_reason == "cancelled"
poll = await session.poll(0, 1000)
assert poll.terminated
assert not poll.timed_out
kill_tree.assert_awaited_once_with(process)
finally:
release_kill.set()
await asyncio.gather(
explicit_kill, *([watcher] if watcher is not None else []), return_exceptions=True,
)
await asyncio.gather(session._stdout_task, session._stderr_task, return_exceptions=True)
await _cancel_session_tasks(session)
+2 -1
View File
@@ -182,7 +182,8 @@ async def test_direct_process_timeout(tmp_path):
result = await ExecTool(working_dir=str(tmp_path)).execute(
command=[sys.executable, "-c", "import time; time.sleep(20)"], timeout=1,
)
assert "timed out after 1 seconds" in result
assert "Reason: max_runtime" in result
assert "Exit code:" in result
async def test_direct_process_cancellation_reaps_child(tmp_path, monkeypatch):
+592
View File
@@ -0,0 +1,592 @@
from __future__ import annotations
import asyncio
import os
import re
import signal
import sys
import time
from contextlib import suppress
from pathlib import Path
import pytest
from nanobot.agent.tools.context import RequestContext, request_context
from nanobot.agent.tools.exec_session import (
ExecSessionManager,
ExecSessionTool,
ListExecSessionsTool,
)
from nanobot.agent.tools.registry import is_tool_error_result
from nanobot.agent.tools.shell import ExecTool
def _python(code: str) -> list[str]:
return [sys.executable, "-u", "-c", code]
def _session_id(output: str) -> str:
match = re.search(r"session_id:\s*([0-9a-f]+)", output)
assert match, output
return match.group(1)
def _listed_ids(output: str) -> list[str]:
return re.findall(r"^([0-9a-f]+)\s*\|", output, flags=re.MULTILINE)
def _exit_code(output: str) -> int:
match = re.search(r"Exit code:\s*(-?\d+)", output)
assert match, output
return int(match.group(1))
def _silent_seconds(output: str) -> float:
match = re.search(r"Output silent[^\n]*?(\d+(?:\.\d+)?)\s*(?:s\b|seconds?\b)", output)
assert match, output
return float(match.group(1))
def _elapsed_seconds(output: str) -> float:
match = re.search(r"Elapsed:\s*(\d+(?:\.\d+)?)s", output)
assert match, output
return float(match.group(1))
async def _file_text(path: Path, *, timeout: float = 5) -> str:
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
if path.exists() and (text := path.read_text()):
return text
await asyncio.sleep(0.02)
raise AssertionError(f"subprocess did not write {path} within {timeout}s")
def _pid_running(pid: int) -> bool:
if sys.platform == "win32":
import ctypes
from ctypes import wintypes
kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
kernel32.OpenProcess.argtypes = [wintypes.DWORD, wintypes.BOOL, wintypes.DWORD]
kernel32.OpenProcess.restype = wintypes.HANDLE
kernel32.WaitForSingleObject.argtypes = [wintypes.HANDLE, wintypes.DWORD]
kernel32.WaitForSingleObject.restype = wintypes.DWORD
kernel32.CloseHandle.argtypes = [wintypes.HANDLE]
handle = kernel32.OpenProcess(0x00100000, False, pid) # SYNCHRONIZE
if not handle:
error = ctypes.get_last_error()
assert error == 87, f"OpenProcess({pid}) failed: {error}"
return False
try:
status = kernel32.WaitForSingleObject(handle, 0)
assert status in (0, 258), f"WaitForSingleObject({pid}) failed: {status}"
return status == 258 # WAIT_TIMEOUT
finally:
kernel32.CloseHandle(handle)
try:
os.kill(pid, 0)
except ProcessLookupError:
return False
# A killed grandchild can remain a zombie until its new parent reaps it.
stat = Path(f"/proc/{pid}/stat")
with suppress(FileNotFoundError):
if stat.exists() and stat.read_text().rsplit(")", 1)[1].split()[0] == "Z":
return False
return True
async def _pid_stopped(pid: int, *, timeout: float = 6) -> None:
deadline = time.monotonic() + timeout
while _pid_running(pid) and time.monotonic() < deadline:
await asyncio.sleep(0.03)
assert not _pid_running(pid), f"subprocess {pid} is still running after {timeout}s"
async def _cleanup_pidfiles(*paths: Path) -> None:
pids = [int(path.read_text()) for path in paths if path.exists() and path.read_text()]
for pid in pids:
if _pid_running(pid):
with suppress(ProcessLookupError, OSError):
os.kill(pid, signal.SIGTERM if sys.platform == "win32" else signal.SIGKILL)
for pid in pids:
await _pid_stopped(pid, timeout=3)
def _waiting_tree(parent_pidfile: Path, child_pidfile: Path) -> str:
child = (
"import os,time; from pathlib import Path; "
f"Path({str(child_pidfile)!r}).write_text(str(os.getpid())); "
"time.sleep(60)"
)
return (
"import os,subprocess,sys; from pathlib import Path; "
f"child=subprocess.Popen([sys.executable, '-u', '-c', {child!r}]); "
f"Path({str(parent_pidfile)!r}).write_text(str(os.getpid())); "
"child.wait()"
)
async def test_trusted_default_runtime_can_exceed_model_request_limit():
manager = ExecSessionManager()
tool = ExecTool(
max_runtime=12, max_runtime_limit=1, idle_timeout=0, session_manager=manager,
)
try:
result = await tool.execute(command=_python(
"import time; time.sleep(1.2); print('trusted default completed')"
))
assert not is_tool_error_result(result), result
assert "trusted default completed" in result
assert _exit_code(result) == 0
finally:
await manager.close_all()
async def test_wait_timeout_leaves_stdin_gated_work_alive(tmp_path):
ready = tmp_path / "ready"
done = tmp_path / "done"
code = (
"import sys; from pathlib import Path; "
f"Path({str(ready)!r}).write_text('ready'); "
"print('waiting for input', flush=True); line=sys.stdin.readline().strip(); "
f"Path({str(done)!r}).write_text(line); "
"print('completed:' + line, flush=True)"
)
manager = ExecSessionManager()
tool = ExecTool(
working_dir=str(tmp_path), max_runtime=12, max_runtime_limit=12,
idle_timeout=1, session_manager=manager,
)
session_tool = ExecSessionTool(manager=manager)
list_tool = ListExecSessionsTool(manager=manager)
try:
initial = await tool.execute(command=_python(code), yield_time_ms=0)
sid = _session_id(initial)
assert await _file_text(ready) == "ready"
waited = await session_tool.execute(session_id=sid, until_exit=True, timeout_ms=200)
assert not is_tool_error_result(waited), waited
assert "Wait timed out after 0.2s; session remains active." in waited
assert f"Process running. session_id: {sid}" in waited
listing = await list_tool.execute()
assert _listed_ids(listing) == [sid]
assert "| running |" in listing
final = await session_tool.execute(
session_id=sid, input="finish after wait\n", until_exit=True, timeout_ms=5000,
)
assert not is_tool_error_result(final), final
assert "completed:finish after wait" in final
assert _exit_code(final) == 0
assert done.read_text() == "finish after wait"
finally:
await manager.close_all()
async def test_default_idle_reporting_survives_unpolled_silence_and_reads(tmp_path):
ready = tmp_path / "ready"
done = tmp_path / "done"
code = (
"import sys; from pathlib import Path; "
f"Path({str(ready)!r}).write_text('ready'); "
"line=sys.stdin.readline().strip(); "
f"Path({str(done)!r}).write_text(line); print('silent work completed', flush=True)"
)
manager = ExecSessionManager(result_retention=1)
tool = ExecTool(
working_dir=str(tmp_path), max_runtime=12, max_runtime_limit=12,
idle_timeout=1, session_manager=manager,
)
session_tool = ExecSessionTool(manager=manager)
list_tool = ListExecSessionsTool(manager=manager)
try:
initial = await tool.execute(command=_python(code), yield_time_ms=0)
sid = _session_id(initial)
assert await _file_text(ready) == "ready"
await asyncio.sleep(1.25)
first = await session_tool.execute(session_id=sid, timeout_ms=0)
first_idle = _silent_seconds(first)
assert first_idle >= 1
assert f"Process running. session_id: {sid}" in first
listing = await list_tool.execute()
assert _listed_ids(listing) == [sid]
assert "| running |" in listing
await asyncio.sleep(0.35)
second = await session_tool.execute(session_id=sid, timeout_ms=0)
assert _silent_seconds(second) >= first_idle + 0.2
assert f"Process running. session_id: {sid}" in second
final = await session_tool.execute(
session_id=sid, input="still alive\n", until_exit=True, timeout_ms=5000,
)
assert not is_tool_error_result(final), final
assert "silent work completed" in final
assert _exit_code(final) == 0
assert done.read_text() == "still alive"
finally:
await manager.close_all()
async def test_partial_stdout_and_stderr_bytes_refresh_idle_without_log_reads(tmp_path):
ready = tmp_path / "ready"
stdout_gate = tmp_path / "emit-stdout"
stderr_gate = tmp_path / "emit-stderr"
finish_gate = tmp_path / "finish"
stdout_ack = tmp_path / "stdout-written"
stderr_ack = tmp_path / "stderr-written"
done = tmp_path / "done"
code = (
"import os,time; from pathlib import Path; "
f"Path({str(ready)!r}).write_text('ready')\n"
f"while not Path({str(stdout_gate)!r}).exists(): time.sleep(0.02)\n"
"os.write(1, bytes([0xE2]))\n"
f"Path({str(stdout_ack)!r}).write_text('stdout')\n"
f"while not Path({str(stderr_gate)!r}).exists(): time.sleep(0.02)\n"
"os.write(2, bytes([0xE2]))\n"
f"Path({str(stderr_ack)!r}).write_text('stderr')\n"
f"while not Path({str(finish_gate)!r}).exists(): time.sleep(0.02)\n"
f"Path({str(done)!r}).write_text(Path({str(finish_gate)!r}).read_text())\n"
"print('byte-gated complete', flush=True)\n"
)
manager = ExecSessionManager()
tool = ExecTool(
working_dir=str(tmp_path), max_runtime=12, max_runtime_limit=12,
idle_timeout=2, idle_action="terminate", session_manager=manager,
)
session_tool = ExecSessionTool(manager=manager)
try:
initial = await tool.execute(command=_python(code), yield_time_ms=0)
sid = _session_id(initial)
assert await _file_text(ready) == "ready"
await asyncio.sleep(1.25)
stdout_gate.write_text("emit")
assert await _file_text(stdout_ack) == "stdout"
await asyncio.sleep(1.25)
stderr_gate.write_text("emit")
assert await _file_text(stderr_ack) == "stderr"
await asyncio.sleep(1.25)
finish_gate.write_text("finish")
final = await session_tool.execute(session_id=sid, until_exit=True, timeout_ms=5000)
assert not is_tool_error_result(final), final
assert "byte-gated complete" in final
assert _exit_code(final) == 0
assert done.read_text() == "finish"
finally:
await manager.close_all()
async def test_idle_termination_stops_owned_tree_without_tool_activity(tmp_path):
parent_pidfile = tmp_path / "parent.pid"
child_pidfile = tmp_path / "child.pid"
manager = ExecSessionManager()
tool = ExecTool(
working_dir=str(tmp_path), max_runtime=12, max_runtime_limit=12,
idle_timeout=2, idle_action="terminate", session_manager=manager,
)
session_tool = ExecSessionTool(manager=manager)
try:
initial = await tool.execute(
command=_python(_waiting_tree(parent_pidfile, child_pidfile)), yield_time_ms=0,
)
sid = _session_id(initial)
parent_pid = int(await _file_text(parent_pidfile))
child_pid = int(await _file_text(child_pidfile))
assert _pid_running(parent_pid)
assert _pid_running(child_pid)
# Observe OS process exit before making another tool or manager call.
await _pid_stopped(parent_pid)
await _pid_stopped(child_pid, timeout=3)
final = await session_tool.execute(session_id=sid, until_exit=True, timeout_ms=3000)
assert is_tool_error_result(final), final
assert "idle_timeout" in final
assert _exit_code(final) != 0
finally:
try:
await manager.close_all()
finally:
await _cleanup_pidfiles(parent_pidfile, child_pidfile)
async def test_hard_budget_counts_down_despite_output_and_repeated_waits(tmp_path):
pidfile = tmp_path / "process.pid"
code = (
"import os,time; from pathlib import Path; "
f"Path({str(pidfile)!r}).write_text(str(os.getpid())); n=0\n"
"while True:\n"
" n+=1\n"
" print('progress:' + str(n), flush=True)\n"
" time.sleep(0.15)\n"
)
manager = ExecSessionManager()
tool = ExecTool(
working_dir=str(tmp_path), max_runtime=3, max_runtime_limit=3,
idle_timeout=1, idle_action="terminate", session_manager=manager,
)
session_tool = ExecSessionTool(manager=manager)
try:
initial = await tool.execute(command=_python(code), yield_time_ms=0)
sid = _session_id(initial)
pid = int(await _file_text(pidfile))
before = (await manager.list())[0]
first = await session_tool.execute(session_id=sid, until_exit=True, timeout_ms=900)
second = await session_tool.execute(session_id=sid, until_exit=True, timeout_ms=900)
for waited in (first, second):
assert "Wait timed out after 0.9s; session remains active." in waited
assert "progress:" in waited
after = (await manager.list())[0]
assert before.remaining_s is not None and after.remaining_s is not None
assert after.remaining_s <= before.remaining_s - 1.4
assert after.idle_s < 0.7
assert _pid_running(pid)
await _pid_stopped(pid, timeout=5)
final = await session_tool.execute(session_id=sid, until_exit=True, timeout_ms=3000)
assert is_tool_error_result(final), final
assert "max_runtime" in final
assert "progress:" in final
assert _exit_code(final) != 0
assert 2.5 <= _elapsed_seconds(final) <= 4.5
progress_counts = re.findall(r"progress:(\d+)", initial + first + second + final)
assert max(map(int, progress_counts)) >= 8
finally:
try:
await manager.close_all()
finally:
await _cleanup_pidfiles(pidfile)
@pytest.mark.parametrize(
("early_root_exit", "stop_reason"),
[
pytest.param(False, "max_runtime", id="ordinary-root-hard-budget"),
pytest.param(True, "max_runtime", id="early-root-hard-budget"),
pytest.param(True, "owner_closed", id="early-root-owner-close"),
],
)
async def test_execution_stop_stops_pipe_inheriting_child_after_root_exits(
tmp_path, monkeypatch, early_root_exit, stop_reason,
):
parent_pidfile = tmp_path / "parent.pid"
child_pidfile = tmp_path / "child.pid"
release_root = tmp_path / "release-root"
release_child = tmp_path / "release-child"
delayed_effect = tmp_path / "delayed-effect"
child_code = (
"import os,time; from pathlib import Path; "
f"Path({str(child_pidfile)!r}).write_text(str(os.getpid()))\n"
f"while not Path({str(release_child)!r}).exists(): time.sleep(0.02)\n"
f"Path({str(delayed_effect)!r}).write_text('child escaped execution stop')\n"
)
parent_code = (
"import os,subprocess,sys,time; from pathlib import Path; "
f"Path({str(parent_pidfile)!r}).write_text(str(os.getpid())); "
f"subprocess.Popen([sys.executable, '-u', '-c', {child_code!r}]); "
"print('worker launched', flush=True)\n"
)
if not early_root_exit:
parent_code += f"while not Path({str(release_root)!r}).exists(): time.sleep(0.02)\n"
real_spawn = ExecTool._spawn
spawn_returned = asyncio.Event()
async def spawn_with_exit_order(*args, **kwargs):
process = await real_spawn(*args, **kwargs)
if early_root_exit:
# Root exit may precede spawn return; inherited pipes must remain intact.
async with asyncio.timeout(5):
while process.returncode is None:
await asyncio.sleep(0.005)
assert process.returncode == 0
else:
assert process.returncode is None
spawn_returned.set()
return process
monkeypatch.setattr(ExecTool, "_spawn", staticmethod(spawn_with_exit_order))
owner = RequestContext(channel="cli", chat_id="pipe-budget", session_key="cli:pipe-budget")
manager = ExecSessionManager()
max_runtime = 12 if stop_reason == "owner_closed" else 2
tool = ExecTool(
working_dir=str(tmp_path), max_runtime=max_runtime, max_runtime_limit=max_runtime,
idle_timeout=1, session_manager=manager,
)
initial_exec_task = None
try:
with request_context(owner):
initial_exec_task = asyncio.create_task(tool.execute(command=_python(parent_code)))
await asyncio.wait_for(spawn_returned.wait(), timeout=5)
parent_pid = int(await _file_text(parent_pidfile))
child_pid = int(await _file_text(child_pidfile))
release_root.write_text("root may exit")
await _pid_stopped(parent_pid, timeout=1)
assert _pid_running(child_pid)
assert not initial_exec_task.done()
if stop_reason == "owner_closed":
assert await asyncio.wait_for(
manager.terminate_by_owner(owner.session_key), timeout=6,
) == 1
await _pid_stopped(child_pid, timeout=5)
release_child.write_text("perform the delayed write")
final = await asyncio.wait_for(initial_exec_task, timeout=3)
if stop_reason == "max_runtime":
assert is_tool_error_result(final), final
assert "Reason: max_runtime." in final
assert 1.5 <= _elapsed_seconds(final) <= 3.5
else:
assert not is_tool_error_result(final), final
assert "Session terminated. Reason: owner_closed." in final
assert "worker launched" in final
assert _exit_code(final) == 0 # Only the root exited successfully.
assert not delayed_effect.exists()
assert await manager.list(owner_session_key=owner.session_key) == []
finally:
try:
await _cleanup_pidfiles(parent_pidfile, child_pidfile)
finally:
try:
await asyncio.wait_for(manager.close_all(), timeout=6)
finally:
if initial_exec_task is not None:
initial_exec_task.cancel()
await asyncio.gather(initial_exec_task, return_exceptions=True)
async def test_inline_work_reports_silence_then_hits_same_fixed_hard_budget(tmp_path):
pidfile = tmp_path / "process.pid"
gate = tmp_path / "emit-output"
ticks = tmp_path / "ticks"
code = (
"import os,time; from pathlib import Path; "
f"Path({str(pidfile)!r}).write_text(str(os.getpid()))\n"
f"while not Path({str(gate)!r}).exists(): time.sleep(0.02)\n"
"n=0\n"
"while True:\n"
" n+=1\n"
" print('inline-progress:' + str(n), flush=True)\n"
f" Path({str(ticks)!r}).write_text(str(n))\n"
" time.sleep(0.15)\n"
)
manager = ExecSessionManager()
tool = ExecTool(
working_dir=str(tmp_path), max_runtime=4, max_runtime_limit=4,
idle_timeout=1, session_manager=manager,
)
list_tool = ListExecSessionsTool(manager=manager)
inline_task = None
try:
inline_task = asyncio.create_task(tool.execute(command=_python(code)))
pid = int(await _file_text(pidfile))
await asyncio.sleep(1.25)
listing = await list_tool.execute()
assert len(_listed_ids(listing)) == 1, listing
assert "| running |" in listing
assert (await manager.list())[0].idle_s >= 1
assert not inline_task.done()
assert _pid_running(pid)
gate.write_text("emit")
assert int(await _file_text(ticks)) >= 1
await _pid_stopped(pid)
final = await asyncio.wait_for(inline_task, timeout=3)
assert is_tool_error_result(final), final
assert "inline-progress:" in final
assert "max_runtime" in final
assert _exit_code(final) != 0
assert 3.5 <= _elapsed_seconds(final) <= 5.5
assert await list_tool.execute() == "No active exec sessions."
finally:
try:
await manager.close_all()
finally:
if inline_task is not None:
inline_task.cancel()
await asyncio.gather(inline_task, return_exceptions=True)
await _cleanup_pidfiles(pidfile)
async def test_owner_close_stops_inline_tree_and_preserves_other_owner_work(tmp_path):
parent_pidfile = tmp_path / "owner-a-parent.pid"
child_pidfile = tmp_path / "owner-a-child.pid"
survivor_pidfile = tmp_path / "owner-b.pid"
done = tmp_path / "owner-b-done"
survivor_code = (
"import os,sys; from pathlib import Path; "
f"Path({str(survivor_pidfile)!r}).write_text(str(os.getpid())); "
"print('owner-b-ready', flush=True); line=sys.stdin.readline().strip(); "
f"Path({str(done)!r}).write_text(line); print('owner-b-completed', flush=True)"
)
owner_a = RequestContext(channel="cli", chat_id="budget-a", session_key="cli:budget-a")
owner_b = RequestContext(channel="cli", chat_id="budget-b", session_key="cli:budget-b")
manager = ExecSessionManager()
tool = ExecTool(
working_dir=str(tmp_path), max_runtime=12, max_runtime_limit=12,
idle_timeout=1, session_manager=manager,
)
session_tool = ExecSessionTool(manager=manager)
list_tool = ListExecSessionsTool(manager=manager)
inline_task = None
try:
with request_context(owner_a):
inline_task = asyncio.create_task(tool.execute(
command=_python(_waiting_tree(parent_pidfile, child_pidfile)),
))
parent_pid = int(await _file_text(parent_pidfile))
child_pid = int(await _file_text(child_pidfile))
owner_listing = await list_tool.execute()
owner_ids = _listed_ids(owner_listing)
assert len(owner_ids) == 1, owner_listing
sid_a = owner_ids[0]
with request_context(owner_b):
initial_b = await tool.execute(command=_python(survivor_code), yield_time_ms=0)
sid_b = _session_id(initial_b)
survivor_pid = int(await _file_text(survivor_pidfile))
assert _listed_ids(await list_tool.execute()) == [sid_b]
denied = await session_tool.execute(session_id=sid_a, terminate=True)
assert is_tool_error_result(denied), denied
assert denied == f"Error: exec session not found: {sid_a!r}"
assert _pid_running(parent_pid)
assert _pid_running(child_pid)
assert await manager.terminate_by_owner("cli:budget-a") == 1
await _pid_stopped(parent_pid, timeout=3)
await _pid_stopped(child_pid, timeout=3)
final_a = await asyncio.wait_for(inline_task, timeout=3)
assert "Session terminated." in final_a
assert _exit_code(final_a) != 0
with request_context(owner_b):
assert _pid_running(survivor_pid)
listing = await list_tool.execute()
assert _listed_ids(listing) == [sid_b]
assert "| running |" in listing
final_b = await session_tool.execute(
session_id=sid_b, input="owner-b-success\n", until_exit=True, timeout_ms=5000,
)
assert not is_tool_error_result(final_b), final_b
assert "owner-b-completed" in final_b
assert _exit_code(final_b) == 0
assert done.read_text() == "owner-b-success"
finally:
try:
await manager.close_all()
finally:
if inline_task is not None:
inline_task.cancel()
await asyncio.gather(inline_task, return_exceptions=True)
await _cleanup_pidfiles(parent_pidfile, child_pidfile, survivor_pidfile)
+274 -121
View File
@@ -11,7 +11,8 @@ from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from nanobot.agent.tools.exec_session import _ExecSession
from nanobot.agent.tools.exec_session import ExecSessionManager, ExecSessionTool, _ExecSession
from nanobot.agent.tools.registry import is_tool_error_result
from nanobot.agent.tools.shell import ExecTool, _reap_pid
@@ -21,6 +22,50 @@ def _python_command(code: str) -> str:
return f"{shlex.quote(sys.executable)} -u -c {shlex.quote(code)}"
class _MockProcess:
def __init__(
self, *, pid: int, returncode: int | None, stdout: bytes = b"", stderr: bytes = b"",
) -> None:
self.pid = pid
self.returncode = returncode
self.stdin = None
self.stdout = asyncio.StreamReader()
self.stderr = asyncio.StreamReader()
self.stdout.feed_data(stdout)
self.stderr.feed_data(stderr)
self.exited = asyncio.Event()
self._exit_code = returncode
self.kill = MagicMock(side_effect=lambda: self.exit(-9))
self.wait = AsyncMock(side_effect=self._wait)
if returncode is not None:
self.exit(returncode)
def exit(self, returncode: int, *, close_streams: bool = True) -> None:
self._exit_code = returncode
if close_streams:
self.stdout.feed_eof()
self.stderr.feed_eof()
self.exited.set()
async def _wait(self) -> int:
await self.exited.wait()
assert self._exit_code is not None
self.returncode = self._exit_code
return self.returncode
async def _cleanup_session(session: _ExecSession) -> None:
await asyncio.wait_for(session.kill(), timeout=5)
tasks = (
session._stdout_task, session._stderr_task, session._completion_task,
session._timeout_task, session._kill_task,
)
await asyncio.wait_for(
asyncio.gather(*(task for task in tasks if task is not None), return_exceptions=True),
timeout=5,
)
def test_reap_pid_noops_without_waitpid():
"""On platforms (or test stubs) without waitpid, reaping is a no-op."""
with patch("nanobot.agent.tools.shell.os") as mock_os:
@@ -50,9 +95,7 @@ def test_reap_pid_swallows_already_reaped_errors():
@pytest.mark.asyncio
async def test_kill_process_skips_kill_when_already_exited():
"""Already-dead processes must not raise ProcessLookupError from kill()."""
process = AsyncMock()
process.pid = 4242
process.returncode = 0
process = _MockProcess(pid=4242, returncode=0)
process.kill = MagicMock(side_effect=ProcessLookupError("already dead"))
with patch("nanobot.agent.tools.shell._reap_pid") as reap:
@@ -65,147 +108,249 @@ async def test_kill_process_skips_kill_when_already_exited():
@pytest.mark.asyncio
async def test_kill_process_kills_and_reaps_live_process():
process = AsyncMock()
process.pid = 77
process.returncode = None
process.kill = MagicMock()
process.wait = AsyncMock(return_value=0)
process = _MockProcess(pid=77, returncode=None)
with patch("nanobot.agent.tools.shell._reap_pid") as reap:
await ExecTool._kill_process(process)
process.kill.assert_called_once()
process.wait.assert_awaited()
assert process.returncode == -9
reap.assert_called_once_with(77)
@pytest.mark.asyncio
async def test_kill_process_reaps_even_if_kill_races_exit():
"""If the child exits between returncode check and kill(), still reap."""
process = AsyncMock()
process.pid = 88
process.returncode = None
process.kill = MagicMock(side_effect=ProcessLookupError("raced exit"))
process.wait = AsyncMock(return_value=0)
process = _MockProcess(pid=88, returncode=None)
def raced_exit() -> None:
process.exit(0)
raise ProcessLookupError("raced exit")
process.kill.side_effect = raced_exit
with patch("nanobot.agent.tools.shell._reap_pid") as reap:
await ExecTool._kill_process(process)
process.kill.assert_called_once()
process.wait.assert_awaited()
assert process.returncode == 0
reap.assert_called_once_with(88)
@pytest.mark.asyncio
async def test_execute_reaps_after_normal_completion():
mock_proc = AsyncMock()
mock_proc.pid = 1001
mock_proc.communicate.return_value = (b"ok\n", b"")
mock_proc.returncode = 0
process = _MockProcess(pid=1001, returncode=0, stdout=b"ok\n")
manager = ExecSessionManager()
with (
patch.object(ExecTool, "_spawn", return_value=mock_proc),
patch.object(ExecTool, "_guard_command", return_value=None),
patch.object(ExecTool, "_spawn", return_value=process),
patch("nanobot.agent.tools.shell._reap_pid") as reap,
):
tool = ExecTool()
result = await tool.execute(command="echo ok")
try:
result = await ExecTool(session_manager=manager).execute(command="echo ok")
finally:
await manager.close_all()
assert not is_tool_error_result(result)
assert "ok" in result
assert "Exit code: 0" in result
process.wait.assert_awaited()
process.kill.assert_not_called()
reap.assert_called_with(1001)
@pytest.mark.asyncio
async def test_execute_timeout_kills_and_reaps():
mock_proc = AsyncMock()
mock_proc.pid = 1002
mock_proc.returncode = None
mock_proc.communicate.side_effect = asyncio.TimeoutError()
process = _MockProcess(pid=1002, returncode=None)
manager = ExecSessionManager()
with (
patch.object(ExecTool, "_spawn", return_value=mock_proc) as spawn,
patch.object(ExecTool, "_guard_command", return_value=None),
patch.object(ExecTool, "_kill_process_tree", new_callable=AsyncMock) as kill_tree,
patch.object(ExecTool, "_spawn", return_value=process) as spawn,
patch.object(ExecTool, "_kill_process_tree", side_effect=ExecTool._kill_process) as kill_tree,
patch("nanobot.agent.tools.shell._reap_pid") as reap,
):
tool = ExecTool(timeout=1)
result = await tool.execute(command="sleep 99", timeout=1)
try:
result = await asyncio.wait_for(
ExecTool(timeout=1, session_manager=manager).execute(command="sleep 99", timeout=1),
timeout=5,
)
finally:
await manager.close_all()
assert is_tool_error_result(result)
assert "timed out" in result.lower()
kill_tree.assert_awaited_once_with(mock_proc)
assert "Reason: max_runtime" in result
kill_tree.assert_awaited_once_with(process)
process.kill.assert_called_once()
process.wait.assert_awaited()
assert process.returncode == -9
reap.assert_any_call(1002)
assert spawn.await_args.kwargs["process_tree"] is True
@pytest.mark.asyncio
async def test_execute_cancellation_kills_process_tree():
mock_proc = AsyncMock()
mock_proc.pid = 1005
mock_proc.returncode = None
mock_proc.communicate.side_effect = asyncio.CancelledError()
process = _MockProcess(pid=1005, returncode=None)
manager = ExecSessionManager()
waiting = asyncio.Event()
wait_exit = _ExecSession.wait_exit
async def inline_wait(session: _ExecSession) -> None:
waiting.set()
await wait_exit(session)
with (
patch.object(ExecTool, "_spawn", return_value=mock_proc) as spawn,
patch.object(ExecTool, "_guard_command", return_value=None),
patch.object(ExecTool, "_kill_process_tree", new_callable=AsyncMock) as kill_tree,
patch.object(ExecTool, "_spawn", return_value=process) as spawn,
patch.object(ExecTool, "_kill_process_tree", side_effect=ExecTool._kill_process) as kill_tree,
patch.object(_ExecSession, "wait_exit", new=inline_wait),
patch("nanobot.agent.tools.shell._reap_pid") as reap,
):
with pytest.raises(asyncio.CancelledError):
await ExecTool().execute(command="sleep 99")
execution = asyncio.create_task(
ExecTool(session_manager=manager).execute(command="sleep 99"),
)
try:
await asyncio.wait_for(waiting.wait(), timeout=5)
assert process.returncode is None
execution.cancel()
with pytest.raises(asyncio.CancelledError):
await asyncio.wait_for(execution, timeout=5)
assert await manager.list() == []
finally:
execution.cancel()
await asyncio.gather(execution, return_exceptions=True)
await manager.close_all()
kill_tree.assert_awaited_once_with(mock_proc)
kill_tree.assert_awaited_once_with(process)
process.kill.assert_called_once()
process.wait.assert_awaited()
assert process.returncode == -9
reap.assert_any_call(1005)
assert spawn.await_args.kwargs["process_tree"] is True
@pytest.mark.asyncio
async def test_execute_exception_after_success_does_not_raise_on_dead_process():
"""Generic except must return ToolResult.error, not ProcessLookupError."""
mock_proc = AsyncMock()
mock_proc.pid = 1003
mock_proc.communicate = AsyncMock(return_value=(b"out\n", b""))
mock_proc.returncode = 0
mock_proc.kill = MagicMock(side_effect=ProcessLookupError("already dead"))
async def test_exec_session_wait_cancellation_does_not_kill_process_tree():
process = _MockProcess(pid=1007, returncode=None)
manager = ExecSessionManager()
session_tool = ExecSessionTool(manager=manager)
with (
patch.object(ExecTool, "_spawn", return_value=mock_proc),
patch.object(ExecTool, "_guard_command", return_value=None),
patch.object(ExecTool, "_spawn", return_value=process),
patch.object(ExecTool, "_kill_process_tree", side_effect=ExecTool._kill_process) as kill_tree,
patch("nanobot.agent.tools.shell._reap_pid") as reap,
patch(
"nanobot.agent.tools.shell.clamp_session_int",
side_effect=RuntimeError("boom after exit"),
),
):
tool = ExecTool()
result = await tool.execute(command="echo out")
observer = None
try:
initial = await ExecTool(session_manager=manager).execute(
command="sleep 99", yield_time_ms=0,
)
session_id, session = next(iter(manager._sessions.items()))
assert session_id in initial
observer = asyncio.create_task(session_tool.execute(
session_id=session_id, until_exit=True, timeout_ms=30_000,
))
await asyncio.sleep(0)
assert not observer.done()
observer.cancel()
with pytest.raises(asyncio.CancelledError):
await observer
assert "Error executing command" in result
assert "boom after exit" in result
mock_proc.kill.assert_not_called()
assert reap.called
assert process.returncode is None
assert not session._completion_task.done()
process.kill.assert_not_called()
kill_tree.assert_not_awaited()
assert [info.session_id for info in await manager.list()] == [session_id]
result = await session_tool.execute(session_id=session_id, terminate=True)
assert "Reason: cancelled" in result
assert "Exit code: -9" in result
finally:
if observer is not None:
observer.cancel()
await asyncio.gather(observer, return_exceptions=True)
await manager.close_all()
kill_tree.assert_awaited_once_with(process)
process.kill.assert_called_once()
reap.assert_any_call(1007)
@pytest.mark.asyncio
async def test_execute_exception_during_communicate_kills_live_process():
mock_proc = AsyncMock()
mock_proc.pid = 1004
mock_proc.returncode = None
mock_proc.communicate.side_effect = OSError("pipe broken")
async def test_execute_exception_after_success_does_not_raise_on_dead_process():
"""Formatting a completed result must not attempt to kill the dead process."""
process = _MockProcess(pid=1003, returncode=0, stdout=b"out\n")
process.kill.side_effect = ProcessLookupError("already dead")
manager = ExecSessionManager()
with (
patch.object(ExecTool, "_spawn", return_value=process),
patch("nanobot.agent.tools.shell._reap_pid") as reap,
patch(
"nanobot.agent.tools.shell.format_session_poll",
side_effect=RuntimeError("boom after exit"),
) as formatter,
):
try:
result = await ExecTool(session_manager=manager).execute(command="echo out")
finally:
await manager.close_all()
assert is_tool_error_result(result)
assert "Error executing command" in result
assert "boom after exit" in result
poll = formatter.call_args.args[1]
assert poll.done is True
assert poll.exit_code == 0
assert poll.output == "out\n"
process.wait.assert_awaited()
process.kill.assert_not_called()
reap.assert_called_with(1003)
@pytest.mark.asyncio
async def test_execute_stream_read_error_kills_live_process(tmp_path):
manager = ExecSessionManager()
tool = ExecTool(working_dir=str(tmp_path), session_manager=manager)
spawn_process = ExecTool._spawn
kill_process_tree = ExecTool._kill_process_tree
process = None
async def spawn_with_broken_stdout(*args, **kwargs):
nonlocal process
process = await spawn_process(*args, **kwargs)
assert process.returncode is None
assert process.stdout is not None
process.stdout.set_exception(OSError("pipe broken"))
return process
with (
patch.object(ExecTool, "_spawn", return_value=mock_proc),
patch.object(ExecTool, "_guard_command", return_value=None),
patch.object(ExecTool, "_kill_process_tree", new_callable=AsyncMock) as kill_tree,
patch.object(ExecTool, "_spawn", side_effect=spawn_with_broken_stdout),
patch.object(ExecTool, "_kill_process_tree", wraps=kill_process_tree) as kill_tree,
patch("nanobot.agent.tools.shell._reap_pid", wraps=_reap_pid) as reap,
):
tool = ExecTool()
result = await tool.execute(command="broken")
try:
result = await asyncio.wait_for(tool.execute(
command=[sys.executable, "-u", "-c", "import time; time.sleep(30)"],
), timeout=10)
finally:
try:
await manager.close_all()
finally:
if process is not None and process.returncode is None:
await kill_process_tree(process)
assert "Error executing command" in result
assert is_tool_error_result(result)
assert "pipe broken" in result
kill_tree.assert_awaited_once_with(mock_proc)
assert "Reason: execution_error" in result
assert "output may be incomplete" in result
assert "Process running" not in result
assert process is not None
assert process.returncode is not None and process.returncode != 0
kill_tree.assert_awaited_once_with(process)
reap.assert_any_call(process.pid)
@pytest.mark.asyncio
async def test_kill_process_tree_targets_group_after_root_exits():
process = AsyncMock()
process.pid = 1006
process.returncode = 0
process = _MockProcess(pid=1006, returncode=0)
with (
patch("nanobot.agent.tools.shell._IS_WINDOWS", False),
@@ -285,22 +430,9 @@ async def test_kill_process_tree_kills_descendant_after_root_exits(tmp_path):
await ExecTool._kill_process_tree(process)
def _mock_session_process(*, pid: int, returncode: int | None):
process = AsyncMock()
process.pid = pid
process.returncode = returncode
process.kill = MagicMock()
process.wait = AsyncMock(return_value=returncode if returncode is not None else -9)
# Constructor starts stream readers; closed streams exit immediately.
process.stdout = None
process.stderr = None
process.stdin = None
return process
@pytest.mark.asyncio
async def test_exec_session_kill_reaps():
process = _mock_session_process(pid=2001, returncode=None)
process = _MockProcess(pid=2001, returncode=None)
session = _ExecSession(
session_id="abc",
process=process,
@@ -313,15 +445,24 @@ async def test_exec_session_kill_reaps():
with patch("nanobot.agent.tools.shell._reap_pid") as reap:
await session.kill()
process.kill.assert_called_once()
reap.assert_called_once_with(2001)
process.wait.assert_awaited()
assert process.returncode == -9
assert session.finish_reason == "cancelled"
assert session.finished_at is not None
reap.assert_any_call(2001)
finally:
await asyncio.gather(session._stdout_task, session._stderr_task, return_exceptions=True)
await _cleanup_session(session)
@pytest.mark.asyncio
async def test_exec_session_kill_reaps_if_process_exits_before_kill():
process = _mock_session_process(pid=2002, returncode=None)
process.kill.side_effect = ProcessLookupError("raced exit")
process = _MockProcess(pid=2002, returncode=None)
def raced_exit() -> None:
process.exit(0)
raise ProcessLookupError("raced exit")
process.kill.side_effect = raced_exit
session = _ExecSession(
session_id="raced",
process=process,
@@ -333,14 +474,20 @@ async def test_exec_session_kill_reaps_if_process_exits_before_kill():
try:
with patch("nanobot.agent.tools.shell._reap_pid") as reap:
await session.kill()
reap.assert_called_once_with(2002)
process.kill.assert_called_once()
process.wait.assert_awaited()
assert process.returncode == 0
assert session.finished_at is not None
reap.assert_any_call(2002)
finally:
await asyncio.gather(session._stdout_task, session._stderr_task, return_exceptions=True)
await _cleanup_session(session)
@pytest.mark.asyncio
async def test_exec_session_kill_waits_for_reader_tasks():
process = _mock_session_process(pid=2003, returncode=None)
process = _MockProcess(pid=2003, returncode=None, stdout=b"head\n")
# OS exit can be observed before the readers have consumed the final pipe bytes.
process.kill.side_effect = lambda: process.exit(-9, close_streams=False)
session = _ExecSession(
session_id="readers",
process=process,
@@ -349,34 +496,36 @@ async def test_exec_session_kill_waits_for_reader_tasks():
timeout=30,
owner_session_key=None,
)
await asyncio.gather(session._stdout_task, session._stderr_task)
release = asyncio.Event()
async def reader() -> None:
await release.wait()
async def wait_for_process() -> int:
release.set()
process.returncode = -9
return -9
session._stdout_task = asyncio.create_task(reader())
session._stderr_task = asyncio.create_task(reader())
process.wait = AsyncMock(side_effect=wait_for_process)
stopping = asyncio.create_task(session.kill())
try:
await session.kill()
await asyncio.wait_for(process.exited.wait(), timeout=5)
await process.wait()
done, _ = await asyncio.wait({stopping}, timeout=0.05)
assert not done, "kill returned before stdout/stderr reached EOF"
assert session.finished_at is None
process.stdout.feed_data(b"tail\n")
process.stderr.feed_data(b"error tail\n")
process.stdout.feed_eof()
process.stderr.feed_eof()
await asyncio.wait_for(stopping, timeout=5)
assert session._stdout_task.done()
assert session._stderr_task.done()
poll = await session.poll(yield_time_ms=0, max_output_chars=1000)
assert poll.done is True
assert poll.output == "head\ntail\n\nSTDERR:\nerror tail\n"
assert not poll.output_incomplete
finally:
release.set()
await asyncio.gather(session._stdout_task, session._stderr_task)
process.stdout.feed_eof()
process.stderr.feed_eof()
await asyncio.gather(stopping, return_exceptions=True)
await _cleanup_session(session)
@pytest.mark.asyncio
async def test_exec_session_poll_reaps_after_exit():
process = _mock_session_process(pid=2002, returncode=0)
process = _MockProcess(pid=2004, returncode=0, stdout=b"hi\n")
session = _ExecSession(
session_id="def",
process=process,
@@ -387,12 +536,16 @@ async def test_exec_session_poll_reaps_after_exit():
)
try:
with patch("nanobot.agent.tools.shell._reap_pid") as reap:
await asyncio.wait_for(session.wait_exit(), timeout=5)
poll = await session.poll(yield_time_ms=0, max_output_chars=1000)
assert poll.done is True
assert poll.exit_code == 0
reap.assert_called_once_with(2002)
assert poll.output == "hi\n"
assert poll.finish_reason == "exit"
process.kill.assert_not_called()
reap.assert_called_with(2004)
finally:
await asyncio.gather(session._stdout_task, session._stderr_task, return_exceptions=True)
await _cleanup_session(session)
@pytest.mark.skipif(sys.platform == "win32", reason="zombie reaping is a Unix waitpid concern")
+12 -1
View File
@@ -55,12 +55,23 @@ def test_coding_tool_descriptions_steer_discovery() -> None:
def test_exec_tool_descriptions_are_concise() -> None:
assert ExecTool().description == "Execute a shell command."
exec_description = ExecTool().description
assert exec_description.startswith("Execute a shell command.")
assert "timeout" in exec_description
assert "max_runtime" in exec_description
assert "mutually exclusive" in exec_description
assert len(exec_description) < 160
assert ExecSessionTool().description == "Manage a session returned by exec."
assert ListExecSessionsTool().description == "List active exec sessions."
exec_parameters = ExecTool().parameters["properties"]
assert "omit to wait for exit" in exec_parameters["yield_time_ms"]["description"]
runtime_description = exec_parameters["max_runtime"]["description"].lower()
assert "hard" in runtime_description
assert "seconds" in runtime_description
timeout_description = exec_parameters["timeout"]["description"].lower()
assert "alias" in timeout_description
assert "max_runtime" in timeout_description
session_parameters = ExecSessionTool().parameters["properties"]
assert set(session_parameters) == {
+17 -20
View File
@@ -294,21 +294,24 @@ def test_exec_tool_enabled():
def test_exec_tool_create():
from nanobot.agent.tools.shell import ExecTool
mock_config = MagicMock()
mock_config.exec.enable = True
mock_config.exec.timeout = 120
mock_config.exec.sandbox = ""
mock_config.exec.path_prepend = "/venv/bin"
mock_config.exec.path_append = ""
mock_config.exec.allowed_env_keys = []
mock_config.exec.allow_patterns = []
mock_config.exec.deny_patterns = []
mock_config.restrict_to_workspace = False
ctx = ToolContext(config=mock_config, workspace="/tmp")
from nanobot.agent.tools.shell import ExecTool, ExecToolConfig
from nanobot.config.schema import ToolsConfig
config = ToolsConfig(exec=ExecToolConfig(
max_runtime=120,
max_runtime_limit=900,
idle_timeout=15,
idle_action="terminate",
path_prepend="/venv/bin",
))
ctx = ToolContext(config=config, workspace="/tmp")
tool = ExecTool.create(ctx)
assert isinstance(tool, ExecTool)
assert tool.path_prepend == "/venv/bin"
assert tool._resolve_timeout(None) == 120
for name in ("max_runtime", "timeout"):
assert tool.parameters["properties"][name]["maximum"] == 900
def test_web_tools_config_cls():
@@ -431,16 +434,10 @@ def test_loader_registers_builtin_tools():
"""Verify the loader produces the same tool set as the old _register_default_tools."""
from nanobot.agent.tools.loader import ToolLoader
from nanobot.agent.tools.registry import ToolRegistry
from nanobot.agent.tools.shell import ExecToolConfig
mock_config = MagicMock()
mock_config.exec.enable = True
mock_config.exec.timeout = 60
mock_config.exec.sandbox = ""
mock_config.exec.path_prepend = ""
mock_config.exec.path_append = ""
mock_config.exec.allowed_env_keys = []
mock_config.exec.allow_patterns = []
mock_config.exec.deny_patterns = []
mock_config.exec = ExecToolConfig(max_runtime=60)
mock_config.restrict_to_workspace = False
mock_config.web.enable = True
mock_config.web.search = MagicMock()
+79 -22
View File
@@ -1,6 +1,7 @@
import shlex
import subprocess
import sys
import time
from pathlib import Path
from typing import Any
from unittest.mock import AsyncMock
@@ -912,27 +913,61 @@ async def test_exec_head_tail_truncation(tmp_path) -> None:
assert "Exit code:" in result
async def test_exec_timeout_parameter() -> None:
"""LLM-supplied timeout should override the constructor default."""
@pytest.mark.parametrize("runtime_parameter", ["timeout", "max_runtime"])
async def test_exec_timeout_parameter(runtime_parameter) -> None:
"""Both runtime spellings override the constructor's hard budget."""
tool = ExecTool(timeout=60)
# A very short timeout should cause the command to be killed
result = await tool.execute(command="sleep 10", timeout=1)
started_at = time.monotonic()
result = await tool.execute(
command=[sys.executable, "-c", "import time; time.sleep(10)"],
**{runtime_parameter: 1},
)
assert "timed out" in result
assert "1 seconds" in result
assert time.monotonic() - started_at < 8
assert "Exit code: 0" not in result
async def test_exec_timeout_capped_at_max() -> None:
"""Timeout values above _MAX_TIMEOUT should be clamped."""
@pytest.mark.parametrize("runtime_parameter", ["timeout", "max_runtime"])
@pytest.mark.parametrize("runtime", [0, -1, 301])
async def test_exec_runtime_rejects_out_of_range(
monkeypatch, runtime_parameter, runtime,
) -> None:
"""Invalid budgets fail before spawning instead of being clamped."""
spawn = AsyncMock(side_effect=AssertionError("Invalid runtime must not start a process"))
monkeypatch.setattr(ExecTool, "_spawn", spawn)
tool = ExecTool(max_runtime=301, max_runtime_limit=300)
result = await tool.execute(command="echo ok", **{runtime_parameter: runtime})
assert result.startswith("Error:")
assert "runtime" in result or "timeout" in result
spawn.assert_not_called()
async def test_exec_runtime_aliases_are_mutually_exclusive(monkeypatch) -> None:
spawn = AsyncMock(side_effect=AssertionError("Conflicting runtime arguments must not spawn"))
monkeypatch.setattr(ExecTool, "_spawn", spawn)
tool = ExecTool()
# Should not raise — just clamp to 600
result = await tool.execute(command="echo ok", timeout=9999)
assert "Exit code: 0" in result
params = {"command": "echo ok", "max_runtime": 5, "timeout": 5}
result = await tool.execute(**params)
assert result.startswith("Error:")
assert "max_runtime" in result
assert "timeout" in result
spawn.assert_not_called()
def test_exec_config_timeout_uncapped_and_zero() -> None:
"""Config timeout is no longer capped at 600 and accepts 0 = no limit (#3595)."""
assert ExecToolConfig(timeout=0).timeout == 0
assert ExecToolConfig(timeout=3600).timeout == 3600
def test_exec_config_runtime_defaults_and_timeout_alias() -> None:
cfg = ExecToolConfig()
assert cfg.max_runtime == 3600
assert cfg.max_runtime_limit == 86400
assert cfg.idle_timeout == 300
assert cfg.idle_action == "report"
assert ExecToolConfig(timeout=5).max_runtime == 5
assert ExecToolConfig(timeout=3600).max_runtime == 3600
assert ExecToolConfig(timeout=0).max_runtime == 0
with pytest.raises(ValidationError):
ExecToolConfig(timeout=-1)
@@ -953,16 +988,38 @@ def test_exec_config_accepts_bwrap_bind_aliases() -> None:
assert dumped["sandboxRwBinds"] == ["/home/user/.cache/uv"]
def test_resolve_timeout_config_uncapped_and_unlimited() -> None:
"""Config timeout drives the hard timeout uncapped; 0 means no limit (#3595)."""
assert ExecTool(timeout=3600)._resolve_timeout(None) == 3600
assert ExecTool(timeout=0)._resolve_timeout(None) is None
def test_resolve_timeout_uses_configured_hard_budget() -> None:
assert ExecTool()._resolve_timeout(None) == 3600
assert ExecTool(timeout=5)._resolve_timeout(None) == 5
assert ExecTool(max_runtime=172800, max_runtime_limit=60)._resolve_timeout(None) == 172800
def test_resolve_timeout_per_call_still_capped() -> None:
"""Per-call (LLM) timeout stays capped at _MAX_TIMEOUT even with unlimited config."""
assert ExecTool(timeout=0)._resolve_timeout(9999) == ExecTool._MAX_TIMEOUT
assert ExecTool(timeout=60)._resolve_timeout(120) == 120
def test_resolve_timeout_respects_configured_limit_without_clamping() -> None:
assert ExecTool()._resolve_timeout(9999) == 9999
tool = ExecTool(max_runtime=60, max_runtime_limit=1200)
assert tool._resolve_timeout(1) == 1
assert tool._resolve_timeout(1200) == 1200
for runtime in (0, -1, 1201):
with pytest.raises(ValueError):
tool._resolve_timeout(runtime)
@pytest.mark.parametrize("limit", [60, 1200, 86400])
@pytest.mark.parametrize("runtime_parameter", ["timeout", "max_runtime"])
def test_exec_runtime_schema_matches_configured_limit(limit, runtime_parameter) -> None:
tool = ExecTool(max_runtime=limit + 1, max_runtime_limit=limit)
runtime_schema = tool.parameters["properties"][runtime_parameter]
assert runtime_schema["minimum"] == 1
assert runtime_schema["maximum"] == limit
assert tool.validate_params({"command": "echo ok"}) == []
for runtime in (1, limit):
assert tool.validate_params({"command": "echo ok", runtime_parameter: runtime}) == []
for runtime in (0, -1, limit + 1):
assert tool.validate_params({"command": "echo ok", runtime_parameter: runtime})
runtime_schema["maximum"] = 1
assert tool.parameters["properties"][runtime_parameter]["maximum"] == limit
assert ExecTool().parameters["properties"][runtime_parameter]["maximum"] == 86400
# --- _resolve_type and nullable param tests ---
+34
View File
@@ -69,6 +69,7 @@ def test_runtime_patch_persists_and_preserves_other_domains(tmp_path):
{"agents.defaults.max_concurrent_subagents": 0},
{"agents.defaults.max_tool_iterations": True},
{"tools.exec.timeout": -1},
{"tools.exec.timeout": 86401},
{"tools.exec.timeout": "60"},
{"tools.exec.enable": "false"},
{"tools.exec.allowed_env_keys": "TOKEN"},
@@ -99,6 +100,39 @@ def test_invalid_patch_is_atomic(tmp_path, values):
assert path.read_bytes() == before
@pytest.mark.parametrize("limit", [120, 86400, 172800])
def test_shell_runtime_editor_uses_the_configured_limit(tmp_path, limit):
path = tmp_path / "config.json"
config = Config.model_validate({"tools": {"exec": {"maxRuntimeLimit": limit}}})
save_config(config, path)
before = path.read_bytes()
with pytest.raises(WebUISettingsError, match=f"1–{limit} seconds"):
update_runtime_config_settings({"tools.exec.timeout": limit + 1}, config_path=path)
assert path.read_bytes() == before
payload = update_runtime_config_settings({"tools.exec.timeout": limit}, config_path=path)
assert payload["advanced"]["exec_max_runtime_limit"] == limit
assert payload["runtime_config"]["tools.exec.timeout"] == limit
saved = load_config(path).tools.exec
assert saved.max_runtime == limit
assert saved.max_runtime_limit == limit
def test_other_settings_preserve_a_longer_trusted_shell_runtime(tmp_path):
path = tmp_path / "config.json"
save_config(Config.model_validate({"tools": {"exec": {
"maxRuntime": 172800, "maxRuntimeLimit": 86400,
}}}), path)
update_runtime_config_settings({"tools.exec.path_append": "extra-bin"}, config_path=path)
saved = load_config(path).tools.exec
assert saved.max_runtime == 172800
assert saved.max_runtime_limit == 86400
assert saved.path_append == "extra-bin"
def test_remote_client_cannot_change_install_policy():
config = Config()
with pytest.raises(WebUISettingsError) as error: