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:
chengyongru authored and GitHub committed 2026-10-21 14:47:55 +08:00
1 parent 743c51e81f
commit f284749d2f
28 files changed
+518 -448

No files matched your search

+9 -25
View File
@@ -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)."""
+1 -117
View File
@@ -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()
+4 -33
View File
@@ -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
+5 -59
View File
@@ -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"
+143
View File
@@ -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)
-50
View File
@@ -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
+21 -9
View File
@@ -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():
+5 -13
View File
@@ -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)
+17 -12
View File
@@ -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"))