fix(webui): update usage and tool progress during active turns (#6553)
* fix(webui): stream model status and usage during active turns * fix(webui): keep live rounds and active-run status consistent * fix(webui): reuse existing run indicators without extra status text * fix(webui): preserve live activity and batch durable delivery Cancel and drain sibling tools when progress notifications fail, retain balanced checkpoints, and keep model telemetry separate from answer provenance. Group-commit already queued activity at the channel delivery boundary while preserving FIFO, generation ownership, per-envelope admission, and commit-before-fanout semantics. Isolate invalid members without dropping valid neighboring events. Retain tool detail lazy grouping and cover scheduling, cancellation, persistence, encoding failures, and projection regressions. * test(webui): separate standard-library imports in batch regression * test: tighten live execution checks and clarify contracts * refactor: remove redundant live execution comments * refactor: settle tool results through one output path
This commit is contained in:
1 parent
006a535537
commit
8ff04aad2b
52 files changed
+2065
-211
No files matched your search
@@ -43,6 +43,7 @@ def _make_loop(tmp_path):
|
||||
async def test_process_direct_websocket_clears_run_status(tmp_path) -> None:
|
||||
loop = _make_loop(tmp_path)
|
||||
gateway = MagicMock()
|
||||
gateway.transcripts.prepare_and_append = AsyncMock(return_value=True)
|
||||
channel = WebSocketChannel(
|
||||
{"enabled": True, "allowFrom": ["*"]},
|
||||
loop.bus,
|
||||
|
||||
@@ -13,7 +13,7 @@ from nanobot.bus.events import InboundMessage
|
||||
from nanobot.bus.outbound_events import StreamedResponseEvent
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.config.schema import AgentDefaults
|
||||
from nanobot.events import RetryStatusEvent
|
||||
from nanobot.events import ModelRequestEvent, RetryStatusEvent
|
||||
from nanobot.goal.assembly import install_goal
|
||||
from nanobot.providers.base import (
|
||||
GenerationSettings,
|
||||
@@ -92,11 +92,14 @@ async def test_loop_uses_structured_retry_status_without_legacy_text(tmp_path):
|
||||
|
||||
assert result is not None
|
||||
assert captured["provider_context"].events.accepts(RetryStatusEvent)
|
||||
assert bus.outbound_size == 1
|
||||
outbound = bus.outbound.get_nowait()
|
||||
assert isinstance(outbound.event, RetryStatusEvent)
|
||||
assert outbound.event.state == "waiting"
|
||||
assert outbound.chat_id == "chat-a"
|
||||
outbound = [bus.outbound.get_nowait() for _ in range(bus.outbound_size)]
|
||||
assert [type(message.event) for message in outbound] == [
|
||||
ModelRequestEvent, RetryStatusEvent, ModelRequestEvent,
|
||||
]
|
||||
retry = outbound[1].event
|
||||
assert isinstance(retry, RetryStatusEvent)
|
||||
assert retry.state == "waiting"
|
||||
assert all(message.chat_id == "chat-a" for message in outbound)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
|
||||
@@ -790,13 +790,16 @@ async def test_resource_prompt_results_keep_runtime_classification(case):
|
||||
assert direct == (with_tool_error_hint(expected) if failed else expected)
|
||||
|
||||
hook = _RecordingToolHook()
|
||||
outputs, events = await execute_tool_calls(
|
||||
settled = []
|
||||
await execute_tool_calls(
|
||||
registry, [call], concurrent=False, external_lookup_counts={},
|
||||
workspace_violation_counts={}, hook=hook,
|
||||
context=AgentHookContext(iteration=0, messages=[]),
|
||||
on_settled=AsyncMock(side_effect=settled.extend),
|
||||
)
|
||||
assert events[0]["status"] == ("error" if failed else "ok")
|
||||
assert expected in outputs[0]
|
||||
[completed] = settled
|
||||
assert completed.event["status"] == ("error" if failed else "ok")
|
||||
assert expected in completed.result
|
||||
assert hook.errors == ([expected] if failed else [])
|
||||
assert hook.successes == ([] if failed else [expected])
|
||||
|
||||
|
||||
@@ -0,0 +1,259 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from contextlib import nullcontext
|
||||
from unittest.mock import AsyncMock, MagicMock
|
||||
|
||||
import pytest
|
||||
|
||||
from agent.runner_helpers import make_run_spec
|
||||
from nanobot.agent.hook import AgentHookContext
|
||||
from nanobot.agent.progress_hook import AgentProgressHook
|
||||
from nanobot.agent.runner import AgentRunner
|
||||
from nanobot.agent.tools.execution import execute_tool_calls
|
||||
from nanobot.events import EventSink, ModelRequestEvent
|
||||
from nanobot.providers.base import LLMResponse, LLMUsage, ToolCallRequest
|
||||
|
||||
|
||||
def spec(provider, sink, **kwargs):
|
||||
tools = MagicMock()
|
||||
tools.get_definitions.return_value = []
|
||||
return make_run_spec(
|
||||
provider, initial_messages=[{"role": "user", "content": "hi"}],
|
||||
tools=tools, model="test-model", max_iterations=2,
|
||||
max_tool_result_chars=10000, events=sink, **kwargs,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_requests_arrive_before_runner_finishes_and_cancel_is_terminal():
|
||||
events = []
|
||||
entered = asyncio.Event()
|
||||
block = asyncio.Event()
|
||||
|
||||
async def publish(event):
|
||||
events.append(event)
|
||||
|
||||
async def provider_call(**kwargs):
|
||||
entered.set()
|
||||
await block.wait()
|
||||
return LLMResponse(content="done")
|
||||
|
||||
provider = MagicMock()
|
||||
provider.chat_stream_with_retry = provider_call
|
||||
task = asyncio.create_task(AgentRunner().run(spec(provider, EventSink(publish))))
|
||||
await asyncio.wait_for(entered.wait(), 2)
|
||||
assert not task.done()
|
||||
assert [e.phase for e in events if isinstance(e, ModelRequestEvent)] == ["started"]
|
||||
task.cancel()
|
||||
with pytest.raises(asyncio.CancelledError):
|
||||
await task
|
||||
requests = [e for e in events if isinstance(e, ModelRequestEvent)]
|
||||
assert [e.phase for e in requests] == ["started", "cancelled"]
|
||||
assert requests[0].request_id == requests[1].request_id
|
||||
assert [e.sequence for e in requests] == [1, 2]
|
||||
assert requests[1].usage is None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_completed_request_usage_is_visible_while_tool_is_blocked():
|
||||
events = []
|
||||
entered = asyncio.Event()
|
||||
release = asyncio.Event()
|
||||
usage = LLMUsage.reported(input_tokens=12, output_tokens=3)
|
||||
|
||||
async def publish(event):
|
||||
events.append(event)
|
||||
|
||||
async def tool_call(*args):
|
||||
entered.set()
|
||||
await release.wait()
|
||||
return "ok"
|
||||
|
||||
provider = MagicMock()
|
||||
provider.chat_stream_with_retry = AsyncMock(side_effect=[
|
||||
LLMResponse(content=None, tool_calls=[ToolCallRequest("c", "tool", {})], usage=usage),
|
||||
LLMResponse(content="done", usage=usage),
|
||||
])
|
||||
run_spec = spec(provider, EventSink(publish))
|
||||
run_spec.tools.prepare_call.return_value = (None, {}, None)
|
||||
run_spec.tools.execute = tool_call
|
||||
task = asyncio.create_task(AgentRunner().run(run_spec))
|
||||
try:
|
||||
await asyncio.wait_for(entered.wait(), 2)
|
||||
assert not task.done()
|
||||
requests = [e for e in events if isinstance(e, ModelRequestEvent)]
|
||||
assert [e.phase for e in requests] == ["started", "completed"]
|
||||
assert requests[-1].usage == usage
|
||||
assert requests[-1].round_usages == (usage,)
|
||||
finally:
|
||||
release.set()
|
||||
await task
|
||||
requests = [e for e in events if isinstance(e, ModelRequestEvent)]
|
||||
assert [e.sequence for e in requests] == [1, 2, 3, 4]
|
||||
assert len({e.run_id for e in requests}) == 1
|
||||
assert requests[0].request_id != requests[2].request_id
|
||||
assert requests[-1].usage == usage + usage
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_live_round_usage_folds_recovery_before_tool_finishes():
|
||||
events = []
|
||||
entered = asyncio.Event()
|
||||
release = asyncio.Event()
|
||||
usages = [LLMUsage.reported(input_tokens=value, output_tokens=1) for value in (10, 20, 30)]
|
||||
|
||||
async def publish(event):
|
||||
if isinstance(event, ModelRequestEvent):
|
||||
events.append(event)
|
||||
|
||||
async def tool_call(*args):
|
||||
entered.set()
|
||||
await release.wait()
|
||||
return "ok"
|
||||
|
||||
provider = MagicMock()
|
||||
provider.chat_stream_with_retry = AsyncMock(side_effect=[
|
||||
LLMResponse(content=None, tool_calls=[ToolCallRequest("bad", "", {})],
|
||||
finish_reason="tool_calls", usage=usages[0]),
|
||||
LLMResponse(content=None, tool_calls=[ToolCallRequest("c", "tool", {})],
|
||||
finish_reason="tool_calls", usage=usages[1]),
|
||||
LLMResponse(content="done", usage=usages[2]),
|
||||
])
|
||||
run_spec = spec(provider, EventSink(publish))
|
||||
run_spec.tools.prepare_call.return_value = (None, {}, None)
|
||||
run_spec.tools.execute = tool_call
|
||||
task = asyncio.create_task(AgentRunner().run(run_spec))
|
||||
try:
|
||||
await asyncio.wait_for(entered.wait(), 2)
|
||||
assert not task.done()
|
||||
completed = [event for event in events if event.phase == "completed"]
|
||||
assert completed[0].round_usages == (usages[0],)
|
||||
assert completed[-1].round_usages == (usages[0] + usages[1],)
|
||||
assert completed[-1].usage == usages[0] + usages[1]
|
||||
finally:
|
||||
release.set()
|
||||
result = await task
|
||||
assert events[-1].round_usages == tuple(result.round_usages)
|
||||
assert events[-1].usage == result.usage
|
||||
assert [usage.input_tokens for usage in result.round_usages] == [30, 30]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_individual_tool_finishes_before_blocked_sibling():
|
||||
emitted = []
|
||||
settled = []
|
||||
fast_finished = asyncio.Event()
|
||||
release = asyncio.Event()
|
||||
tools = MagicMock()
|
||||
tools.prepare_call.return_value = (None, {}, None)
|
||||
|
||||
async def execute(name, args):
|
||||
if name == "slow":
|
||||
await release.wait()
|
||||
return name
|
||||
|
||||
tools.execute = execute
|
||||
|
||||
async def publish(event):
|
||||
emitted.extend(event.tool_events or [])
|
||||
if any(e["call_id"] == "fast" and e["phase"] == "end" for e in event.tool_events or []):
|
||||
fast_finished.set()
|
||||
|
||||
task = asyncio.create_task(execute_tool_calls(
|
||||
tools, [ToolCallRequest("slow", "slow", {}), ToolCallRequest("fast", "fast", {})],
|
||||
concurrent=True, external_lookup_counts={}, workspace_violation_counts={},
|
||||
hook=AgentProgressHook(EventSink(publish)), context=AgentHookContext(0, []),
|
||||
on_settled=AsyncMock(side_effect=settled.extend),
|
||||
))
|
||||
try:
|
||||
await asyncio.wait_for(fast_finished.wait(), 2)
|
||||
assert not task.done()
|
||||
assert not any(e["call_id"] == "slow" and e["phase"] == "end" for e in emitted)
|
||||
finally:
|
||||
release.set()
|
||||
await task
|
||||
assert [completed.result for completed in settled] == ["slow", "fast"]
|
||||
assert [(e["call_id"], e["phase"]) for e in emitted].count(("fast", "end")) == 1
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_request_snapshots_bound_rounds_without_losing_cumulative_usage():
|
||||
events = []
|
||||
usage = LLMUsage.reported(input_tokens=12, output_tokens=3)
|
||||
|
||||
async def publish(event):
|
||||
events.append(event)
|
||||
|
||||
provider = MagicMock()
|
||||
provider.chat_stream_with_retry = AsyncMock(side_effect=[
|
||||
*[LLMResponse(content=None, tool_calls=[ToolCallRequest(str(i), "tool", {})], usage=usage)
|
||||
for i in range(9)],
|
||||
LLMResponse(content="done", usage=usage),
|
||||
])
|
||||
run_spec = spec(provider, EventSink(publish))
|
||||
run_spec.max_iterations = 10
|
||||
run_spec.tools.prepare_call.return_value = (None, {}, None)
|
||||
run_spec.tools.execute = AsyncMock(return_value="ok")
|
||||
result = await AgentRunner().run(run_spec)
|
||||
completed = [e for e in events if isinstance(e, ModelRequestEvent) and e.phase == "completed"]
|
||||
assert len(completed) == 10
|
||||
assert len(completed[-1].round_usages) == 8
|
||||
assert completed[-1].usage == result.usage
|
||||
assert len(result.round_usages) == 10
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("response", [LLMResponse(content="error", finish_reason="error"), RuntimeError("failure")])
|
||||
async def test_request_failure_has_one_terminal_event(response):
|
||||
events = []
|
||||
|
||||
async def publish(event):
|
||||
events.append(event)
|
||||
|
||||
provider = MagicMock()
|
||||
provider.chat_stream_with_retry = AsyncMock(side_effect=[response])
|
||||
expected = pytest.raises(RuntimeError, match="failure") if isinstance(response, RuntimeError) else nullcontext()
|
||||
with expected:
|
||||
await AgentRunner().run(spec(provider, EventSink(publish)))
|
||||
requests = [e for e in events if isinstance(e, ModelRequestEvent)]
|
||||
assert [e.phase for e in requests] == ["started", "failed"]
|
||||
assert requests[-1].usage is None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_tool_cancellation_closes_started_call_without_masking_cancel():
|
||||
emitted = []
|
||||
entered = asyncio.Event()
|
||||
tools = MagicMock()
|
||||
tools.prepare_call.return_value = (None, {}, None)
|
||||
|
||||
async def execute(*args):
|
||||
entered.set()
|
||||
await asyncio.Event().wait()
|
||||
|
||||
tools.execute = execute
|
||||
|
||||
async def publish(event):
|
||||
emitted.extend(event.tool_events or [])
|
||||
if event.tool_events and event.tool_events[0]["phase"] == "error":
|
||||
raise RuntimeError("notification failure must not replace cancellation")
|
||||
|
||||
task = asyncio.create_task(execute_tool_calls(
|
||||
tools, [ToolCallRequest("blocked", "blocked", {})], concurrent=False,
|
||||
external_lookup_counts={}, workspace_violation_counts={},
|
||||
hook=AgentProgressHook(EventSink(publish)), context=AgentHookContext(0, []),
|
||||
))
|
||||
await asyncio.wait_for(entered.wait(), 2)
|
||||
task.cancel()
|
||||
with pytest.raises(asyncio.CancelledError):
|
||||
await task
|
||||
assert [event["phase"] for event in emitted] == ["start", "error"]
|
||||
|
||||
|
||||
def test_model_requests_are_optional_for_non_webui_channels():
|
||||
from nanobot.bus.notification_delivery import notification_is_deliverable
|
||||
|
||||
for channel in ("telegram", "slack", "cli", "discord"):
|
||||
assert not notification_is_deliverable(ModelRequestEvent, channel=channel, publish_lifecycle=True)
|
||||
assert notification_is_deliverable(ModelRequestEvent, channel="websocket", publish_lifecycle=True)
|
||||
@@ -8,6 +8,7 @@ from agent.runner_helpers import make_run_spec
|
||||
from nanobot.agent.context import TranscriptInput
|
||||
from nanobot.agent.context_governance import ContextWindowExceededError
|
||||
from nanobot.config.schema import AgentDefaults
|
||||
from nanobot.events import EventSink, ModelRequestEvent
|
||||
from nanobot.providers.base import (
|
||||
LLMProvider,
|
||||
LLMResponse,
|
||||
@@ -609,6 +610,7 @@ async def test_runner_returns_max_iterations_fallback():
|
||||
async def test_runner_uses_no_tools_finalization_after_max_iterations():
|
||||
from nanobot.agent.runner import AgentRunner
|
||||
|
||||
publish = AsyncMock()
|
||||
provider = MagicMock(spec=LLMProvider)
|
||||
calls: list[dict] = []
|
||||
|
||||
@@ -644,6 +646,7 @@ async def test_runner_uses_no_tools_finalization_after_max_iterations():
|
||||
model="test-model",
|
||||
max_iterations=2,
|
||||
max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,
|
||||
events=EventSink(publish),
|
||||
))
|
||||
|
||||
assert result.stop_reason == "max_iterations"
|
||||
@@ -664,6 +667,10 @@ async def test_runner_uses_no_tools_finalization_after_max_iterations():
|
||||
(1, 1),
|
||||
(10, 7),
|
||||
]
|
||||
completed = [call.args[0] for call in publish.await_args_list
|
||||
if isinstance(call.args[0], ModelRequestEvent) and call.args[0].phase == "completed"]
|
||||
assert completed[-1].round_usages == tuple(result.round_usages)
|
||||
assert completed[-1].usage == result.usage
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -671,6 +678,7 @@ async def test_runner_accounts_for_malformed_retry_and_no_tools_recovery():
|
||||
from nanobot.agent.hook import AgentHook
|
||||
from nanobot.agent.runner import AgentRunner
|
||||
|
||||
publish = AsyncMock()
|
||||
provider = MagicMock(spec=LLMProvider)
|
||||
calls: list[dict] = []
|
||||
|
||||
@@ -703,6 +711,7 @@ async def test_runner_accounts_for_malformed_retry_and_no_tools_recovery():
|
||||
max_iterations=1,
|
||||
max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,
|
||||
hook=hook,
|
||||
events=EventSink(publish),
|
||||
))
|
||||
|
||||
assert result.final_content == "recovered answer"
|
||||
@@ -722,6 +731,11 @@ async def test_runner_accounts_for_malformed_retry_and_no_tools_recovery():
|
||||
assert result.usage is not None
|
||||
assert (result.usage.input_tokens, result.usage.output_tokens) == (60, 6)
|
||||
assert [(item.input_tokens, item.output_tokens) for item in result.round_usages] == [(60, 6)]
|
||||
completed = [call.args[0] for call in publish.await_args_list
|
||||
if isinstance(call.args[0], ModelRequestEvent) and call.args[0].phase == "completed"]
|
||||
assert [len(event.round_usages) for event in completed] == [1, 1, 1]
|
||||
assert completed[-1].round_usages == tuple(result.round_usages)
|
||||
assert completed[-1].usage == result.usage
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -766,6 +780,7 @@ async def test_runner_replaces_empty_tool_result_with_marker():
|
||||
async def test_runner_retries_empty_final_response_with_summary_prompt():
|
||||
from nanobot.agent.runner import AgentRunner
|
||||
|
||||
publish = AsyncMock()
|
||||
provider = MagicMock(spec=LLMProvider)
|
||||
calls: list[dict] = []
|
||||
|
||||
@@ -794,6 +809,7 @@ async def test_runner_retries_empty_final_response_with_summary_prompt():
|
||||
model="test-model",
|
||||
max_iterations=3,
|
||||
max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,
|
||||
events=EventSink(publish),
|
||||
))
|
||||
|
||||
assert result.final_content == "final answer"
|
||||
@@ -809,6 +825,10 @@ async def test_runner_retries_empty_final_response_with_summary_prompt():
|
||||
(5, 1),
|
||||
(3, 7),
|
||||
]
|
||||
completed = [call.args[0] for call in publish.await_args_list
|
||||
if isinstance(call.args[0], ModelRequestEvent) and call.args[0].phase == "completed"]
|
||||
assert completed[-1].round_usages == tuple(result.round_usages)
|
||||
assert completed[-1].usage == result.usage
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -1190,7 +1210,7 @@ async def test_runner_carries_retry_notifications_in_provider_context():
|
||||
assert "on_retry_wait" not in captured
|
||||
event = RetryWaitEvent("waiting")
|
||||
await captured["provider_context"].events.emit(event)
|
||||
retry_wait_cb.assert_awaited_once_with(event)
|
||||
retry_wait_cb.assert_any_await(event)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
|
||||
@@ -71,7 +71,8 @@ async def test_tool_execution_does_not_duplicate_existing_error_hint():
|
||||
execute=AsyncMock(return_value=ToolResult.error("Error: boom" + error_hint)),
|
||||
)
|
||||
|
||||
results, events = await execute_tool_calls(
|
||||
settled = []
|
||||
await execute_tool_calls(
|
||||
tools,
|
||||
[ToolCallRequest(id="call_1", name="list_dir", arguments={})],
|
||||
concurrent=False,
|
||||
@@ -79,11 +80,13 @@ async def test_tool_execution_does_not_duplicate_existing_error_hint():
|
||||
workspace_violation_counts={},
|
||||
hook=AgentHook(),
|
||||
context=AgentHookContext(iteration=0, messages=[]),
|
||||
on_settled=AsyncMock(side_effect=settled.extend),
|
||||
)
|
||||
|
||||
assert results == ["Error: boom" + error_hint]
|
||||
assert results[0].count(error_hint) == 1
|
||||
assert events[0]["status"] == "error"
|
||||
[completed] = settled
|
||||
assert completed.result == "Error: boom" + error_hint
|
||||
assert completed.result.count(error_hint) == 1
|
||||
assert completed.event["status"] == "error"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
|
||||
@@ -147,11 +147,13 @@ async def test_only_repeat_reads_scan_model_results_once_per_batch(tmp_path, ope
|
||||
if operation == "repeat_batch":
|
||||
calls.append(ToolCallRequest(id="batch-2", name=name, arguments=arguments))
|
||||
|
||||
results, _ = await execute_tool_calls(
|
||||
settled = []
|
||||
await execute_tool_calls(
|
||||
tools, calls, concurrent=True, external_lookup_counts={}, workspace_violation_counts={},
|
||||
hook=AgentHook(), context=AgentHookContext(iteration=0, messages=[]),
|
||||
model_messages=messages,
|
||||
model_messages=messages, on_settled=AsyncMock(side_effect=settled.extend),
|
||||
)
|
||||
results = [completed.result for completed in settled]
|
||||
|
||||
if operation == "repeat_batch":
|
||||
assert results == ["[File unchanged since last read: data.txt]"] * 2
|
||||
@@ -176,18 +178,20 @@ async def test_failed_file_read_restores_context(tmp_path, monkeypatch, error):
|
||||
raise error("read interrupted")
|
||||
|
||||
monkeypatch.setattr(tool, "execute", fail)
|
||||
settled = []
|
||||
request = execute_tool_calls(
|
||||
tools, [ToolCallRequest(id="failed-read", name="read_file", arguments={"path": "data.txt"})],
|
||||
concurrent=False, external_lookup_counts={}, workspace_violation_counts={},
|
||||
hook=AgentHook(), context=AgentHookContext(iteration=0, messages=[]),
|
||||
model_messages=first.messages,
|
||||
model_messages=first.messages, on_settled=AsyncMock(side_effect=settled.extend),
|
||||
)
|
||||
if error is asyncio.CancelledError:
|
||||
with pytest.raises(asyncio.CancelledError):
|
||||
await request
|
||||
else:
|
||||
results, _ = await request
|
||||
assert results[0].startswith("Error: RuntimeError: read interrupted")
|
||||
await request
|
||||
[completed] = settled
|
||||
assert completed.result.startswith("Error: RuntimeError: read interrupted")
|
||||
|
||||
monkeypatch.setattr(tool, "execute", original_execute)
|
||||
assert await tools.execute("read_file", {"path": "data.txt"}) == contents
|
||||
|
||||
@@ -97,7 +97,7 @@ async def test_provider_can_emit_without_an_event_specific_runner_callback():
|
||||
initial_messages=[{"role": "user", "content": "hello"}],
|
||||
events=EventSink(observe),
|
||||
))
|
||||
assert received == [event]
|
||||
assert received.count(event) == 1
|
||||
|
||||
|
||||
async def test_runner_propagates_context_governance_failure():
|
||||
@@ -347,7 +347,8 @@ async def test_native_compaction_uses_provider_request_boundary(
|
||||
compaction_events: list[ContextCompactionEvent] = []
|
||||
|
||||
async def observe_compaction(event: ContextCompactionEvent) -> None:
|
||||
compaction_events.append(event)
|
||||
if isinstance(event, ContextCompactionEvent):
|
||||
compaction_events.append(event)
|
||||
|
||||
result = await AgentRunner().run(make_run_spec(
|
||||
provider,
|
||||
@@ -530,7 +531,8 @@ async def test_repeated_pressure_advances_summary_boundary(monkeypatch):
|
||||
compaction_events: list[ContextCompactionEvent] = []
|
||||
|
||||
async def observe_compaction(event: ContextCompactionEvent) -> None:
|
||||
compaction_events.append(event)
|
||||
if isinstance(event, ContextCompactionEvent):
|
||||
compaction_events.append(event)
|
||||
|
||||
result = await AgentRunner().run(make_run_spec(
|
||||
provider,
|
||||
|
||||
@@ -7,6 +7,7 @@ import pytest
|
||||
|
||||
from agent.runner_helpers import make_run_spec
|
||||
from nanobot.config.schema import AgentDefaults
|
||||
from nanobot.events import EventSink, ModelRequestEvent
|
||||
from nanobot.providers.base import LLMProvider, LLMResponse, LLMUsage, ToolCallRequest
|
||||
|
||||
_MAX_TOOL_RESULT_CHARS = AgentDefaults().max_tool_result_chars
|
||||
@@ -147,13 +148,14 @@ async def test_runner_measures_stream_generation_without_time_to_first_token():
|
||||
from nanobot.agent.runner import AgentRunner
|
||||
|
||||
provider = MagicMock(spec=LLMProvider)
|
||||
publish = AsyncMock()
|
||||
|
||||
async def chat_stream_with_retry(*, on_content_delta, **kwargs):
|
||||
await on_content_delta("he")
|
||||
await on_content_delta("llo")
|
||||
return LLMResponse(
|
||||
content="hello",
|
||||
usage=LLMUsage.reported(input_tokens=100, output_tokens=12),
|
||||
usage=LLMUsage.reported(input_tokens=100, output_tokens=12, cache_read_tokens=4),
|
||||
)
|
||||
|
||||
provider.chat_stream_with_retry = chat_stream_with_retry
|
||||
@@ -177,6 +179,7 @@ async def test_runner_measures_stream_generation_without_time_to_first_token():
|
||||
max_iterations=1,
|
||||
max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,
|
||||
hook=StreamingHook(),
|
||||
events=EventSink(publish),
|
||||
))
|
||||
|
||||
assert result.usage is not None
|
||||
@@ -184,6 +187,11 @@ async def test_runner_measures_stream_generation_without_time_to_first_token():
|
||||
assert result.usage.measured_output_tokens == 12
|
||||
assert result.usage.ttft_ms == 200
|
||||
assert result.usage.timed_requests == 1
|
||||
assert result.usage.cache_read_tokens == 4
|
||||
[completed] = [call.args[0] for call in publish.await_args_list
|
||||
if isinstance(call.args[0], ModelRequestEvent) and call.args[0].phase == "completed"]
|
||||
assert completed.usage == result.usage
|
||||
assert completed.round_usages == tuple(result.round_usages)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import asyncio
|
||||
from unittest.mock import AsyncMock, MagicMock
|
||||
|
||||
import pytest
|
||||
@@ -175,12 +176,172 @@ async def test_batched_file_reads_keep_each_call_and_complete_arguments() -> Non
|
||||
))
|
||||
|
||||
assert result.final_content == "Done"
|
||||
assert [(content, hint) for content, hint, _events in progress] == [("", True), ("", False)]
|
||||
for _content, _hint, events in progress:
|
||||
assert len(progress) == 4
|
||||
for phase, hint in (("start", True), ("end", False)):
|
||||
events = [item for content, is_hint, items in progress if is_hint == hint for item in items]
|
||||
assert [(item["call_id"], item["name"], item["arguments"]) for item in events] == [
|
||||
(call.id, call.name, call.arguments) for call in calls
|
||||
]
|
||||
assert [item["phase"] for item in progress[0][2]] == ["start", "start"]
|
||||
assert [(item["phase"], item["result"]) for item in progress[1][2]] == [
|
||||
("end", "file contents"), ("end", "file contents"),
|
||||
]
|
||||
assert [item["phase"] for item in events] == [phase, phase]
|
||||
if phase == "end":
|
||||
assert [item["result"] for item in events] == ["file contents", "file contents"]
|
||||
|
||||
|
||||
def _notification_run_spec(execute, on_progress, calls, checkpoints):
|
||||
provider = MagicMock()
|
||||
provider.chat_stream_with_retry = AsyncMock(side_effect=[
|
||||
LLMResponse(content=None, tool_calls=calls),
|
||||
LLMResponse(content="Done"),
|
||||
])
|
||||
tools = MagicMock()
|
||||
tools.get_definitions.return_value = []
|
||||
tools.prepare_call.return_value = (None, {}, None)
|
||||
tools.execute = execute
|
||||
|
||||
async def checkpoint(payload):
|
||||
checkpoints.append(payload)
|
||||
|
||||
return make_run_spec(
|
||||
provider, initial_messages=[], tools=tools, model="test-model",
|
||||
max_iterations=2, max_tool_result_chars=_DEFAULTS.max_tool_result_chars,
|
||||
concurrent_tools=True, hook=AgentProgressHook(output_events(on_progress=on_progress)),
|
||||
checkpoint_callback=checkpoint,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("failure_phase", ["start", "end"])
|
||||
async def test_tool_notification_failure_settles_results_and_cancels_siblings(failure_phase):
|
||||
entered = asyncio.Event()
|
||||
release = asyncio.Event()
|
||||
stopped = asyncio.Event()
|
||||
effects = []
|
||||
checkpoints = []
|
||||
error = BrokenPipeError("progress consumer closed")
|
||||
|
||||
async def execute(name, arguments):
|
||||
if name == "slow":
|
||||
entered.set()
|
||||
try:
|
||||
await release.wait()
|
||||
effects.append("slow")
|
||||
return "slow result"
|
||||
finally:
|
||||
stopped.set()
|
||||
effects.append("fast")
|
||||
return "fast result"
|
||||
|
||||
async def progress(content, *, tool_events=None, **kwargs):
|
||||
if any(event["call_id"] == "fast" and event["phase"] == failure_phase
|
||||
for event in tool_events or []):
|
||||
await entered.wait()
|
||||
raise error
|
||||
|
||||
task = asyncio.create_task(AgentRunner().run(_notification_run_spec(
|
||||
execute, progress,
|
||||
[ToolCallRequest("slow", "slow", {}), ToolCallRequest("fast", "fast", {})],
|
||||
checkpoints,
|
||||
)))
|
||||
try:
|
||||
with pytest.raises(BrokenPipeError) as raised:
|
||||
await asyncio.wait_for(task, 2)
|
||||
assert raised.value is error
|
||||
assert stopped.is_set()
|
||||
assert effects == (["fast"] if failure_phase == "end" else [])
|
||||
if failure_phase == "end":
|
||||
checkpoint = checkpoints[-1]
|
||||
assert checkpoint["phase"] == "tools_completed"
|
||||
slow, fast = checkpoint["completed_tool_results"]
|
||||
assert (fast["tool_call_id"], fast["content"]) == ("fast", "fast result")
|
||||
assert slow["tool_call_id"] == "slow"
|
||||
assert slow["_recovery_interrupted"] is True
|
||||
assert "outcome is unknown" in slow["content"]
|
||||
assert checkpoint["pending_tool_calls"] == []
|
||||
from nanobot.session.recovery import runtime_checkpoint_is_well_formed
|
||||
|
||||
assert runtime_checkpoint_is_well_formed(checkpoint)
|
||||
else:
|
||||
assert [checkpoint["phase"] for checkpoint in checkpoints] == ["awaiting_tools"]
|
||||
finally:
|
||||
release.set()
|
||||
await asyncio.gather(task, return_exceptions=True)
|
||||
await asyncio.wait_for(stopped.wait(), 2)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_tool_completion_notification_error_preserves_completed_checkpoint():
|
||||
checkpoints = []
|
||||
error = BrokenPipeError("progress consumer closed")
|
||||
|
||||
async def progress(content, *, tool_events=None, **kwargs):
|
||||
if any(event["phase"] == "end" for event in tool_events or []):
|
||||
raise error
|
||||
|
||||
with pytest.raises(BrokenPipeError) as raised:
|
||||
await AgentRunner().run(_notification_run_spec(
|
||||
AsyncMock(return_value="completed effect"), progress,
|
||||
[ToolCallRequest("fast", "fast", {})], checkpoints,
|
||||
))
|
||||
assert raised.value is error
|
||||
assert [checkpoint["phase"] for checkpoint in checkpoints] == ["awaiting_tools", "tools_completed"]
|
||||
assert checkpoints[-1]["completed_tool_results"][0]["content"] == "completed effect"
|
||||
assert checkpoints[-1]["pending_tool_calls"] == []
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("cancel_during", ["start", "execution", "end"])
|
||||
async def test_tool_cancellation_does_not_wait_for_blocked_progress(cancel_during):
|
||||
queue = asyncio.Queue(maxsize=1)
|
||||
if cancel_during == "start":
|
||||
queue.put_nowait([])
|
||||
entered = asyncio.Event()
|
||||
release = asyncio.Event()
|
||||
stopped = asyncio.Event()
|
||||
checkpoints = []
|
||||
effects = []
|
||||
notifications = set()
|
||||
|
||||
async def execute(name, arguments):
|
||||
if cancel_during == "execution":
|
||||
entered.set()
|
||||
try:
|
||||
await release.wait()
|
||||
finally:
|
||||
stopped.set()
|
||||
effects.append(name)
|
||||
return "completed effect"
|
||||
|
||||
async def progress(content, *, tool_events=None, **kwargs):
|
||||
if tool_events:
|
||||
notification = asyncio.current_task()
|
||||
notifications.add(notification)
|
||||
try:
|
||||
if any(event["phase"] == cancel_during for event in tool_events):
|
||||
entered.set()
|
||||
await queue.put(tool_events)
|
||||
finally:
|
||||
notifications.remove(notification)
|
||||
|
||||
task = asyncio.create_task(AgentRunner().run(_notification_run_spec(
|
||||
execute, progress, [ToolCallRequest("tool", "tool", {})], checkpoints,
|
||||
)))
|
||||
try:
|
||||
await asyncio.wait_for(entered.wait(), 2)
|
||||
task.cancel()
|
||||
done, _ = await asyncio.wait({task}, timeout=1)
|
||||
assert done, "cancellation must settle without a second cancel or queue consumer"
|
||||
with pytest.raises(asyncio.CancelledError):
|
||||
await task
|
||||
assert not notifications
|
||||
assert effects == (["tool"] if cancel_during == "end" else [])
|
||||
if cancel_during == "end":
|
||||
assert checkpoints[-1]["phase"] == "tools_completed"
|
||||
assert checkpoints[-1]["completed_tool_results"][0]["content"] == "completed effect"
|
||||
elif cancel_during == "execution":
|
||||
assert stopped.is_set()
|
||||
finally:
|
||||
# Keep the failure reproduction bounded even with the old shielded send.
|
||||
if not queue.empty():
|
||||
queue.get_nowait()
|
||||
release.set()
|
||||
await asyncio.gather(task, return_exceptions=True)
|
||||
@@ -42,6 +42,7 @@ async def test_tool_log_privacy_preserves_user_visible_progress(ephemeral, hoste
|
||||
})
|
||||
else:
|
||||
await hook.before_execute_tools(context)
|
||||
await hook.on_tool_execution_event(context)
|
||||
finally:
|
||||
logger.remove(sink)
|
||||
|
||||
|
||||
@@ -470,6 +470,7 @@ async def test_runner_executes_inline_spawn_batch_concurrently(tmp_path):
|
||||
),
|
||||
]
|
||||
|
||||
settled = []
|
||||
with request_context(RequestContext(
|
||||
channel="test",
|
||||
chat_id="c1",
|
||||
@@ -484,14 +485,15 @@ async def test_runner_executes_inline_spawn_batch_concurrently(tmp_path):
|
||||
workspace_violation_counts={},
|
||||
hook=AgentHook(),
|
||||
context=AgentHookContext(iteration=0, messages=[], session_key="test:c1"),
|
||||
on_settled=AsyncMock(side_effect=settled.extend),
|
||||
))
|
||||
await asyncio.wait_for(both_entered.wait(), timeout=1.0)
|
||||
release.set()
|
||||
results, events = await execution
|
||||
await execution
|
||||
|
||||
assert set(entered) == {"first", "second"}
|
||||
assert results == ["first", "second"]
|
||||
assert [event["status"] for event in events] == ["ok", "ok"]
|
||||
assert [completed.result for completed in settled] == ["first", "second"]
|
||||
assert [completed.event["status"] for completed in settled] == ["ok", "ok"]
|
||||
assert manager._running_tasks == {}
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user