From 8607b6445cdaedb2cd93f248a0ffbe952c93ea98 Mon Sep 17 00:00:00 2001 From: Xubin Ren <52506698+Re-bin@users.noreply.github.com> Date: Thu, 12 Nov 2026 11:44:48 +0800 Subject: [PATCH] refactor(exec): centralize process-tree lifecycle (#6623) Co-authored-by: chengyongru --- .agent/navigation.md | 1 + nanobot/agent/tools/exec_session.py | 53 +--- nanobot/agent/tools/shell.py | 261 +----------------- nanobot/execution/__init__.py | 1 + .../tools => execution}/_windows_job.py | 0 nanobot/execution/processes.py | 172 ++++++++++++ scripts/check_import_boundaries.py | 5 + scripts/verify_packaged_update.py | 4 +- tests/agent/test_runtime_maintenance.py | 3 +- tests/tools/test_exec_platform.py | 163 +++++------ tests/tools/test_exec_session_startup.py | 5 +- tests/tools/test_exec_session_tools.py | 23 +- tests/tools/test_rg_tool.py | 15 +- tests/tools/test_shell_execution_budgets.py | 10 +- tests/tools/test_shell_reap.py | 165 ++++------- tests/tools/test_tool_validation.py | 9 +- 16 files changed, 356 insertions(+), 534 deletions(-) create mode 100644 nanobot/execution/__init__.py rename nanobot/{agent/tools => execution}/_windows_job.py (100%) create mode 100644 nanobot/execution/processes.py diff --git a/.agent/navigation.md b/.agent/navigation.md index e57e730d7..dc395c766 100644 --- a/.agent/navigation.md +++ b/.agent/navigation.md @@ -9,6 +9,7 @@ Choose the affected behavior below, then read its owner and existing tests. Foll | A chat channel or its setup UI | [Channel package guide](../docs/channel-package-guide.md), then its package in [`nanobot/channels/`](../nanobot/channels/) | The channel's own `tests/`, including `tests/webui/`; shared contracts in [`tests/channels/`](../tests/channels/) | | Provider selection or model requests | [Provider extension guide](../docs/development.md#adding-an-llm-provider), [`providers/routing.py`](../nanobot/providers/routing.py), then the selected adapter | [`tests/providers/`](../tests/providers/) | | A tool's arguments or execution | The implementation and adjacent configuration in [`agent/tools/`](../nanobot/agent/tools/); [`base.py`](../nanobot/agent/tools/base.py) for the shared contract | [`tests/tools/`](../tests/tools/); runtime/session tools in [`tests/agent/tools/`](../tests/agent/tools/) | +| Shell process launch or cleanup | [`execution/processes.py`](../nanobot/execution/processes.py) owns native process trees; [`agent/tools/exec_session.py`](../nanobot/agent/tools/exec_session.py) owns session state and output | [`test_exec_platform.py`](../tests/tools/test_exec_platform.py), [`test_shell_reap.py`](../tests/tools/test_shell_reap.py), [`test_shell_execution_budgets.py`](../tests/tools/test_shell_execution_budgets.py) | | Slash commands or command dispatch | [`command/router.py`](../nanobot/command/router.py), [`command/builtin.py`](../nanobot/command/builtin.py) | [`tests/command/`](../tests/command/) | | Turn scheduling, cancellation, or delivery | [`agent/loop.py`](../nanobot/agent/loop.py), [`agent/turn_delivery.py`](../nanobot/agent/turn_delivery.py) | [`test_loop_concurrency.py`](../tests/agent/test_loop_concurrency.py), [`test_task_cancel.py`](../tests/agent/test_task_cancel.py), [`test_turn_delivery.py`](../tests/agent/test_turn_delivery.py) | | Model/tool iterations, retry, or injected input | [`agent/runner.py`](../nanobot/agent/runner.py) | [`test_runner_core.py`](../tests/agent/test_runner_core.py), [`test_runner_fallback.py`](../tests/agent/test_runner_fallback.py), [`test_runner_injections.py`](../tests/agent/test_runner_injections.py) | diff --git a/nanobot/agent/tools/exec_session.py b/nanobot/agent/tools/exec_session.py index 46adcf8df..a9c003a3c 100644 --- a/nanobot/agent/tools/exec_session.py +++ b/nanobot/agent/tools/exec_session.py @@ -26,6 +26,7 @@ from nanobot.agent.tools.schema import ( ) from nanobot.agent.tools.shell_config import ExecToolConfig from nanobot.agent.tools.shell_output import ShellOutputFilter +from nanobot.execution import processes DEFAULT_YIELD_MS = 1000 MAX_YIELD_MS = 30_000 @@ -151,22 +152,21 @@ class _ExecSession: self, *, session_id: str, - process: asyncio.subprocess.Process, + process_tree: processes.ProcessTree, command: str, cwd: str, timeout: int | None, owner_session_key: str | None = None, - process_tree: bool = False, idle_timeout: int = 300, idle_action: Literal["report", "terminate"] = "report", started_at: float | None = None, ) -> None: self.session_id = session_id - self.process = process + self._process_tree = process_tree + process = process_tree.process self.command = command self.cwd = cwd self.owner_session_key = owner_session_key - self._process_tree = process_tree self.started_at = time.monotonic() if started_at is None else started_at self.deadline = self.started_at + timeout if timeout else float("inf") self.last_output_at: float | None = None @@ -196,6 +196,10 @@ class _ExecSession: if self._timeout_task is not None: self._timeout_task.add_done_callback(self._on_supervisor_done) + @property + def process(self) -> asyncio.subprocess.Process: + return self._process_tree.process + @property def stopping(self) -> bool: return self._stop_reason is not None and self.finished_at is None @@ -236,13 +240,7 @@ class _ExecSession: finally: stopped.cancel() await asyncio.gather(stopped, return_exceptions=True) - from nanobot.agent.tools.shell import ( - ExecTool, - _reap_pid, # pyright: ignore[reportPrivateUsage] - ) - - ExecTool._release_process_tree(self.process) # pyright: ignore[reportPrivateUsage] - _reap_pid(self.process.pid) + self._process_tree.finish() self.finish_reason = self._stop_reason or "exit" self.finished_at = time.monotonic() self._state_changed.set() @@ -410,12 +408,7 @@ class _ExecSession: # kill() replaces it on an explicit retry. async def _kill(self) -> None: - from nanobot.agent.tools.shell import ExecTool - - if self._process_tree: - await ExecTool._kill_process_tree(self.process) # pyright: ignore[reportPrivateUsage] - else: - await ExecTool._kill_process(self.process) # pyright: ignore[reportPrivateUsage] + await self._process_tree.terminate() self._stop_complete.set() @@ -503,12 +496,14 @@ class ExecSessionManager: session: _ExecSession | None = None try: started_at = time.monotonic() - process = await self._spawn(command, cwd, env, shell_program, login, stdin=stdin) + process_tree = await processes.spawn_process_tree( + command, cwd, env, shell_program, login, stdin=stdin, + ) session = _ExecSession( - session_id=session_id, process=process, + session_id=session_id, process_tree=process_tree, command=shlex.join(command) if isinstance(command, list) else command, cwd=cwd, timeout=timeout, owner_session_key=owner_session_key, - process_tree=True, idle_timeout=idle_timeout, idle_action=idle_action, + idle_timeout=idle_timeout, idle_action=idle_action, started_at=started_at, ) async with self._lock: @@ -669,24 +664,6 @@ class ExecSessionManager: for session_id in stale: self._sessions.pop(session_id) - async def _spawn( - self, - command: str | list[str], - cwd: str, - env: dict[str, str], - shell_program: str | None, - login: bool, - *, - stdin: int = asyncio.subprocess.PIPE, - ) -> asyncio.subprocess.Process: - from nanobot.agent.tools.shell import ExecTool - - return await ExecTool._spawn( # pyright: ignore[reportPrivateUsage] - command, cwd, env, shell_program, login, - stdin=stdin, - process_tree=True, - ) - DEFAULT_EXEC_SESSION_MANAGER = ExecSessionManager() diff --git a/nanobot/agent/tools/shell.py b/nanobot/agent/tools/shell.py index f7b429a0d..506d0e02a 100644 --- a/nanobot/agent/tools/shell.py +++ b/nanobot/agent/tools/shell.py @@ -5,13 +5,11 @@ import os import re import shlex import shutil -import signal -import subprocess import sys from contextlib import suppress from dataclasses import dataclass -from pathlib import Path, PureWindowsPath -from typing import Any, Literal, Protocol, cast +from pathlib import Path +from typing import Any, Literal from urllib.parse import unquote from loguru import logger @@ -42,41 +40,6 @@ from nanobot.security.workspace_access import current_scope_allows_loopback, cur from nanobot.security.workspace_policy import is_path_within _IS_WINDOWS = sys.platform == "win32" -_PROCESS_TREE_OWNER_ATTR = "_nanobot_process_tree_owner" - - -class _ProcessTreeOwner(Protocol): - creation_flags: int - - def assign_and_resume(self, pid: int) -> None: ... - - def release(self) -> None: ... - - def terminate(self) -> None: ... - - -def _reap_pid(pid: int) -> None: - """Best-effort ``waitpid`` to reap a child and prevent zombies. - - Call this after killing or after normal completion of any subprocess - as a safety net — asyncio's child-watcher *should* have reaped it, - but in containers / edge-cases it sometimes doesn't. - - Uses ``os`` capability checks rather than ``_IS_WINDOWS`` so this is - safe when tests patch the platform flag while still running on Windows - (``os.waitpid`` / ``os.WNOHANG`` do not exist there). - """ - waitpid = getattr(os, "waitpid", None) - wnohang = getattr(os, "WNOHANG", None) - if waitpid is None or wnohang is None: - return - try: - waitpid(pid, wnohang) - except (ProcessLookupError, ChildProcessError): - # Already reaped, or not our child — both are fine. - pass - except OSError as exc: - logger.debug("_reap_pid({}): {}", pid, exc) _WORKSPACE_BOUNDARY_NOTE = ( @@ -528,146 +491,6 @@ class ExecTool(Tool): path_expr = os.pathsep.join(segments) return f'export PATH="{path_expr}"; {command}' - @staticmethod - async def _spawn( - command: str | list[str], cwd: str, env: dict[str, str], - shell_program: str | None = None, - login: bool = False, - *, - stdin: int = asyncio.subprocess.DEVNULL, - process_tree: bool = False, - ) -> asyncio.subprocess.Process: - """Launch an argument vector directly or a command string through a shell.""" - if isinstance(command, list): - executable = shutil.which(command[0], path=env.get("PATH", "")) - if executable is None: - raise FileNotFoundError(f"Executable not found: {command[0]}") - windows_job = None - process = None - try: - if process_tree and sys.platform == "win32": - windows_job = ExecTool._create_windows_job() - process = await asyncio.create_subprocess_exec( - executable, *command[1:], - stdin=stdin, - stdout=asyncio.subprocess.PIPE, - stderr=asyncio.subprocess.PIPE, - cwd=cwd, - env=env, - creationflags=windows_job.creation_flags if windows_job else 0, - start_new_session=process_tree and sys.platform != "win32", - ) - if windows_job is not None: - windows_job.assign_and_resume(process.pid) - setattr(process, _PROCESS_TREE_OWNER_ATTR, windows_job) - return process - except BaseException: - if windows_job is not None: - windows_job.terminate() - if process is not None: - await ExecTool._kill_process(process) - raise - if _IS_WINDOWS: - windows_job = None - process = None - creation_flags = 0 - if process_tree and sys.platform == "win32": - windows_job = ExecTool._create_windows_job() - creation_flags = windows_job.creation_flags - # Default to PowerShell so single-line and multi-line commands - # share the same shell semantics. cmd.exe is reachable via the - # explicit shell="cmd" parameter (see _resolve_shell). - default_program = shutil.which("pwsh") or shutil.which("powershell") or "powershell" - program = shell_program or default_program - program_name = PureWindowsPath(program).name.lower() - try: - if program_name in ("cmd", "cmd.exe"): - cmd_env = {**env, "COMSPEC": program} - process = await asyncio.create_subprocess_shell( - command, - stdin=stdin, - stdout=asyncio.subprocess.PIPE, - stderr=asyncio.subprocess.PIPE, - cwd=cwd, - env=cmd_env, - creationflags=creation_flags, - ) - else: - command = ExecTool._normalize_powershell_command(command) - command = ( - "[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false)\n" - "if ($PSVersionTable.PSVersion.Major -lt 6) { $OutputEncoding = [Console]::OutputEncoding }\n" - "$PSDefaultParameterValues['Out-File:Encoding'] = 'utf8'\n" - f"{command}\n" - "if ($LASTEXITCODE -ne $null) { exit $LASTEXITCODE }" - ) - process = await asyncio.create_subprocess_exec( - program, "-NoProfile", "-NonInteractive", "-Command", command, - stdin=stdin, - stdout=asyncio.subprocess.PIPE, - stderr=asyncio.subprocess.PIPE, - cwd=cwd, - env=env, - creationflags=creation_flags, - ) - if windows_job is not None: - windows_job.assign_and_resume(process.pid) - setattr(process, _PROCESS_TREE_OWNER_ATTR, windows_job) - return process - except BaseException: - if windows_job is not None: - windows_job.terminate() - if process is not None: - await ExecTool._kill_process(process) - raise - shell_program = shell_program or shutil.which("bash") or "/bin/bash" - args: list[str] = [shell_program] - shell_name = Path(shell_program).name.lower() - if login and shell_name in {"bash", "bash.exe", "zsh", "zsh.exe"}: - args.append("-l") - args.extend(["-c", command]) - if process_tree: - return await asyncio.create_subprocess_exec( - *args, - stdin=stdin, - stdout=asyncio.subprocess.PIPE, - stderr=asyncio.subprocess.PIPE, - cwd=cwd, - env=env, - start_new_session=True, - ) - return await asyncio.create_subprocess_exec( - *args, - stdin=stdin, - stdout=asyncio.subprocess.PIPE, - stderr=asyncio.subprocess.PIPE, - cwd=cwd, - env=env, - ) - - @staticmethod - def _normalize_powershell_command(command: str) -> str: - stripped = command.lstrip() - if not stripped or stripped[0] not in {"'", '"'}: - return command - - quote = stripped[0] - end = stripped.find(quote, 1) - if end == -1 or (end + 1 < len(stripped) and not stripped[end + 1].isspace()): - return command - - executable = stripped[1:end] - looks_like_windows_executable = ( - bool(re.match(r"^[A-Za-z]:[\\/]", executable)) - or executable.startswith(r"\\") - or executable.lower().endswith((".exe", ".cmd", ".bat", ".ps1")) - ) - if not looks_like_windows_executable: - return command - - leading = command[: len(command) - len(stripped)] - return f"{leading}& {stripped}" - @staticmethod def _resolve_shell(shell: str | None) -> tuple[str | None, str | None]: if not shell: @@ -716,86 +539,6 @@ class ExecTool(Tool): return None, ToolResult.error(f"Error: shell not found: {shell}") return resolved, None - @staticmethod - async def _kill_process(process: asyncio.subprocess.Process) -> None: - """Kill a subprocess and reap it to prevent zombies. - - Safe to call when the process has already exited (e.g. generic - exception handlers after a successful ``communicate()``): skips - ``kill()`` and only runs the safety-net reap. - """ - if process.returncode is not None: - _reap_pid(process.pid) - return - try: - with suppress(ProcessLookupError): - process.kill() - with suppress(asyncio.TimeoutError): - await asyncio.wait_for(process.wait(), timeout=5.0) - finally: - _reap_pid(process.pid) - - @staticmethod - async def _kill_process_tree(process: asyncio.subprocess.Process) -> None: - """Kill a session process and descendants, then reap the root process.""" - owner = ExecTool._process_tree_owner(process) - try: - if owner is not None: - owner.terminate() - elif _IS_WINDOWS: - if process.returncode is None: - with suppress(OSError, asyncio.TimeoutError): - await asyncio.wait_for( - asyncio.to_thread( - subprocess.run, - ["taskkill", "/PID", str(process.pid), "/T", "/F"], - check=False, - stdout=subprocess.DEVNULL, - stderr=subprocess.DEVNULL, - ), - timeout=5.0, - ) - else: - try: - os.killpg(process.pid, signal.SIGKILL) - except ProcessLookupError: - pass - - if process.returncode is None: - with suppress(ProcessLookupError): - process.kill() - await asyncio.wait_for(process.wait(), timeout=5.0) - if owner is not None: - ExecTool._drop_process_tree_owner(process) - finally: - _reap_pid(process.pid) - - @staticmethod - def _process_tree_owner( - process: asyncio.subprocess.Process, - ) -> _ProcessTreeOwner | None: - # _spawn is the only writer for this private ownership marker. - return cast(_ProcessTreeOwner | None, vars(process).get(_PROCESS_TREE_OWNER_ATTR)) - - @staticmethod - def _create_windows_job() -> _ProcessTreeOwner: - from nanobot.agent.tools._windows_job import WindowsJob - - return WindowsJob.create() - - @staticmethod - def _drop_process_tree_owner(process: asyncio.subprocess.Process) -> None: - with suppress(AttributeError): - delattr(process, _PROCESS_TREE_OWNER_ATTR) - - @staticmethod - def _release_process_tree(process: asyncio.subprocess.Process) -> None: - owner = ExecTool._process_tree_owner(process) - if owner is None: - return - owner.release() - ExecTool._drop_process_tree_owner(process) - def _build_env(self) -> dict[str, str]: """Use platform defaults plus explicitly allowed environment keys. diff --git a/nanobot/execution/__init__.py b/nanobot/execution/__init__.py new file mode 100644 index 000000000..789f84bd4 --- /dev/null +++ b/nanobot/execution/__init__.py @@ -0,0 +1 @@ +"""Resource operations used by the gateway's tools.""" diff --git a/nanobot/agent/tools/_windows_job.py b/nanobot/execution/_windows_job.py similarity index 100% rename from nanobot/agent/tools/_windows_job.py rename to nanobot/execution/_windows_job.py diff --git a/nanobot/execution/processes.py b/nanobot/execution/processes.py new file mode 100644 index 000000000..ac1afe882 --- /dev/null +++ b/nanobot/execution/processes.py @@ -0,0 +1,172 @@ +"""Platform subprocess launch and process-tree cleanup for exec sessions.""" + +from __future__ import annotations + +import asyncio +import os +import re +import shutil +import signal +import sys +from contextlib import suppress +from pathlib import Path, PureWindowsPath +from typing import TYPE_CHECKING + +from loguru import logger + +if TYPE_CHECKING: + from nanobot.execution._windows_job import WindowsJob + +_IS_WINDOWS = sys.platform == "win32" + + +class ProcessTree: + """Keep the root's streams and its native process-tree ownership together.""" + + __slots__ = ("process", "_job") + + def __init__(self, process: asyncio.subprocess.Process, job: WindowsJob | None = None) -> None: + self.process = process + self._job = job + + async def terminate(self) -> None: + """Stop descendants even if the root has already exited.""" + try: + if self._job is not None: + self._job.terminate() + else: + with suppress(ProcessLookupError): + os.killpg(self.process.pid, signal.SIGKILL) + await _stop_root(self.process) + finally: + _reap_pid(self.process.pid) + + def finish(self) -> None: + """Release native ownership once the session has drained the streams.""" + if self._job is not None: + self._job.release() + _reap_pid(self.process.pid) + + +async def spawn_process_tree( + command: str | list[str], + cwd: str, + env: dict[str, str], + shell_program: str | None = None, + login: bool = False, + *, + stdin: int = asyncio.subprocess.DEVNULL, +) -> ProcessTree: + """Start a prepared command in its own process group or Windows job.""" + if isinstance(command, list): + executable = shutil.which(command[0], path=env.get("PATH", "")) + if executable is None: + raise FileNotFoundError(f"Executable not found: {command[0]}") + launch = [executable, *command[1:]] + elif _IS_WINDOWS: + program = shell_program or shutil.which("pwsh") or shutil.which("powershell") or "powershell" + if PureWindowsPath(program).name.lower() in ("cmd", "cmd.exe"): + env = {**env, "COMSPEC": program} + launch = command + else: + command = _normalize_powershell_command(command) + command = ( + "[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false)\n" + "if ($PSVersionTable.PSVersion.Major -lt 6) { $OutputEncoding = [Console]::OutputEncoding }\n" + "$PSDefaultParameterValues['Out-File:Encoding'] = 'utf8'\n" + f"{command}\n" + "if ($LASTEXITCODE -ne $null) { exit $LASTEXITCODE }" + ) + launch = [program, "-NoProfile", "-NonInteractive", "-Command", command] + else: + program = shell_program or shutil.which("bash") or "/bin/bash" + launch = [program] + if login and Path(program).name.lower() in {"bash", "bash.exe", "zsh", "zsh.exe"}: + launch.append("-l") + launch.extend(["-c", command]) + + job = _create_windows_job() if _IS_WINDOWS else None + creationflags = job.creation_flags if job is not None else 0 + process = None + try: + if isinstance(launch, str): + process = await asyncio.create_subprocess_shell( + launch, stdin=stdin, stdout=asyncio.subprocess.PIPE, + stderr=asyncio.subprocess.PIPE, cwd=cwd, env=env, + creationflags=creationflags, + ) + else: + process = await asyncio.create_subprocess_exec( + *launch, stdin=stdin, stdout=asyncio.subprocess.PIPE, + stderr=asyncio.subprocess.PIPE, cwd=cwd, env=env, + creationflags=creationflags, + start_new_session=not _IS_WINDOWS, + ) + if job is not None: + job.assign_and_resume(process.pid) + return ProcessTree(process, job) + except BaseException: + if job is not None: + job.terminate() + if process is not None: + try: + with suppress(asyncio.TimeoutError): + await _stop_root(process) + finally: + _reap_pid(process.pid) + raise + + +def _normalize_powershell_command(command: str) -> str: + stripped = command.lstrip() + if not stripped or stripped[0] not in {"'", '"'}: + return command + + quote = stripped[0] + end = stripped.find(quote, 1) + if end == -1 or (end + 1 < len(stripped) and not stripped[end + 1].isspace()): + return command + + executable = stripped[1:end] + looks_like_windows_executable = ( + bool(re.match(r"^[A-Za-z]:[\\/]", executable)) + or executable.startswith(r"\\") + or executable.lower().endswith((".exe", ".cmd", ".bat", ".ps1")) + ) + if not looks_like_windows_executable: + return command + + leading = command[: len(command) - len(stripped)] + return f"{leading}& {stripped}" + + +def _reap_pid(pid: int) -> None: + """Best-effort ``waitpid`` to reap a child and prevent zombies. + + Call this after killing or after normal completion of any subprocess + as a safety net if asyncio has not reaped it. + """ + waitpid = getattr(os, "waitpid", None) + wnohang = getattr(os, "WNOHANG", None) + if waitpid is None or wnohang is None: + return + try: + waitpid(pid, wnohang) + except (ProcessLookupError, ChildProcessError): + # Already reaped, or not our child — both are fine. + pass + except OSError as exc: + logger.debug("_reap_pid({}): {}", pid, exc) + + +async def _stop_root(process: asyncio.subprocess.Process) -> None: + if process.returncode is None: + with suppress(ProcessLookupError): + process.kill() + await asyncio.wait_for(process.wait(), timeout=5.0) + + +def _create_windows_job() -> WindowsJob: + from nanobot.execution._windows_job import WindowsJob + + return WindowsJob.create() diff --git a/scripts/check_import_boundaries.py b/scripts/check_import_boundaries.py index 21d4e3da2..215b92a88 100644 --- a/scripts/check_import_boundaries.py +++ b/scripts/check_import_boundaries.py @@ -82,6 +82,11 @@ IMPORT_RULES = ( _ADAPTERS, allowed_targets=("nanobot.channels.notification_routes",), ), + ImportRule( + "process-execution", + ("nanobot.execution.processes", "nanobot.execution._windows_job"), + (*_ADAPTERS, "nanobot.agent", "nanobot.config", "nanobot.security", "nanobot.session"), + ), ImportRule( "channel-routing-contracts", ("nanobot.channels.notification_routes",), diff --git a/scripts/verify_packaged_update.py b/scripts/verify_packaged_update.py index 2aed77981..5359f3929 100644 --- a/scripts/verify_packaged_update.py +++ b/scripts/verify_packaged_update.py @@ -35,7 +35,7 @@ from urllib.parse import quote from zipfile import ZIP_DEFLATED, ZipFile if TYPE_CHECKING: - from nanobot.agent.tools._windows_job import WindowsJob + from nanobot.execution._windows_job import WindowsJob SCENARIOS = ("upgrade", "upgrade-again", "skipped-preview", "import-failure", "restart-failure", "backup-failure", "worker-exit", "metadata-loss", "restore-interruption") @@ -819,7 +819,7 @@ def run_parallel(args, root: Path, target: Path, version: str, original_hash: st owner = None flags = 0 if os.name == "nt": - from nanobot.agent.tools._windows_job import WindowsJob + from nanobot.execution._windows_job import WindowsJob owner = stack.enter_context(closing(WindowsJob.create())) flags = subprocess.CREATE_NEW_PROCESS_GROUP | owner.creation_flags diff --git a/tests/agent/test_runtime_maintenance.py b/tests/agent/test_runtime_maintenance.py index 42f6299ce..4a1ffaec9 100644 --- a/tests/agent/test_runtime_maintenance.py +++ b/tests/agent/test_runtime_maintenance.py @@ -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, diff --git a/tests/tools/test_exec_platform.py b/tests/tools/test_exec_platform.py index 236265892..21a07b651 100644 --- a/tests/tools/test_exec_platform.py +++ b/tests/tools/test_exec_platform.py @@ -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 diff --git a/tests/tools/test_exec_session_startup.py b/tests/tools/test_exec_session_startup.py index 87f3561ee..f5117663c 100644 --- a/tests/tools/test_exec_session_startup.py +++ b/tests/tools/test_exec_session_startup.py @@ -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)) diff --git a/tests/tools/test_exec_session_tools.py b/tests/tools/test_exec_session_tools.py index ef02d9f8f..a9d409851 100644 --- a/tests/tools/test_exec_session_tools.py +++ b/tests/tools/test_exec_session_tools.py @@ -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: diff --git a/tests/tools/test_rg_tool.py b/tests/tools/test_rg_tool.py index 585d00ec9..4a18463c3 100644 --- a/tests/tools/test_rg_tool.py +++ b/tests/tools/test_rg_tool.py @@ -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") diff --git a/tests/tools/test_shell_execution_budgets.py b/tests/tools/test_shell_execution_budgets.py index 5d02f1fe9..a0067d6e9 100644 --- a/tests/tools/test_shell_execution_budgets.py +++ b/tests/tools/test_shell_execution_budgets.py @@ -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 diff --git a/tests/tools/test_shell_reap.py b/tests/tools/test_shell_reap.py index fb54b34c8..eda32db22 100644 --- a/tests/tools/test_shell_reap.py +++ b/tests/tools/test_shell_reap.py @@ -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 diff --git a/tests/tools/test_tool_validation.py b/tests/tools/test_tool_validation.py index 9e88d7257..66774d9b1 100644 --- a/tests/tools/test_tool_validation.py +++ b/tests/tools/test_tool_validation.py @@ -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}