fix(exec): yield long-running commands by default (NAN-328) (#6385)
* fix(exec): yield long-running commands by default (NAN-328) * test(exec): avoid waiting for already observed output * test(exec): observe hard-timeout cleanup before asserting completion
This commit is contained in:
1 parent
421bd6b593
commit
26e1f41a00
14 files changed
+164
-49
No files matched your search
@@ -62,7 +62,7 @@ async def test_exec_child_receives_filtered_env(monkeypatch, allowed_env_keys, e
|
||||
async def test_exec_has_working_path():
|
||||
"""Basic commands should be available via the login shell's PATH."""
|
||||
tool = ExecTool()
|
||||
result = await tool.execute(command="echo hello")
|
||||
result = await tool.execute(command="echo hello", yield_time_ms=10000)
|
||||
assert "hello" in result
|
||||
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@ platform-specific binaries (all subprocess calls are mocked).
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import sys
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
@@ -876,10 +877,24 @@ class TestResolveShellWindows:
|
||||
)
|
||||
class TestWindowsRealExec:
|
||||
|
||||
async def _execute(self, command, shell=None, **kwargs):
|
||||
manager = ExecSessionManager()
|
||||
try:
|
||||
initial = await ExecTool(session_manager=manager, **kwargs).execute(command=command, shell=shell)
|
||||
match = re.search(r"session_id:\s*([0-9a-f]+)", initial)
|
||||
if match is None:
|
||||
return initial
|
||||
final = await ExecSessionTool(manager=manager).execute(
|
||||
session_id=match.group(1), until_exit=True,
|
||||
)
|
||||
return initial + "\n" + final
|
||||
finally:
|
||||
await manager.close_all()
|
||||
|
||||
@pytest.mark.skipif(shutil.which("pwsh") is None, reason="requires PowerShell 7")
|
||||
@pytest.mark.asyncio
|
||||
async def test_single_line_and_separator_uses_pwsh(self):
|
||||
result = await ExecTool(timeout=10).execute(command="echo before && echo after")
|
||||
result = await self._execute(command="echo before && echo after", timeout=10)
|
||||
|
||||
assert "before" in result
|
||||
assert "after" in result
|
||||
@@ -887,7 +902,7 @@ class TestWindowsRealExec:
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_explicit_cmd_preserves_embedded_quotes(self):
|
||||
result = await ExecTool(timeout=10).execute(command='echo "a & b"', shell="cmd")
|
||||
result = await self._execute(command='echo "a & b"', shell="cmd", timeout=10)
|
||||
|
||||
assert '"a & b"' in result
|
||||
assert r'\"a & b\"' not in result
|
||||
@@ -895,13 +910,14 @@ class TestWindowsRealExec:
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_default_powershell_preserves_native_exit_code(self):
|
||||
result = await ExecTool(timeout=10).execute(command="cmd /c exit 7")
|
||||
result = await self._execute(command="cmd /c exit 7", timeout=10)
|
||||
|
||||
assert "Exit code: 7" in result
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_windows_powershell_output_and_redirection_are_utf8(self, tmp_path):
|
||||
result = await ExecTool(working_dir=str(tmp_path), timeout=180).execute(
|
||||
result = await self._execute(
|
||||
working_dir=str(tmp_path), timeout=180,
|
||||
command=(
|
||||
"Write-Output 'file café λ 你好' > marker.txt; "
|
||||
"Write-Output 'café λ 你好'; "
|
||||
@@ -922,7 +938,8 @@ class TestWindowsRealExec:
|
||||
@pytest.mark.asyncio
|
||||
async def test_windows_powershell_native_pipeline_input_is_utf8(self):
|
||||
python = sys.executable.replace("'", "''")
|
||||
result = await ExecTool(timeout=180).execute(
|
||||
result = await self._execute(
|
||||
timeout=180,
|
||||
command=(
|
||||
f"[string][char]0x4F1A | & '{python}' "
|
||||
'-c "import sys; print(sys.stdin.buffer.read().hex())"'
|
||||
|
||||
@@ -124,7 +124,7 @@ async def test_exec_full_access_skips_command_guard(tmp_path, command):
|
||||
restrict_to_workspace=False,
|
||||
deny_patterns=[r"echo\s+blocked"],
|
||||
)
|
||||
result = await tool.execute(command=command)
|
||||
result = await tool.execute(command=command, yield_time_ms=10000)
|
||||
|
||||
assert "Exit code: 0" in result
|
||||
assert "Command blocked" not in result
|
||||
@@ -136,7 +136,7 @@ async def test_exec_full_workspace_scope_skips_command_guard(tmp_path):
|
||||
token = bind_workspace_scope(scope)
|
||||
try:
|
||||
result = await tool.execute(
|
||||
command="echo http://169.254.169.254/latest/meta-data/",
|
||||
command="echo http://169.254.169.254/latest/meta-data/", yield_time_ms=10000,
|
||||
)
|
||||
finally:
|
||||
reset_workspace_scope(token)
|
||||
@@ -148,7 +148,7 @@ async def test_exec_full_workspace_scope_skips_command_guard(tmp_path):
|
||||
@pytest.mark.asyncio
|
||||
async def test_exec_allows_normal_commands():
|
||||
tool = ExecTool(timeout=5)
|
||||
result = await tool.execute(command="echo hello")
|
||||
result = await tool.execute(command="echo hello", yield_time_ms=10000)
|
||||
assert "hello" in result
|
||||
assert "Error" not in result.split("\n")[0]
|
||||
|
||||
@@ -283,7 +283,7 @@ async def test_exec_allows_working_dir_within_workspace(tmp_path):
|
||||
subdir = workspace / "project"
|
||||
subdir.mkdir(parents=True)
|
||||
tool = ExecTool(working_dir=str(workspace), restrict_to_workspace=True, timeout=5)
|
||||
result = await tool.execute(command="echo ok", working_dir=str(subdir))
|
||||
result = await tool.execute(command="echo ok", working_dir=str(subdir), yield_time_ms=10000)
|
||||
assert "ok" in result
|
||||
assert "outside the configured workspace" not in result
|
||||
|
||||
@@ -294,7 +294,7 @@ async def test_exec_allows_working_dir_equal_to_workspace(tmp_path):
|
||||
workspace = tmp_path / "workspace"
|
||||
workspace.mkdir()
|
||||
tool = ExecTool(working_dir=str(workspace), restrict_to_workspace=True, timeout=5)
|
||||
result = await tool.execute(command="echo ok", working_dir=str(workspace))
|
||||
result = await tool.execute(command="echo ok", working_dir=str(workspace), yield_time_ms=10000)
|
||||
assert "ok" in result
|
||||
assert "outside the configured workspace" not in result
|
||||
|
||||
@@ -307,7 +307,7 @@ async def test_exec_ignores_workspace_check_when_not_restricted(tmp_path):
|
||||
other = tmp_path / "other"
|
||||
other.mkdir()
|
||||
tool = ExecTool(working_dir=str(workspace), restrict_to_workspace=False, timeout=5)
|
||||
result = await tool.execute(command="echo ok", working_dir=str(other))
|
||||
result = await tool.execute(command="echo ok", working_dir=str(other), yield_time_ms=10000)
|
||||
assert "ok" in result
|
||||
assert "outside the configured workspace" not in result
|
||||
|
||||
|
||||
@@ -100,21 +100,89 @@ async def _poll_if_running(
|
||||
return initial, initial
|
||||
final = await tool.execute(
|
||||
session_id=_session_id(initial),
|
||||
input="",
|
||||
until_exit=True,
|
||||
timeout_ms=timeout_ms,
|
||||
)
|
||||
return f"{initial}\n{final}", final
|
||||
|
||||
|
||||
def test_exec_keeps_one_shot_behavior_without_yield_time_ms(tmp_path):
|
||||
@pytest.mark.parametrize("diagnostic", [False, True], ids=["silent", "error-output"])
|
||||
def test_exec_default_observation_returns_live_session(tmp_path, diagnostic):
|
||||
async def run() -> None:
|
||||
manager = ExecSessionManager()
|
||||
tool = ExecTool(working_dir=str(tmp_path), timeout=20, session_manager=manager)
|
||||
observer = ExecSessionTool(manager=manager)
|
||||
release = tmp_path / "release"
|
||||
command = _python_command(
|
||||
"import sys,time\n"
|
||||
"from pathlib import Path\n"
|
||||
"assert sys.stdin.read() == ''\n"
|
||||
+ ("print('locator failed', file=sys.stderr, flush=True)\n" if diagnostic else "")
|
||||
+ "print('ready with stdin EOF', flush=True)\n"
|
||||
"while not Path('release').exists(): time.sleep(0.01)\n"
|
||||
"print('released', flush=True)\n"
|
||||
"sys.exit(7)"
|
||||
)
|
||||
try:
|
||||
initial = await asyncio.wait_for(tool.execute(command=command), timeout=5)
|
||||
sid = _session_id(initial)
|
||||
assert "Initial wait ended; session remains active." in initial
|
||||
assert "Elapsed:" in initial
|
||||
assert "Runtime remaining:" in initial
|
||||
combined = initial
|
||||
expected = ["ready with stdin EOF"]
|
||||
if diagnostic:
|
||||
expected.append("locator failed")
|
||||
for marker in expected:
|
||||
if marker not in combined:
|
||||
combined += await observer.execute(session_id=sid, wait_for=marker)
|
||||
assert "ready with stdin EOF" in combined
|
||||
if diagnostic:
|
||||
assert "locator failed" in combined
|
||||
assert "released" not in combined
|
||||
release.touch()
|
||||
final = await observer.execute(session_id=sid, until_exit=True, timeout_ms=5000)
|
||||
assert "released" in final
|
||||
assert "Exit code: 7" in final
|
||||
finally:
|
||||
release.touch()
|
||||
await manager.close_all()
|
||||
|
||||
asyncio.run(run())
|
||||
|
||||
|
||||
def test_exec_short_command_returns_output_and_exit_code(tmp_path):
|
||||
async def run() -> str:
|
||||
tool = ExecTool(working_dir=str(tmp_path), timeout=5)
|
||||
return await tool.execute(command="echo hello")
|
||||
manager = ExecSessionManager()
|
||||
tool = ExecTool(working_dir=str(tmp_path), timeout=5, session_manager=manager)
|
||||
try:
|
||||
initial = await tool.execute(command="echo hello")
|
||||
combined, _ = await _poll_if_running(initial, ExecSessionTool(manager=manager), timeout_ms=5000)
|
||||
return combined
|
||||
finally:
|
||||
await manager.close_all()
|
||||
|
||||
result = asyncio.run(run())
|
||||
|
||||
assert "hello" in result
|
||||
assert "Exit code: 0" in result
|
||||
|
||||
|
||||
def test_trusted_user_shell_waits_for_complete_result(tmp_path):
|
||||
async def run() -> str:
|
||||
manager = ExecSessionManager()
|
||||
tool = ExecTool(working_dir=str(tmp_path), timeout=10, session_manager=manager)
|
||||
try:
|
||||
return await tool.execute_to_completion(
|
||||
command=_python_command("import time,sys; time.sleep(1.2); print('user result'); sys.exit(7)"),
|
||||
working_dir=str(tmp_path),
|
||||
)
|
||||
finally:
|
||||
await manager.close_all()
|
||||
|
||||
result = asyncio.run(run())
|
||||
assert "user result" in result
|
||||
assert "Exit code: 7" in result
|
||||
assert "session_id:" not in result
|
||||
|
||||
|
||||
@@ -123,7 +191,7 @@ def test_exec_accepts_command_aliases(tmp_path):
|
||||
tool = ExecTool(working_dir="/")
|
||||
return await tool.execute(
|
||||
cmd=_python_command("import os; print(os.getcwd())"),
|
||||
workdir=str(tmp_path),
|
||||
workdir=str(tmp_path), yield_time_ms=10000,
|
||||
)
|
||||
|
||||
result = asyncio.run(run())
|
||||
@@ -342,7 +410,7 @@ def test_exec_one_shot_accepts_max_output_tokens_alias(tmp_path):
|
||||
async def run() -> str:
|
||||
tool = ExecTool(working_dir=str(tmp_path), timeout=5)
|
||||
command = _python_command("print('A' * 2000)")
|
||||
return await tool.execute(command=command, max_output_tokens=1000)
|
||||
return await tool.execute(command=command, max_output_tokens=1000, yield_time_ms=10000)
|
||||
|
||||
result = asyncio.run(run())
|
||||
|
||||
|
||||
@@ -181,6 +181,7 @@ async def test_direct_process_preserves_arguments_and_output_limit(tmp_path):
|
||||
async def test_direct_process_timeout(tmp_path):
|
||||
result = await ExecTool(working_dir=str(tmp_path)).execute(
|
||||
command=[sys.executable, "-c", "import time; time.sleep(20)"], timeout=1,
|
||||
yield_time_ms=5000,
|
||||
)
|
||||
assert "Reason: max_runtime" in result
|
||||
assert "Exit code:" in result
|
||||
|
||||
@@ -167,9 +167,12 @@ async def test_trusted_default_runtime_can_exceed_model_request_limit():
|
||||
max_runtime=12, max_runtime_limit=1, idle_timeout=0, session_manager=manager,
|
||||
)
|
||||
try:
|
||||
result = await tool.execute(command=_python(
|
||||
initial = await tool.execute(command=_python(
|
||||
"import time; time.sleep(1.2); print('trusted default completed')"
|
||||
))
|
||||
result = await ExecSessionTool(manager=manager).execute(
|
||||
session_id=_session_id(initial), until_exit=True, timeout_ms=5000,
|
||||
)
|
||||
|
||||
assert not is_tool_error_result(result), result
|
||||
assert "trusted default completed" in result
|
||||
@@ -469,7 +472,9 @@ async def test_execution_stop_stops_pipe_inheriting_child_after_root_exits(
|
||||
initial_exec_task = None
|
||||
try:
|
||||
with request_context(owner):
|
||||
initial_exec_task = asyncio.create_task(tool.execute(command=_python(parent_code)))
|
||||
initial_exec_task = asyncio.create_task(tool.execute(
|
||||
command=_python(parent_code), yield_time_ms=10000,
|
||||
))
|
||||
await asyncio.wait_for(spawn_returned.wait(), timeout=5)
|
||||
parent_pid = int(await _file_text(parent_pidfile))
|
||||
child_pid = int(await _file_text(child_pidfile))
|
||||
@@ -509,7 +514,7 @@ async def test_execution_stop_stops_pipe_inheriting_child_after_root_exits(
|
||||
await asyncio.gather(initial_exec_task, return_exceptions=True)
|
||||
|
||||
|
||||
async def test_inline_work_reports_silence_then_hits_same_fixed_hard_budget(tmp_path):
|
||||
async def test_default_yield_reports_silence_then_hits_same_fixed_hard_budget(tmp_path):
|
||||
pidfile = tmp_path / "process.pid"
|
||||
gate = tmp_path / "emit-output"
|
||||
ticks = tmp_path / "ticks"
|
||||
@@ -540,13 +545,17 @@ async def test_inline_work_reports_silence_then_hits_same_fixed_hard_budget(tmp_
|
||||
assert len(_listed_ids(listing)) == 1, listing
|
||||
assert "| running |" in listing
|
||||
assert (await manager.list())[0].idle_s >= 1
|
||||
assert not inline_task.done()
|
||||
initial = await asyncio.wait_for(inline_task, timeout=2)
|
||||
sid = _session_id(initial)
|
||||
assert _listed_ids(listing) == [sid]
|
||||
assert _pid_running(pid)
|
||||
|
||||
gate.write_text("emit")
|
||||
assert int(await _file_text(ticks)) >= 1
|
||||
final = await ExecSessionTool(manager=manager).execute(
|
||||
session_id=sid, until_exit=True, timeout_ms=6000,
|
||||
)
|
||||
await _pid_stopped(pid)
|
||||
final = await asyncio.wait_for(inline_task, timeout=3)
|
||||
|
||||
assert is_tool_error_result(final), final
|
||||
assert "inline-progress:" in final
|
||||
@@ -588,7 +597,7 @@ async def test_owner_close_stops_inline_tree_and_preserves_other_owner_work(tmp_
|
||||
try:
|
||||
with request_context(owner_a):
|
||||
inline_task = asyncio.create_task(tool.execute(
|
||||
command=_python(_waiting_tree(parent_pidfile, child_pidfile)),
|
||||
command=_python(_waiting_tree(parent_pidfile, child_pidfile)), yield_time_ms=10000,
|
||||
))
|
||||
parent_pid = int(await _file_text(parent_pidfile))
|
||||
child_pid = int(await _file_text(child_pidfile))
|
||||
|
||||
@@ -171,7 +171,9 @@ async def test_execute_timeout_kills_and_reaps():
|
||||
):
|
||||
try:
|
||||
result = await asyncio.wait_for(
|
||||
ExecTool(timeout=1, session_manager=manager).execute(command="sleep 99", timeout=1),
|
||||
ExecTool(timeout=1, session_manager=manager).execute(
|
||||
command="sleep 99", timeout=1, yield_time_ms=5000,
|
||||
),
|
||||
timeout=5,
|
||||
)
|
||||
finally:
|
||||
@@ -193,16 +195,16 @@ async def test_execute_cancellation_kills_process_tree():
|
||||
process = _MockProcess(pid=1005, returncode=None)
|
||||
manager = ExecSessionManager()
|
||||
waiting = asyncio.Event()
|
||||
wait_exit = _ExecSession.wait_exit
|
||||
poll = _ExecSession.poll
|
||||
|
||||
async def inline_wait(session: _ExecSession) -> None:
|
||||
async def initial_poll(session: _ExecSession, *args, **kwargs):
|
||||
waiting.set()
|
||||
await wait_exit(session)
|
||||
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(_ExecSession, "wait_exit", new=inline_wait),
|
||||
patch.object(_ExecSession, "poll", new=initial_poll),
|
||||
patch("nanobot.agent.tools.shell._reap_pid") as reap,
|
||||
):
|
||||
execution = asyncio.create_task(
|
||||
@@ -375,6 +377,7 @@ async def test_execute_timeout_kills_background_process_tree(tmp_path):
|
||||
result = await ExecTool(working_dir=str(tmp_path), timeout=1).execute(
|
||||
command=command,
|
||||
timeout=1,
|
||||
yield_time_ms=5000,
|
||||
)
|
||||
|
||||
assert "timed out" in result.lower()
|
||||
@@ -555,7 +558,7 @@ async def test_real_timeout_leaves_no_zombie(tmp_path):
|
||||
import os
|
||||
|
||||
tool = ExecTool(working_dir=str(tmp_path), timeout=1)
|
||||
result = await tool.execute(command="sleep 30", timeout=1)
|
||||
result = await tool.execute(command="sleep 30", timeout=1, yield_time_ms=5000)
|
||||
assert "timed out" in result.lower()
|
||||
|
||||
await asyncio.sleep(0.05)
|
||||
|
||||
@@ -65,7 +65,8 @@ def test_exec_tool_descriptions_are_concise() -> None:
|
||||
assert ListExecSessionsTool().description == "List active exec sessions."
|
||||
|
||||
exec_parameters = ExecTool().parameters["properties"]
|
||||
assert "omit to wait for exit" in exec_parameters["yield_time_ms"]["description"]
|
||||
assert "default 1000" in exec_parameters["yield_time_ms"]["description"]
|
||||
assert "execution continues" in exec_parameters["yield_time_ms"]["description"]
|
||||
runtime_description = exec_parameters["max_runtime"]["description"].lower()
|
||||
assert "hard" in runtime_description
|
||||
assert "seconds" in runtime_description
|
||||
@@ -83,7 +84,7 @@ def test_exec_tool_descriptions_are_concise() -> None:
|
||||
"until_exit",
|
||||
"timeout_ms",
|
||||
}
|
||||
assert session_parameters["until_exit"]["description"] == "Wait for the process to exit."
|
||||
assert "within timeout_ms" in session_parameters["until_exit"]["description"]
|
||||
assert "wait_for" in session_parameters["timeout_ms"]["description"]
|
||||
assert "until_exit" in session_parameters["timeout_ms"]["description"]
|
||||
|
||||
|
||||
@@ -457,7 +457,7 @@ async def test_exec_allows_resolved_home_inside_workspace(tmp_path, monkeypatch)
|
||||
(tmp_path / "file.txt").write_text("allowed home content", encoding="utf-8")
|
||||
result = await ExecTool(
|
||||
working_dir=str(tmp_path), restrict_to_workspace=True,
|
||||
).execute(command="cat ~/file.txt", login=False)
|
||||
).execute(command="cat ~/file.txt", login=False, yield_time_ms=10000)
|
||||
|
||||
assert "allowed home content" in result
|
||||
assert "Exit code: 0" in result
|
||||
@@ -939,10 +939,10 @@ def test_cast_params_single_value_not_auto_wrapped_to_array() -> None:
|
||||
# --- ExecTool enhancement tests ---
|
||||
|
||||
|
||||
async def test_exec_always_returns_exit_code() -> None:
|
||||
"""Exit code should appear in output even on success (exit 0)."""
|
||||
async def test_completed_exec_returns_exit_code() -> None:
|
||||
"""Completed output includes the exit code even on success (exit 0)."""
|
||||
tool = ExecTool()
|
||||
result = await tool.execute(command="echo hello")
|
||||
result = await tool.execute(command="echo hello", yield_time_ms=10000)
|
||||
assert "Exit code: 0" in result
|
||||
assert "hello" in result
|
||||
|
||||
@@ -964,7 +964,7 @@ async def test_exec_head_tail_truncation(tmp_path) -> None:
|
||||
command = subprocess.list2cmdline([sys.executable, str(script_file)])
|
||||
else:
|
||||
command = f"{shlex.quote(sys.executable)} {shlex.quote(str(script_file))}"
|
||||
result = await tool.execute(command=command)
|
||||
result = await tool.execute(command=command, yield_time_ms=10000)
|
||||
assert "chars truncated" in result
|
||||
# Head portion should start with As
|
||||
assert result.startswith("A")
|
||||
@@ -979,6 +979,7 @@ async def test_exec_timeout_parameter(runtime_parameter) -> None:
|
||||
started_at = time.monotonic()
|
||||
result = await tool.execute(
|
||||
command=[sys.executable, "-c", "import time; time.sleep(10)"],
|
||||
yield_time_ms=5000,
|
||||
**{runtime_parameter: 1},
|
||||
)
|
||||
|
||||
|
||||
Reference in new issue
Block a user