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

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

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

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

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

No files matched your search

+112 -46
View File
@@ -65,6 +65,31 @@ def _session_id(output: str) -> str:
return match.group(1)
def _session_process(
*,
stdout: asyncio.StreamReader | None = None,
stderr: asyncio.StreamReader | None = None,
) -> tuple[SimpleNamespace, asyncio.Event]:
exited = asyncio.Event()
process = SimpleNamespace(pid=12345, stdout=stdout, stderr=stderr, returncode=None)
async def wait() -> int:
await exited.wait()
assert process.returncode is not None
return process.returncode
process.wait = wait
return process, exited
async def _cancel_session_tasks(session: _ExecSession) -> None:
tasks = [session._stdout_task, session._stderr_task, session._completion_task]
tasks.extend(task for task in (session._timeout_task, session._kill_task) if task is not None)
for task in tasks:
task.cancel()
await asyncio.gather(*tasks, return_exceptions=True)
async def _poll_if_running(
initial: str,
tool: ExecSessionTool,
@@ -160,23 +185,29 @@ async def test_exec_session_preserves_utf8_across_stdout_and_stderr_chunks():
stderr_bytes = b"b" * 4094 + "🙂é".encode() + b"\xff"
stdout.feed_data(stdout_bytes[:4096])
stderr.feed_data(stderr_bytes[:4096])
process, exited = _session_process(stdout=stdout, stderr=stderr)
session = _ExecSession(
session_id="utf8-output",
process=SimpleNamespace(stdout=stdout, stderr=stderr),
process=process,
command="test",
cwd=".",
timeout=None,
)
await asyncio.sleep(0)
stdout.feed_data(stdout_bytes[4096:])
stderr.feed_data(stderr_bytes[4096:])
stdout.feed_eof()
stderr.feed_eof()
await asyncio.gather(session._stdout_task, session._stderr_task)
try:
await asyncio.sleep(0)
stdout.feed_data(stdout_bytes[4096:])
stderr.feed_data(stderr_bytes[4096:])
stdout.feed_eof()
stderr.feed_eof()
process.returncode = 0
exited.set()
await asyncio.wait_for(session._completion_task, timeout=2)
assert session._stdout.drain() == ("a" * 4095 + "你好🙂\ufffd", 0)
assert session._stderr.drain() == ("b" * 4094 + "🙂é\ufffd", 0)
assert session._stdout.drain() == ("a" * 4095 + "你好🙂\ufffd", 0)
assert session._stderr.drain() == ("b" * 4094 + "🙂é\ufffd", 0)
finally:
await _cancel_session_tasks(session)
def test_exec_session_bounds_unpolled_stdout_and_stderr(tmp_path):
@@ -196,11 +227,9 @@ def test_exec_session_bounds_unpolled_stdout_and_stderr(tmp_path):
)
sid = _session_id(initial)
session = manager._sessions[sid]
await asyncio.wait_for(session.process.wait(), timeout=15)
await asyncio.wait_for(
asyncio.gather(session._stdout_task, session._stderr_task),
timeout=15,
)
await asyncio.wait_for(session._completion_task, timeout=15)
assert session.finish_reason == "exit"
assert session.finished_at is not None
retained_stdout = session._stdout.retained_chars
retained_stderr = session._stderr.retained_chars
poll = await manager.write(
@@ -246,7 +275,7 @@ def test_exec_session_wait_for_keeps_aggregate_within_output_budget():
assert result.startswith("HEAD")
assert "Wait target not observed" not in result
assert "(8,000 chars truncated from output)" in result
assert len(result) < 10100
assert len(result.partition("\n")[0]) == 10_000
def test_exec_session_wait_for_searches_before_response_truncation():
@@ -291,7 +320,7 @@ def test_exec_session_wait_for_searches_before_response_truncation():
assert observed_limits == [MAX_OUTPUT_CHARS]
assert "Wait target not observed" not in result
assert "(20,006 chars truncated from output)" in result
assert len(result) < 10100
assert len(result.partition("\n")[0]) == 10_000
def test_exec_one_shot_accepts_max_output_tokens_alias(tmp_path):
@@ -424,7 +453,10 @@ def test_exec_session_preserves_completed_session_output_until_polled(tmp_path):
initial = await exec_tool.execute(command=command, yield_time_ms=50)
sid = _session_id(initial)
await asyncio.wait_for(manager._sessions[sid].process.wait(), timeout=2)
session = manager._sessions[sid]
await asyncio.wait_for(session._completion_task, timeout=2)
assert session.finish_reason == "exit"
assert session.finished_at is not None
final = await stdin_tool.execute(session_id=sid, input="", timeout_ms=0)
return initial, final
@@ -832,8 +864,8 @@ def test_exec_session_manager_retains_and_aggregates_failed_cleanup():
assert len(exc_info.value.exceptions) == 2
assert manager._sessions == {first.session_id: first, second.session_id: second}
first.kill.assert_awaited_once()
second.kill.assert_awaited_once()
first.kill.assert_awaited_once_with("shutdown")
second.kill.assert_awaited_once_with("shutdown")
first.kill.side_effect = None
second.kill.side_effect = None
@@ -979,7 +1011,7 @@ def test_terminate_by_owner_retains_failed_sessions():
await manager.terminate_by_owner("cli:a")
assert manager._sessions == {session.session_id: session}
session.kill.assert_awaited_once()
session.kill.assert_awaited_once_with("owner_closed")
session.kill.side_effect = None
assert await manager.terminate_by_owner("cli:a") == 1
@@ -988,26 +1020,48 @@ def test_terminate_by_owner_retains_failed_sessions():
asyncio.run(run())
def test_stale_cleanup_retains_session_when_kill_fails():
def test_result_retention_only_cleans_completed_sessions(tmp_path, monkeypatch):
async def run() -> None:
manager = ExecSessionManager(idle_timeout=1)
session = SimpleNamespace(
session_id="stale-failed",
owner_session_key="cli:a",
last_access=time.monotonic() - 10,
kill=AsyncMock(side_effect=OSError("termination failed")),
now = time.monotonic()
monkeypatch.setattr(
"nanobot.agent.tools.exec_session.time",
SimpleNamespace(monotonic=lambda: now),
)
manager = ExecSessionManager(result_retention=10)
tool = ExecTool(working_dir=str(tmp_path), max_runtime=0, session_manager=manager)
command = _python_command(
"import sys; print('ready', flush=True); "
"sys.stdin.read(); print('done', flush=True)"
)
manager._sessions[session.session_id] = session
with pytest.raises(OSError, match="termination failed"):
await manager.list(owner_session_key="cli:a")
try:
initial = await tool.execute(command=command, yield_time_ms=0)
sid = _session_id(initial)
session = manager._sessions[sid]
assert manager._sessions == {session.session_id: session}
session.kill.assert_awaited_once()
now += 100
listing = await manager.list()
assert [info.session_id for info in listing] == [sid]
assert session.process.returncode is None
assert session.finished_at is None
session.kill.side_effect = None
assert await manager.list(owner_session_key="cli:a") == []
assert manager._sessions == {}
assert await session.close_stdin() is None
await asyncio.wait_for(session._completion_task, timeout=10)
assert session.finish_reason == "exit"
assert session.finished_at == now
assert session._stdout.has_output
now += 9
listing = await manager.list()
assert [info.session_id for info in listing] == [sid]
assert listing[0].finish_reason == "exit"
assert listing[0].returncode == 0
now += 2
assert await manager.list() == []
assert manager._sessions == {}
finally:
await manager.close_all()
asyncio.run(run())
@@ -1055,7 +1109,7 @@ def test_agent_loop_shutdown_preserves_single_cleanup_error():
async def test_exec_session_shared_kill_survives_cancelled_caller(monkeypatch):
process = SimpleNamespace(stdout=None, stderr=None, returncode=None)
process, exited = _session_process()
session = _ExecSession(
session_id="shared-kill", process=process, command="test", cwd=".",
timeout=None, process_tree=True,
@@ -1069,6 +1123,7 @@ async def test_exec_session_shared_kill_survives_cancelled_caller(monkeypatch):
kill_started.set()
await release_kill.wait()
process.returncode = -9
exited.set()
kill_tree = AsyncMock(side_effect=kill_process_tree)
monkeypatch.setattr(ExecTool, "_kill_process_tree", kill_tree)
@@ -1092,16 +1147,18 @@ async def test_exec_session_shared_kill_survives_cancelled_caller(monkeypatch):
release_kill.set()
await asyncio.wait_for(second, timeout=2)
assert process.returncode == -9
assert session.finish_reason == "cancelled"
assert session.finished_at is not None
kill_tree.assert_awaited_once_with(process)
finally:
release_kill.set()
await asyncio.gather(first, *([second] if second is not None else []), return_exceptions=True)
await asyncio.gather(session._stdout_task, session._stderr_task, return_exceptions=True)
await _cancel_session_tasks(session)
@pytest.mark.parametrize("log_content", [True, False])
async def test_exec_session_failed_kill_can_be_retried(monkeypatch, log_content):
process = SimpleNamespace(stdout=None, stderr=None, returncode=None)
process, exited = _session_process()
session = _ExecSession(
session_id="retry-kill", process=process, command="test", cwd=".",
timeout=None, process_tree=True,
@@ -1115,6 +1172,7 @@ async def test_exec_session_failed_kill_can_be_retried(monkeypatch, log_content)
if attempts == 1:
raise OSError("temporary process-tree cleanup failure")
process.returncode = -9
exited.set()
monkeypatch.setattr(ExecTool, "_kill_process_tree", kill_process_tree)
records = []
@@ -1126,8 +1184,12 @@ async def test_exec_session_failed_kill_can_be_retried(monkeypatch, log_content)
with pytest.raises(OSError, match="temporary process-tree cleanup failure"):
await session.kill()
assert process.returncode is None
assert session.finished_at is None
await session.kill()
assert process.returncode == -9
assert session.finish_reason == "cancelled"
assert session.finished_at is not None
assert session.cleanup_error is None
assert attempts == 2
assert len(records) == 1
assert (records[0]["exception"] is not None) is log_content
@@ -1135,12 +1197,11 @@ async def test_exec_session_failed_kill_can_be_retried(monkeypatch, log_content)
finally:
reset_request_context(token)
logger.remove(sink)
await asyncio.gather(session._stdout_task, session._stderr_task, return_exceptions=True)
await _cancel_session_tasks(session)
async def test_exec_session_deadline_during_explicit_kill_is_not_timeout(monkeypatch):
exited = asyncio.Event()
process = SimpleNamespace(stdout=None, stderr=None, returncode=None, wait=exited.wait)
process, exited = _session_process()
session = _ExecSession(
session_id="explicit-kill", process=process, command="test", cwd=".",
timeout=None, process_tree=True,
@@ -1164,25 +1225,30 @@ async def test_exec_session_deadline_during_explicit_kill_is_not_timeout(monkeyp
await asyncio.wait_for(kill_started.wait(), timeout=2)
original_kill = session.kill
async def join_existing_kill():
async def join_existing_kill(reason="cancelled"):
assert reason == "max_runtime"
watcher_joined.set()
await original_kill()
await original_kill(reason)
monkeypatch.setattr(session, "kill", join_existing_kill)
session.deadline = time.monotonic() - 1
watcher = asyncio.create_task(session._watch_timeout())
await asyncio.wait_for(watcher_joined.wait(), timeout=2)
assert not session._timed_out
assert session.finish_reason is None
assert session.stopping
assert not watcher.done()
kill_tree.assert_awaited_once_with(process)
release_kill.set()
await asyncio.wait_for(asyncio.gather(explicit_kill, watcher), timeout=2)
assert process.returncode == -9
assert not session._timed_out
assert session.finish_reason == "cancelled"
poll = await session.poll(0, 1000)
assert poll.terminated
assert not poll.timed_out
kill_tree.assert_awaited_once_with(process)
finally:
release_kill.set()
await asyncio.gather(
explicit_kill, *([watcher] if watcher is not None else []), return_exceptions=True,
)
await asyncio.gather(session._stdout_task, session._stderr_task, return_exceptions=True)
await _cancel_session_tasks(session)