fix(exec): enforce session hard timeouts without polling

This commit is contained in:
Kail Tian authored and Xubin Ren committed 2026-10-03 00:22:31 +08:00
1 parent 0dcc03c4a9
commit 1535cb1b6b
3 files changed
+297 -2

No files matched your search

+47 -2
View File
@@ -12,8 +12,14 @@ from contextlib import suppress
from dataclasses import dataclass from dataclasses import dataclass
from typing import Any from typing import Any
from loguru import logger
from nanobot.agent.tools.base import Tool, ToolResult, tool_parameters from nanobot.agent.tools.base import Tool, ToolResult, tool_parameters
from nanobot.agent.tools.context import ToolContext, current_request_session_key from nanobot.agent.tools.context import (
ToolContext,
current_request_session_key,
tool_log_content_allowed,
)
from nanobot.agent.tools.schema import ( from nanobot.agent.tools.schema import (
BooleanSchema, BooleanSchema,
IntegerSchema, IntegerSchema,
@@ -141,8 +147,24 @@ class _ExecSession:
self._stderr = _BoundedOutputBuffer(MAX_OUTPUT_CHARS) self._stderr = _BoundedOutputBuffer(MAX_OUTPUT_CHARS)
self._lock = asyncio.Lock() self._lock = asyncio.Lock()
self._timed_out = False self._timed_out = False
self._kill_task: asyncio.Task[None] | None = None
self._stdout_task = asyncio.create_task(self._read_stream(process.stdout, self._stdout)) self._stdout_task = asyncio.create_task(self._read_stream(process.stdout, self._stdout))
self._stderr_task = asyncio.create_task(self._read_stream(process.stderr, self._stderr)) self._stderr_task = asyncio.create_task(self._read_stream(process.stderr, self._stderr))
self._timeout_task = asyncio.create_task(self._watch_timeout()) if timeout else None
async def _watch_timeout(self) -> None:
"""Enforce the hard deadline even when nobody polls this session."""
try:
await asyncio.wait_for(
self.process.wait(), timeout=max(0.0, self.deadline - time.monotonic()),
)
except asyncio.TimeoutError:
if self.process.returncode is None:
if self._kill_task is None:
self._timed_out = True
# The kill callback logs failures; leave the session available for retry.
with suppress(Exception):
await self.kill()
async def _read_stream( async def _read_stream(
self, self,
@@ -203,9 +225,14 @@ class _ExecSession:
await asyncio.wait_for(self.process.wait(), timeout=wait_s) await asyncio.wait_for(self.process.wait(), timeout=wait_s)
if self.process.returncode is None and time.monotonic() >= self.deadline: if self.process.returncode is None and time.monotonic() >= self.deadline:
self._timed_out = True if self._kill_task is None:
self._timed_out = True
await self.kill() await self.kill()
if self._kill_task is not None:
# Finish termination before releasing process-tree ownership or returning output.
await asyncio.shield(self._kill_task)
if self.process.returncode is not None: if self.process.returncode is not None:
with suppress(asyncio.TimeoutError): with suppress(asyncio.TimeoutError):
await asyncio.wait_for( await asyncio.wait_for(
@@ -243,6 +270,24 @@ class _ExecSession:
) )
async def kill(self) -> None: async def kill(self) -> None:
# A cancelled poll must not cancel the session's process-tree cleanup.
if self._kill_task is None or (
self._kill_task.done() and self.process.returncode is None
):
self._kill_task = asyncio.create_task(self._kill())
self._kill_task.add_done_callback(self._on_kill_done)
await asyncio.shield(self._kill_task)
def _on_kill_done(self, task: asyncio.Task[None]) -> None:
error = None if task.cancelled() else task.exception()
if error is not None:
logger.opt(exception=error if tool_log_content_allowed() else False).error(
"Failed to terminate exec session {}", self.session_id,
)
if (task.cancelled() or error is not None) and self._kill_task is task:
self._kill_task = None
async def _kill(self) -> None:
from nanobot.agent.tools.shell import ExecTool from nanobot.agent.tools.shell import ExecTool
try: try:
+115
View File
@@ -0,0 +1,115 @@
from __future__ import annotations
import asyncio
import re
import sys
from nanobot.agent.tools.exec_session import ExecSessionManager, ExecSessionTool
from nanobot.agent.tools.registry import is_tool_error_result
from nanobot.agent.tools.shell import ExecTool
def _session_id(result: str) -> str:
match = re.search(r"session_id:\s*([0-9a-f]+)", result)
assert match, result
return match.group(1)
async def test_exec_session_hard_timeout_kills_process_tree_without_polling(tmp_path):
ready = tmp_path / "child-started.txt"
late_write = tmp_path / "child-survived-timeout.txt"
child_code = (
"import pathlib,time; "
f"pathlib.Path({str(ready)!r}).write_text('started'); "
"time.sleep(3); "
f"pathlib.Path({str(late_write)!r}).write_text('survived timeout')"
)
parent_code = (
"import subprocess,sys; "
f"child=subprocess.Popen([sys.executable, '-u', '-c', {child_code!r}]); "
"print('parent started', flush=True); child.wait()"
)
manager = ExecSessionManager()
tool = ExecTool(working_dir=str(tmp_path), timeout=1, session_manager=manager)
session_tool = ExecSessionTool(manager=manager)
try:
initial = await tool.execute(
command=[sys.executable, "-u", "-c", parent_code], yield_time_ms=0,
)
sid = _session_id(initial)
session = manager._sessions[sid]
# Waiting on the OS process must not need another nanobot tool call to enforce
# the deadline. The child inherits the pipes, so an orphan would also delay EOF.
await asyncio.wait_for(session.process.wait(), timeout=6)
await asyncio.wait_for(
asyncio.gather(session._stdout_task, session._stderr_task), timeout=2,
)
assert ready.exists(), "the descendant must have started before the timeout"
assert not late_write.exists(), "the descendant wrote after the hard timeout"
assert session.process.returncode != 0
final = await session_tool.execute(session_id=sid, timeout_ms=0)
assert is_tool_error_result(final)
assert "Command timed out; session was terminated." in final
assert "parent started" in initial + final
assert "Process running" not in final
assert sid not in manager._sessions
finally:
await manager.close_all()
async def test_exec_session_completed_before_deadline_keeps_output_for_late_poll(tmp_path):
manager = ExecSessionManager()
tool = ExecTool(working_dir=str(tmp_path), timeout=1, session_manager=manager)
session_tool = ExecSessionTool(manager=manager)
try:
initial = await tool.execute(
command=[
sys.executable, "-u", "-c",
"import time; time.sleep(0.1); print('completed normally')",
],
yield_time_ms=0,
)
sid = _session_id(initial)
await asyncio.wait_for(manager._sessions[sid].process.wait(), timeout=3)
# Read only after the original deadline: completion must not turn into a timeout.
await asyncio.sleep(1.1)
final = await session_tool.execute(session_id=sid, timeout_ms=0)
assert not is_tool_error_result(final)
assert "completed normally" in initial + final
assert "Exit code: 0" in final
assert "timed out" not in final
assert sid not in manager._sessions
finally:
await manager.close_all()
async def test_exec_session_zero_config_timeout_allows_unpolled_longer_process(tmp_path):
manager = ExecSessionManager()
tool = ExecTool(working_dir=str(tmp_path), timeout=0, session_manager=manager)
session_tool = ExecSessionTool(manager=manager)
try:
initial = await tool.execute(
command=[
sys.executable, "-u", "-c",
"import time; time.sleep(1.2); print('completed without deadline')",
],
yield_time_ms=0,
)
sid = _session_id(initial)
await asyncio.wait_for(manager._sessions[sid].process.wait(), timeout=5)
final = await session_tool.execute(session_id=sid, timeout_ms=0)
assert not is_tool_error_result(final)
assert "completed without deadline" in initial + final
assert "Exit code: 0" in final
assert "timed out" not in final
assert sid not in manager._sessions
finally:
await manager.close_all()
+135
View File
@@ -11,6 +11,7 @@ from types import SimpleNamespace
from unittest.mock import AsyncMock from unittest.mock import AsyncMock
import pytest import pytest
from loguru import logger
from nanobot.agent.loop import AgentLoop from nanobot.agent.loop import AgentLoop
from nanobot.agent.tools.context import RequestContext, bind_request_context, reset_request_context from nanobot.agent.tools.context import RequestContext, bind_request_context, reset_request_context
@@ -1048,3 +1049,137 @@ def test_agent_loop_shutdown_preserves_single_cleanup_error():
loop._exec_session_manager.close_all.assert_awaited_once() loop._exec_session_manager.close_all.assert_awaited_once()
asyncio.run(run()) asyncio.run(run())
async def test_exec_session_shared_kill_survives_cancelled_caller(monkeypatch):
process = SimpleNamespace(stdout=None, stderr=None, returncode=None)
session = _ExecSession(
session_id="shared-kill", process=process, command="test", cwd=".",
timeout=None, process_tree=True,
)
kill_started = asyncio.Event()
release_kill = asyncio.Event()
second_started = asyncio.Event()
async def kill_process_tree(target):
assert target is process
kill_started.set()
await release_kill.wait()
process.returncode = -9
kill_tree = AsyncMock(side_effect=kill_process_tree)
monkeypatch.setattr(ExecTool, "_kill_process_tree", kill_tree)
async def second_caller():
second_started.set()
await session.kill()
first = asyncio.create_task(session.kill())
second = None
try:
await asyncio.wait_for(kill_started.wait(), timeout=2)
second = asyncio.create_task(second_caller())
await asyncio.wait_for(second_started.wait(), timeout=2)
first.cancel()
with pytest.raises(asyncio.CancelledError):
await first
assert process.returncode is None
assert not second.done()
kill_tree.assert_awaited_once_with(process)
release_kill.set()
await asyncio.wait_for(second, timeout=2)
assert process.returncode == -9
kill_tree.assert_awaited_once_with(process)
finally:
release_kill.set()
await asyncio.gather(first, *([second] if second is not None else []), return_exceptions=True)
await asyncio.gather(session._stdout_task, session._stderr_task, return_exceptions=True)
@pytest.mark.parametrize("log_content", [True, False])
async def test_exec_session_failed_kill_can_be_retried(monkeypatch, log_content):
process = SimpleNamespace(stdout=None, stderr=None, returncode=None)
session = _ExecSession(
session_id="retry-kill", process=process, command="test", cwd=".",
timeout=None, process_tree=True,
)
attempts = 0
async def kill_process_tree(target):
nonlocal attempts
assert target is process
attempts += 1
if attempts == 1:
raise OSError("temporary process-tree cleanup failure")
process.returncode = -9
monkeypatch.setattr(ExecTool, "_kill_process_tree", kill_process_tree)
records = []
sink = logger.add(lambda message: records.append(message.record), format="{message}")
token = bind_request_context(RequestContext(
channel="websocket", chat_id="test", log_content=log_content,
))
try:
with pytest.raises(OSError, match="temporary process-tree cleanup failure"):
await session.kill()
assert process.returncode is None
await session.kill()
assert process.returncode == -9
assert attempts == 2
assert len(records) == 1
assert (records[0]["exception"] is not None) is log_content
assert "temporary process-tree cleanup failure" not in records[0]["message"]
finally:
reset_request_context(token)
logger.remove(sink)
await asyncio.gather(session._stdout_task, session._stderr_task, return_exceptions=True)
async def test_exec_session_deadline_during_explicit_kill_is_not_timeout(monkeypatch):
exited = asyncio.Event()
process = SimpleNamespace(stdout=None, stderr=None, returncode=None, wait=exited.wait)
session = _ExecSession(
session_id="explicit-kill", process=process, command="test", cwd=".",
timeout=None, process_tree=True,
)
kill_started = asyncio.Event()
release_kill = asyncio.Event()
watcher_joined = asyncio.Event()
async def kill_process_tree(target):
assert target is process
kill_started.set()
await release_kill.wait()
process.returncode = -9
exited.set()
kill_tree = AsyncMock(side_effect=kill_process_tree)
monkeypatch.setattr(ExecTool, "_kill_process_tree", kill_tree)
explicit_kill = asyncio.create_task(session.kill())
watcher = None
try:
await asyncio.wait_for(kill_started.wait(), timeout=2)
original_kill = session.kill
async def join_existing_kill():
watcher_joined.set()
await original_kill()
monkeypatch.setattr(session, "kill", join_existing_kill)
session.deadline = time.monotonic() - 1
watcher = asyncio.create_task(session._watch_timeout())
await asyncio.wait_for(watcher_joined.wait(), timeout=2)
assert not session._timed_out
assert not watcher.done()
kill_tree.assert_awaited_once_with(process)
release_kill.set()
await asyncio.wait_for(asyncio.gather(explicit_kill, watcher), timeout=2)
assert process.returncode == -9
assert not session._timed_out
kill_tree.assert_awaited_once_with(process)
finally:
release_kill.set()
await asyncio.gather(
explicit_kill, *([watcher] if watcher is not None else []), return_exceptions=True,
)
await asyncio.gather(session._stdout_task, session._stderr_task, return_exceptions=True)