ci: reduce Python test overhead and Windows latency (#6357)
* test: merge overlapping semantic contract coverage Consolidate the six confirmed NAN-310 overlap groups while preserving replay, usage, generation kwargs, archive metadata, inspect fields, and subagent crash/redelivery assertions. * test: lighten history seeds and layer runner progress rules * ci: defer test storage setup and record phase timings Close each listener-owned binary bridge before waiting for its TCP server; retain active upload and undecided-connection regressions. Avoid consuming readiness twice and run the repository import scan once in its static gate. NAN-310. * test: scope filesystem mocks and observe consumed socket prefixes * test: publish subprocess readiness files atomically * ci: isolate external tool discovery and use three Windows workers
This commit is contained in:
1 parent
743c51e81f
commit
f284749d2f
28 files changed
+518
-448
No files matched your search
@@ -467,11 +467,13 @@ class TestAutoCompact:
|
||||
await loop.aclose()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_auto_compact_stores_summary(self, tmp_path):
|
||||
"""_archive should store the summary in _summaries."""
|
||||
async def test_auto_compact_stores_summary_in_cache_and_metadata(self, tmp_path):
|
||||
"""_archive caches and persists the summary without exposing archived history."""
|
||||
loop = _make_loop(tmp_path, session_ttl_minutes=15)
|
||||
session = loop.sessions.get_or_create("cli:test")
|
||||
_add_turns(session, 6, prefix="hello")
|
||||
last_active = datetime.now() - timedelta(minutes=20)
|
||||
session.updated_at = last_active
|
||||
loop.sessions.save(session)
|
||||
|
||||
loop.consolidator.compact_idle_session = _make_fake_compact(
|
||||
@@ -483,7 +485,12 @@ class TestAutoCompact:
|
||||
entry = loop.auto_compact._summaries.get("cli:test")
|
||||
assert entry is not None
|
||||
assert entry["text"] == "User said hello."
|
||||
loop.sessions.invalidate("cli:test")
|
||||
session_after = loop.sessions.get_or_create("cli:test")
|
||||
meta = session_after.metadata.get("_last_summary")
|
||||
assert meta is not None
|
||||
assert meta["text"] == "User said hello."
|
||||
assert meta["last_active"] == last_active.isoformat()
|
||||
assert len(session_after.messages) == 13
|
||||
assert session_after.get_history(max_messages=12) == []
|
||||
await loop.aclose()
|
||||
@@ -1238,29 +1245,6 @@ class TestProactiveAutoCompact:
|
||||
class TestSummaryPersistence:
|
||||
"""Test that summary survives restart via session metadata."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_summary_persisted_in_session_metadata(self, tmp_path):
|
||||
"""After archive, _last_summary should be in session metadata."""
|
||||
loop = _make_loop(tmp_path, session_ttl_minutes=15)
|
||||
session = loop.sessions.get_or_create("cli:test")
|
||||
_add_turns(session, 6, prefix="hello")
|
||||
session.updated_at = datetime.now() - timedelta(minutes=20)
|
||||
loop.sessions.save(session)
|
||||
|
||||
loop.consolidator.compact_idle_session = _make_fake_compact(
|
||||
loop, summary="User said hello.",
|
||||
)
|
||||
|
||||
await loop.auto_compact._archive("cli:test", runtime=loop.llm_runtime())
|
||||
|
||||
# Summary should be persisted in session metadata
|
||||
session_after = loop.sessions.get_or_create("cli:test")
|
||||
meta = session_after.metadata.get("_last_summary")
|
||||
assert meta is not None
|
||||
assert meta["text"] == "User said hello."
|
||||
assert "last_active" in meta
|
||||
await loop.aclose()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_summary_recovered_after_restart(self, tmp_path):
|
||||
"""Summary should be recovered from metadata when _summaries is empty (simulates restart)."""
|
||||
|
||||
@@ -57,71 +57,7 @@ def _attach_webui_runtime_events(loop: AgentLoop, bus: MessageBus) -> None:
|
||||
|
||||
|
||||
class TestToolEventProgress:
|
||||
"""_run_agent_loop emits structured tool_events via on_progress."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_start_and_finish_events_emitted(self, tmp_path: Path) -> None:
|
||||
loop = _make_loop(tmp_path)
|
||||
tool_call = ToolCallRequest(id="call1", name="custom_tool", arguments={"path": "foo.txt"})
|
||||
calls = iter([
|
||||
LLMResponse(content="Visible", tool_calls=[tool_call]),
|
||||
LLMResponse(content="Done", tool_calls=[]),
|
||||
])
|
||||
loop.provider.chat_stream_with_retry = AsyncMock(side_effect=lambda *a, **kw: next(calls))
|
||||
loop.tools.get_definitions = MagicMock(return_value=[])
|
||||
loop.tools.prepare_call = MagicMock(return_value=(None, {"path": "foo.txt"}, None))
|
||||
loop.tools.execute = AsyncMock(return_value="ok")
|
||||
|
||||
progress: list[tuple[str, bool, list[dict] | None]] = []
|
||||
|
||||
async def on_progress(
|
||||
content: str,
|
||||
*,
|
||||
tool_hint: bool = False,
|
||||
tool_events: list[dict] | None = None,
|
||||
) -> None:
|
||||
progress.append((content, tool_hint, tool_events))
|
||||
|
||||
result = await loop._run_agent_loop(
|
||||
TranscriptInput(history=[], current_message=None),
|
||||
runtime=loop.llm_runtime(),
|
||||
events=output_events(on_progress=on_progress),
|
||||
)
|
||||
|
||||
assert result.final_content == "Done"
|
||||
assert progress == [
|
||||
("Visible", False, None),
|
||||
(
|
||||
'custom_tool("foo.txt")',
|
||||
True,
|
||||
[{
|
||||
"version": 1,
|
||||
"phase": "start",
|
||||
"call_id": "call1",
|
||||
"name": "custom_tool",
|
||||
"arguments": {"path": "foo.txt"},
|
||||
"result": None,
|
||||
"error": None,
|
||||
"files": [],
|
||||
"embeds": [],
|
||||
}],
|
||||
),
|
||||
(
|
||||
"",
|
||||
False,
|
||||
[{
|
||||
"version": 1,
|
||||
"phase": "end",
|
||||
"call_id": "call1",
|
||||
"name": "custom_tool",
|
||||
"arguments": {"path": "foo.txt"},
|
||||
"result": "ok",
|
||||
"error": None,
|
||||
"files": [],
|
||||
"embeds": [],
|
||||
}],
|
||||
),
|
||||
]
|
||||
"""AgentLoop wires tool hooks and turn delivery into progress events."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_write_file_emits_file_edit_progress(self, tmp_path: Path) -> None:
|
||||
@@ -1033,58 +969,6 @@ class TestToolEventProgress:
|
||||
assert isinstance(final[-1].event, StreamedResponseEvent)
|
||||
provider.chat_with_retry.assert_not_awaited()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_streamed_content_is_not_repeated_before_tool_execution(
|
||||
self,
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
"""If content was already streamed, tool setup should not repeat it."""
|
||||
loop = _make_loop(tmp_path)
|
||||
tool_call = ToolCallRequest(id="call1", name="custom_tool", arguments={"path": "foo.txt"})
|
||||
calls = iter([
|
||||
LLMResponse(content="I will inspect it.", tool_calls=[tool_call]),
|
||||
LLMResponse(content="Done", tool_calls=[]),
|
||||
])
|
||||
|
||||
async def chat_stream_with_retry(*, on_content_delta, **kwargs):
|
||||
response = next(calls)
|
||||
if response.tool_calls:
|
||||
await on_content_delta("I will ")
|
||||
await on_content_delta("inspect it.")
|
||||
return response
|
||||
|
||||
loop.provider.chat_stream_with_retry = chat_stream_with_retry
|
||||
loop.provider.chat_with_retry = AsyncMock()
|
||||
loop.tools.get_definitions = MagicMock(return_value=[])
|
||||
loop.tools.prepare_call = MagicMock(return_value=(None, {"path": "foo.txt"}, None))
|
||||
loop.tools.execute = AsyncMock(return_value="ok")
|
||||
|
||||
streamed: list[str] = []
|
||||
progress: list[tuple[str, bool, list[dict] | None]] = []
|
||||
|
||||
async def on_stream(delta: str) -> None:
|
||||
streamed.append(delta)
|
||||
|
||||
async def on_progress(
|
||||
content: str,
|
||||
*,
|
||||
tool_hint: bool = False,
|
||||
tool_events: list[dict] | None = None,
|
||||
) -> None:
|
||||
progress.append((content, tool_hint, tool_events))
|
||||
|
||||
result = await loop._run_agent_loop(
|
||||
TranscriptInput(history=[], current_message=None),
|
||||
runtime=loop.llm_runtime(),
|
||||
events=output_events(on_progress=on_progress, on_stream=on_stream),
|
||||
streaming=True,
|
||||
)
|
||||
|
||||
assert result.final_content == "Done"
|
||||
assert streamed == ["I will", " inspect it."]
|
||||
assert progress[0][0] == 'custom_tool("foo.txt")'
|
||||
assert all(item[0] != "I will inspect it." for item in progress)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_websocket_dispatch_publishes_final_turn_end_marker(self, tmp_path: Path) -> None:
|
||||
bus = MessageBus()
|
||||
|
||||
@@ -1104,39 +1104,6 @@ async def test_subagent_followup_stages_provider_state_before_turn_runs(
|
||||
assert persisted.provider_state.pending_messages[-1]["content"] == "subagent result"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_subagent_followup_state_is_durable_before_prompt_assembly(
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
loop = _make_full_loop(tmp_path)
|
||||
loop.provider.can_resume_conversation_state.return_value = True
|
||||
loop.context.build_system_prompt = MagicMock( # type: ignore[method-assign]
|
||||
side_effect=RuntimeError("prompt boom"),
|
||||
)
|
||||
session = loop.sessions.get_or_create("cli:subagent-prompt-crash")
|
||||
session.provider_state = _provider_state()
|
||||
loop.sessions.save(session)
|
||||
await save_completed_subagent(loop, "sub-1", session.key)
|
||||
|
||||
msg = InboundMessage(
|
||||
channel="system",
|
||||
sender_id="subagent",
|
||||
chat_id="cli:subagent-prompt-crash",
|
||||
content="subagent result",
|
||||
metadata={"subagent_task_id": "sub-1"},
|
||||
)
|
||||
with pytest.raises(RuntimeError, match="prompt boom"):
|
||||
await loop._process_message(msg)
|
||||
|
||||
loop.sessions.invalidate("cli:subagent-prompt-crash")
|
||||
persisted = loop.sessions.get_or_create("cli:subagent-prompt-crash")
|
||||
assert persisted.messages[-1]["content"] == "subagent result"
|
||||
assert persisted.provider_state is not None
|
||||
assert persisted.provider_state.pending_messages[-1]["content"] == (
|
||||
"subagent result"
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_subagent_redelivery_does_not_duplicate_staged_provider_input(
|
||||
tmp_path: Path,
|
||||
@@ -1164,7 +1131,11 @@ async def test_subagent_redelivery_does_not_duplicate_staged_provider_input(
|
||||
|
||||
loop.sessions.invalidate("cli:subagent-redelivery")
|
||||
persisted = loop.sessions.get_or_create("cli:subagent-redelivery")
|
||||
assert persisted.messages[-1]["content"] == "subagent result"
|
||||
assert persisted.provider_state is not None
|
||||
assert persisted.provider_state.pending_messages[-1]["content"] == (
|
||||
"subagent result"
|
||||
)
|
||||
assert [
|
||||
message.get("content")
|
||||
for message in persisted.provider_state.pending_messages
|
||||
|
||||
@@ -1210,37 +1210,8 @@ async def test_runner_carries_retry_notifications_in_provider_context():
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_runner_passes_temperature_to_provider():
|
||||
"""temperature from AgentRunSpec should reach provider.chat_stream_with_retry."""
|
||||
from nanobot.agent.runner import AgentRunner
|
||||
|
||||
captured: dict = {}
|
||||
|
||||
async def chat_stream_with_retry(**kwargs):
|
||||
captured.update(kwargs)
|
||||
return LLMResponse(content="done", tool_calls=[], usage=None)
|
||||
|
||||
provider = MagicMock(spec=LLMProvider)
|
||||
provider.chat_stream_with_retry = chat_stream_with_retry
|
||||
tools = MagicMock()
|
||||
tools.get_definitions.return_value = []
|
||||
|
||||
runner = AgentRunner()
|
||||
await runner.run(make_run_spec(provider,
|
||||
initial_messages=[{"role": "user", "content": "hi"}],
|
||||
tools=tools,
|
||||
model="test-model",
|
||||
max_iterations=1,
|
||||
max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,
|
||||
temperature=0.7,
|
||||
))
|
||||
|
||||
assert captured["temperature"] == 0.7
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_runner_passes_max_tokens_to_provider():
|
||||
"""max_tokens from AgentRunSpec should reach provider.chat_stream_with_retry."""
|
||||
async def test_runner_passes_generation_settings_to_provider():
|
||||
"""Non-default generation settings should reach provider.chat_stream_with_retry."""
|
||||
from nanobot.agent.runner import AgentRunner
|
||||
|
||||
captured: dict = {}
|
||||
@@ -1261,36 +1232,11 @@ async def test_runner_passes_max_tokens_to_provider():
|
||||
model="test-model",
|
||||
max_iterations=1,
|
||||
max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,
|
||||
temperature=0.3,
|
||||
max_tokens=8192,
|
||||
))
|
||||
|
||||
assert captured["max_tokens"] == 8192
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_runner_passes_reasoning_effort_to_provider():
|
||||
"""reasoning_effort from AgentRunSpec should reach provider.chat_stream_with_retry."""
|
||||
from nanobot.agent.runner import AgentRunner
|
||||
|
||||
captured: dict = {}
|
||||
|
||||
async def chat_stream_with_retry(**kwargs):
|
||||
captured.update(kwargs)
|
||||
return LLMResponse(content="done", tool_calls=[], usage=None)
|
||||
|
||||
provider = MagicMock(spec=LLMProvider)
|
||||
provider.chat_stream_with_retry = chat_stream_with_retry
|
||||
tools = MagicMock()
|
||||
tools.get_definitions.return_value = []
|
||||
|
||||
runner = AgentRunner()
|
||||
await runner.run(make_run_spec(provider,
|
||||
initial_messages=[{"role": "user", "content": "hi"}],
|
||||
tools=tools,
|
||||
model="test-model",
|
||||
max_iterations=1,
|
||||
max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,
|
||||
reasoning_effort="high",
|
||||
))
|
||||
|
||||
assert captured["temperature"] == 0.3
|
||||
assert captured["max_tokens"] == 8192
|
||||
assert captured["reasoning_effort"] == "high"
|
||||
@@ -0,0 +1,143 @@
|
||||
"""Runner-owned tool progress rules, without session or channel setup."""
|
||||
|
||||
from unittest.mock import AsyncMock, MagicMock
|
||||
|
||||
import pytest
|
||||
|
||||
from agent.runner_helpers import make_run_spec
|
||||
from nanobot.agent.progress_hook import AgentProgressHook
|
||||
from nanobot.agent.runner import AgentRunner
|
||||
from nanobot.config.schema import AgentDefaults
|
||||
from nanobot.providers.base import LLMResponse, ToolCallRequest
|
||||
from nanobot.utils.progress_events import output_events
|
||||
|
||||
_DEFAULTS = AgentDefaults()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_start_and_finish_events_emitted() -> None:
|
||||
provider = MagicMock()
|
||||
tools = MagicMock()
|
||||
tool_call = ToolCallRequest(id="call1", name="custom_tool", arguments={"path": "foo.txt"})
|
||||
calls = iter([
|
||||
LLMResponse(content="Visible", tool_calls=[tool_call]),
|
||||
LLMResponse(content="Done", tool_calls=[]),
|
||||
])
|
||||
provider.chat_stream_with_retry = AsyncMock(side_effect=lambda *a, **kw: next(calls))
|
||||
tools.get_definitions.return_value = []
|
||||
tools.prepare_call.return_value = (None, {"path": "foo.txt"}, None)
|
||||
tools.execute = AsyncMock(return_value="ok")
|
||||
|
||||
progress: list[tuple[str, bool, list[dict] | None]] = []
|
||||
|
||||
async def on_progress(
|
||||
content: str,
|
||||
*,
|
||||
tool_hint: bool = False,
|
||||
tool_events: list[dict] | None = None,
|
||||
) -> None:
|
||||
progress.append((content, tool_hint, tool_events))
|
||||
|
||||
result = await AgentRunner().run(make_run_spec(
|
||||
provider,
|
||||
initial_messages=[],
|
||||
tools=tools,
|
||||
model="test-model",
|
||||
max_iterations=_DEFAULTS.max_tool_iterations,
|
||||
max_tool_result_chars=_DEFAULTS.max_tool_result_chars,
|
||||
concurrent_tools=True,
|
||||
hook=AgentProgressHook(output_events(on_progress=on_progress)),
|
||||
))
|
||||
|
||||
assert result.final_content == "Done"
|
||||
assert progress == [
|
||||
("Visible", False, None),
|
||||
(
|
||||
'custom_tool("foo.txt")',
|
||||
True,
|
||||
[{
|
||||
"version": 1,
|
||||
"phase": "start",
|
||||
"call_id": "call1",
|
||||
"name": "custom_tool",
|
||||
"arguments": {"path": "foo.txt"},
|
||||
"result": None,
|
||||
"error": None,
|
||||
"files": [],
|
||||
"embeds": [],
|
||||
}],
|
||||
),
|
||||
(
|
||||
"",
|
||||
False,
|
||||
[{
|
||||
"version": 1,
|
||||
"phase": "end",
|
||||
"call_id": "call1",
|
||||
"name": "custom_tool",
|
||||
"arguments": {"path": "foo.txt"},
|
||||
"result": "ok",
|
||||
"error": None,
|
||||
"files": [],
|
||||
"embeds": [],
|
||||
}],
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_streamed_content_is_not_repeated_before_tool_execution() -> None:
|
||||
"""If content was already streamed, tool setup should not repeat it."""
|
||||
provider = MagicMock()
|
||||
tools = MagicMock()
|
||||
tool_call = ToolCallRequest(id="call1", name="custom_tool", arguments={"path": "foo.txt"})
|
||||
calls = iter([
|
||||
LLMResponse(content="I will inspect it.", tool_calls=[tool_call]),
|
||||
LLMResponse(content="Done", tool_calls=[]),
|
||||
])
|
||||
|
||||
async def chat_stream_with_retry(*, on_content_delta, **kwargs):
|
||||
response = next(calls)
|
||||
if response.tool_calls:
|
||||
await on_content_delta("I will ")
|
||||
await on_content_delta("inspect it.")
|
||||
return response
|
||||
|
||||
provider.chat_stream_with_retry = chat_stream_with_retry
|
||||
provider.chat_with_retry = AsyncMock()
|
||||
tools.get_definitions.return_value = []
|
||||
tools.prepare_call.return_value = (None, {"path": "foo.txt"}, None)
|
||||
tools.execute = AsyncMock(return_value="ok")
|
||||
|
||||
streamed: list[str] = []
|
||||
progress: list[tuple[str, bool, list[dict] | None]] = []
|
||||
|
||||
async def on_stream(delta: str) -> None:
|
||||
streamed.append(delta)
|
||||
|
||||
async def on_progress(
|
||||
content: str,
|
||||
*,
|
||||
tool_hint: bool = False,
|
||||
tool_events: list[dict] | None = None,
|
||||
) -> None:
|
||||
progress.append((content, tool_hint, tool_events))
|
||||
|
||||
result = await AgentRunner().run(make_run_spec(
|
||||
provider,
|
||||
initial_messages=[],
|
||||
tools=tools,
|
||||
model="test-model",
|
||||
max_iterations=_DEFAULTS.max_tool_iterations,
|
||||
max_tool_result_chars=_DEFAULTS.max_tool_result_chars,
|
||||
concurrent_tools=True,
|
||||
hook=AgentProgressHook(
|
||||
output_events(on_progress=on_progress, on_stream=on_stream),
|
||||
streaming=True,
|
||||
),
|
||||
))
|
||||
|
||||
assert result.final_content == "Done"
|
||||
assert streamed == ["I will", " inspect it."]
|
||||
assert progress[0][0] == 'custom_tool("foo.txt")'
|
||||
assert all(item[0] != "I will inspect it." for item in progress)
|
||||
@@ -96,56 +96,6 @@ class _BlockingReasoningEndHook(_LifecycleRecordingHook):
|
||||
await super().emit_reasoning_end()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_runner_preserves_reasoning_fields_in_assistant_history():
|
||||
"""Reasoning fields ride along on the persisted assistant message so
|
||||
follow-up provider calls retain the model's prior thinking context."""
|
||||
from nanobot.agent.runner import AgentRunner
|
||||
|
||||
provider = MagicMock()
|
||||
captured_second_call: list[dict] = []
|
||||
call_count = {"n": 0}
|
||||
|
||||
async def chat_stream_with_retry(*, messages, **kwargs):
|
||||
call_count["n"] += 1
|
||||
if call_count["n"] == 1:
|
||||
return LLMResponse(
|
||||
content="thinking",
|
||||
tool_calls=[ToolCallRequest(id="call_1", name="list_dir", arguments={"path": "."})],
|
||||
reasoning_content="hidden reasoning",
|
||||
thinking_blocks=[{"type": "thinking", "thinking": "step"}],
|
||||
usage=LLMUsage.reported(input_tokens=5, output_tokens=3),
|
||||
)
|
||||
captured_second_call[:] = messages
|
||||
return LLMResponse(content="done", tool_calls=[], usage=None)
|
||||
|
||||
provider.chat_stream_with_retry = chat_stream_with_retry
|
||||
tools = MagicMock()
|
||||
tools.get_definitions.return_value = []
|
||||
tools.execute = AsyncMock(return_value="tool result")
|
||||
|
||||
runner = AgentRunner()
|
||||
result = await runner.run(make_run_spec(provider,
|
||||
initial_messages=[
|
||||
{"role": "system", "content": "system"},
|
||||
{"role": "user", "content": "do task"},
|
||||
],
|
||||
tools=tools,
|
||||
model="test-model",
|
||||
max_iterations=3,
|
||||
max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,
|
||||
))
|
||||
|
||||
assert result.final_content == "done"
|
||||
assistant_messages = [
|
||||
msg for msg in captured_second_call
|
||||
if msg.get("role") == "assistant" and msg.get("tool_calls")
|
||||
]
|
||||
assert len(assistant_messages) == 1
|
||||
assert assistant_messages[0]["reasoning_content"] == "hidden reasoning"
|
||||
assert assistant_messages[0]["thinking_blocks"] == [{"type": "thinking", "thinking": "step"}]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_runner_emits_anthropic_thinking_blocks():
|
||||
from nanobot.agent.runner import AgentRunner
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
import sys
|
||||
from importlib.metadata import entry_points
|
||||
from types import ModuleType
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
@@ -8,10 +11,8 @@ from nanobot.agent.tools.loader import ToolLoader
|
||||
from nanobot.agent.tools.registry import ToolRegistry, is_tool_error_result
|
||||
|
||||
|
||||
def test_loader_discovers_entry_point_tools():
|
||||
"""Simulate an entry-point plugin being discovered."""
|
||||
mock_ep = MagicMock()
|
||||
mock_ep.name = "my_plugin"
|
||||
def test_loader_discovers_entry_point_tools(tmp_path, monkeypatch):
|
||||
"""Discover a real distribution descriptor in the tool entry-point group."""
|
||||
|
||||
class _FakeTool(Tool):
|
||||
__name__ = "FakeTool"
|
||||
@@ -41,14 +42,25 @@ def test_loader_discovers_entry_point_tools():
|
||||
async def execute(self, **_):
|
||||
return "ok"
|
||||
|
||||
mock_ep.load.return_value = _FakeTool
|
||||
|
||||
with patch("nanobot.agent.tools.loader.entry_points", return_value=[mock_ep]):
|
||||
loader = ToolLoader()
|
||||
discovered = loader._discover_plugins()
|
||||
plugin = ModuleType("test_tool_plugin")
|
||||
monkeypatch.setattr(plugin, "FakeTool", _FakeTool, raising=False)
|
||||
monkeypatch.setitem(sys.modules, plugin.__name__, plugin)
|
||||
distribution = tmp_path / "test_tool_plugin-1.0.dist-info"
|
||||
distribution.mkdir()
|
||||
(distribution / "METADATA").write_text(
|
||||
"Metadata-Version: 2.1\nName: test-tool-plugin\nVersion: 1.0\n", encoding="utf-8",
|
||||
)
|
||||
(distribution / "entry_points.txt").write_text(
|
||||
"[nanobot.tools]\nmy_plugin = test_tool_plugin:FakeTool\n"
|
||||
"[other.tools]\nother_plugin = test_tool_plugin:FakeTool\n", encoding="utf-8",
|
||||
)
|
||||
monkeypatch.syspath_prepend(str(tmp_path))
|
||||
monkeypatch.setattr("nanobot.agent.tools.loader.entry_points", entry_points)
|
||||
discovered = ToolLoader()._discover_plugins()
|
||||
|
||||
assert "my_plugin" in discovered
|
||||
assert discovered["my_plugin"] is _FakeTool
|
||||
assert "other_plugin" not in discovered
|
||||
|
||||
|
||||
def test_loader_skips_abstract_entry_point_tools():
|
||||
|
||||
@@ -80,11 +80,15 @@ def _make_tool(loop=None):
|
||||
class TestInspectSummary:
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_inspect_returns_current_state(self):
|
||||
async def test_inspect_returns_current_state_and_description_keys(self):
|
||||
tool = _make_tool()
|
||||
result = await tool.execute(action="check")
|
||||
assert "max_iterations: 40" in result
|
||||
assert "context_window_tokens: 65536" in result
|
||||
assert "model" in result
|
||||
assert "workspace" in result
|
||||
assert "provider_retry_mode" in result
|
||||
assert "max_tool_result_chars" in result
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_inspect_includes_scratchpad(self):
|
||||
@@ -94,18 +98,6 @@ class TestInspectSummary:
|
||||
result = await tool.execute(action="check")
|
||||
assert "task" in result
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_inspect_summary_shows_all_description_keys(self):
|
||||
"""check without key should show all top-level keys listed in description."""
|
||||
tool = _make_tool()
|
||||
result = await tool.execute(action="check")
|
||||
assert "max_iterations" in result
|
||||
assert "context_window_tokens" in result
|
||||
assert "model" in result
|
||||
assert "workspace" in result
|
||||
assert "provider_retry_mode" in result
|
||||
assert "max_tool_result_chars" in result
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# check — single key (direct)
|
||||
|
||||
@@ -80,21 +80,26 @@ def test_session_tools_do_not_own_runtime_context(tmp_path) -> None:
|
||||
@pytest.mark.asyncio
|
||||
async def test_search_sessions_has_no_hidden_content_scan_cutoff(tmp_path):
|
||||
manager = SessionManager(tmp_path)
|
||||
for index in range(200):
|
||||
# Seed offline on this thread; nested saves share the existing store transaction.
|
||||
with manager._store.transaction():
|
||||
for index in range(200):
|
||||
_save_session(
|
||||
manager,
|
||||
f"websocket:recent-{index:03d}",
|
||||
title=f"Recent {index}",
|
||||
messages=[{"role": "user", "content": "ordinary"}],
|
||||
updated_at=datetime(2025, 1, 1),
|
||||
)
|
||||
_save_session(
|
||||
manager,
|
||||
f"websocket:recent-{index:03d}",
|
||||
title=f"Recent {index}",
|
||||
messages=[{"role": "user", "content": "ordinary"}],
|
||||
updated_at=datetime(2025, 1, 1),
|
||||
"websocket:old-target",
|
||||
title="Old target",
|
||||
messages=[{"role": "user", "content": "needle after two hundred sessions"}],
|
||||
updated_at=datetime(2024, 1, 1),
|
||||
)
|
||||
_save_session(
|
||||
manager,
|
||||
"websocket:old-target",
|
||||
title="Old target",
|
||||
messages=[{"role": "user", "content": "needle after two hundred sessions"}],
|
||||
updated_at=datetime(2024, 1, 1),
|
||||
)
|
||||
persisted = manager.list_sessions()
|
||||
assert len(persisted) == 201
|
||||
assert persisted[-1]["key"] == "websocket:old-target"
|
||||
|
||||
with _webui_request():
|
||||
result = _decode(await SearchSessionsTool(manager).execute(query="needle"))
|
||||
|
||||
@@ -11,18 +11,6 @@ import pytest
|
||||
from scripts.check_import_boundaries import Violation, find_violations
|
||||
|
||||
|
||||
def test_repository_respects_import_boundaries() -> None:
|
||||
result = subprocess.run(
|
||||
[sys.executable, "-m", "scripts.check_import_boundaries"],
|
||||
cwd=Path(__file__).resolve().parents[2],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
)
|
||||
|
||||
assert result.returncode == 0, result.stderr
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("source", "target", "line"),
|
||||
[
|
||||
|
||||
@@ -211,11 +211,12 @@ def test_atomic_write_ignores_unsupported_directory_fsync(
|
||||
def fake_close(fd: int) -> None:
|
||||
assert fd == dir_fd
|
||||
|
||||
monkeypatch.setattr("os.open", fake_open)
|
||||
monkeypatch.setattr("os.fsync", fake_fsync)
|
||||
monkeypatch.setattr("os.close", fake_close)
|
||||
with monkeypatch.context() as patch:
|
||||
patch.setattr("os.open", fake_open)
|
||||
patch.setattr("os.fsync", fake_fsync)
|
||||
patch.setattr("os.close", fake_close)
|
||||
|
||||
CronService._atomic_write(store_path, '{"version": 1, "jobs": []}')
|
||||
CronService._atomic_write(store_path, '{"version": 1, "jobs": []}')
|
||||
|
||||
assert store_path.read_text(encoding="utf-8") == '{"version": 1, "jobs": []}'
|
||||
assert list(store_path.parent.glob("*.tmp")) == []
|
||||
|
||||
@@ -229,7 +229,9 @@ root = Path(sys.argv[1])
|
||||
runtime = GatewayRuntime(paths=GatewayInstance.resolve(config_path=root / 'config.json').paths)
|
||||
with runtime.foreground_instance(GatewayStartOptions(port=0)):
|
||||
child = subprocess.Popen([sys._base_executable, '-c', 'import time; time.sleep(60)'])
|
||||
(root / 'ready.json').write_text(json.dumps({'child': child.pid}), encoding='utf-8')
|
||||
ready = root / 'ready.tmp'
|
||||
ready.write_text(json.dumps({'child': child.pid}), encoding='utf-8')
|
||||
ready.replace(root / 'ready.json')
|
||||
time.sleep(60) # Models a blocked event loop that cannot service the kernel event.
|
||||
"""
|
||||
|
||||
|
||||
@@ -682,16 +682,6 @@ class TestParseResponseOutput:
|
||||
assert result.usage is not None
|
||||
assert result.usage.input_tokens == 1
|
||||
|
||||
def test_usage_maps_responses_api_keys(self):
|
||||
"""Responses API uses input_tokens/output_tokens, not prompt_tokens/completion_tokens."""
|
||||
resp = {
|
||||
"output": [],
|
||||
"status": "completed",
|
||||
"usage": {"input_tokens": 100, "output_tokens": 50, "total_tokens": 150},
|
||||
}
|
||||
result = parse_response_output(resp)
|
||||
assert result.usage == LLMUsage.reported(input_tokens=100, output_tokens=50)
|
||||
|
||||
def test_non_stream_preserves_provider_reported_total(self):
|
||||
result = parse_response_output({
|
||||
"output": [],
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
"""Exercise the CI timing artifact with real pytest reports, without child processes."""
|
||||
|
||||
import json
|
||||
|
||||
import pytest
|
||||
|
||||
pytest_plugins = ["pytester"]
|
||||
|
||||
|
||||
def test_timing_report_preserves_phases_and_failed_results(pytester: pytest.Pytester) -> None:
|
||||
pytester.makeini("[pytest]\nasyncio_default_fixture_loop_scope = function\n")
|
||||
pytester.makepyfile(
|
||||
"import pytest\n"
|
||||
"def test_pass(): pass\n"
|
||||
"def test_fail(): assert False\n"
|
||||
"@pytest.mark.skip(reason='sample')\n"
|
||||
"def test_skip(): pass\n",
|
||||
)
|
||||
output = pytester.path / "timings" / "sample.json"
|
||||
result = pytester.runpytest_inprocess(
|
||||
"-p", "scripts.pytest_timing", "--timing-report", str(output),
|
||||
)
|
||||
result.assert_outcomes(passed=1, failed=1, skipped=1)
|
||||
report = json.loads(output.read_text(encoding="utf-8"))
|
||||
assert report["exitstatus"] == 1
|
||||
cases = {key.rsplit("::", 1)[-1]: value for key, value in report["cases"].items()}
|
||||
assert cases["test_pass"]["phases"]["call"]["outcome"] == "passed"
|
||||
assert cases["test_fail"]["phases"]["call"]["outcome"] == "failed"
|
||||
assert cases["test_skip"]["phases"]["setup"]["outcome"] == "skipped"
|
||||
assert sum(phase["seconds"] for case in cases.values()
|
||||
for phase in case["phases"].values()) > 0
|
||||
assert 0 < report["collection_finish_seconds"] <= report["configured_to_finish_seconds"]
|
||||
@@ -2,19 +2,35 @@
|
||||
|
||||
import pytest
|
||||
|
||||
from nanobot.session.manager import SessionManager
|
||||
from nanobot.session.manager import Session, SessionManager
|
||||
from nanobot.session.sqlite_store import SessionConflictError
|
||||
|
||||
|
||||
async def test_committed_view_cache_is_bounded(tmp_path):
|
||||
state = SessionManager(tmp_path).state
|
||||
for i in range(140):
|
||||
await state.get(str(i))
|
||||
await state.update_metadata(str(i), {"title": str(i)})
|
||||
assert len(state._snapshots) <= 128
|
||||
assert state.peek("0") is None
|
||||
assert (await state.get("0")).metadata["title"] == "0"
|
||||
await state.aclose()
|
||||
manager = SessionManager(tmp_path)
|
||||
# Persist the input before binding the async owner; exercise real cache reads below.
|
||||
with manager._store.transaction():
|
||||
for i in range(140):
|
||||
manager.save(Session(key=str(i), metadata={"title": str(i)}))
|
||||
state = manager.state
|
||||
try:
|
||||
for i in range(140):
|
||||
await state.get(str(i))
|
||||
assert len(state._snapshots) <= 128
|
||||
if i == 127:
|
||||
assert len(state._snapshots) == 128
|
||||
assert state.peek("0") is not None
|
||||
elif i == 128:
|
||||
assert len(state._snapshots) == 128
|
||||
assert state.peek("0") is None
|
||||
await state.update_metadata("139", {"title": "updated"})
|
||||
assert state.peek("139").metadata["title"] == "updated"
|
||||
assert len(state._snapshots) == 128
|
||||
assert state.peek("0") is None
|
||||
assert (await state.get("0")).metadata["title"] == "0"
|
||||
assert len(state._snapshots) == 128
|
||||
finally:
|
||||
await state.aclose()
|
||||
|
||||
|
||||
async def test_cached_views_are_detached(tmp_path):
|
||||
|
||||
@@ -4,6 +4,7 @@ from pathlib import Path
|
||||
import pytest
|
||||
|
||||
from nanobot.llm_usage import LLMCallRecord, get_llm_usage_store
|
||||
from nanobot.pairing import store as pairing_store
|
||||
from nanobot.session.manager import SessionManager
|
||||
from nanobot.webui import star_prompt
|
||||
|
||||
@@ -18,7 +19,7 @@ def test_runtime_stores_are_isolated_between_parameter_cases(
|
||||
session.add_message("user", "isolated message")
|
||||
sessions.save(session)
|
||||
|
||||
usage = get_llm_usage_store(tmp_path / "usage.sqlite3")
|
||||
usage = get_llm_usage_store()
|
||||
assert usage.recent_calls() == []
|
||||
usage.record(LLMCallRecord(
|
||||
started_at_ms=int(time.time() * 1000), duration_ms=1, provider="test", model="test",
|
||||
@@ -30,3 +31,8 @@ def test_runtime_stores_are_isolated_between_parameter_cases(
|
||||
assert not state_path.exists()
|
||||
star_prompt.update_star_prompt("completed", turn_id="fixture-isolation")
|
||||
assert state_path.exists()
|
||||
|
||||
assert not pairing_store.is_approved("test", "isolated-user")
|
||||
code = pairing_store.generate_code("test", "isolated-user")
|
||||
assert pairing_store.approve_code(code) is not None
|
||||
assert pairing_store.is_approved("test", "isolated-user")
|
||||
@@ -439,16 +439,17 @@ def test_exec_session_can_terminate_session(tmp_path):
|
||||
|
||||
initial = await exec_tool.execute(command=command, yield_time_ms=100)
|
||||
sid = _session_id(initial)
|
||||
waited = await stdin_tool.execute(
|
||||
session_id=sid,
|
||||
wait_for="ready",
|
||||
timeout_ms=10000,
|
||||
)
|
||||
if "ready" not in initial:
|
||||
initial += await stdin_tool.execute(
|
||||
session_id=sid,
|
||||
wait_for="ready",
|
||||
timeout_ms=10000,
|
||||
)
|
||||
result = await stdin_tool.execute(
|
||||
session_id=sid,
|
||||
terminate=True,
|
||||
)
|
||||
return initial + waited, result
|
||||
return initial, result
|
||||
|
||||
initial, result = asyncio.run(run())
|
||||
assert "ready" in initial
|
||||
|
||||
@@ -161,11 +161,12 @@ def test_write_text_atomic_fsyncs_file_and_parent_directory(
|
||||
def fake_fsync(fd: int) -> None:
|
||||
fsync_calls.append(fd)
|
||||
|
||||
monkeypatch.setattr(helpers.os, "fsync", fake_fsync)
|
||||
monkeypatch.setattr(helpers.os, "open", lambda path, flags: 12345)
|
||||
monkeypatch.setattr(helpers.os, "close", lambda fd: closed_fds.append(fd))
|
||||
with monkeypatch.context() as patch:
|
||||
patch.setattr(helpers.os, "fsync", fake_fsync)
|
||||
patch.setattr(helpers.os, "open", lambda path, flags: 12345)
|
||||
patch.setattr(helpers.os, "close", lambda fd: closed_fds.append(fd))
|
||||
|
||||
_write_text_atomic(target, '{"approved": {}}')
|
||||
_write_text_atomic(target, '{"approved": {}}')
|
||||
|
||||
assert target.read_text(encoding="utf-8") == '{"approved": {}}'
|
||||
assert len(fsync_calls) == 2
|
||||
@@ -183,10 +184,11 @@ def test_write_text_atomic_keeps_file_when_directory_fsync_is_unsupported(
|
||||
def fake_open(path, flags):
|
||||
raise OSError("directory fsync unsupported")
|
||||
|
||||
monkeypatch.setattr(helpers.os, "fsync", lambda fd: fsync_calls.append(fd))
|
||||
monkeypatch.setattr(helpers.os, "open", fake_open)
|
||||
with monkeypatch.context() as patch:
|
||||
patch.setattr(helpers.os, "fsync", lambda fd: fsync_calls.append(fd))
|
||||
patch.setattr(helpers.os, "open", fake_open)
|
||||
|
||||
_write_text_atomic(target, '{"pending": {}}')
|
||||
_write_text_atomic(target, '{"pending": {}}')
|
||||
|
||||
assert target.read_text(encoding="utf-8") == '{"pending": {}}'
|
||||
assert len(fsync_calls) == 1
|
||||
|
||||
@@ -359,25 +359,25 @@ def test_many_short_trace_rows_are_bounded_and_resolved(tmp_path, monkeypatch) -
|
||||
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)
|
||||
key = "websocket:deferred-many-traces"
|
||||
trace_count = 2_000
|
||||
append_transcript_object(
|
||||
key,
|
||||
rows = [
|
||||
{"event": "user", "chat_id": "deferred-many-traces", "text": "run many tools"},
|
||||
)
|
||||
for index in range(trace_count):
|
||||
append_transcript_object(
|
||||
key,
|
||||
*(
|
||||
{
|
||||
"event": "message",
|
||||
"chat_id": "deferred-many-traces",
|
||||
"kind": "progress",
|
||||
"text": f"tool_{index}(value)",
|
||||
},
|
||||
)
|
||||
append_transcript_object(
|
||||
key,
|
||||
}
|
||||
for index in range(trace_count)
|
||||
),
|
||||
{"event": "message", "chat_id": "deferred-many-traces", "text": "done"},
|
||||
{"event": "turn_end", "chat_id": "deferred-many-traces"},
|
||||
]
|
||||
# Replay needs the full stored input, not one durable append per trace row.
|
||||
transcript_module._write_records_to_path(
|
||||
transcript_module.webui_transcript_path(key),
|
||||
[{**row, "created_at_ms": 1_700_000_000_000} for row in rows],
|
||||
)
|
||||
append_transcript_object(key, {"event": "turn_end", "chat_id": "deferred-many-traces"})
|
||||
|
||||
payload = build_webui_thread_response(key, limit=40, direction="latest")
|
||||
|
||||
|
||||
@@ -102,10 +102,11 @@ def test_webui_session_list_scans_empty_display_directory_once_per_request(tmp_p
|
||||
scans.append(Path(path))
|
||||
return original_scandir(path)
|
||||
|
||||
monkeypatch.setattr(Path, "stat", stored_files_only)
|
||||
monkeypatch.setattr(session_list_index.os, "scandir", scan)
|
||||
for _ in range(2):
|
||||
assert {row["key"] for row in list_webui_sessions(manager)} == keys
|
||||
with monkeypatch.context() as patch:
|
||||
patch.setattr(Path, "stat", stored_files_only)
|
||||
patch.setattr(session_list_index.os, "scandir", scan)
|
||||
for _ in range(2):
|
||||
assert {row["key"] for row in list_webui_sessions(manager)} == keys
|
||||
assert scans == [webui_dir, webui_dir]
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user