refactor(exec): centralize process-tree lifecycle (#6623)

Co-authored-by: chengyongru <chengyongru.ai@gmail.com>
This commit is contained in:
Xubin Renandchengyongru authored and GitHub committed 2026-11-12 11:44:48 +08:00
1 parent c37af82e3f
commit 8607b6445c
16 files changed
+356 -534

No files matched your search

+2 -1
View File
@@ -13,6 +13,7 @@ from nanobot.bus.events import InboundMessage
from nanobot.bus.runtime_events import RuntimeModelChanged
from nanobot.cron.service import CronService
from nanobot.cron.types import CronSchedule
from nanobot.execution import processes
from nanobot.providers.base import LLMResponse
from nanobot.runtime_admission import RuntimeBusyError, RuntimeMaintenanceError
from nanobot.session.sqlite_store import SessionConflictError
@@ -465,7 +466,7 @@ async def test_cancelled_exec_startup_stays_busy_until_cleanup_finishes(agent, t
cancelling.set()
await release.wait()
monkeypatch.setattr(manager, "_spawn", spawn)
monkeypatch.setattr(processes, "spawn_process_tree", spawn)
task = asyncio.create_task(manager.start(
command=[sys.executable, "-c", "pass"], cwd=str(tmp_path), env=dict(os.environ),
timeout=10, shell_program=None, login=False, yield_time_ms=0,
+71 -92
View File
@@ -16,6 +16,7 @@ import pytest
from nanobot.agent.tools.exec_session import ExecSessionManager, ExecSessionTool
from nanobot.agent.tools.shell import ExecTool
from nanobot.execution import processes
_WINDOWS_ENV_KEYS = {
"APPDATA", "LOCALAPPDATA", "ProgramData",
@@ -144,11 +145,11 @@ class TestSpawnUnix:
@pytest.mark.asyncio
async def test_uses_bash(self):
with (
patch("nanobot.agent.tools.shell._IS_WINDOWS", False),
patch.object(processes, "_IS_WINDOWS", False),
patch("asyncio.create_subprocess_exec", new_callable=AsyncMock) as mock_exec,
):
mock_exec.return_value = AsyncMock()
await ExecTool._spawn("echo hi", "/tmp", {"HOME": "/tmp"})
await processes.spawn_process_tree("echo hi", "/tmp", {"HOME": "/tmp"})
args = mock_exec.call_args[0]
assert "bash" in args[0]
@@ -162,24 +163,32 @@ class TestSpawnUnix:
@pytest.mark.asyncio
async def test_process_tree_starts_new_session(self):
with (
patch("nanobot.agent.tools.shell._IS_WINDOWS", False),
patch.object(processes, "_IS_WINDOWS", False),
patch("asyncio.create_subprocess_exec", new_callable=AsyncMock) as mock_exec,
):
mock_exec.return_value = AsyncMock()
await ExecTool._spawn(
await processes.spawn_process_tree(
"echo hi",
"/tmp",
{"HOME": "/tmp"},
process_tree=True,
)
assert mock_exec.call_args.kwargs["start_new_session"] is True
class TestSpawnWindows:
@pytest.fixture(autouse=True)
def windows_launcher(self, monkeypatch):
monkeypatch.setattr(processes, "_IS_WINDOWS", True)
monkeypatch.setattr(processes, "_create_windows_job", _FakeWindowsJob)
@pytest.mark.asyncio
async def test_job_assignment_failure_kills_suspended_process(self):
@pytest.mark.parametrize(("command", "shell_program"), [
("echo hi", None),
("echo hi", "cmd"),
([sys.executable, "--version"], None),
])
async def test_job_assignment_failure_kills_suspended_process(self, command, shell_program):
env = {"PATH": ""}
process = AsyncMock()
process.pid = 123
@@ -191,15 +200,16 @@ class TestSpawnWindows:
job.assign_and_resume.side_effect = OSError("OpenProcess failed")
with (
patch("nanobot.agent.tools.shell._IS_WINDOWS", True),
patch("nanobot.agent.tools.shell.sys", MagicMock(platform="win32")),
patch("asyncio.create_subprocess_exec", new_callable=AsyncMock) as mock_exec,
patch.object(ExecTool, "_create_windows_job", return_value=job),
patch("asyncio.create_subprocess_exec", return_value=process) as mock_exec,
patch("asyncio.create_subprocess_shell", return_value=process) as mock_shell,
patch.object(processes, "_create_windows_job", return_value=job),
pytest.raises(OSError, match="OpenProcess failed"),
):
mock_exec.return_value = process
await ExecTool._spawn("echo hi", r"C:\work", env, process_tree=True)
await processes.spawn_process_tree(command, r"C:\work", env, shell_program)
launcher = mock_shell if shell_program == "cmd" else mock_exec
assert launcher.call_args.kwargs["creationflags"] == job.creation_flags
job.assign_and_resume.assert_called_once_with(process.pid)
job.terminate.assert_called_once_with()
process.kill.assert_called_once_with()
process.wait.assert_awaited_once_with()
@@ -208,11 +218,10 @@ class TestSpawnWindows:
async def test_single_line_uses_powershell(self):
env = {"COMSPEC": r"C:\Windows\system32\cmd.exe", "PATH": ""}
with (
patch("nanobot.agent.tools.shell._IS_WINDOWS", True),
patch("asyncio.create_subprocess_exec", new_callable=AsyncMock) as mock_exec,
):
mock_exec.return_value = AsyncMock()
await ExecTool._spawn("dir", r"C:\work", env)
await processes.spawn_process_tree("dir", r"C:\work", env)
args = mock_exec.call_args[0]
assert any(shell in args[0].lower() for shell in ("pwsh", "powershell"))
@@ -228,11 +237,10 @@ class TestSpawnWindows:
async def test_single_line_passes_cwd_and_env(self):
env = {"PATH": "/usr/bin"}
with (
patch("nanobot.agent.tools.shell._IS_WINDOWS", True),
patch("asyncio.create_subprocess_exec", new_callable=AsyncMock) as mock_exec,
):
mock_exec.return_value = AsyncMock()
await ExecTool._spawn("echo hi", r"C:\work", env)
await processes.spawn_process_tree("echo hi", r"C:\work", env)
kwargs = mock_exec.call_args[1]
assert kwargs["cwd"] == r"C:\work"
@@ -242,11 +250,10 @@ class TestSpawnWindows:
async def test_multiline_uses_powershell(self):
env = {"PATH": ""}
with (
patch("nanobot.agent.tools.shell._IS_WINDOWS", True),
patch("asyncio.create_subprocess_exec", new_callable=AsyncMock) as mock_exec,
):
mock_exec.return_value = AsyncMock()
await ExecTool._spawn('python -c "print(1)\nprint(2)"', r"C:\work", env)
await processes.spawn_process_tree('python -c "print(1)\nprint(2)"', r"C:\work", env)
args = mock_exec.call_args[0]
assert any(shell in args[0].lower() for shell in ("pwsh", "powershell"))
@@ -264,11 +271,10 @@ class TestSpawnWindows:
async def test_explicit_cmd_shell_uses_raw_shell_string(self):
env = {"COMSPEC": r"C:\Windows\system32\cmd.exe", "PATH": ""}
with (
patch("nanobot.agent.tools.shell._IS_WINDOWS", True),
patch("asyncio.create_subprocess_shell", new_callable=AsyncMock) as mock_shell,
):
mock_shell.return_value = AsyncMock()
await ExecTool._spawn(
await processes.spawn_process_tree(
'echo "a & b"', r"C:\work", env,
shell_program=r"C:\Windows\system32\cmd.exe",
)
@@ -286,11 +292,10 @@ class TestSpawnWindows:
async def test_powershell_preserves_last_native_exit_code(self):
env = {"PATH": ""}
with (
patch("nanobot.agent.tools.shell._IS_WINDOWS", True),
patch("asyncio.create_subprocess_exec", new_callable=AsyncMock) as mock_exec,
):
mock_exec.return_value = AsyncMock()
await ExecTool._spawn("cmd /c exit 7", r"C:\work", env)
await processes.spawn_process_tree("cmd /c exit 7", r"C:\work", env)
command = mock_exec.call_args[0][-1]
assert "cmd /c exit 7" in command
@@ -300,11 +305,10 @@ class TestSpawnWindows:
async def test_powershell_configures_utf8_io(self):
env = {"PATH": ""}
with (
patch("nanobot.agent.tools.shell._IS_WINDOWS", True),
patch("asyncio.create_subprocess_exec", new_callable=AsyncMock) as mock_exec,
):
mock_exec.return_value = AsyncMock()
await ExecTool._spawn("Write-Output 'café 你好'", r"C:\work", env)
await processes.spawn_process_tree("Write-Output 'café 你好'", r"C:\work", env)
command = mock_exec.call_args[0][-1]
assert "[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false)" in command
@@ -319,11 +323,10 @@ class TestSpawnWindows:
env = {"PATH": ""}
command = r'"D:\Program Files\Python\python.exe" -u -c "print(1)"'
with (
patch("nanobot.agent.tools.shell._IS_WINDOWS", True),
patch("asyncio.create_subprocess_exec", new_callable=AsyncMock) as mock_exec,
):
mock_exec.return_value = AsyncMock()
await ExecTool._spawn(command, r"C:\work", env)
await processes.spawn_process_tree(command, r"C:\work", env)
powershell_command = mock_exec.call_args[0][-1]
assert f"\n& {command}\n" in powershell_command
@@ -333,11 +336,10 @@ class TestSpawnWindows:
env = {"PATH": ""}
command = r'"D:\Program Files\Git\cmd\git.exe"'
with (
patch("nanobot.agent.tools.shell._IS_WINDOWS", True),
patch("asyncio.create_subprocess_exec", new_callable=AsyncMock) as mock_exec,
):
mock_exec.return_value = AsyncMock()
await ExecTool._spawn(command, r"C:\work", env)
await processes.spawn_process_tree(command, r"C:\work", env)
powershell_command = mock_exec.call_args[0][-1]
assert f"\n& {command}\n" in powershell_command
@@ -354,12 +356,11 @@ class TestSpawnWindows:
return None
with (
patch("nanobot.agent.tools.shell._IS_WINDOWS", True),
patch("nanobot.agent.tools.shell.shutil.which", side_effect=fake_which),
patch.object(processes.shutil, "which", side_effect=fake_which),
patch("asyncio.create_subprocess_exec", new_callable=AsyncMock) as mock_exec,
):
mock_exec.return_value = AsyncMock()
await ExecTool._spawn("dir", r"C:\work", env)
await processes.spawn_process_tree("dir", r"C:\work", env)
args = mock_exec.call_args[0]
assert "pwsh" in args[0].lower()
@@ -375,17 +376,17 @@ class TestPathAppendPlatform:
captured_env = {}
async def capture_spawn(
cmd, cwd, env, shell_program=None, login=True, *, stdin=None, process_tree=False,
cmd, cwd, env, shell_program=None, login=True, *, stdin=None,
):
nonlocal captured_cmd
captured_cmd = cmd
captured_env.update(env)
return mock_proc
return processes.ProcessTree(mock_proc)
with (
patch("nanobot.agent.tools.shell._IS_WINDOWS", False),
patch("nanobot.agent.tools.shell.os.pathsep", ":"),
patch.object(ExecTool, "_spawn", side_effect=capture_spawn),
patch.object(processes, "spawn_process_tree", side_effect=capture_spawn),
patch.object(ExecTool, "_guard_command", return_value=None),
):
tool = ExecTool(path_append="/opt/bin; echo INJECTED")
@@ -403,17 +404,17 @@ class TestPathAppendPlatform:
captured_env = {}
async def capture_spawn(
cmd, cwd, env, shell_program=None, login=True, *, stdin=None, process_tree=False,
cmd, cwd, env, shell_program=None, login=True, *, stdin=None,
):
nonlocal captured_cmd
captured_cmd = cmd
captured_env.update(env)
return mock_proc
return processes.ProcessTree(mock_proc)
with (
patch("nanobot.agent.tools.shell._IS_WINDOWS", False),
patch("nanobot.agent.tools.shell.os.pathsep", ":"),
patch.object(ExecTool, "_spawn", side_effect=capture_spawn),
patch.object(processes, "spawn_process_tree", side_effect=capture_spawn),
patch.object(ExecTool, "_guard_command", return_value=None),
):
tool = ExecTool(path_prepend="/venv/bin; echo INJECTED")
@@ -431,17 +432,17 @@ class TestPathAppendPlatform:
captured_env = {}
async def capture_spawn(
cmd, cwd, env, shell_program=None, login=True, *, stdin=None, process_tree=False,
cmd, cwd, env, shell_program=None, login=True, *, stdin=None,
):
nonlocal captured_cmd
captured_cmd = cmd
captured_env.update(env)
return mock_proc
return processes.ProcessTree(mock_proc)
with (
patch("nanobot.agent.tools.shell._IS_WINDOWS", False),
patch("nanobot.agent.tools.shell.os.pathsep", ":"),
patch.object(ExecTool, "_spawn", side_effect=capture_spawn),
patch.object(processes, "spawn_process_tree", side_effect=capture_spawn),
patch.object(ExecTool, "_guard_command", return_value=None),
):
tool = ExecTool(path_prepend="/venv/bin", path_append="/usr/sbin")
@@ -460,15 +461,15 @@ class TestPathAppendPlatform:
captured_env = {}
async def capture_spawn(
cmd, cwd, env, shell_program=None, login=True, *, stdin=None, process_tree=False,
cmd, cwd, env, shell_program=None, login=True, *, stdin=None,
):
captured_env.update(env)
return mock_proc
return processes.ProcessTree(mock_proc)
with (
patch("nanobot.agent.tools.shell._IS_WINDOWS", True),
patch("nanobot.agent.tools.shell.os.pathsep", ";"),
patch.object(ExecTool, "_spawn", side_effect=capture_spawn),
patch.object(processes, "spawn_process_tree", side_effect=capture_spawn),
patch.object(ExecTool, "_guard_command", return_value=None),
):
tool = ExecTool(path_append=r"C:\tools\bin")
@@ -483,16 +484,16 @@ class TestPathAppendPlatform:
captured_env = {}
async def capture_spawn(
cmd, cwd, env, shell_program=None, login=True, *, stdin=None, process_tree=False,
cmd, cwd, env, shell_program=None, login=True, *, stdin=None,
):
captured_env.update(env)
return mock_proc
return processes.ProcessTree(mock_proc)
with (
patch("nanobot.agent.tools.shell._IS_WINDOWS", True),
patch("nanobot.agent.tools.shell.os.pathsep", ";"),
patch.object(ExecTool, "_build_env", return_value={"PATH": r"C:\Windows\System32"}),
patch.object(ExecTool, "_spawn", side_effect=capture_spawn),
patch.object(processes, "spawn_process_tree", side_effect=capture_spawn),
patch.object(ExecTool, "_guard_command", return_value=None),
):
tool = ExecTool(path_prepend=r"C:\venv\Scripts", path_append=r"C:\tools\bin")
@@ -512,7 +513,7 @@ class TestSandboxPlatform:
with (
patch("nanobot.agent.tools.shell._IS_WINDOWS", True),
patch.object(ExecTool, "_spawn", return_value=mock_proc) as mock_spawn,
patch.object(processes, "spawn_process_tree", return_value=processes.ProcessTree(mock_proc)) as mock_spawn,
patch.object(ExecTool, "_guard_command", return_value=None),
):
tool = ExecTool(sandbox=backend)
@@ -533,7 +534,7 @@ class TestSandboxPlatform:
patch("nanobot.agent.tools.shell._IS_WINDOWS", False),
patch("nanobot.agent.tools.shell.shutil.which", side_effect=lambda name, **_kwargs: str(trusted_bin / name)),
patch("nanobot.agent.tools.shell.wrap_command", return_value=f"{launcher} -- sh -c ls") as mock_wrap,
patch.object(ExecTool, "_spawn", return_value=mock_proc) as mock_spawn,
patch.object(processes, "spawn_process_tree", return_value=processes.ProcessTree(mock_proc)) as mock_spawn,
patch.object(ExecTool, "_guard_command", return_value=None),
):
tool = ExecTool(sandbox=backend, working_dir="/workspace")
@@ -555,7 +556,7 @@ class TestSandboxPlatform:
patch("nanobot.agent.tools.shell._IS_WINDOWS", False),
patch("nanobot.agent.tools.shell.shutil.which", side_effect=lambda name, **_kwargs: f"/usr/bin/{name}"),
patch("nanobot.agent.tools.shell.wrap_command", return_value=f"{backend} -- sh -c ls") as mock_wrap,
patch.object(ExecTool, "_spawn", return_value=mock_proc),
patch.object(processes, "spawn_process_tree", return_value=processes.ProcessTree(mock_proc)),
patch.object(ExecTool, "_guard_command", return_value=None),
):
tool = ExecTool(
@@ -584,10 +585,14 @@ class TestExecuteEndToEnd:
)
async def test_windows_full_path(self, yield_time_ms, stdin):
mock_proc = _CompletedProcess(b"hello world\r\n")
job = MagicMock(spec=_FakeWindowsJob)
job.creation_flags = 0x4
with (
patch("nanobot.agent.tools.shell._IS_WINDOWS", True),
patch.object(ExecTool, "_spawn", return_value=mock_proc) as mock_spawn,
patch.object(processes, "_IS_WINDOWS", True),
patch.object(processes, "_create_windows_job", return_value=job),
patch("asyncio.create_subprocess_exec", return_value=mock_proc) as mock_exec,
patch.object(ExecTool, "_guard_command", return_value=None),
):
tool = ExecTool()
@@ -596,8 +601,10 @@ class TestExecuteEndToEnd:
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
assert mock_exec.call_args.kwargs["stdin"] == stdin
job.assign_and_resume.assert_called_once_with(mock_proc.pid)
job.release.assert_called_once_with()
job.terminate.assert_not_called()
@pytest.mark.asyncio
@pytest.mark.parametrize(
@@ -609,7 +616,7 @@ class TestExecuteEndToEnd:
with (
patch("nanobot.agent.tools.shell._IS_WINDOWS", False),
patch.object(ExecTool, "_spawn", return_value=mock_proc) as mock_spawn,
patch.object(processes, "spawn_process_tree", return_value=processes.ProcessTree(mock_proc)) as mock_spawn,
patch.object(ExecTool, "_guard_command", return_value=None),
):
tool = ExecTool()
@@ -619,21 +626,20 @@ class TestExecuteEndToEnd:
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):
captured_login = []
async def capture_spawn(
cmd, cwd, env, shell_program=None, login=None, *, stdin=None, process_tree=False,
cmd, cwd, env, shell_program=None, login=None, *, stdin=None,
):
captured_login.append(login)
return _CompletedProcess(b"ok\n")
return processes.ProcessTree(_CompletedProcess(b"ok\n"))
with (
patch("nanobot.agent.tools.shell._IS_WINDOWS", False),
patch.object(ExecTool, "_spawn", side_effect=capture_spawn),
patch.object(processes, "spawn_process_tree", side_effect=capture_spawn),
patch.object(ExecTool, "_guard_command", return_value=None),
):
tool = ExecTool()
@@ -698,7 +704,8 @@ class TestWindowsMultilineExec:
with (
patch("nanobot.agent.tools.shell._IS_WINDOWS", True),
patch("asyncio.create_subprocess_exec", new_callable=AsyncMock) as mock_exec,
patch.object(ExecTool, "_create_windows_job", side_effect=_FakeWindowsJob),
patch.object(processes, "_IS_WINDOWS", True),
patch.object(processes, "_create_windows_job", side_effect=_FakeWindowsJob),
patch.object(ExecTool, "_guard_command", return_value=None),
):
mock_exec.return_value = mock_proc
@@ -718,7 +725,8 @@ class TestWindowsMultilineExec:
with (
patch("nanobot.agent.tools.shell._IS_WINDOWS", True),
patch("asyncio.create_subprocess_exec", new_callable=AsyncMock) as mock_exec,
patch.object(ExecTool, "_create_windows_job", side_effect=_FakeWindowsJob),
patch.object(processes, "_IS_WINDOWS", True),
patch.object(processes, "_create_windows_job", side_effect=_FakeWindowsJob),
patch.object(ExecTool, "_guard_command", return_value=None),
):
mock_exec.return_value = mock_proc
@@ -729,37 +737,6 @@ class TestWindowsMultilineExec:
args = mock_exec.call_args[0]
assert any(shell in args[0].lower() for shell in ("pwsh", "powershell"))
@pytest.mark.asyncio
async def test_single_line_uses_powershell(self):
mock_proc = _CompletedProcess(b"1\n")
with (
patch("nanobot.agent.tools.shell._IS_WINDOWS", True),
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='python -c "print(1)"')
assert "1" in result
mock_spawn.assert_called_once()
@pytest.mark.asyncio
async def test_unix_unchanged(self):
mock_proc = _CompletedProcess(b"1\n2\n")
with (
patch("nanobot.agent.tools.shell._IS_WINDOWS", False),
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='python -c "print(1)\nprint(2)"')
assert "1" in result
mock_spawn.assert_called_once()
class TestResolveShellWindows:
@pytest.mark.asyncio
@@ -769,7 +746,8 @@ class TestResolveShellWindows:
with (
patch("nanobot.agent.tools.shell._IS_WINDOWS", True),
patch("asyncio.create_subprocess_exec", new_callable=AsyncMock) as mock_exec,
patch.object(ExecTool, "_create_windows_job", side_effect=_FakeWindowsJob),
patch.object(processes, "_IS_WINDOWS", True),
patch.object(processes, "_create_windows_job", side_effect=_FakeWindowsJob),
patch.object(ExecTool, "_guard_command", return_value=None),
):
mock_exec.return_value = mock_proc
@@ -788,7 +766,8 @@ class TestResolveShellWindows:
with (
patch("nanobot.agent.tools.shell._IS_WINDOWS", True),
patch("asyncio.create_subprocess_shell", new_callable=AsyncMock) as mock_shell,
patch.object(ExecTool, "_create_windows_job", side_effect=_FakeWindowsJob),
patch.object(processes, "_IS_WINDOWS", True),
patch.object(processes, "_create_windows_job", side_effect=_FakeWindowsJob),
patch.object(ExecTool, "_guard_command", return_value=None),
):
mock_shell.return_value = mock_proc
+3 -2
View File
@@ -8,6 +8,7 @@ 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
from nanobot.execution import processes
async def test_owner_cancellation_during_startup_preserves_other_execution(tmp_path, monkeypatch):
@@ -16,7 +17,7 @@ async def test_owner_cancellation_during_startup_preserves_other_execution(tmp_p
blocked_command = [sys.executable, "-u", "-c", "print('blocked launch')"]
entered = asyncio.Event()
release = asyncio.Event()
spawn = manager._spawn
spawn = processes.spawn_process_tree
async def gated_spawn(command, cwd, env, shell_program, login, *, stdin):
if command == blocked_command:
@@ -24,7 +25,7 @@ async def test_owner_cancellation_during_startup_preserves_other_execution(tmp_p
await release.wait()
return await spawn(command, cwd, env, shell_program, login, stdin=stdin)
monkeypatch.setattr(manager, "_spawn", gated_spawn)
monkeypatch.setattr(processes, "spawn_process_tree", 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))
+13 -10
View File
@@ -27,6 +27,7 @@ from nanobot.agent.tools.exec_session import (
)
from nanobot.agent.tools.registry import is_tool_error_result
from nanobot.agent.tools.shell import ExecTool
from nanobot.execution import processes
def _python_command(code: str) -> str:
@@ -270,7 +271,7 @@ async def test_exec_session_preserves_utf8_across_stdout_and_stderr_chunks():
process, exited = _session_process(stdout=stdout, stderr=stderr)
session = _ExecSession(
session_id="utf8-output",
process=process,
process_tree=processes.ProcessTree(process),
command="test",
cwd=".",
timeout=None,
@@ -1204,8 +1205,8 @@ def test_agent_loop_shutdown_preserves_single_cleanup_error():
async def test_exec_session_shared_kill_survives_cancelled_caller(monkeypatch):
process, exited = _session_process()
session = _ExecSession(
session_id="shared-kill", process=process, command="test", cwd=".",
timeout=None, process_tree=True,
session_id="shared-kill", process_tree=processes.ProcessTree(process), command="test", cwd=".",
timeout=None,
)
kill_started = asyncio.Event()
release_kill = asyncio.Event()
@@ -1219,7 +1220,7 @@ async def test_exec_session_shared_kill_survives_cancelled_caller(monkeypatch):
exited.set()
kill_tree = AsyncMock(side_effect=kill_process_tree)
monkeypatch.setattr(ExecTool, "_kill_process_tree", kill_tree)
monkeypatch.setattr(processes.ProcessTree, "terminate", lambda tree: kill_tree(tree.process))
async def second_caller():
second_started.set()
@@ -1253,8 +1254,8 @@ async def test_exec_session_shared_kill_survives_cancelled_caller(monkeypatch):
async def test_exec_session_failed_kill_can_be_retried(monkeypatch, log_content):
process, exited = _session_process()
session = _ExecSession(
session_id="retry-kill", process=process, command="test", cwd=".",
timeout=None, process_tree=True,
session_id="retry-kill", process_tree=processes.ProcessTree(process), command="test", cwd=".",
timeout=None,
)
attempts = 0
@@ -1267,7 +1268,9 @@ async def test_exec_session_failed_kill_can_be_retried(monkeypatch, log_content)
process.returncode = -9
exited.set()
monkeypatch.setattr(ExecTool, "_kill_process_tree", kill_process_tree)
monkeypatch.setattr(
processes.ProcessTree, "terminate", lambda tree: kill_process_tree(tree.process),
)
records = []
sink = logger.add(lambda message: records.append(message.record), format="{message}")
token = bind_request_context(RequestContext(
@@ -1296,8 +1299,8 @@ async def test_exec_session_failed_kill_can_be_retried(monkeypatch, log_content)
async def test_exec_session_deadline_during_explicit_kill_is_not_timeout(monkeypatch):
process, exited = _session_process()
session = _ExecSession(
session_id="explicit-kill", process=process, command="test", cwd=".",
timeout=None, process_tree=True,
session_id="explicit-kill", process_tree=processes.ProcessTree(process), command="test", cwd=".",
timeout=None,
)
kill_started = asyncio.Event()
release_kill = asyncio.Event()
@@ -1311,7 +1314,7 @@ async def test_exec_session_deadline_during_explicit_kill_is_not_timeout(monkeyp
exited.set()
kill_tree = AsyncMock(side_effect=kill_process_tree)
monkeypatch.setattr(ExecTool, "_kill_process_tree", kill_tree)
monkeypatch.setattr(processes.ProcessTree, "terminate", lambda tree: kill_tree(tree.process))
explicit_kill = asyncio.create_task(session.kill())
watcher = None
try:
+8 -7
View File
@@ -16,6 +16,7 @@ from nanobot.agent.tools.rg import RgTool
from nanobot.agent.tools.search import FindFilesTool, GrepTool
from nanobot.agent.tools.shell import ExecTool, _PreparedCommand
from nanobot.config.schema import ToolsConfig
from nanobot.execution import processes
@pytest.mark.parametrize("installed", [True, False])
@@ -187,16 +188,16 @@ async def test_direct_process_timeout(tmp_path):
async def test_direct_process_cancellation_reaps_child(tmp_path, monkeypatch):
spawned = asyncio.Event()
processes = []
original_spawn = ExecTool._spawn
children = []
original_spawn = processes.spawn_process_tree
async def capture(*args, **kwargs):
process = await original_spawn(*args, **kwargs)
processes.append(process)
tree = await original_spawn(*args, **kwargs)
children.append(tree.process)
spawned.set()
return process
return tree
monkeypatch.setattr(ExecTool, "_spawn", staticmethod(capture))
monkeypatch.setattr(processes, "spawn_process_tree", capture)
task = asyncio.create_task(ExecTool(working_dir=str(tmp_path)).execute(
command=[sys.executable, "-c", "import time; time.sleep(20)"],
))
@@ -204,7 +205,7 @@ async def test_direct_process_cancellation_reaps_child(tmp_path, monkeypatch):
task.cancel()
with pytest.raises(asyncio.CancelledError):
await task
assert isinstance(processes[0].returncode, int)
assert isinstance(children[0].returncode, int)
@pytest.mark.skipif(shutil.which("rg") is None, reason="ripgrep not installed")
+6 -4
View File
@@ -20,6 +20,7 @@ from nanobot.agent.tools.exec_session import (
)
from nanobot.agent.tools.registry import is_tool_error_result
from nanobot.agent.tools.shell import ExecTool
from nanobot.execution import processes
def _python(code: str) -> list[str]:
@@ -443,11 +444,12 @@ async def test_execution_stop_stops_pipe_inheriting_child_after_root_exits(
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
real_spawn = processes.spawn_process_tree
spawn_returned = asyncio.Event()
async def spawn_with_exit_order(*args, **kwargs):
process = await real_spawn(*args, **kwargs)
tree = await real_spawn(*args, **kwargs)
process = tree.process
if early_root_exit:
async with asyncio.timeout(5):
while process.returncode is None:
@@ -456,9 +458,9 @@ async def test_execution_stop_stops_pipe_inheriting_child_after_root_exits(
else:
assert process.returncode is None
spawn_returned.set()
return process
return tree
monkeypatch.setattr(ExecTool, "_spawn", staticmethod(spawn_with_exit_order))
monkeypatch.setattr(processes, "spawn_process_tree", 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
+50 -115
View File
@@ -11,7 +11,8 @@ import pytest
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
from nanobot.agent.tools.shell import ExecTool
from nanobot.execution import processes
def _python_command(code: str) -> str:
@@ -52,6 +53,11 @@ class _MockProcess:
return self.returncode
def _fake_tree(process: _MockProcess) -> processes.ProcessTree:
# A stand-in job keeps fabricated PIDs away from the host process table.
return processes.ProcessTree(process, MagicMock())
async def _cleanup_session(session: _ExecSession) -> None:
await asyncio.wait_for(session.kill(), timeout=5)
tasks = (
@@ -65,73 +71,28 @@ async def _cleanup_session(session: _ExecSession) -> None:
def test_reap_pid_noops_without_waitpid():
with patch("nanobot.agent.tools.shell.os") as mock_os:
with patch("nanobot.execution.processes.os") as mock_os:
mock_os.waitpid = None
mock_os.WNOHANG = None
_reap_pid(12345)
processes._reap_pid(12345)
def test_reap_pid_calls_waitpid_wnohang():
with patch("nanobot.agent.tools.shell.os") as mock_os:
with patch("nanobot.execution.processes.os") as mock_os:
mock_os.waitpid = MagicMock(return_value=(12345, 0))
mock_os.WNOHANG = 1
_reap_pid(12345)
processes._reap_pid(12345)
mock_os.waitpid.assert_called_once_with(12345, 1)
def test_reap_pid_swallows_already_reaped_errors():
with patch("nanobot.agent.tools.shell.os") as mock_os:
with patch("nanobot.execution.processes.os") as mock_os:
mock_os.WNOHANG = 1
mock_os.waitpid = MagicMock(side_effect=ChildProcessError("no child"))
_reap_pid(99)
processes._reap_pid(99)
mock_os.waitpid = MagicMock(side_effect=ProcessLookupError("gone"))
_reap_pid(99)
@pytest.mark.asyncio
async def test_kill_process_skips_kill_when_already_exited():
process = _MockProcess(pid=4242, returncode=0)
process.kill = MagicMock(side_effect=ProcessLookupError("already dead"))
with patch("nanobot.agent.tools.shell._reap_pid") as reap:
await ExecTool._kill_process(process)
process.kill.assert_not_called()
process.wait.assert_not_called()
reap.assert_called_once_with(4242)
@pytest.mark.asyncio
async def test_kill_process_kills_and_reaps_live_process():
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():
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)
processes._reap_pid(99)
@pytest.mark.asyncio
@@ -139,8 +100,8 @@ async def test_execute_reaps_after_normal_completion():
process = _MockProcess(pid=1001, returncode=0, stdout=b"ok\n")
manager = ExecSessionManager()
with (
patch.object(ExecTool, "_spawn", return_value=process),
patch("nanobot.agent.tools.shell._reap_pid") as reap,
patch.object(processes, "spawn_process_tree", return_value=_fake_tree(process)),
patch("nanobot.execution.processes._reap_pid") as reap,
):
try:
result = await ExecTool(session_manager=manager).execute(command="echo ok")
@@ -160,9 +121,8 @@ async def test_execute_timeout_kills_and_reaps():
process = _MockProcess(pid=1002, returncode=None)
manager = ExecSessionManager()
with (
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,
patch.object(processes, "spawn_process_tree", return_value=_fake_tree(process)) as spawn,
patch("nanobot.execution.processes._reap_pid") as reap,
):
try:
result = await asyncio.wait_for(
@@ -177,12 +137,11 @@ async def test_execute_timeout_kills_and_reaps():
assert is_tool_error_result(result)
assert "timed out" in result.lower()
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
spawn.assert_awaited_once()
@pytest.mark.asyncio
@@ -197,10 +156,9 @@ async def test_execute_cancellation_kills_process_tree():
return await poll(session, *args, **kwargs)
with (
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(processes, "spawn_process_tree", return_value=_fake_tree(process)) as spawn,
patch.object(_ExecSession, "poll", new=initial_poll),
patch("nanobot.agent.tools.shell._reap_pid") as reap,
patch("nanobot.execution.processes._reap_pid") as reap,
):
execution = asyncio.create_task(
ExecTool(session_manager=manager).execute(command="sleep 99"),
@@ -217,12 +175,11 @@ async def test_execute_cancellation_kills_process_tree():
await asyncio.gather(execution, return_exceptions=True)
await manager.close_all()
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
spawn.assert_awaited_once()
@pytest.mark.asyncio
@@ -231,9 +188,8 @@ async def test_exec_session_wait_cancellation_does_not_kill_process_tree():
manager = ExecSessionManager()
session_tool = ExecSessionTool(manager=manager)
with (
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.object(processes, "spawn_process_tree", return_value=_fake_tree(process)),
patch("nanobot.execution.processes._reap_pid") as reap,
):
observer = None
try:
@@ -254,7 +210,6 @@ async def test_exec_session_wait_cancellation_does_not_kill_process_tree():
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)
@@ -266,7 +221,6 @@ async def test_exec_session_wait_cancellation_does_not_kill_process_tree():
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)
@@ -277,8 +231,8 @@ async def test_execute_exception_after_success_does_not_raise_on_dead_process():
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.object(processes, "spawn_process_tree", return_value=_fake_tree(process)),
patch("nanobot.execution.processes._reap_pid") as reap,
patch(
"nanobot.agent.tools.shell.format_session_poll",
side_effect=RuntimeError("boom after exit"),
@@ -305,22 +259,21 @@ async def test_execute_exception_after_success_does_not_raise_on_dead_process():
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
spawn_process = processes.spawn_process_tree
tree = None
async def spawn_with_broken_stdout(*args, **kwargs):
nonlocal process
process = await spawn_process(*args, **kwargs)
nonlocal tree
tree = await spawn_process(*args, **kwargs)
process = tree.process
assert process.returncode is None
assert process.stdout is not None
process.stdout.set_exception(OSError("pipe broken"))
return process
return tree
with (
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,
patch.object(processes, "spawn_process_tree", side_effect=spawn_with_broken_stdout),
patch.object(processes, "_reap_pid", wraps=processes._reap_pid) as reap,
):
try:
result = await asyncio.wait_for(tool.execute(
@@ -330,35 +283,17 @@ async def test_execute_stream_read_error_kills_live_process(tmp_path):
try:
await manager.close_all()
finally:
if process is not None and process.returncode is None:
await kill_process_tree(process)
if tree is not None and tree.process.returncode is None:
await tree.terminate()
assert is_tool_error_result(result)
assert "pipe broken" in result
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 = _MockProcess(pid=1006, returncode=0)
with (
patch("nanobot.agent.tools.shell._IS_WINDOWS", False),
patch("nanobot.agent.tools.shell.os.killpg", create=True) as kill_group,
patch("nanobot.agent.tools.shell.signal.SIGKILL", 9, create=True),
patch("nanobot.agent.tools.shell._reap_pid") as reap,
):
await ExecTool._kill_process_tree(process)
kill_group.assert_called_once_with(1006, 9)
process.kill.assert_not_called()
reap.assert_called_once_with(1006)
assert tree is not None
assert tree.process.returncode is not None and tree.process.returncode != 0
reap.assert_any_call(tree.process.pid)
@pytest.mark.skipif(sys.platform == "win32", reason="requires Unix process groups")
@@ -403,12 +338,12 @@ async def test_kill_process_tree_kills_descendant_after_root_exits(tmp_path):
"stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)"
)
tool = ExecTool(working_dir=str(tmp_path), timeout=10)
process = await tool._spawn(
tree = await processes.spawn_process_tree(
_python_command(parent_code),
str(tmp_path),
tool._build_env(),
process_tree=True,
)
process = tree.process
try:
await asyncio.wait_for(process.wait(), timeout=10)
assert process.returncode == 0
@@ -416,13 +351,13 @@ async def test_kill_process_tree_kills_descendant_after_root_exits(tmp_path):
while not started.exists():
await asyncio.sleep(0.01)
await ExecTool._kill_process_tree(process)
await tree.terminate()
await asyncio.wait_for(process.communicate(), timeout=5)
release.write_text("go")
await asyncio.sleep(1)
assert not marker.exists()
finally:
await ExecTool._kill_process_tree(process)
await tree.terminate()
@pytest.mark.asyncio
@@ -430,14 +365,14 @@ async def test_exec_session_kill_reaps():
process = _MockProcess(pid=2001, returncode=None)
session = _ExecSession(
session_id="abc",
process=process,
process_tree=_fake_tree(process),
command="sleep 1",
cwd="/tmp",
timeout=30,
owner_session_key=None,
)
try:
with patch("nanobot.agent.tools.shell._reap_pid") as reap:
with patch("nanobot.execution.processes._reap_pid") as reap:
await session.kill()
process.kill.assert_called_once()
process.wait.assert_awaited()
@@ -460,14 +395,14 @@ async def test_exec_session_kill_reaps_if_process_exits_before_kill():
process.kill.side_effect = raced_exit
session = _ExecSession(
session_id="raced",
process=process,
process_tree=_fake_tree(process),
command="sleep 1",
cwd="/tmp",
timeout=30,
owner_session_key=None,
)
try:
with patch("nanobot.agent.tools.shell._reap_pid") as reap:
with patch("nanobot.execution.processes._reap_pid") as reap:
await session.kill()
process.kill.assert_called_once()
process.wait.assert_awaited()
@@ -485,7 +420,7 @@ async def test_exec_session_kill_waits_for_reader_tasks():
process.kill.side_effect = lambda: process.exit(-9, close_streams=False)
session = _ExecSession(
session_id="readers",
process=process,
process_tree=_fake_tree(process),
command="sleep 1",
cwd="/tmp",
timeout=30,
@@ -523,14 +458,14 @@ async def test_exec_session_poll_reaps_after_exit():
process = _MockProcess(pid=2004, returncode=0, stdout=b"hi\n")
session = _ExecSession(
session_id="def",
process=process,
process_tree=_fake_tree(process),
command="echo hi",
cwd="/tmp",
timeout=30,
owner_session_key=None,
)
try:
with patch("nanobot.agent.tools.shell._reap_pid") as reap:
with patch("nanobot.execution.processes._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
+5 -4
View File
@@ -21,6 +21,7 @@ from nanobot.agent.tools import (
from nanobot.agent.tools.base import Tool
from nanobot.agent.tools.registry import ToolRegistry
from nanobot.agent.tools.shell import ExecTool, ExecToolConfig
from nanobot.execution import processes
from nanobot.security.network import configure_ssrf_whitelist
@@ -414,7 +415,7 @@ async def test_exec_rejects_unknown_user_home(tmp_path, monkeypatch, command) ->
Path(home_path).expanduser()
spawn = AsyncMock(side_effect=AssertionError("Blocked commands must not start a process"))
monkeypatch.setattr(ExecTool, "_spawn", spawn)
monkeypatch.setattr(processes, "spawn_process_tree", spawn)
result = await ExecTool(
working_dir=str(tmp_path), restrict_to_workspace=True,
).execute(command=command)
@@ -439,7 +440,7 @@ async def test_exec_rejects_home_path_without_home_directory(tmp_path, monkeypat
Path("~/file.txt").expanduser()
spawn = AsyncMock(side_effect=AssertionError("Blocked commands must not start a process"))
monkeypatch.setattr(ExecTool, "_spawn", spawn)
monkeypatch.setattr(processes, "spawn_process_tree", spawn)
result = await ExecTool(
working_dir=str(tmp_path), restrict_to_workspace=True,
).execute(command="cat ~/file.txt")
@@ -967,7 +968,7 @@ async def test_exec_runtime_rejects_out_of_range(
monkeypatch, runtime_parameter, runtime,
) -> None:
spawn = AsyncMock(side_effect=AssertionError("Invalid runtime must not start a process"))
monkeypatch.setattr(ExecTool, "_spawn", spawn)
monkeypatch.setattr(processes, "spawn_process_tree", spawn)
tool = ExecTool(max_runtime=301, max_runtime_limit=300)
result = await tool.execute(command="echo ok", **{runtime_parameter: runtime})
@@ -979,7 +980,7 @@ async def test_exec_runtime_rejects_out_of_range(
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)
monkeypatch.setattr(processes, "spawn_process_tree", spawn)
tool = ExecTool()
params = {"command": "echo ok", "max_runtime": 5, "timeout": 5}