Skip to content

Your lightweight open-source personal agent.

ci: reduce Python test overhead and Windows latency (#6357)

chengyongruf284749d2fa9
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 36020cc03..d8afd9dab 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -143,7 +143,7 @@ jobs:
runs-on: ${{ matrix.os }}
timeout-minutes: 20
env:
- PYTEST_ADDOPTS: "-o tmp_path_retention_policy=failed"
+ PYTEST_ADDOPTS: "-o tmp_path_retention_policy=failed -p scripts.pytest_timing"
strategy:
fail-fast: false
matrix:
@@ -166,8 +166,8 @@ jobs:
coverage: false
# Real PowerShell, browser-handoff, and process-tree tests run
# serially so xdist workers do not compete for native processes.
- # Bound concurrent threaded storage work on the Windows runner.
- pytest_args: "-n 2 --dist loadfile --ignore=tests/cli/test_commands.py --ignore=tests/tools/test_exec_platform.py --ignore=tests/cli/test_wsl_browser.py"
+ # Keep threaded storage work bounded without adding another runner.
+ pytest_args: "-n 3 --dist loadfile --ignore=tests/cli/test_commands.py --ignore=tests/tools/test_exec_platform.py --ignore=tests/cli/test_wsl_browser.py"
steps:
- uses: actions/checkout@v4
@@ -204,7 +204,7 @@ jobs:
# later uv run sync pruning the packages installed by the previous step.
- name: Lint with ruff
if: matrix.coverage
- run: uv run --no-sync ruff check nanobot tests conftest.py scripts/check_import_boundaries.py
+ run: uv run --no-sync ruff check nanobot tests conftest.py scripts/check_import_boundaries.py scripts/pytest_timing.py
- name: Type check with BasedPyright (strict)
if: matrix.coverage
@@ -216,7 +216,8 @@ jobs:
uv run --no-sync python -m pytest
${{ matrix.pytest_args }}
--cov=nanobot --cov-report=term-missing:skip-covered
- -vv -o faulthandler_timeout=60
+ -o faulthandler_timeout=60
+ --junitxml=test-results/main.xml --timing-report=test-results/main.json
--durations=25 --durations-min=1.0
- name: Run serial CLI command tests with coverage
@@ -225,6 +226,7 @@ jobs:
uv run --no-sync python -m pytest
tests/cli/test_commands.py
--cov=nanobot --cov-append --cov-report=term-missing:skip-covered
+ --junitxml=test-results/cli.xml --timing-report=test-results/cli.json
--durations=25 --durations-min=1.0
- name: Run compatibility tests
@@ -232,6 +234,7 @@ jobs:
run: >-
uv run --no-sync python -m pytest
${{ matrix.pytest_args }}
+ --junitxml=test-results/main.xml --timing-report=test-results/main.json
--durations=25 --durations-min=1.0
- name: Run serial CLI command compatibility tests
@@ -239,10 +242,21 @@ jobs:
run: >-
uv run --no-sync python -m pytest
tests/cli/test_commands.py
+ --junitxml=test-results/cli.xml --timing-report=test-results/cli.json
--durations=25 --durations-min=1.0
+ - name: Upload Python test timings
+ if: always()
+ uses: actions/upload-artifact@v4
+ with:
+ name: python-timings-${{ matrix.os }}-${{ matrix.python-version }}
+ path: test-results/
+ retention-days: 7
+
windows_process:
name: Python (Windows process compatibility)
+ env:
+ PYTEST_ADDOPTS: "-o tmp_path_retention_policy=failed -p scripts.pytest_timing"
needs: changes
if: needs.changes.outputs.python_required == 'true'
runs-on: windows-latest
@@ -276,8 +290,17 @@ jobs:
uv run --no-sync python -m pytest
tests/tools/test_exec_platform.py
tests/cli/test_wsl_browser.py
+ --junitxml=test-results/process.xml --timing-report=test-results/process.json
--durations=25 --durations-min=1.0
+ - name: Upload Windows process test timings
+ if: always()
+ uses: actions/upload-artifact@v4
+ with:
+ name: python-timings-windows-process
+ path: test-results/
+ retention-days: 7
+
webui_checks:
name: WebUI checks and build
needs: changes
diff --git a/conftest.py b/conftest.py
index e69d8fc50..fd16878ea 100644
--- a/conftest.py
+++ b/conftest.py
@@ -22,6 +22,12 @@ def _isolate_tokenizer_warmup(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr("nanobot.utils.token_encoding._warmup_thread", Thread())
[email protected](autouse=True)
+def _isolate_tool_entry_points(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Only load external tool plugins explicitly provided by the test."""
+ monkeypatch.setattr("nanobot.agent.tools.loader.entry_points", lambda **_kwargs: ())
+
+
@pytest.fixture(autouse=True)
def _isolate_nanobot_log_activation() -> Iterator[None]:
"""Keep CLI log settings from leaking into later tests in the same process."""
@@ -33,33 +39,32 @@ def _isolate_nanobot_log_activation() -> Iterator[None]:
@pytest.fixture(autouse=True)
-def _isolate_sessions_root(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Iterator[None]:
- """Redirect session storage away from the real active config data directory.
+def _isolate_runtime_stores(
+ tmp_path_factory: pytest.TempPathFactory, monkeypatch: pytest.MonkeyPatch,
+) -> Iterator[None]:
+ """Isolate writable stores without making a directory for pure tests."""
+ import nanobot.llm_usage.service as llm_usage
+ import nanobot.pairing.store as pairing_store
+ import nanobot.session.location as session_location
+ from nanobot.webui import star_prompt
- Session storage lives under the active runtime data root (outside the workspace,
- per ADR-0001), so without redirection tests would write into the real home.
- """
- data_root = tmp_path.parent / "session-data" / uuid4().hex
- runtime_root = data_root / "runtime"
+ # A sibling of tmp_path stays outside any test's agent workspace. mkdir is
+ # deferred until a store is used and remains safe for concurrent callers.
+ data_root = tmp_path_factory.getbasetemp() / "runtime-data" / uuid4().hex
+
+ def data_dir() -> Path:
+ data_root.mkdir(parents=True, exist_ok=True)
+ return data_root
def runtime_subdir(name: str) -> Path:
- path = runtime_root / name
+ path = data_root / name
path.mkdir(parents=True, exist_ok=True)
return path
- monkeypatch.setattr(
- "nanobot.session.location.get_runtime_subdir",
- runtime_subdir,
- )
- yield
-
-
[email protected](autouse=True)
-def _isolate_llm_usage_stores(
- tmp_path: Path, monkeypatch: pytest.MonkeyPatch,
-) -> Iterator[None]:
- import nanobot.llm_usage.service as llm_usage
-
+ monkeypatch.setattr(session_location, "get_runtime_subdir", runtime_subdir)
+ monkeypatch.setattr(star_prompt, "get_webui_dir", lambda: runtime_subdir("webui"))
+ monkeypatch.setattr(pairing_store, "_store_path", lambda: data_dir() / "pairing.json")
+ monkeypatch.setattr(llm_usage, "get_data_dir", data_dir)
stores: dict[Path, llm_usage.LLMUsageStore] = {}
monkeypatch.setattr(llm_usage, "_STORES", stores)
try:
@@ -69,30 +74,6 @@ def _isolate_llm_usage_stores(
store.close()
[email protected](autouse=True)
-def _isolate_star_prompt_store(
- tmp_path: Path, monkeypatch: pytest.MonkeyPatch
-) -> None:
- """Keep WebUI completion events out of the user's invitation state and lock."""
- webui_dir = tmp_path.parent / "star-prompt-webui" / uuid4().hex
-
- def get_webui_dir() -> Path:
- webui_dir.mkdir(parents=True, exist_ok=True)
- return webui_dir
-
- monkeypatch.setattr("nanobot.webui.star_prompt.get_webui_dir", get_webui_dir)
-
-
[email protected](autouse=True)
-def _isolate_pairing_store(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
- """Keep channel pairing tests out of the user's active pairing store."""
- pairing_path = tmp_path / "pairing.json"
- monkeypatch.setattr(
- "nanobot.pairing.store._store_path",
- lambda: pairing_path,
- )
-
-
@pytest.fixture(scope="session", autouse=True)
def _use_windows_system_ca_for_default_http_clients() -> Iterator[None]:
"""Avoid reparsing certifi's CA bundle for every offline HTTP client.
diff --git a/nanobot/channels/websocket/binary_http.py b/nanobot/channels/websocket/binary_http.py
index 263d93d6d..02ee6168a 100644
--- a/nanobot/channels/websocket/binary_http.py
+++ b/nanobot/channels/websocket/binary_http.py
@@ -25,8 +25,8 @@ class BinaryHTTPBridge:
"""Own HTTP connections alongside a websockets ``serve`` instance.
Pass ``connection_factory`` as ``create_connection`` to serve/unix_serve.
- After closing the listening server, await ``shutdown`` before disposing the
- upload store. Request decompression is deliberately disabled: declared body
+ After closing the listener, await ``shutdown`` before ``server.wait_closed``
+ and disposing the upload store. Request decompression is deliberately disabled: declared body
lengths must measure the exact bytes the upload store writes.
"""
diff --git a/nanobot/channels/websocket/runtime.py b/nanobot/channels/websocket/runtime.py
index 09bb816f7..e17a736fa 100644
--- a/nanobot/channels/websocket/runtime.py
+++ b/nanobot/channels/websocket/runtime.py
@@ -646,9 +646,12 @@ class WebSocketChannel(BaseChannel):
"WebSocket listener is no longer accepting connections"
)
- async def _close_server(self, server: Server, socket_path: str) -> None:
+ async def _close_server(
+ self, server: Server, socket_path: str, bridge: BinaryHTTPBridge,
+ ) -> None:
server.close()
try:
+ await bridge.shutdown()
await server.wait_closed()
except OSError as exc:
self.logger.warning("WebSocket server close failed: {}", exc)
@@ -701,8 +704,6 @@ class WebSocketChannel(BaseChannel):
async def handler(connection: ServerConnection) -> None:
await self._connection_loop(connection)
- bridge = BinaryHTTPBridge(self._uploads.handle)
-
async def prune_uploads() -> None:
while not stop_event.is_set():
self._uploads.store.prune()
@@ -718,6 +719,7 @@ class WebSocketChannel(BaseChannel):
failures = 0
while not stop_event.is_set():
server: Server | None = None
+ bridge = BinaryHTTPBridge(self._uploads.handle)
was_serving = False
started_at = 0.0
try:
@@ -797,7 +799,9 @@ class WebSocketChannel(BaseChannel):
finally:
self._running = False
if server is not None:
- await self._close_server(server, socket_path)
+ await self._close_server(server, socket_path, bridge)
+ else:
+ await bridge.shutdown()
if self._server is server:
self._server = None
@@ -808,7 +812,6 @@ class WebSocketChannel(BaseChannel):
finally:
prune_task.cancel()
await asyncio.gather(prune_task, return_exceptions=True)
- await bridge.shutdown()
self._uploads.store.clear()
self._running = False
if self._server_task is task:
diff --git a/nanobot/channels/websocket/tests/test_attachment_ingress.py b/nanobot/channels/websocket/tests/test_attachment_ingress.py
index 3658999e3..d25c19d93 100644
--- a/nanobot/channels/websocket/tests/test_attachment_ingress.py
+++ b/nanobot/channels/websocket/tests/test_attachment_ingress.py
@@ -176,3 +176,30 @@ async def test_stalled_upload_reports_timeout_and_keeps_connection_retryable(gat
assert not [p for p in channel.gateway.uploads.store.media_dir.rglob("*") if p.is_file()]
async with http.post(http_url + capability["path"], data=b"xy", headers=headers) as response:
assert response.status == 201
+
+
+async def test_stopping_listener_cancels_active_upload_before_clearing_store(gateway):
+ channel, _, http_url, ws_url = gateway
+ port = int(http_url.rsplit(":", 1)[1])
+ async with connect(ws_url) as ws:
+ capability = (await event(ws, "ready"))["upload"]
+ reader, writer = await asyncio.open_connection("127.0.0.1", port)
+ try:
+ writer.write((
+ f"POST {capability['path']} HTTP/1.1\r\nHost: localhost\r\n"
+ f"Authorization: Bearer {capability['token']}\r\n"
+ "Content-Type: image/png\r\nContent-Length: 1024\r\n"
+ "Expect: 100-continue\r\n\r\n"
+ ).encode("ascii"))
+ await writer.drain()
+ assert b"100 Continue" in await asyncio.wait_for(reader.readuntil(b"\r\n\r\n"), 2)
+ writer.write(b"partial")
+ await writer.drain()
+ async with asyncio.timeout(3):
+ await channel.stop()
+ await reader.read()
+ await ws.wait_closed()
+ assert not [p for p in channel.gateway.uploads.store.media_dir.rglob("*") if p.is_file()]
+ finally:
+ writer.close()
+ await writer.wait_closed()
diff --git a/nanobot/channels/websocket/tests/test_binary_http.py b/nanobot/channels/websocket/tests/test_binary_http.py
index 2dfccf3d4..b02b4d77a 100644
--- a/nanobot/channels/websocket/tests/test_binary_http.py
+++ b/nanobot/channels/websocket/tests/test_binary_http.py
@@ -60,8 +60,8 @@ async def test_binary_body_exceeds_ws_frame_limit_without_changing_ws(tmp_path):
assert ws.close_code == 1009
finally:
server.close()
- await server.wait_closed()
await bridge.shutdown()
+ await server.wait_closed()
store.clear()
@@ -90,10 +90,12 @@ async def test_fragmented_method_and_shutdown_of_undecided_connection():
idle_reader, idle_writer = await asyncio.open_connection("127.0.0.1", port)
idle_writer.write(b"P")
await idle_writer.drain()
- await asyncio.sleep(0.01)
+ async with asyncio.timeout(2):
+ while not any(connection._prefix == b"P" for connection in bridge.pending_connections):
+ await asyncio.sleep(0)
server.close()
- await server.wait_closed()
await bridge.shutdown()
+ await server.wait_closed()
assert await asyncio.wait_for(idle_reader.read(), 2) == b""
idle_writer.close()
await idle_writer.wait_closed()
@@ -101,8 +103,8 @@ async def test_fragmented_method_and_shutdown_of_undecided_connection():
writer.close()
await writer.wait_closed()
server.close()
- await server.wait_closed()
await bridge.shutdown()
+ await server.wait_closed()
@pytest.mark.asyncio
@@ -136,8 +138,8 @@ async def test_ambiguous_http_framing_is_rejected_before_handler(headers):
writer.close()
await writer.wait_closed()
server.close()
- await server.wait_closed()
await bridge.shutdown()
+ await server.wait_closed()
@pytest.mark.asyncio
@@ -165,8 +167,8 @@ async def test_request_body_is_not_automatically_decompressed():
assert received == [body]
finally:
server.close()
- await server.wait_closed()
await bridge.shutdown()
+ await server.wait_closed()
@pytest.mark.asyncio
@@ -191,8 +193,8 @@ async def test_incomplete_http_headers_have_a_deadline(monkeypatch):
writer.close()
await writer.wait_closed()
server.close()
- await server.wait_closed()
await bridge.shutdown()
+ await server.wait_closed()
@pytest.mark.asyncio
@@ -233,6 +235,6 @@ async def test_parsed_request_outlasts_header_deadline(tmp_path, monkeypatch):
writer.close()
await writer.wait_closed()
server.close()
- await server.wait_closed()
await bridge.shutdown()
+ await server.wait_closed()
store.clear()
diff --git a/nanobot/channels/websocket/tests/test_websocket_channel.py b/nanobot/channels/websocket/tests/test_websocket_channel.py
index 0631d5ad0..2f313f98c 100644
--- a/nanobot/channels/websocket/tests/test_websocket_channel.py
+++ b/nanobot/channels/websocket/tests/test_websocket_channel.py
@@ -40,6 +40,7 @@ from nanobot.bus.outbound_events import (
UserInputEvent,
)
from nanobot.bus.queue import MessageBus
+from nanobot.channels.websocket import runtime as websocket_runtime
from nanobot.channels.websocket.runtime import (
WebSocketChannel,
WebSocketConfig,
@@ -212,6 +213,44 @@ async def start_listener():
await asyncio.gather(task, return_exceptions=True)
+async def test_shutdown_closes_undecided_connections_before_waiting_for_server(
+ bus, start_listener, monkeypatch,
+) -> None:
+ bridges = []
+ bridge_type = websocket_runtime.BinaryHTTPBridge
+
+ def create_bridge(handler):
+ bridge = bridge_type(handler)
+ bridges.append(bridge)
+ return bridge
+
+ monkeypatch.setattr(websocket_runtime, "BinaryHTTPBridge", create_bridge)
+ channel = _ch(bus)
+ port, start_task = await start_listener(channel)
+ async with websockets.connect(f"ws://127.0.0.1:{port}/ws") as client:
+ assert json.loads(await client.recv())["event"] == "ready"
+ reader, writer = await asyncio.open_connection("127.0.0.1", port)
+ try:
+ writer.write(b"P")
+ await writer.drain()
+ async with asyncio.timeout(2):
+ while not any(
+ connection._prefix == b"P" for connection in bridges[0].pending_connections
+ ):
+ await asyncio.sleep(0)
+ async with asyncio.timeout(2):
+ await channel.stop()
+ await start_task
+ assert await reader.read() == b""
+ await client.wait_closed()
+ assert not bridges[0].pending_connections
+ assert channel._server is None
+ finally:
+ writer.close()
+ await writer.wait_closed()
+
+
async def _wait_for_connection_cleanup(
channel: WebSocketChannel,
connection: Any,
diff --git a/scripts/pytest_timing.py b/scripts/pytest_timing.py
new file mode 100644
index 000000000..80a9cd150
--- /dev/null
+++ b/scripts/pytest_timing.py
@@ -0,0 +1,69 @@
+"""Opt-in pytest phase timings for CI artifacts (including xdist workers)."""
+
+from __future__ import annotations
+
+import json
+import os
+import platform
+import time
+from pathlib import Path
+
+import pytest
+
+
+def pytest_addoption(parser: pytest.Parser) -> None:
+ parser.addoption("--timing-report", help="Write phase timings as JSON, with one file per worker")
+
+
+def pytest_configure(config: pytest.Config) -> None:
+ path = config.getoption("--timing-report")
+ if path:
+ config.pluginmanager.register(_TimingReport(config, Path(path)), "phase-timing-report")
+
+
+class _TimingReport:
+ def __init__(self, config: pytest.Config, path: Path) -> None:
+ self.started = time.perf_counter()
+ self.path = path
+ self.worker = getattr(config, "workerinput", {}).get("workerid", "controller")
+ self.args = list(config.invocation_params.args)
+ self.collection_seconds: float | None = None
+ self.worker_collection: dict[str, dict[str, float | int]] = {}
+ self.cases: dict[str, dict] = {}
+
+ def pytest_collection_finish(self) -> None:
+ self.collection_seconds = time.perf_counter() - self.started
+
+ @pytest.hookimpl(optionalhook=True)
+ def pytest_xdist_node_collection_finished(self, node, ids: list[str]) -> None:
+ self.worker_collection[node.gateway.id] = {
+ "ready_seconds": time.perf_counter() - self.started,
+ "items": len(ids),
+ }
+
+ def pytest_runtest_logreport(self, report: pytest.TestReport) -> None:
+ case = self.cases.setdefault(report.nodeid, {
+ "worker": getattr(report, "worker_id", self.worker), "phases": {},
+ })
+ case["phases"][report.when] = {
+ "seconds": report.duration, "outcome": report.outcome,
+ }
+
+ def pytest_sessionfinish(self, exitstatus: int) -> None:
+ elapsed = time.perf_counter() - self.started
+ path = self.path
+ if self.worker != "controller":
+ path = path.with_stem(f"{path.stem}-{self.worker}")
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(json.dumps({
+ "python": platform.python_version(),
+ "platform": platform.platform(),
+ "cpu_count": os.cpu_count(),
+ "worker": self.worker,
+ "args": self.args,
+ "exitstatus": int(exitstatus),
+ "configured_to_finish_seconds": elapsed,
+ "collection_finish_seconds": self.collection_seconds,
+ "worker_collection": self.worker_collection,
+ "cases": self.cases,
+ }, indent=2), encoding="utf-8")
diff --git a/tests/agent/test_auto_compact.py b/tests/agent/test_auto_compact.py
index 67e285275..cae22dcfe 100644
--- a/tests/agent/test_auto_compact.py
+++ b/tests/agent/test_auto_compact.py
@@ -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)."""
diff --git a/tests/agent/test_loop_progress.py b/tests/agent/test_loop_progress.py
index ed37b0d53..b722a334d 100644
--- a/tests/agent/test_loop_progress.py
+++ b/tests/agent/test_loop_progress.py
@@ -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()
diff --git a/tests/agent/test_loop_save_turn.py b/tests/agent/test_loop_save_turn.py
index c4d7b2104..4675d2570 100644
--- a/tests/agent/test_loop_save_turn.py
+++ b/tests/agent/test_loop_save_turn.py
@@ -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"
-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
diff --git a/tests/agent/test_runner_core.py b/tests/agent/test_runner_core.py
index bc700c4af..e1f4359cf 100644
--- a/tests/agent/test_runner_core.py
+++ b/tests/agent/test_runner_core.py
@@ -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
-
-
-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
-
-
-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"
diff --git a/tests/agent/test_runner_progress_events.py b/tests/agent/test_runner_progress_events.py
new file mode 100644
index 000000000..e4c62d3b1
--- /dev/null
+++ b/tests/agent/test_runner_progress_events.py
@@ -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()
+
+
+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": [],
+ }],
+ ),
+ ]
+
+
+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)
diff --git a/tests/agent/test_runner_reasoning.py b/tests/agent/test_runner_reasoning.py
index 8dfdfcbee..aa5c8d686 100644
--- a/tests/agent/test_runner_reasoning.py
+++ b/tests/agent/test_runner_reasoning.py
@@ -96,56 +96,6 @@ class _BlockingReasoningEndHook(_LifecycleRecordingHook):
await super().emit_reasoning_end()
-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
diff --git a/tests/agent/test_tool_loader_entrypoints.py b/tests/agent/test_tool_loader_entrypoints.py
index ace6924d0..a588a481c 100644
--- a/tests/agent/test_tool_loader_entrypoints.py
+++ b/tests/agent/test_tool_loader_entrypoints.py
@@ -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():
diff --git a/tests/agent/tools/test_self_tool.py b/tests/agent/tools/test_self_tool.py
index 286aa0187..f563f25b1 100644
--- a/tests/agent/tools/test_self_tool.py
+++ b/tests/agent/tools/test_self_tool.py
@@ -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)
diff --git a/tests/agent/tools/test_sessions.py b/tests/agent/tools/test_sessions.py
index 185e12f33..bf733abca 100644
--- a/tests/agent/tools/test_sessions.py
+++ b/tests/agent/tools/test_sessions.py
@@ -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"))
diff --git a/tests/architecture/test_import_boundaries.py b/tests/architecture/test_import_boundaries.py
index b9dbff07d..08029cf36 100644
--- a/tests/architecture/test_import_boundaries.py
+++ b/tests/architecture/test_import_boundaries.py
@@ -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"),
[
diff --git a/tests/cron/test_cron_persistence.py b/tests/cron/test_cron_persistence.py
index dc766f2d9..2c8cd6874 100644
--- a/tests/cron/test_cron_persistence.py
+++ b/tests/cron/test_cron_persistence.py
@@ -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")) == []
diff --git a/tests/gateway/test_windows_shutdown.py b/tests/gateway/test_windows_shutdown.py
index 78cbe453b..f6d0cfbad 100644
--- a/tests/gateway/test_windows_shutdown.py
+++ b/tests/gateway/test_windows_shutdown.py
@@ -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.
"""
diff --git a/tests/providers/test_openai_responses.py b/tests/providers/test_openai_responses.py
index 55778c1ed..5960a372d 100644
--- a/tests/providers/test_openai_responses.py
+++ b/tests/providers/test_openai_responses.py
@@ -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": [],
diff --git a/tests/scripts/test_pytest_timing.py b/tests/scripts/test_pytest_timing.py
new file mode 100644
index 000000000..48c68d230
--- /dev/null
+++ b/tests/scripts/test_pytest_timing.py
@@ -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"]
diff --git a/tests/session/test_session_cache.py b/tests/session/test_session_cache.py
index cf3373453..6d691e873 100644
--- a/tests/session/test_session_cache.py
+++ b/tests/session/test_session_cache.py
@@ -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):
diff --git a/tests/test_fixture_isolation.py b/tests/test_fixture_isolation.py
index fb82ddfc4..c333c0103 100644
--- a/tests/test_fixture_isolation.py
+++ b/tests/test_fixture_isolation.py
@@ -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")
diff --git a/tests/tools/test_exec_session_tools.py b/tests/tools/test_exec_session_tools.py
index 29069c708..0aa1b7800 100644
--- a/tests/tools/test_exec_session_tools.py
+++ b/tests/tools/test_exec_session_tools.py
@@ -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
diff --git a/tests/utils/test_helpers.py b/tests/utils/test_helpers.py
index d649f9390..6cf677202 100644
--- a/tests/utils/test_helpers.py
+++ b/tests/utils/test_helpers.py
@@ -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
diff --git a/tests/utils/test_webui_transcript.py b/tests/utils/test_webui_transcript.py
index 8c27a39e3..17b055f85 100644
--- a/tests/utils/test_webui_transcript.py
+++ b/tests/utils/test_webui_transcript.py
@@ -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")
diff --git a/tests/webui/test_session_list_index.py b/tests/webui/test_session_list_index.py
index 97b4f38ff..369639d79 100644
--- a/tests/webui/test_session_list_index.py
+++ b/tests/webui/test_session_list_index.py
@@ -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]