refactor(session): centralize state ownership in SQLite (#5943)
* fix(session): move persistence off event loop * refactor(session): isolate async persistence boundary * refactor(session): keep a single session manager * refactor(session): use stateless async adapters * fix(session): serialize local persistence without file-lock contention * refactor(session): own async persistence and snapshot commits * refactor(session): narrow persistence changes to async adapters * refactor(session): remove redundant async forwarding helpers * fix(command): offload compact session persistence * fix(session): adapt idle compaction to current main * fix(webui): offload session metadata persistence * refactor(session): centralize state ownership in SQLite * fix(session): skip storage for non-recoverable followups * test(webui): honor the full gateway event deadline * perf(session): persist incremental changes and reuse owner snapshots * test(agent): allow durable worker shutdown in burst test * fix(gateway): drain session storage on Windows console shutdown * fix(session): enforce bounded ownership and lifecycle-safe persistence * fix: reject unresolved home paths and stabilize platform tests * fix(session): preserve request context compatibility and owner-backed tests * docs: focus configuration guide on user-facing behavior * fix(session): adapt goal admission to async ownership after rebase * fix(session): integrate current gateway and subagent contracts * fix(session): align rebased workspace admission and async tests * fix(session): support compatible SQLite schema evolution * test(agent): use session owner in workspace context regressions * test: stabilize Windows lifecycle and browser checks * refactor(session): remove premature JSONL file export * ci: bound Windows full-suite worker concurrency * chore: remove session state refactor notes * fix(session): queue writes and retain worker connections * perf(webui): read detached metadata for session and task lists * perf(agent): bound prompt preparation and local token counting * docs: remove internal session storage guide * perf(session): skip archived transcripts during idle scans * fix(session): coordinate turns and isolate legacy session data Bind WebUI input generations to the execution session and serialize idle and SDK compaction with turns. Keep turn drafts through preparation so the latest channel route persists. Move imported workspace JSONL and checkpoints to durable private backups before gateway admission, resuming cleanup after interruptions. Remove committed child sessions when task creation is cancelled. Validation: focused Python and frontend regressions, Ruff, BasedPyright, import boundaries, WebUI build, and isolated gateway/browser flows. * fix(agent): keep cancellation hooks independent of prompt preparation * fix(session): preserve admission, delivery, and migration contracts * fix(agent): preserve cancellation settlement after rebase * fix(session): preserve request attribution through async ownership
This commit is contained in:
1 parent
33ff520d12
commit
8f6a5594fb
144 files changed
+8293
-4912
No files matched your search
@@ -80,7 +80,6 @@ def make_loop(
|
||||
|
||||
if patch_deps:
|
||||
with patch("nanobot.agent.loop.ContextBuilder"), \
|
||||
patch("nanobot.agent.loop.SessionManager"), \
|
||||
patch("nanobot.agent.loop.SubagentManager") as mock_sub_mgr:
|
||||
mock_sub_mgr.return_value.cancel_by_session = AsyncMock(return_value=0)
|
||||
return AgentLoop(**kwargs)
|
||||
|
||||
@@ -21,11 +21,11 @@ def visible_message(message: dict) -> dict:
|
||||
return public_history_message(message)
|
||||
|
||||
|
||||
def save_completed_subagent(loop: AgentLoop, task_id: str, owner: str) -> None:
|
||||
async def save_completed_subagent(loop: AgentLoop, task_id: str, owner: str) -> None:
|
||||
"""Persist the child that owns a synthetic completion notification."""
|
||||
assert loop.subagents.sessions is not None
|
||||
now = time.monotonic()
|
||||
loop.subagents.sessions.create(SubagentStatus(
|
||||
await loop.subagents.sessions.create(SubagentStatus(
|
||||
task_id=task_id, label=task_id, task_description="Background work",
|
||||
owner=owner, started_at=now, finished_at=now, completed_at=time.time(),
|
||||
state="done", phase="done",
|
||||
@@ -34,5 +34,23 @@ def save_completed_subagent(loop: AgentLoop, task_id: str, owner: str) -> None:
|
||||
|
||||
async def run_session(loop: AgentLoop, msg: InboundMessage) -> None:
|
||||
"""Submit input and wait for its session worker to finish."""
|
||||
loop._enqueue_session_message(msg)
|
||||
(await loop._enqueue_session_message(msg))
|
||||
await asyncio.gather(*loop._active_tasks[loop._effective_session_key(msg)])
|
||||
|
||||
|
||||
def mock_session_manager(*_args, **_kwargs):
|
||||
"""Model the asynchronous state boundary in scheduler-only unit tests."""
|
||||
from unittest.mock import AsyncMock, MagicMock
|
||||
|
||||
from nanobot.session.manager import Session, SessionManager
|
||||
from nanobot.session.state import SessionState
|
||||
|
||||
manager = MagicMock(spec=SessionManager)
|
||||
manager.get_or_create.side_effect = lambda key: Session(key=key)
|
||||
manager.state = MagicMock(spec=SessionState)
|
||||
manager.state.get = AsyncMock(side_effect=lambda key: manager.get_or_create(key))
|
||||
manager.state.read = AsyncMock(return_value=None)
|
||||
manager.state.read_metadata = AsyncMock(return_value=None)
|
||||
manager.state.list_sessions = AsyncMock(return_value=[])
|
||||
manager.state.peek.return_value = None
|
||||
return manager
|
||||
@@ -1,13 +1,16 @@
|
||||
"""Tests for auto compact (idle TTL) feature."""
|
||||
|
||||
import asyncio
|
||||
import time
|
||||
from datetime import datetime, timedelta
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import AsyncMock, MagicMock
|
||||
|
||||
import pytest
|
||||
|
||||
from nanobot.agent.loop import AgentLoop
|
||||
from nanobot.agent.tools.context import current_request_context
|
||||
from nanobot.agent.tools.registry import ToolRegistry
|
||||
from nanobot.bus.events import InboundMessage
|
||||
from nanobot.bus.queue import MessageBus
|
||||
@@ -16,12 +19,14 @@ from nanobot.config.schema import AgentDefaults, Config
|
||||
from nanobot.events import NO_EVENTS
|
||||
from nanobot.providers.base import LLMResponse
|
||||
from nanobot.runtime_context import public_history_message
|
||||
from nanobot.session.keys import HEARTBEAT_SESSION_KEY
|
||||
from nanobot.sdk.clients import RuntimeClient
|
||||
from nanobot.session.keys import HEARTBEAT_SESSION_KEY, UNIFIED_SESSION_KEY
|
||||
|
||||
|
||||
def _make_loop(
|
||||
tmp_path: Path,
|
||||
session_ttl_minutes: int = 15,
|
||||
unified_session: bool = False,
|
||||
) -> AgentLoop:
|
||||
"""Create a minimal AgentLoop for testing."""
|
||||
bus = MessageBus()
|
||||
@@ -37,6 +42,7 @@ def _make_loop(
|
||||
model="test-model",
|
||||
context_window_tokens=128_000,
|
||||
session_ttl_minutes=session_ttl_minutes,
|
||||
unified_session=unified_session,
|
||||
)
|
||||
loop.tools.get_definitions = MagicMock(return_value=[])
|
||||
return loop
|
||||
@@ -94,16 +100,14 @@ def _make_fake_compact(
|
||||
events=NO_EVENTS,
|
||||
) -> str:
|
||||
state["count"] += 1
|
||||
session = loop.sessions.get_or_create(key)
|
||||
session = await loop.sessions.state.get(key)
|
||||
|
||||
tail = list(session.messages[session.last_archived:])
|
||||
if not tail:
|
||||
loop.sessions.save(session)
|
||||
return ""
|
||||
archive_end = session.last_archived + len(tail)
|
||||
archive_msgs = tail
|
||||
|
||||
last_active = session.updated_at
|
||||
s = summary
|
||||
if on_archive:
|
||||
result = on_archive(archive_msgs)
|
||||
@@ -111,14 +115,7 @@ def _make_fake_compact(
|
||||
if track_archived is not None:
|
||||
track_archived.extend(archive_msgs)
|
||||
|
||||
if s and s != "(nothing)":
|
||||
session.metadata["_last_summary"] = {
|
||||
"text": s,
|
||||
"last_active": last_active.isoformat(),
|
||||
}
|
||||
|
||||
session.commit_summary_checkpoint(s, insert_at=archive_end, last_active=last_active)
|
||||
loop.sessions.save(session)
|
||||
await loop.sessions.state.commit_summary(session, s, archive_end=archive_end)
|
||||
return s
|
||||
|
||||
# Attach state for count access
|
||||
@@ -142,7 +139,7 @@ async def test_heartbeat_idle_compaction_persists_summary_without_channel_notice
|
||||
loop.sessions.save(session)
|
||||
loop.consolidator.archive_session = AsyncMock(return_value="Heartbeat summary.")
|
||||
|
||||
loop.auto_compact.check_expired(loop.schedule_background, loop.runtime_for_session)
|
||||
await loop.auto_compact.check_expired(loop.schedule_background, loop.runtime_for_session)
|
||||
await _drain_background_tasks(loop)
|
||||
|
||||
loop.consolidator.archive_session.assert_awaited_once()
|
||||
@@ -152,6 +149,100 @@ async def test_heartbeat_idle_compaction_persists_summary_without_channel_notice
|
||||
assert loop.bus.outbound.empty()
|
||||
|
||||
|
||||
async def test_expired_unified_turn_keeps_latest_delivery_route(tmp_path, monkeypatch):
|
||||
monkeypatch.setattr("nanobot.config.home._home_path", tmp_path / "home")
|
||||
monkeypatch.setattr("nanobot.config.loader._current_config_path", tmp_path / "config.json")
|
||||
loop = _make_loop(tmp_path / "workspace", unified_session=True)
|
||||
session = loop.sessions.get_or_create(UNIFIED_SESSION_KEY)
|
||||
session.metadata["last_channel"] = "telegram:old"
|
||||
session.metadata["_compaction_route"] = {
|
||||
"channel": "telegram", "chat_id": "old", "metadata": {},
|
||||
}
|
||||
session.updated_at = datetime.now() - timedelta(minutes=20)
|
||||
loop.sessions.save(session)
|
||||
try:
|
||||
response = await loop.process_direct(
|
||||
"hello", session_key=UNIFIED_SESSION_KEY, channel="discord", chat_id="new",
|
||||
)
|
||||
|
||||
assert response is not None and response.content == "ok"
|
||||
saved = await loop.sessions.state.get(UNIFIED_SESSION_KEY)
|
||||
assert saved.generation == session.generation
|
||||
assert saved.metadata["last_channel"] == "discord:new"
|
||||
assert saved.metadata["_compaction_route"] == {
|
||||
"channel": "discord", "chat_id": "new", "metadata": {},
|
||||
}
|
||||
finally:
|
||||
await loop.aclose()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("compaction", ["idle", "compact_session", "compact_idle_session"])
|
||||
async def test_turn_resuming_during_archive_commits_reply(tmp_path, monkeypatch, compaction):
|
||||
monkeypatch.setattr("nanobot.config.home._home_path", tmp_path / "home")
|
||||
monkeypatch.setattr("nanobot.config.loader._current_config_path", tmp_path / "config.json")
|
||||
loop = _make_loop(tmp_path / "workspace")
|
||||
session = loop.sessions.get_or_create("cli:idle")
|
||||
_add_turns(session, 1, prefix="old")
|
||||
session.updated_at = datetime.now() - timedelta(minutes=20)
|
||||
loop.sessions.save(session)
|
||||
entered, release = asyncio.Event(), asyncio.Event()
|
||||
archive_committed = asyncio.Event()
|
||||
|
||||
async def archive(_session, **_kwargs):
|
||||
entered.set()
|
||||
await release.wait()
|
||||
return "Old session summary."
|
||||
|
||||
loop.consolidator.archive_session = archive
|
||||
|
||||
async def respond(**_kwargs):
|
||||
request = current_request_context()
|
||||
if request is not None and request.session_key == session.key:
|
||||
await archive_committed.wait()
|
||||
return LLMResponse(content="new reply")
|
||||
|
||||
loop.provider.chat_stream_with_retry.side_effect = respond
|
||||
turn = None
|
||||
compact_task = None
|
||||
try:
|
||||
if compaction == "idle":
|
||||
await loop.auto_compact.check_expired(loop.schedule_background, loop.runtime_for_session)
|
||||
else:
|
||||
compact_task = asyncio.create_task(getattr(RuntimeClient(loop), compaction)(session.key))
|
||||
await asyncio.wait_for(entered.wait(), 5)
|
||||
turn = asyncio.create_task(loop.process_direct("new input", session_key=session.key))
|
||||
|
||||
# The pending archive only holds its own conversation's execution slot.
|
||||
other = await asyncio.wait_for(
|
||||
loop.process_direct("other input", session_key="cli:other"), 5,
|
||||
)
|
||||
assert other is not None and other.content == "new reply"
|
||||
|
||||
release.set()
|
||||
if compact_task is not None:
|
||||
await compact_task
|
||||
else:
|
||||
await _drain_background_tasks(loop)
|
||||
archive_committed.set()
|
||||
response = await asyncio.wait_for(turn, 5)
|
||||
assert response is not None and response.content == "new reply"
|
||||
saved = await loop.sessions.state.get(session.key)
|
||||
assert saved.generation == session.generation
|
||||
assert saved.metadata["_last_summary"]["text"] == "Old session summary."
|
||||
assert saved.messages[-1]["content"] == "new reply"
|
||||
assert saved.messages[-2]["content"].startswith("new input")
|
||||
assert "pending_user_turn" not in saved.metadata
|
||||
assert "runtime_checkpoint" not in saved.metadata
|
||||
finally:
|
||||
release.set()
|
||||
archive_committed.set()
|
||||
if turn is not None:
|
||||
await asyncio.gather(turn, return_exceptions=True)
|
||||
if compact_task is not None:
|
||||
await compact_task
|
||||
await loop.aclose()
|
||||
|
||||
|
||||
class TestSessionTTLConfig:
|
||||
"""Test session TTL configuration."""
|
||||
|
||||
@@ -202,10 +293,10 @@ class TestSessionTTLConfig:
|
||||
class TestIdleScanThrottling:
|
||||
"""Test scheduling of full idle-session scans."""
|
||||
|
||||
def test_configured_idle_scan_interval_throttles_checks(self, tmp_path, monkeypatch):
|
||||
async def test_configured_idle_scan_interval_throttles_checks(self, tmp_path, monkeypatch):
|
||||
"""The configured interval should reach the loop and gate session scans."""
|
||||
ticks = iter((1_000.0, 1_000.0, 1_009.999, 1_010.0))
|
||||
monkeypatch.setattr("nanobot.agent.loop.time.monotonic", lambda: next(ticks))
|
||||
monkeypatch.setattr("nanobot.agent.loop.time", SimpleNamespace(time=time.time, monotonic=lambda: next(ticks)))
|
||||
config = Config.model_validate({
|
||||
"agents": {
|
||||
"defaults": {
|
||||
@@ -221,24 +312,24 @@ class TestIdleScanThrottling:
|
||||
tool_registry=ToolRegistry(),
|
||||
provider=provider,
|
||||
)
|
||||
loop.auto_compact.check_expired = MagicMock()
|
||||
loop.auto_compact.check_expired = AsyncMock()
|
||||
|
||||
loop._check_expired_sessions_if_due()
|
||||
await loop._check_expired_sessions_if_due()
|
||||
loop.auto_compact.check_expired.assert_called_once()
|
||||
loop._check_expired_sessions_if_due()
|
||||
await loop._check_expired_sessions_if_due()
|
||||
loop.auto_compact.check_expired.assert_called_once()
|
||||
loop._check_expired_sessions_if_due()
|
||||
await loop._check_expired_sessions_if_due()
|
||||
|
||||
assert loop.auto_compact.check_expired.call_count == 2
|
||||
|
||||
def test_zero_idle_scan_interval_checks_every_tick(self, tmp_path, monkeypatch):
|
||||
async def test_zero_idle_scan_interval_checks_every_tick(self, tmp_path, monkeypatch):
|
||||
"""An explicit zero should leave each idle tick eligible to scan."""
|
||||
monkeypatch.setattr("nanobot.agent.loop.time.monotonic", lambda: 1_000.0)
|
||||
monkeypatch.setattr("nanobot.agent.loop.time", SimpleNamespace(time=time.time, monotonic=lambda: 1_000.0))
|
||||
loop = _make_loop(tmp_path)
|
||||
loop.auto_compact.check_expired = MagicMock()
|
||||
loop.auto_compact.check_expired = AsyncMock()
|
||||
|
||||
loop._check_expired_sessions_if_due()
|
||||
loop._check_expired_sessions_if_due()
|
||||
await loop._check_expired_sessions_if_due()
|
||||
await loop._check_expired_sessions_if_due()
|
||||
|
||||
assert loop.auto_compact.check_expired.call_count == 2
|
||||
|
||||
@@ -274,7 +365,7 @@ class TestAutoCompact:
|
||||
loop.sessions.save(s2)
|
||||
|
||||
loop.consolidator.compact_idle_session = _make_fake_compact(loop)
|
||||
loop.auto_compact.check_expired(loop.schedule_background, loop.runtime_for_session)
|
||||
await loop.auto_compact.check_expired(loop.schedule_background, loop.runtime_for_session)
|
||||
await _drain_background_tasks(loop)
|
||||
|
||||
active_after = loop.sessions.get_or_create("cli:active")
|
||||
@@ -742,7 +833,7 @@ class TestProactiveAutoCompact:
|
||||
@staticmethod
|
||||
async def _run_check_expired(loop, active_session_keys=()):
|
||||
"""Helper: run check_expired via callback and wait for background tasks."""
|
||||
loop.auto_compact.check_expired(
|
||||
await loop.auto_compact.check_expired(
|
||||
loop.schedule_background,
|
||||
loop.runtime_for_session,
|
||||
active_session_keys=active_session_keys,
|
||||
@@ -763,15 +854,12 @@ class TestProactiveAutoCompact:
|
||||
healthy.add_message("user", "keep me")
|
||||
loop.sessions.save(healthy)
|
||||
|
||||
removed_path = loop.sessions._get_session_path(removed.key)
|
||||
original_open = open
|
||||
|
||||
def remove_before_open(path, *args, **kwargs):
|
||||
if Path(path) == removed_path:
|
||||
removed_path.unlink()
|
||||
return original_open(path, *args, **kwargs)
|
||||
|
||||
monkeypatch.setattr("builtins.open", remove_before_open)
|
||||
original_list = loop.sessions.list_sessions
|
||||
def delete_after_listing():
|
||||
rows = original_list()
|
||||
loop.sessions.delete_session(removed.key)
|
||||
return rows
|
||||
monkeypatch.setattr(loop.sessions.state, "list_sessions", AsyncMock(side_effect=delete_after_listing))
|
||||
|
||||
async def idle_once():
|
||||
loop._running = False
|
||||
@@ -881,12 +969,12 @@ class TestProactiveAutoCompact:
|
||||
loop.consolidator.compact_idle_session = _slow_compact
|
||||
|
||||
# First call starts archiving via callback
|
||||
loop.auto_compact.check_expired(loop.schedule_background, loop.runtime_for_session)
|
||||
await loop.auto_compact.check_expired(loop.schedule_background, loop.runtime_for_session)
|
||||
await started.wait()
|
||||
assert archive_count == 1
|
||||
|
||||
# Second call should skip (key is in _archiving)
|
||||
loop.auto_compact.check_expired(loop.schedule_background, loop.runtime_for_session)
|
||||
await loop.auto_compact.check_expired(loop.schedule_background, loop.runtime_for_session)
|
||||
assert archive_count == 1
|
||||
|
||||
# Clean up
|
||||
@@ -1008,8 +1096,9 @@ class TestProactiveAutoCompact:
|
||||
await loop.aclose()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_no_reschedule_after_successful_archive(self, tmp_path):
|
||||
"""Already-archived session should NOT be re-scheduled on subsequent ticks."""
|
||||
@pytest.mark.parametrize("command_tail", [False, True])
|
||||
async def test_no_reschedule_after_successful_archive(self, tmp_path, monkeypatch, command_tail):
|
||||
"""Idle scans skip archived history until another ordinary message arrives."""
|
||||
loop = _make_loop(tmp_path, session_ttl_minutes=15)
|
||||
session = loop.sessions.get_or_create("cli:test")
|
||||
_add_turns(session, 5, prefix="old")
|
||||
@@ -1019,14 +1108,33 @@ class TestProactiveAutoCompact:
|
||||
_fake_compact = _make_fake_compact(loop)
|
||||
loop.consolidator.compact_idle_session = _fake_compact
|
||||
|
||||
# First tick: archives the session
|
||||
await self._run_check_expired(loop)
|
||||
assert _fake_compact.state["count"] == 1
|
||||
try:
|
||||
await self._run_check_expired(loop)
|
||||
assert _fake_compact.state["count"] == 1
|
||||
|
||||
# Second tick: should NOT re-schedule because the session has no removable tail.
|
||||
await self._run_check_expired(loop)
|
||||
assert _fake_compact.state["count"] == 1 # Still 1, not re-scheduled
|
||||
await loop.aclose()
|
||||
if command_tail:
|
||||
session = await loop.sessions.state.get(session.key)
|
||||
session.add_message("user", "/status", _command=True)
|
||||
session.add_message("assistant", "Ready.", _command=True)
|
||||
session.updated_at = datetime.now() - timedelta(minutes=20)
|
||||
await loop.sessions.state.finish_turn(session)
|
||||
|
||||
await loop.sessions.state.discard(session.key)
|
||||
with monkeypatch.context() as patch:
|
||||
patch.setattr(loop.sessions.state, "get", AsyncMock(side_effect=AssertionError(
|
||||
"an idle scan must not load an already-archived transcript",
|
||||
)))
|
||||
await self._run_check_expired(loop)
|
||||
assert _fake_compact.state["count"] == 1
|
||||
|
||||
session = await loop.sessions.state.get(session.key)
|
||||
session.add_message("user", "Another topic.")
|
||||
session.updated_at = datetime.now() - timedelta(minutes=20)
|
||||
await loop.sessions.state.finish_turn(session)
|
||||
await self._run_check_expired(loop)
|
||||
assert _fake_compact.state["count"] == 2
|
||||
finally:
|
||||
await loop.aclose()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_empty_session_does_not_schedule_idle_compact(self, tmp_path):
|
||||
@@ -1068,12 +1176,7 @@ class TestProactiveAutoCompact:
|
||||
msg = InboundMessage(channel="cli", sender_id="user", chat_id="test", content="second topic")
|
||||
await loop._process_message(msg)
|
||||
|
||||
# Simulate idle again
|
||||
loop.sessions.invalidate("cli:test")
|
||||
session2 = loop.sessions.get_or_create("cli:test")
|
||||
session2.updated_at = datetime.now() - timedelta(minutes=20)
|
||||
loop.sessions.save(session2)
|
||||
|
||||
# Explicit archival does not require another TTL scan.
|
||||
# Second compact cycle should succeed
|
||||
await loop.auto_compact._archive("cli:test", runtime=loop.llm_runtime())
|
||||
assert _fake_compact.state["count"] == 2
|
||||
@@ -1131,7 +1234,7 @@ class TestSummaryPersistence:
|
||||
reloaded = loop.sessions.get_or_create("cli:test")
|
||||
assert len(reloaded.messages) == 13
|
||||
assert reloaded.get_history(max_messages=12) == []
|
||||
_, summary = loop.auto_compact.prepare_session(reloaded, "cli:test")
|
||||
_, summary = await loop.auto_compact.prepare_session(reloaded, "cli:test")
|
||||
|
||||
assert summary is not None
|
||||
assert summary["text"] == "User said hello."
|
||||
@@ -1158,9 +1261,9 @@ class TestSummaryPersistence:
|
||||
reloaded = loop.sessions.get_or_create("cli:test")
|
||||
|
||||
# Every call returns the persisted summary.
|
||||
_, summary = loop.auto_compact.prepare_session(reloaded, "cli:test")
|
||||
_, summary = await loop.auto_compact.prepare_session(reloaded, "cli:test")
|
||||
assert summary is not None
|
||||
_, summary2 = loop.auto_compact.prepare_session(reloaded, "cli:test")
|
||||
_, summary2 = await loop.auto_compact.prepare_session(reloaded, "cli:test")
|
||||
assert summary2 is not None
|
||||
assert summary2["text"] == "Summary."
|
||||
# _last_summary persists in metadata for restart survival.
|
||||
@@ -1187,7 +1290,7 @@ class TestSummaryPersistence:
|
||||
assert "_last_summary" in reloaded.metadata
|
||||
|
||||
# In-memory path is taken (no restart)
|
||||
_, summary = loop.auto_compact.prepare_session(reloaded, "cli:test")
|
||||
_, summary = await loop.auto_compact.prepare_session(reloaded, "cli:test")
|
||||
assert summary is not None
|
||||
# _last_summary persists in metadata for restart survival.
|
||||
assert "_last_summary" in reloaded.metadata
|
||||
@@ -1208,17 +1311,17 @@ class TestSummaryPersistence:
|
||||
await loop.auto_compact._archive("cli:test", runtime=loop.llm_runtime())
|
||||
|
||||
# Consume the first summary via hot path
|
||||
_, summary1 = loop.auto_compact.prepare_session(
|
||||
_, summary1 = await loop.auto_compact.prepare_session(
|
||||
loop.sessions.get_or_create("cli:test"), "cli:test"
|
||||
)
|
||||
assert summary1 is not None
|
||||
assert summary1["text"] == "First summary."
|
||||
assert "cli:test" not in loop.auto_compact._summaries # popped by hot path
|
||||
|
||||
# Add new messages and archive again (simulating a later turn)
|
||||
# Read the committed snapshot before starting the next edit.
|
||||
session = await loop.sessions.state.get("cli:test")
|
||||
_add_turns(session, 4, prefix="world")
|
||||
session.updated_at = datetime.now() - timedelta(minutes=20)
|
||||
loop.sessions.save(session)
|
||||
await loop.sessions.state.finish_turn(session)
|
||||
|
||||
loop.consolidator.compact_idle_session = _make_fake_compact(
|
||||
loop, summary="Second summary.",
|
||||
@@ -1230,7 +1333,7 @@ class TestSummaryPersistence:
|
||||
|
||||
# prepare_session must return the new summary
|
||||
reloaded = loop.sessions.get_or_create("cli:test")
|
||||
_, summary2 = loop.auto_compact.prepare_session(reloaded, "cli:test")
|
||||
_, summary2 = await loop.auto_compact.prepare_session(reloaded, "cli:test")
|
||||
assert summary2 is not None
|
||||
assert summary2["text"] == "Second summary."
|
||||
await loop.aclose()
|
||||
@@ -1254,9 +1357,7 @@ class TestSummaryPersistence:
|
||||
assert "_last_summary" in reloaded.metadata
|
||||
|
||||
# Simulate /new command
|
||||
reloaded.clear()
|
||||
loop.sessions.save(reloaded)
|
||||
loop.sessions.invalidate(reloaded.key)
|
||||
await loop.sessions.state.reset(reloaded.key)
|
||||
|
||||
# After /new, metadata should no longer contain _last_summary
|
||||
fresh = loop.sessions.get_or_create("cli:test")
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"""Direct unit tests for AutoCompact class methods in isolation."""
|
||||
|
||||
import asyncio
|
||||
from collections import defaultdict
|
||||
from datetime import datetime, timedelta
|
||||
from unittest.mock import AsyncMock, MagicMock
|
||||
|
||||
@@ -11,10 +12,22 @@ from nanobot.events import NO_EVENTS, ContextCompactionEvent, EventSink
|
||||
from nanobot.session.manager import Session, SessionManager
|
||||
|
||||
|
||||
def _mock_sessions():
|
||||
sessions = MagicMock(spec=SessionManager)
|
||||
sessions.state.get = AsyncMock(side_effect=lambda key: sessions.get_or_create(key))
|
||||
sessions.state.list_sessions = AsyncMock(side_effect=lambda: sessions.list_sessions())
|
||||
sessions.state.has_unarchived_messages = AsyncMock(return_value=True)
|
||||
return sessions
|
||||
|
||||
|
||||
def _runtime(_session: Session | None = None):
|
||||
return MagicMock(name="runtime")
|
||||
|
||||
|
||||
async def _resolve_runtime(session: Session):
|
||||
return _runtime(session)
|
||||
|
||||
|
||||
def _make_session(
|
||||
key: str = "cli:test",
|
||||
messages: list | None = None,
|
||||
@@ -41,7 +54,10 @@ def _make_autocompact(
|
||||
) -> AutoCompact:
|
||||
"""Create an AutoCompact with mock dependencies."""
|
||||
if sessions is None:
|
||||
sessions = MagicMock(spec=SessionManager)
|
||||
sessions = _mock_sessions()
|
||||
sessions.get_or_create.return_value = Session(key="cli:test")
|
||||
if isinstance(sessions, MagicMock):
|
||||
sessions.state.get = AsyncMock(side_effect=lambda key: sessions.get_or_create(key))
|
||||
if consolidator is None:
|
||||
consolidator = MagicMock()
|
||||
consolidator.compact_idle_session = AsyncMock(return_value="Summary.")
|
||||
@@ -49,7 +65,7 @@ def _make_autocompact(
|
||||
sessions=sessions,
|
||||
consolidator=consolidator,
|
||||
session_ttl_minutes=ttl,
|
||||
session_lock=lambda _key: asyncio.Lock(),
|
||||
session_lock=defaultdict(asyncio.Lock).__getitem__,
|
||||
)
|
||||
|
||||
|
||||
@@ -60,19 +76,21 @@ def _add_turns(session: Session, turns: int, *, prefix: str = "msg") -> None:
|
||||
session.add_message("assistant", f"{prefix} assistant {i}")
|
||||
|
||||
|
||||
def test_default_ttl_disables_idle_compaction():
|
||||
sessions = MagicMock(spec=SessionManager)
|
||||
async def test_default_ttl_disables_idle_compaction():
|
||||
sessions = _mock_sessions()
|
||||
sessions.list_sessions.return_value = [
|
||||
{"key": "cli:idle", "updated_at": datetime.now() - timedelta(days=365)},
|
||||
]
|
||||
sessions.get_or_create.return_value = _make_session(
|
||||
key="cli:idle", messages=[{"role": "user", "content": "pending"}],
|
||||
)
|
||||
ac = AutoCompact(sessions=sessions, consolidator=MagicMock(),
|
||||
session_lock=lambda _key: asyncio.Lock())
|
||||
ac = AutoCompact(
|
||||
sessions=sessions, consolidator=MagicMock(),
|
||||
session_lock=defaultdict(asyncio.Lock).__getitem__,
|
||||
)
|
||||
schedule = MagicMock(side_effect=lambda pending: pending.close())
|
||||
|
||||
ac.check_expired(schedule, _runtime)
|
||||
await ac.check_expired(schedule, _resolve_runtime)
|
||||
|
||||
assert schedule.call_count == 0
|
||||
|
||||
@@ -162,20 +180,20 @@ class TestIsExpired:
|
||||
class TestCheckExpired:
|
||||
"""Test AutoCompact.check_expired scheduling logic."""
|
||||
|
||||
def test_empty_sessions_list(self):
|
||||
async def test_empty_sessions_list(self):
|
||||
"""No sessions → schedule_background should never be called."""
|
||||
ac = _make_autocompact(ttl=15)
|
||||
mock_sm = MagicMock(spec=SessionManager)
|
||||
mock_sm = _mock_sessions()
|
||||
mock_sm.list_sessions.return_value = []
|
||||
ac.sessions = mock_sm
|
||||
scheduler = MagicMock()
|
||||
ac.check_expired(scheduler, _runtime)
|
||||
await ac.check_expired(scheduler, _resolve_runtime)
|
||||
scheduler.assert_not_called()
|
||||
|
||||
def test_expired_session_schedules_background(self):
|
||||
async def test_expired_session_schedules_background(self):
|
||||
"""Expired session should trigger schedule_background."""
|
||||
ac = _make_autocompact(ttl=15)
|
||||
mock_sm = MagicMock(spec=SessionManager)
|
||||
mock_sm = _mock_sessions()
|
||||
old_dt = datetime.now() - timedelta(minutes=20)
|
||||
session = _make_session("cli:old", updated_at=old_dt)
|
||||
_add_turns(session, 5)
|
||||
@@ -189,11 +207,11 @@ class TestCheckExpired:
|
||||
scheduled.append(coro)
|
||||
coro.close()
|
||||
|
||||
ac.check_expired(scheduler, _runtime)
|
||||
await ac.check_expired(scheduler, _resolve_runtime)
|
||||
assert len(scheduled) == 1
|
||||
assert "cli:old" in ac._archiving
|
||||
|
||||
def test_unparseable_updated_at_does_not_stop_scan(self):
|
||||
async def test_unparseable_updated_at_does_not_stop_scan(self):
|
||||
"""A malformed timestamp is skipped without hiding later sessions.
|
||||
|
||||
The idle scan runs from the agent loop's inbound-timeout branch, so a
|
||||
@@ -202,7 +220,7 @@ class TestCheckExpired:
|
||||
does when loading.
|
||||
"""
|
||||
ac = _make_autocompact(ttl=15)
|
||||
mock_sm = MagicMock(spec=SessionManager)
|
||||
mock_sm = _mock_sessions()
|
||||
old_dt = datetime.now() - timedelta(minutes=20)
|
||||
session = _make_session("cli:old", updated_at=old_dt)
|
||||
_add_turns(session, 5)
|
||||
@@ -218,7 +236,7 @@ class TestCheckExpired:
|
||||
scheduled.append(coro)
|
||||
coro.close()
|
||||
|
||||
ac.check_expired(scheduler, _runtime)
|
||||
await ac.check_expired(scheduler, _resolve_runtime)
|
||||
|
||||
assert len(scheduled) == 1
|
||||
assert ac._archiving == {"cli:old"}
|
||||
@@ -235,10 +253,10 @@ class TestCheckExpired:
|
||||
ac.sessions.get_or_create.return_value = session
|
||||
admitted = _runtime()
|
||||
replacement = _runtime()
|
||||
resolve_runtime = MagicMock(return_value=admitted)
|
||||
resolve_runtime = AsyncMock(return_value=admitted)
|
||||
scheduled = []
|
||||
|
||||
ac.check_expired(scheduled.append, resolve_runtime)
|
||||
await ac.check_expired(scheduled.append, resolve_runtime)
|
||||
resolve_runtime.return_value = replacement
|
||||
await scheduled[0]
|
||||
|
||||
@@ -250,7 +268,7 @@ class TestCheckExpired:
|
||||
)
|
||||
|
||||
@pytest.mark.parametrize("resolution_error", [KeyError, ValueError])
|
||||
def test_invalid_preset_is_isolated_to_one_session(self, resolution_error):
|
||||
async def test_invalid_preset_is_isolated_to_one_session(self, resolution_error):
|
||||
ac = _make_autocompact(ttl=15)
|
||||
old_dt = datetime.now() - timedelta(minutes=20)
|
||||
sessions = {
|
||||
@@ -266,7 +284,7 @@ class TestCheckExpired:
|
||||
ac.sessions.get_or_create.side_effect = sessions.__getitem__
|
||||
healthy_runtime = _runtime()
|
||||
|
||||
def resolve_runtime(session: Session):
|
||||
async def resolve_runtime(session: Session):
|
||||
if session.key == "cli:removed":
|
||||
raise resolution_error("model preset cannot be resolved")
|
||||
return healthy_runtime
|
||||
@@ -277,12 +295,12 @@ class TestCheckExpired:
|
||||
scheduled.append(coro)
|
||||
coro.close()
|
||||
|
||||
ac.check_expired(scheduler, resolve_runtime)
|
||||
await ac.check_expired(scheduler, resolve_runtime)
|
||||
|
||||
assert len(scheduled) == 1
|
||||
assert ac._archiving == {"cli:healthy"}
|
||||
|
||||
def test_unexpected_runtime_resolution_failure_propagates(self):
|
||||
async def test_unexpected_runtime_resolution_failure_propagates(self):
|
||||
ac = _make_autocompact(ttl=15)
|
||||
old_dt = datetime.now() - timedelta(minutes=20)
|
||||
session = _make_session("cli:old", updated_at=old_dt)
|
||||
@@ -292,59 +310,59 @@ class TestCheckExpired:
|
||||
]
|
||||
ac.sessions.get_or_create.return_value = session
|
||||
|
||||
def fail(_session: Session):
|
||||
async def fail(_session: Session):
|
||||
raise RuntimeError("unexpected resolver failure")
|
||||
|
||||
with pytest.raises(RuntimeError, match="unexpected resolver failure"):
|
||||
ac.check_expired(MagicMock(), fail)
|
||||
await ac.check_expired(MagicMock(), fail)
|
||||
|
||||
def test_active_session_key_skips(self):
|
||||
async def test_active_session_key_skips(self):
|
||||
"""Session in active_session_keys should be skipped."""
|
||||
ac = _make_autocompact(ttl=15)
|
||||
mock_sm = MagicMock(spec=SessionManager)
|
||||
mock_sm = _mock_sessions()
|
||||
old_ts = (datetime.now() - timedelta(minutes=20)).isoformat()
|
||||
mock_sm.list_sessions.return_value = [{"key": "cli:busy", "updated_at": old_ts}]
|
||||
ac.sessions = mock_sm
|
||||
scheduler = MagicMock()
|
||||
ac.check_expired(scheduler, _runtime, active_session_keys={"cli:busy"})
|
||||
await ac.check_expired(scheduler, _resolve_runtime, active_session_keys={"cli:busy"})
|
||||
scheduler.assert_not_called()
|
||||
|
||||
def test_session_already_in_archiving_skips(self):
|
||||
async def test_session_already_in_archiving_skips(self):
|
||||
"""Session already in _archiving set should be skipped."""
|
||||
ac = _make_autocompact(ttl=15)
|
||||
mock_sm = MagicMock(spec=SessionManager)
|
||||
mock_sm = _mock_sessions()
|
||||
old_ts = (datetime.now() - timedelta(minutes=20)).isoformat()
|
||||
mock_sm.list_sessions.return_value = [{"key": "cli:dup", "updated_at": old_ts}]
|
||||
ac.sessions = mock_sm
|
||||
ac._archiving.add("cli:dup")
|
||||
scheduler = MagicMock()
|
||||
ac.check_expired(scheduler, _runtime)
|
||||
await ac.check_expired(scheduler, _resolve_runtime)
|
||||
scheduler.assert_not_called()
|
||||
|
||||
def test_session_with_no_key_skips(self):
|
||||
async def test_session_with_no_key_skips(self):
|
||||
"""Session info with empty/missing key should be skipped."""
|
||||
ac = _make_autocompact(ttl=15)
|
||||
mock_sm = MagicMock(spec=SessionManager)
|
||||
mock_sm = _mock_sessions()
|
||||
mock_sm.list_sessions.return_value = [{"key": "", "updated_at": "old"}]
|
||||
ac.sessions = mock_sm
|
||||
scheduler = MagicMock()
|
||||
ac.check_expired(scheduler, _runtime)
|
||||
await ac.check_expired(scheduler, _resolve_runtime)
|
||||
scheduler.assert_not_called()
|
||||
|
||||
def test_session_with_missing_key_field_skips(self):
|
||||
async def test_session_with_missing_key_field_skips(self):
|
||||
"""Session info dict without 'key' field should be skipped."""
|
||||
ac = _make_autocompact(ttl=15)
|
||||
mock_sm = MagicMock(spec=SessionManager)
|
||||
mock_sm = _mock_sessions()
|
||||
mock_sm.list_sessions.return_value = [{"updated_at": "old"}]
|
||||
ac.sessions = mock_sm
|
||||
scheduler = MagicMock()
|
||||
ac.check_expired(scheduler, _runtime)
|
||||
await ac.check_expired(scheduler, _resolve_runtime)
|
||||
scheduler.assert_not_called()
|
||||
|
||||
def test_dream_session_skips(self):
|
||||
async def test_dream_session_skips(self):
|
||||
"""Internal Dream sessions should not be scheduled for idle compact."""
|
||||
ac = _make_autocompact(ttl=15)
|
||||
mock_sm = MagicMock(spec=SessionManager)
|
||||
mock_sm = _mock_sessions()
|
||||
old_ts = (datetime.now() - timedelta(minutes=20)).isoformat()
|
||||
mock_sm.list_sessions.return_value = [
|
||||
{"key": "dream:20260602-155256", "updated_at": old_ts},
|
||||
@@ -352,15 +370,15 @@ class TestCheckExpired:
|
||||
ac.sessions = mock_sm
|
||||
scheduler = MagicMock()
|
||||
|
||||
ac.check_expired(scheduler, _runtime)
|
||||
await ac.check_expired(scheduler, _resolve_runtime)
|
||||
|
||||
scheduler.assert_not_called()
|
||||
assert "dream:20260602-155256" not in ac._archiving
|
||||
|
||||
def test_short_unarchived_session_schedules(self):
|
||||
async def test_short_unarchived_session_schedules(self):
|
||||
"""A short idle session still needs an archive entry for Dream."""
|
||||
ac = _make_autocompact(ttl=15)
|
||||
mock_sm = MagicMock(spec=SessionManager)
|
||||
mock_sm = _mock_sessions()
|
||||
last_active = datetime(2026, 1, 1, 10, 0, 0)
|
||||
session = _make_session("cli:short", updated_at=last_active)
|
||||
_add_turns(session, 2)
|
||||
@@ -376,14 +394,14 @@ class TestCheckExpired:
|
||||
scheduled.append(coro)
|
||||
coro.close()
|
||||
|
||||
ac.check_expired(scheduler, _runtime)
|
||||
await ac.check_expired(scheduler, _resolve_runtime)
|
||||
|
||||
assert len(scheduled) == 1
|
||||
assert ac._archiving == {"cli:short"}
|
||||
|
||||
def test_fully_archived_session_skips(self):
|
||||
async def test_fully_archived_session_skips(self):
|
||||
ac = _make_autocompact(ttl=15)
|
||||
mock_sm = MagicMock(spec=SessionManager)
|
||||
mock_sm = _mock_sessions()
|
||||
last_active = datetime(2026, 1, 1, 10, 0, 0)
|
||||
session = _make_session("cli:done", updated_at=last_active)
|
||||
_add_turns(session, 2)
|
||||
@@ -392,12 +410,14 @@ class TestCheckExpired:
|
||||
{"key": "cli:done", "updated_at": last_active.isoformat()},
|
||||
]
|
||||
mock_sm.get_or_create.return_value = session
|
||||
mock_sm.state.has_unarchived_messages.return_value = False
|
||||
ac.sessions = mock_sm
|
||||
|
||||
scheduler = MagicMock()
|
||||
ac.check_expired(scheduler, _runtime)
|
||||
await ac.check_expired(scheduler, _resolve_runtime)
|
||||
|
||||
scheduler.assert_not_called()
|
||||
mock_sm.state.get.assert_not_awaited()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -411,7 +431,8 @@ class TestArchiveDelegates:
|
||||
@pytest.mark.asyncio
|
||||
async def test_calls_compact_idle_session(self):
|
||||
ac = _make_autocompact()
|
||||
mock_sm = MagicMock(spec=SessionManager)
|
||||
mock_sm = _mock_sessions()
|
||||
mock_sm.get_or_create.return_value = Session(key="cli:test")
|
||||
ac.sessions = mock_sm
|
||||
ac.consolidator.compact_idle_session = AsyncMock(return_value="Summary.")
|
||||
|
||||
@@ -426,7 +447,8 @@ class TestArchiveDelegates:
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_forwards_timeout_compaction_events_with_session_key(self):
|
||||
sessions = MagicMock(spec=SessionManager)
|
||||
sessions = _mock_sessions()
|
||||
sessions.get_or_create.return_value = Session(key="cli:test")
|
||||
consolidator = MagicMock()
|
||||
observed: list[tuple[str, ContextCompactionEvent]] = []
|
||||
|
||||
@@ -446,7 +468,7 @@ class TestArchiveDelegates:
|
||||
consolidator=consolidator,
|
||||
session_ttl_minutes=15,
|
||||
bind_events=bind,
|
||||
session_lock=lambda _key: asyncio.Lock(),
|
||||
session_lock=defaultdict(asyncio.Lock).__getitem__,
|
||||
)
|
||||
|
||||
await ac._archive("cli:test", runtime=_runtime())
|
||||
@@ -469,7 +491,7 @@ class TestArchiveDelegates:
|
||||
@pytest.mark.asyncio
|
||||
async def test_populates_summaries_from_metadata(self):
|
||||
ac = _make_autocompact()
|
||||
mock_sm = MagicMock(spec=SessionManager)
|
||||
mock_sm = _mock_sessions()
|
||||
session = _make_session(
|
||||
metadata={"_last_summary": {"text": "Hello.", "last_active": "2026-05-13T10:00:00"}}
|
||||
)
|
||||
@@ -486,7 +508,7 @@ class TestArchiveDelegates:
|
||||
@pytest.mark.asyncio
|
||||
async def test_no_summary_when_compact_returns_empty(self):
|
||||
ac = _make_autocompact()
|
||||
mock_sm = MagicMock(spec=SessionManager)
|
||||
mock_sm = _mock_sessions()
|
||||
ac.sessions = mock_sm
|
||||
ac.consolidator.compact_idle_session = AsyncMock(return_value="")
|
||||
|
||||
@@ -497,7 +519,7 @@ class TestArchiveDelegates:
|
||||
@pytest.mark.asyncio
|
||||
async def test_no_summary_when_compact_returns_nothing(self):
|
||||
ac = _make_autocompact()
|
||||
mock_sm = MagicMock(spec=SessionManager)
|
||||
mock_sm = _mock_sessions()
|
||||
ac.sessions = mock_sm
|
||||
ac.consolidator.compact_idle_session = AsyncMock(return_value="(nothing)")
|
||||
|
||||
@@ -508,7 +530,7 @@ class TestArchiveDelegates:
|
||||
@pytest.mark.asyncio
|
||||
async def test_exception_still_removes_from_archiving(self):
|
||||
ac = _make_autocompact()
|
||||
mock_sm = MagicMock(spec=SessionManager)
|
||||
mock_sm = _mock_sessions()
|
||||
ac.sessions = mock_sm
|
||||
ac.consolidator.compact_idle_session = AsyncMock(side_effect=RuntimeError("fail"))
|
||||
|
||||
@@ -526,36 +548,21 @@ class TestArchiveDelegates:
|
||||
class TestPrepareSession:
|
||||
"""Test AutoCompact.prepare_session logic."""
|
||||
|
||||
def test_key_in_archiving_reloads_session(self):
|
||||
"""If key is in _archiving, session should be reloaded via get_or_create."""
|
||||
ac = _make_autocompact()
|
||||
mock_sm = MagicMock(spec=SessionManager)
|
||||
reloaded = _make_session(key="cli:test")
|
||||
mock_sm.get_or_create.return_value = reloaded
|
||||
ac.sessions = mock_sm
|
||||
ac._archiving.add("cli:test")
|
||||
|
||||
original_session = _make_session()
|
||||
result_session, summary = ac.prepare_session(original_session, "cli:test")
|
||||
|
||||
mock_sm.get_or_create.assert_called_once_with("cli:test")
|
||||
assert result_session is reloaded
|
||||
|
||||
def test_expired_session_reloads(self):
|
||||
"""If session is expired, it should be reloaded via get_or_create."""
|
||||
@pytest.mark.parametrize("archiving", [False, True])
|
||||
async def test_preparing_idle_session_preserves_turn_metadata(self, archiving):
|
||||
ac = _make_autocompact(ttl=15)
|
||||
mock_sm = MagicMock(spec=SessionManager)
|
||||
reloaded = _make_session(key="cli:test", updated_at=datetime.now())
|
||||
mock_sm.get_or_create.return_value = reloaded
|
||||
ac.sessions = mock_sm
|
||||
session = _make_session(
|
||||
updated_at=datetime.now() - timedelta(minutes=20),
|
||||
metadata={"last_channel": "discord:new"},
|
||||
)
|
||||
if archiving:
|
||||
ac._archiving.add(session.key)
|
||||
|
||||
old_session = _make_session(updated_at=datetime.now() - timedelta(minutes=20))
|
||||
result_session, summary = ac.prepare_session(old_session, "cli:test")
|
||||
prepared, _ = await ac.prepare_session(session, session.key)
|
||||
|
||||
mock_sm.get_or_create.assert_called_once_with("cli:test")
|
||||
assert result_session is reloaded
|
||||
assert prepared.metadata["last_channel"] == "discord:new"
|
||||
|
||||
def test_hot_path_summary_from_summaries(self):
|
||||
async def test_hot_path_summary_from_summaries(self):
|
||||
"""Summary from _summaries dict should be returned (hot path)."""
|
||||
ac = _make_autocompact()
|
||||
session = _make_session()
|
||||
@@ -565,7 +572,7 @@ class TestPrepareSession:
|
||||
"last_active": last_active.isoformat(),
|
||||
}
|
||||
|
||||
result_session, summary = ac.prepare_session(session, "cli:test")
|
||||
result_session, summary = await ac.prepare_session(session, "cli:test")
|
||||
|
||||
assert result_session is session
|
||||
assert summary is not None
|
||||
@@ -574,7 +581,7 @@ class TestPrepareSession:
|
||||
"last_active": last_active.isoformat(),
|
||||
}
|
||||
|
||||
def test_hot_path_pops_summary_one_shot(self):
|
||||
async def test_hot_path_pops_summary_one_shot(self):
|
||||
"""Hot path should pop the summary (one-shot; second call returns None)."""
|
||||
ac = _make_autocompact()
|
||||
session = _make_session()
|
||||
@@ -584,13 +591,13 @@ class TestPrepareSession:
|
||||
"last_active": last_active.isoformat(),
|
||||
}
|
||||
|
||||
_, summary1 = ac.prepare_session(session, "cli:test")
|
||||
_, summary1 = await ac.prepare_session(session, "cli:test")
|
||||
assert summary1 is not None
|
||||
# Second call: hot path entry was popped
|
||||
_, summary2 = ac.prepare_session(session, "cli:test")
|
||||
_, summary2 = await ac.prepare_session(session, "cli:test")
|
||||
assert summary2 is None
|
||||
|
||||
def test_cold_path_summary_from_metadata(self):
|
||||
async def test_cold_path_summary_from_metadata(self):
|
||||
"""When _summaries is empty, summary should come from metadata (cold path)."""
|
||||
ac = _make_autocompact()
|
||||
last_active = datetime(2026, 5, 13, 14, 0, 0)
|
||||
@@ -601,13 +608,13 @@ class TestPrepareSession:
|
||||
},
|
||||
})
|
||||
|
||||
result_session, summary = ac.prepare_session(session, "cli:test")
|
||||
result_session, summary = await ac.prepare_session(session, "cli:test")
|
||||
|
||||
assert result_session is session
|
||||
assert summary is not None
|
||||
assert summary["text"] == "Cold summary."
|
||||
|
||||
def test_cold_path_tolerates_malformed_last_active(self):
|
||||
async def test_cold_path_tolerates_malformed_last_active(self):
|
||||
"""A malformed persisted last_active must not raise on the turn path.
|
||||
|
||||
prepare_session runs from _compact_session on every turn. Persisted
|
||||
@@ -624,7 +631,7 @@ class TestPrepareSession:
|
||||
updated_at=fallback,
|
||||
)
|
||||
|
||||
result_session, summary = ac.prepare_session(session, "cli:test")
|
||||
result_session, summary = await ac.prepare_session(session, "cli:test")
|
||||
|
||||
assert result_session is session
|
||||
assert summary is not None
|
||||
@@ -633,7 +640,7 @@ class TestPrepareSession:
|
||||
"last_active": fallback.isoformat(),
|
||||
}
|
||||
|
||||
def test_cold_path_tolerates_missing_last_active(self):
|
||||
async def test_cold_path_tolerates_missing_last_active(self):
|
||||
"""A _last_summary dict without last_active must not raise."""
|
||||
ac = _make_autocompact(ttl=0)
|
||||
fallback = datetime(2026, 1, 2, 3, 4, 5)
|
||||
@@ -642,7 +649,7 @@ class TestPrepareSession:
|
||||
updated_at=fallback,
|
||||
)
|
||||
|
||||
result_session, summary = ac.prepare_session(session, "cli:test")
|
||||
result_session, summary = await ac.prepare_session(session, "cli:test")
|
||||
|
||||
assert result_session is session
|
||||
assert summary is not None
|
||||
@@ -651,32 +658,32 @@ class TestPrepareSession:
|
||||
"last_active": fallback.isoformat(),
|
||||
}
|
||||
|
||||
def test_cold_path_missing_text_returns_none(self):
|
||||
async def test_cold_path_missing_text_returns_none(self):
|
||||
"""A _last_summary without a non-empty string text yields no summary."""
|
||||
ac = _make_autocompact()
|
||||
session = _make_session(metadata={
|
||||
"_last_summary": {"last_active": datetime(2026, 1, 1).isoformat()},
|
||||
})
|
||||
|
||||
result_session, summary = ac.prepare_session(session, "cli:test")
|
||||
result_session, summary = await ac.prepare_session(session, "cli:test")
|
||||
|
||||
assert result_session is session
|
||||
assert summary is None
|
||||
|
||||
def test_no_summary_available_returns_none(self):
|
||||
async def test_no_summary_available_returns_none(self):
|
||||
"""When no summary is available, should return (session, None)."""
|
||||
ac = _make_autocompact()
|
||||
session = _make_session()
|
||||
|
||||
result_session, summary = ac.prepare_session(session, "cli:test")
|
||||
result_session, summary = await ac.prepare_session(session, "cli:test")
|
||||
|
||||
assert result_session is session
|
||||
assert summary is None
|
||||
|
||||
def test_dream_session_skips_reload_and_summaries(self):
|
||||
async def test_dream_session_skips_reload_and_summaries(self):
|
||||
"""Internal Dream sessions should not reload or receive compact summaries."""
|
||||
ac = _make_autocompact(ttl=15)
|
||||
mock_sm = MagicMock(spec=SessionManager)
|
||||
mock_sm = _mock_sessions()
|
||||
ac.sessions = mock_sm
|
||||
key = "dream:20260602-155256"
|
||||
ac._archiving.add(key)
|
||||
@@ -695,7 +702,7 @@ class TestPrepareSession:
|
||||
},
|
||||
)
|
||||
|
||||
result_session, summary = ac.prepare_session(session, key)
|
||||
result_session, summary = await ac.prepare_session(session, key)
|
||||
|
||||
mock_sm.get_or_create.assert_not_called()
|
||||
assert result_session is session
|
||||
@@ -703,17 +710,17 @@ class TestPrepareSession:
|
||||
assert key not in ac._archiving
|
||||
assert key not in ac._summaries
|
||||
|
||||
def test_cold_path_metadata_not_dict_returns_none(self):
|
||||
async def test_cold_path_metadata_not_dict_returns_none(self):
|
||||
"""If metadata _last_summary is not a dict, should return None summary."""
|
||||
ac = _make_autocompact()
|
||||
session = _make_session(metadata={"_last_summary": "not a dict"})
|
||||
|
||||
result_session, summary = ac.prepare_session(session, "cli:test")
|
||||
result_session, summary = await ac.prepare_session(session, "cli:test")
|
||||
|
||||
assert result_session is session
|
||||
assert summary is None
|
||||
|
||||
def test_hot_path_takes_priority_over_metadata(self):
|
||||
async def test_hot_path_takes_priority_over_metadata(self):
|
||||
"""Hot path (_summaries) should take priority over metadata."""
|
||||
ac = _make_autocompact()
|
||||
session = _make_session(metadata={
|
||||
@@ -728,7 +735,7 @@ class TestPrepareSession:
|
||||
"last_active": last_active.isoformat(),
|
||||
}
|
||||
|
||||
_, summary = ac.prepare_session(session, "cli:test")
|
||||
_, summary = await ac.prepare_session(session, "cli:test")
|
||||
assert summary is not None
|
||||
assert summary["text"] == "Hot summary."
|
||||
# After hot path pops, cold path would kick in on next call
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
import asyncio
|
||||
from datetime import datetime, timedelta
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
|
||||
@@ -56,18 +57,18 @@ async def seed_history(bot, key):
|
||||
])
|
||||
|
||||
|
||||
def schedule_idle_archive(bot, key):
|
||||
session = bot._loop.sessions.get_or_create(key)
|
||||
session.updated_at = datetime.now() - timedelta(minutes=30)
|
||||
bot._loop.sessions.save(session)
|
||||
async def schedule_idle_archive(bot):
|
||||
scheduled = []
|
||||
bot._loop.auto_compact.check_expired(scheduled.append, bot._loop.runtime_for_session)
|
||||
with patch("nanobot.agent.autocompact.datetime") as clock:
|
||||
clock.now.return_value = datetime.now() + timedelta(minutes=30)
|
||||
clock.fromisoformat.side_effect = datetime.fromisoformat
|
||||
await bot._loop.auto_compact.check_expired(scheduled.append, bot._loop.runtime_for_session)
|
||||
assert len(scheduled) == 1
|
||||
return scheduled[0]
|
||||
|
||||
|
||||
def assert_reply_and_summary(bot, key):
|
||||
snapshot = bot.sessions.export(key)
|
||||
async def assert_reply_and_summary(bot, key):
|
||||
snapshot = await bot.sessions.export(key)
|
||||
assert snapshot is not None
|
||||
assert ("assistant", "new reply") in [
|
||||
(message["role"], message["content"]) for message in snapshot.messages
|
||||
@@ -82,7 +83,7 @@ async def test_compaction_waits_for_active_sdk_turn_and_preserves_reply(
|
||||
bot, provider = bot
|
||||
key = "sdk:shared"
|
||||
await seed_history(bot, key)
|
||||
idle_archive = schedule_idle_archive(bot, key) if trigger == "scheduled_idle" else None
|
||||
idle_archive = await schedule_idle_archive(bot) if trigger == "scheduled_idle" else None
|
||||
compact_attempted = asyncio.Event()
|
||||
|
||||
async def compact():
|
||||
@@ -112,7 +113,7 @@ async def test_compaction_waits_for_active_sdk_turn_and_preserves_reply(
|
||||
provider.release_summary.set()
|
||||
compacted = await asyncio.wait_for(compaction, timeout=5)
|
||||
|
||||
assert_reply_and_summary(bot, key)
|
||||
await assert_reply_and_summary(bot, key)
|
||||
assert summary_started_during_turn is False
|
||||
assert {"role": "assistant", "content": "new reply"} in provider.summary_messages
|
||||
if trigger == "compact_session":
|
||||
@@ -123,7 +124,7 @@ async def test_compaction_waits_for_active_sdk_turn_and_preserves_reply(
|
||||
|
||||
await bot.aclose()
|
||||
async with Nanobot(loop_factory(provider=ControlledProvider())) as restarted:
|
||||
assert_reply_and_summary(restarted, key)
|
||||
await assert_reply_and_summary(restarted, key)
|
||||
finally:
|
||||
provider.release_turn.set()
|
||||
provider.release_summary.set()
|
||||
@@ -136,7 +137,7 @@ async def test_sdk_turn_waits_for_running_idle_archive_and_uses_its_summary(bot)
|
||||
bot, provider = bot
|
||||
key = "sdk:shared"
|
||||
await seed_history(bot, key)
|
||||
archive = asyncio.create_task(schedule_idle_archive(bot, key))
|
||||
archive = asyncio.create_task(await schedule_idle_archive(bot))
|
||||
turn_attempted = asyncio.Event()
|
||||
|
||||
async def run():
|
||||
@@ -160,7 +161,7 @@ async def test_sdk_turn_waits_for_running_idle_archive_and_uses_its_summary(bot)
|
||||
provider.release_turn.set()
|
||||
result = await asyncio.wait_for(turn, timeout=5)
|
||||
assert result.content == "new reply"
|
||||
assert_reply_and_summary(bot, key)
|
||||
await assert_reply_and_summary(bot, key)
|
||||
finally:
|
||||
provider.release_turn.set()
|
||||
provider.release_summary.set()
|
||||
|
||||
@@ -880,10 +880,10 @@ class TestCompactIdleSession:
|
||||
"cli:incremental",
|
||||
runtime=runtime,
|
||||
)
|
||||
current = sessions.get_or_create("cli:incremental")
|
||||
current = await sessions.state.get("cli:incremental")
|
||||
current.add_message("user", "second user")
|
||||
current.add_message("assistant", "second assistant")
|
||||
sessions.save(current)
|
||||
await sessions.state.finish_turn(current)
|
||||
second = await real_consolidator.compact_idle_session(
|
||||
"cli:incremental",
|
||||
runtime=runtime,
|
||||
@@ -928,10 +928,10 @@ class TestCompactIdleSession:
|
||||
"cli:cumulative-fallback",
|
||||
runtime=runtime,
|
||||
)
|
||||
current = sessions.get_or_create("cli:cumulative-fallback")
|
||||
current = await sessions.state.get("cli:cumulative-fallback")
|
||||
current.add_message("user", "second user")
|
||||
current.add_message("assistant", "newest working state")
|
||||
sessions.save(current)
|
||||
await sessions.state.finish_turn(current)
|
||||
|
||||
fallback = await real_consolidator.compact_idle_session(
|
||||
"cli:cumulative-fallback",
|
||||
@@ -971,10 +971,10 @@ class TestCompactIdleSession:
|
||||
runtime=runtime,
|
||||
)
|
||||
|
||||
current = sessions.get_or_create("cli:nothing-after-summary")
|
||||
current = await sessions.state.get("cli:nothing-after-summary")
|
||||
current.add_message("user", "thanks")
|
||||
current.add_message("assistant", "you're welcome")
|
||||
sessions.save(current)
|
||||
await sessions.state.finish_turn(current)
|
||||
result = await real_consolidator.compact_idle_session(
|
||||
"cli:nothing-after-summary",
|
||||
runtime=runtime,
|
||||
@@ -999,9 +999,10 @@ class TestCompactIdleSession:
|
||||
sessions.save(session)
|
||||
|
||||
async def append_during_archive(**_kwargs):
|
||||
current = sessions.get_or_create("cli:concurrent")
|
||||
current = await sessions.state.get("cli:concurrent")
|
||||
current.add_message("user", "late user")
|
||||
current.add_message("assistant", "late assistant")
|
||||
await sessions.state.finish_turn(current)
|
||||
return LLMResponse(content="Summary.", finish_reason="stop")
|
||||
|
||||
mock_provider.chat_stream_with_retry.side_effect = append_during_archive
|
||||
|
||||
@@ -402,9 +402,7 @@ class TestEphemeralDirect:
|
||||
)
|
||||
|
||||
with (
|
||||
patch("nanobot.agent.loop.SessionManager"),
|
||||
patch("nanobot.agent.loop.SubagentManager") as mock_sub,
|
||||
patch("nanobot.agent.loop.Consolidator"),
|
||||
):
|
||||
mock_sub.return_value.cancel_by_session = AsyncMock(return_value=0)
|
||||
loop = AgentLoop(
|
||||
@@ -695,7 +693,7 @@ class TestEphemeralDirect:
|
||||
for marker in [*markers.values(), "DREAM_AGENTS_MARKER"]:
|
||||
assert marker in system_prompt
|
||||
assert request_text.count(marker) == 1
|
||||
assert loop.sessions._get_session_path(session_key).exists()
|
||||
assert loop.sessions.read_session_snapshot(session_key) is not None
|
||||
|
||||
|
||||
class TestEphemeralHooks:
|
||||
@@ -725,13 +723,12 @@ class TestEphemeralHooks:
|
||||
|
||||
spy = MagicMock(spec=AgentHook)
|
||||
spy.wants_streaming.return_value = False
|
||||
spy.before_iteration = AsyncMock()
|
||||
spy.after_iteration = AsyncMock()
|
||||
spy.finalize_content.side_effect = lambda context, content: content
|
||||
spy.before_iteration = AsyncMock(return_value=None)
|
||||
spy.after_iteration = AsyncMock(return_value=None)
|
||||
|
||||
with (
|
||||
patch("nanobot.agent.loop.SessionManager"),
|
||||
patch("nanobot.agent.loop.SubagentManager") as mock_sub,
|
||||
patch("nanobot.agent.loop.Consolidator"),
|
||||
):
|
||||
mock_sub.return_value.cancel_by_session = AsyncMock(return_value=0)
|
||||
loop = AgentLoop(
|
||||
|
||||
@@ -25,91 +25,39 @@ class TestDreamSessionKey:
|
||||
|
||||
|
||||
class TestPruneDreamSessions:
|
||||
def test_keeps_n_most_recent(self, tmp_path):
|
||||
import os
|
||||
import time
|
||||
async def test_keeps_n_most_recent(self, tmp_path):
|
||||
manager = SessionManager(tmp_path / "workspace", sessions_root=tmp_path / "runtime")
|
||||
keys = [f"dream:20260528-{100000 + i:06d}" for i in range(15)]
|
||||
for i, key in enumerate(keys):
|
||||
session = manager.get_or_create(key)
|
||||
session.updated_at = datetime(2026, 5, 28, 10, 0, i)
|
||||
manager.save(session)
|
||||
manager.save(manager.get_or_create("telegram:normal"))
|
||||
|
||||
manager = SessionManager(
|
||||
tmp_path / "workspace",
|
||||
sessions_root=tmp_path / "runtime",
|
||||
)
|
||||
sessions_dir = manager.sessions_dir
|
||||
assert await manager.state.prune_dream_sessions(keep=10) == 5
|
||||
await manager.state.aclose()
|
||||
|
||||
base_time = time.time() - 100
|
||||
dream_paths = []
|
||||
assert [manager.read_session_snapshot(key) is not None for key in keys] == [False] * 5 + [True] * 10
|
||||
assert manager.read_session_snapshot("telegram:normal") is not None
|
||||
|
||||
for i in range(15):
|
||||
key = f"dream:20260528-{100000 + i:06d}"
|
||||
path = sessions_dir / f"{SessionManager._storage_key(key)}.jsonl"
|
||||
path.write_text(
|
||||
f'{{"_type": "metadata", "key": "{key}", '
|
||||
f'"created_at": "2026-05-28T10:00:{i:02d}", '
|
||||
f'"updated_at": "2026-05-28T10:00:{i:02d}"}}\n',
|
||||
encoding="utf-8",
|
||||
)
|
||||
os.utime(path, (base_time + i, base_time + i))
|
||||
dream_paths.append(path)
|
||||
async def test_leaves_legacy_backup_untouched(self, tmp_path):
|
||||
manager = SessionManager(tmp_path / "workspace", sessions_root=tmp_path / "runtime")
|
||||
path = manager.sessions_dir / "dream_20260713-095959.jsonl"
|
||||
path.write_text('legacy backup', encoding="utf-8")
|
||||
await manager.state.prune_dream_sessions(keep=0)
|
||||
await manager.state.aclose()
|
||||
assert path.read_text(encoding="utf-8") == 'legacy backup'
|
||||
|
||||
normal_path = sessions_dir / "telegram_123.jsonl"
|
||||
normal_path.write_text('{"_type": "metadata"}\n', encoding="utf-8")
|
||||
|
||||
MemoryStore.prune_dream_sessions(manager, keep=10)
|
||||
|
||||
assert [path.exists() for path in dream_paths] == [False] * 5 + [True] * 10
|
||||
assert normal_path.exists()
|
||||
|
||||
def test_ignores_legacy_dream_filenames(self, tmp_path):
|
||||
import os
|
||||
import time
|
||||
|
||||
manager = SessionManager(
|
||||
tmp_path / "workspace",
|
||||
sessions_root=tmp_path / "runtime",
|
||||
)
|
||||
sessions_dir = manager.sessions_dir
|
||||
base_time = time.time() - 100
|
||||
current_paths = []
|
||||
|
||||
for i in range(2):
|
||||
key = f"dream:20260713-{100000 + i:06d}"
|
||||
path = sessions_dir / f"{SessionManager._storage_key(key)}.jsonl"
|
||||
path.write_text(
|
||||
f'{{"_type": "metadata", "key": "{key}"}}\n',
|
||||
encoding="utf-8",
|
||||
)
|
||||
os.utime(path, (base_time + i, base_time + i))
|
||||
current_paths.append(path)
|
||||
|
||||
legacy_path = sessions_dir / "dream_20260713-095959.jsonl"
|
||||
legacy_path.write_text(
|
||||
'{"_type": "metadata", "key": "dream:20260713-095959"}\n',
|
||||
encoding="utf-8",
|
||||
)
|
||||
os.utime(legacy_path, (base_time - 1, base_time - 1))
|
||||
|
||||
MemoryStore.prune_dream_sessions(manager, keep=1)
|
||||
|
||||
assert [path.exists() for path in current_paths] == [False, True]
|
||||
assert legacy_path.exists()
|
||||
|
||||
def test_noop_when_under_limit(self, tmp_path):
|
||||
manager = SessionManager(
|
||||
tmp_path / "workspace",
|
||||
sessions_root=tmp_path / "runtime",
|
||||
)
|
||||
sessions_dir = manager.sessions_dir
|
||||
async def test_noop_when_under_limit(self, tmp_path):
|
||||
manager = SessionManager(tmp_path / "workspace", sessions_root=tmp_path / "runtime")
|
||||
for i in range(3):
|
||||
key = f"dream:20260528-{100000 + i:06d}"
|
||||
path = sessions_dir / f"{SessionManager._storage_key(key)}.jsonl"
|
||||
path.write_text("{}", encoding="utf-8")
|
||||
manager.save(manager.get_or_create(f"dream:20260528-{100000 + i:06d}"))
|
||||
assert await manager.state.prune_dream_sessions(keep=10) == 0
|
||||
await manager.state.aclose()
|
||||
assert len(manager.list_sessions()) == 3
|
||||
|
||||
MemoryStore.prune_dream_sessions(manager, keep=10)
|
||||
assert len(list(sessions_dir.glob("*.jsonl"))) == 3
|
||||
|
||||
def test_empty_dir_noop(self, tmp_path):
|
||||
manager = SessionManager(
|
||||
tmp_path / "workspace",
|
||||
sessions_root=tmp_path / "runtime",
|
||||
)
|
||||
MemoryStore.prune_dream_sessions(manager, keep=10)
|
||||
assert list(manager.sessions_dir.glob("*.jsonl")) == []
|
||||
async def test_empty_store_noop(self, tmp_path):
|
||||
manager = SessionManager(tmp_path / "workspace", sessions_root=tmp_path / "runtime")
|
||||
assert await manager.state.prune_dream_sessions(keep=10) == 0
|
||||
await manager.state.aclose()
|
||||
assert manager.list_sessions() == []
|
||||
@@ -73,8 +73,7 @@ async def test_process_message_hands_complete_replay_to_runner(tmp_path: Path) -
|
||||
)
|
||||
loop.tools.get_definitions = MagicMock(return_value=[])
|
||||
|
||||
session = loop.sessions.get_or_create("cli:test")
|
||||
session.messages = _populated_session(30).messages
|
||||
session = await loop.sessions.state.import_messages("cli:test", _populated_session(30).messages)
|
||||
expected_history = session.get_history()
|
||||
loop.provider.aclose = AsyncMock()
|
||||
result = await loop.process_direct("hello", session_key="cli:test")
|
||||
|
||||
@@ -6,6 +6,7 @@ from unittest.mock import AsyncMock, MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from agent.session_helpers import mock_session_manager
|
||||
from nanobot.agent.context import TranscriptInput
|
||||
from nanobot.agent.hook import (
|
||||
AgentHook,
|
||||
@@ -438,7 +439,7 @@ def _make_loop(tmp_path, hooks=None, hook_factories=None):
|
||||
provider.generation.max_tokens = 4096
|
||||
|
||||
with patch("nanobot.agent.loop.ContextBuilder"), \
|
||||
patch("nanobot.agent.loop.SessionManager"), \
|
||||
patch("nanobot.agent.loop.SessionManager", side_effect=mock_session_manager), \
|
||||
patch("nanobot.agent.loop.SubagentManager") as mock_sub_mgr, \
|
||||
patch("nanobot.agent.loop.Consolidator"):
|
||||
mock_sub_mgr.return_value.cancel_by_session = AsyncMock(return_value=0)
|
||||
|
||||
@@ -596,10 +596,10 @@ class TestToolEventProgress:
|
||||
calls += 1
|
||||
if calls == 1:
|
||||
await on_content_delta("old partial")
|
||||
loop._enqueue_session_message(InboundMessage(
|
||||
(await loop._enqueue_session_message(InboundMessage(
|
||||
channel="websocket", sender_id="u", chat_id="test", content="new question",
|
||||
metadata={"_wants_stream": True},
|
||||
))
|
||||
)))
|
||||
return LLMResponse(content="old partial", finish_reason="length")
|
||||
has_followup = any(
|
||||
"new question" in str(message.get("content", ""))
|
||||
@@ -869,7 +869,7 @@ class TestToolEventProgress:
|
||||
session.add_message("user", "Run this in the background")
|
||||
session.metadata.update({"webui": True, "title": "Existing title"})
|
||||
loop.sessions.save(session)
|
||||
save_completed_subagent(loop, "sub-1", session_key)
|
||||
await save_completed_subagent(loop, "sub-1", session_key)
|
||||
dispatch = asyncio.create_task(run_session(loop, InboundMessage(
|
||||
channel="system",
|
||||
sender_id="subagent",
|
||||
|
||||
@@ -108,7 +108,8 @@ async def test_recovery_preserves_turn_origin_until_the_next_user_turn(
|
||||
channel="websocket", sender_id="user", chat_id="chat", content="Inspect configuration",
|
||||
metadata={"webui": True, "webui_turn_id": "user-request", "message_id": "user-message"},
|
||||
)
|
||||
loop.sessions.get_or_create(request.session_key).metadata["title"] = "Configuration"
|
||||
await loop.sessions.state.get(request.session_key)
|
||||
await loop.sessions.state.update_metadata(request.session_key, {"title": "Configuration"})
|
||||
with coordinator.connected():
|
||||
if late_result:
|
||||
provider.chat_stream_with_retry = AsyncMock(side_effect=[
|
||||
@@ -119,7 +120,7 @@ async def test_recovery_preserves_turn_origin_until_the_next_user_turn(
|
||||
channel="websocket", sender_id="user", chat_id="chat", content="New request B",
|
||||
metadata={"webui": True, "webui_turn_id": "request-b", "message_id": "message-b"},
|
||||
), asyncio.Queue())
|
||||
save_completed_subagent(loop, "task-a", request.session_key)
|
||||
await save_completed_subagent(loop, "task-a", request.session_key)
|
||||
request = InboundMessage(
|
||||
channel="system", sender_id="subagent", chat_id=request.session_key,
|
||||
content="Background check for the original request completed",
|
||||
|
||||
@@ -7,6 +7,7 @@ from unittest.mock import AsyncMock, MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from agent.session_helpers import mock_session_manager
|
||||
from nanobot.agent.context import TranscriptInput
|
||||
from nanobot.agent.goal_permission import goal_mutation_allowed, goal_mutation_permission
|
||||
from nanobot.agent.tools.context import RequestContext
|
||||
@@ -46,7 +47,7 @@ def _make_loop(tmp_path):
|
||||
provider.generation = GenerationSettings()
|
||||
|
||||
with patch("nanobot.agent.loop.ContextBuilder"), \
|
||||
patch("nanobot.agent.loop.SessionManager"), \
|
||||
patch("nanobot.agent.loop.SessionManager", side_effect=mock_session_manager), \
|
||||
patch("nanobot.agent.loop.SubagentManager") as mock_sub_mgr:
|
||||
mock_sub_mgr.return_value.cancel_by_session = AsyncMock(return_value=0)
|
||||
loop = AgentLoop(bus=bus, provider=provider, workspace=tmp_path)
|
||||
@@ -159,6 +160,7 @@ async def test_goal_command_can_implement_plan_from_prior_discussion(tmp_path):
|
||||
session = loop.sessions.get_or_create("cli:direct")
|
||||
session.add_message("user", "Let's agree on the migration implementation.")
|
||||
session.add_message("assistant", "Use the staged migration plan and run integration tests.")
|
||||
loop.sessions.save(session)
|
||||
|
||||
result = await loop._process_message(
|
||||
InboundMessage(
|
||||
@@ -172,6 +174,7 @@ async def test_goal_command_can_implement_plan_from_prior_discussion(tmp_path):
|
||||
assert result is not None
|
||||
assert result.content == "done"
|
||||
assert goal_mutation_allowed() is False
|
||||
session = await loop.sessions.state.get(session.key)
|
||||
assert session.metadata[GOAL_STATE_KEY]["status"] == "completed"
|
||||
first_request = provider.chat_stream_with_retry.await_args_list[0].kwargs["messages"]
|
||||
assert "staged migration plan" in str(first_request)
|
||||
@@ -243,6 +246,7 @@ async def test_runtime_context_is_persisted_as_next_turn_prompt_prefix(tmp_path)
|
||||
assert second_wire[3]["content"].startswith("second turn")
|
||||
assert len(provider_calls) == 2
|
||||
|
||||
session = await loop.sessions.state.get(session.key)
|
||||
persisted_first_user = session.messages[0]
|
||||
assert persisted_first_user["content"] == first_wire[1]["content"]
|
||||
assert public_history_message(persisted_first_user)["content"] == "first turn $review"
|
||||
@@ -276,6 +280,7 @@ async def test_webui_quote_reaches_model_without_leaking_into_public_history(tmp
|
||||
request = provider.chat_stream_with_retry.await_args.kwargs["messages"]
|
||||
assert "What does this mean?" in str(request)
|
||||
assert "the selected answer excerpt" in str(request)
|
||||
session = await loop.sessions.state.get(session.key)
|
||||
assert "the selected answer excerpt" in str(session.messages[0]["content"])
|
||||
assert public_history_message(session.messages[0])["content"] == "What does this mean?"
|
||||
|
||||
|
||||
@@ -161,12 +161,12 @@ def test_agent_loop_llm_runtime_reflects_current_provider_and_model(tmp_path: Pa
|
||||
assert runtime.model == "next-model"
|
||||
|
||||
|
||||
def test_persist_cron_turn_uses_distinct_history_marker(tmp_path: Path) -> None:
|
||||
async def test_persist_cron_turn_uses_distinct_history_marker(tmp_path: Path) -> None:
|
||||
loop = _make_full_loop(tmp_path)
|
||||
session = loop.sessions.get_or_create("websocket:auto")
|
||||
session = await loop.sessions.state.get("websocket:auto")
|
||||
prompt_ref = {"id": "cron.agent_turn.reminder", "version": 1, "sha256": "abc"}
|
||||
|
||||
persisted = loop._persist_user_message_early(
|
||||
persisted = await loop._persist_user_message_early(
|
||||
InboundMessage(
|
||||
channel="websocket",
|
||||
sender_id="cron",
|
||||
@@ -203,9 +203,9 @@ def test_persist_cron_turn_uses_distinct_history_marker(tmp_path: Path) -> None:
|
||||
assert message["cron_prompt_ref"] == prompt_ref
|
||||
|
||||
|
||||
def test_persist_user_message_acknowledges_durable_followup(tmp_path: Path) -> None:
|
||||
async def test_persist_user_message_acknowledges_durable_followup(tmp_path: Path) -> None:
|
||||
loop = _make_full_loop(tmp_path)
|
||||
session = loop.sessions.get_or_create("websocket:chat")
|
||||
session = await loop.sessions.state.get("websocket:chat")
|
||||
session.metadata[PENDING_FOLLOWUPS_KEY] = [
|
||||
{
|
||||
"id": "followup-1",
|
||||
@@ -217,7 +217,7 @@ def test_persist_user_message_acknowledges_durable_followup(tmp_path: Path) -> N
|
||||
}
|
||||
]
|
||||
|
||||
persisted = loop._persist_user_message_early(
|
||||
persisted = await loop._persist_user_message_early(
|
||||
InboundMessage(
|
||||
channel="websocket",
|
||||
sender_id="user",
|
||||
@@ -232,11 +232,11 @@ def test_persist_user_message_acknowledges_durable_followup(tmp_path: Path) -> N
|
||||
assert PENDING_FOLLOWUPS_KEY not in session.metadata
|
||||
|
||||
|
||||
def test_persist_local_trigger_turn_uses_hidden_automation_marker(tmp_path: Path) -> None:
|
||||
async def test_persist_local_trigger_turn_uses_hidden_automation_marker(tmp_path: Path) -> None:
|
||||
loop = _make_full_loop(tmp_path)
|
||||
session = loop.sessions.get_or_create("websocket:auto")
|
||||
session = await loop.sessions.state.get("websocket:auto")
|
||||
|
||||
persisted = loop._persist_user_message_early(
|
||||
persisted = await loop._persist_user_message_early(
|
||||
InboundMessage(
|
||||
channel="websocket",
|
||||
sender_id="trigger",
|
||||
@@ -384,6 +384,7 @@ async def test_generate_webui_title_only_for_marked_webui_sessions(tmp_path: Pat
|
||||
)
|
||||
|
||||
assert generated is True
|
||||
session = await loop.sessions.state.get(session.key)
|
||||
assert session.metadata[WEBUI_TITLE_METADATA_KEY] == "优化 WebUI 侧边栏"
|
||||
loop.provider.chat_stream_with_retry.assert_awaited_once()
|
||||
assert loop.provider.chat_stream_with_retry.await_args.kwargs["max_tokens"] == TITLE_GENERATION_MAX_TOKENS
|
||||
@@ -510,6 +511,7 @@ async def test_projected_title_generation_skips_existing_chat_title(tmp_path: Pa
|
||||
unified.add_message("assistant", "以下是临期 IP 列表。")
|
||||
chat = loop.sessions.get_or_create("websocket:chat-existing")
|
||||
chat.metadata[WEBUI_TITLE_METADATA_KEY] = "Existing title"
|
||||
loop.sessions.save(chat)
|
||||
loop.sessions.save(unified)
|
||||
|
||||
generated = await maybe_generate_webui_title_after_turn(
|
||||
@@ -1064,7 +1066,7 @@ async def test_runtime_checkpoint_keeps_provider_state_out_of_public_metadata(
|
||||
loop.provider.chat_stream_with_retry = AsyncMock(
|
||||
return_value=LLMResponse(content="done", provider_state=state)
|
||||
)
|
||||
session = loop.sessions.get_or_create("cli:private-checkpoint")
|
||||
session = await loop.sessions.state.get("cli:private-checkpoint")
|
||||
|
||||
await loop._run_agent_loop(
|
||||
TranscriptInput(
|
||||
@@ -1089,8 +1091,9 @@ async def test_runtime_checkpoint_keeps_provider_state_out_of_public_metadata(
|
||||
public_payload = loop.sessions.read_session_file(session.key)
|
||||
assert public_payload is not None
|
||||
assert "private-checkpoint-blob" not in json.dumps(public_payload)
|
||||
raw = loop.sessions._get_session_path(session.key).read_text(encoding="utf-8")
|
||||
assert "private-checkpoint-blob" in raw
|
||||
stored = loop.sessions.read_session_snapshot(session.key)
|
||||
assert stored is not None and stored.provider_state is not None
|
||||
assert stored.provider_state.payload == state.payload
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -1120,7 +1123,7 @@ async def test_subagent_followup_stages_provider_state_before_turn_runs(
|
||||
session = loop.sessions.get_or_create("cli:subagent-crash")
|
||||
session.provider_state = _provider_state()
|
||||
loop.sessions.save(session)
|
||||
save_completed_subagent(loop, "sub-1", session.key)
|
||||
await save_completed_subagent(loop, "sub-1", session.key)
|
||||
|
||||
msg = InboundMessage(
|
||||
channel="system",
|
||||
@@ -1152,7 +1155,7 @@ async def test_subagent_followup_state_is_durable_before_prompt_assembly(
|
||||
session = loop.sessions.get_or_create("cli:subagent-prompt-crash")
|
||||
session.provider_state = _provider_state()
|
||||
loop.sessions.save(session)
|
||||
save_completed_subagent(loop, "sub-1", session.key)
|
||||
await save_completed_subagent(loop, "sub-1", session.key)
|
||||
|
||||
msg = InboundMessage(
|
||||
channel="system",
|
||||
@@ -1186,7 +1189,7 @@ async def test_subagent_redelivery_does_not_duplicate_staged_provider_input(
|
||||
session = loop.sessions.get_or_create("cli:subagent-redelivery")
|
||||
session.provider_state = _provider_state()
|
||||
loop.sessions.save(session)
|
||||
save_completed_subagent(loop, "sub-1", session.key)
|
||||
await save_completed_subagent(loop, "sub-1", session.key)
|
||||
msg = InboundMessage(
|
||||
channel="system",
|
||||
sender_id="subagent",
|
||||
@@ -1236,7 +1239,7 @@ async def test_subagent_followup_clears_state_before_compatibility_failure(
|
||||
session = loop.sessions.get_or_create("cli:subagent-compat-crash")
|
||||
session.provider_state = _provider_state()
|
||||
loop.sessions.save(session)
|
||||
save_completed_subagent(loop, "sub-1", session.key)
|
||||
await save_completed_subagent(loop, "sub-1", session.key)
|
||||
|
||||
msg = InboundMessage(
|
||||
channel="system",
|
||||
@@ -1712,7 +1715,8 @@ async def test_process_message_uses_explicit_session_for_goal_context(
|
||||
assert result is not None
|
||||
assert result.content == "ok"
|
||||
kwargs = loop._run_agent_loop.call_args.kwargs
|
||||
assert kwargs["session"] is system_session
|
||||
assert kwargs["session"].key == system_session.key
|
||||
assert kwargs["session"] is not system_session
|
||||
assert kwargs["request_context"].session_key == "system"
|
||||
assert GOAL_STATE_KEY not in kwargs["session"].metadata
|
||||
|
||||
@@ -1724,16 +1728,16 @@ async def test_run_agent_loop_continuation_reads_latest_goal_metadata(
|
||||
from nanobot.agent.runner import AgentRunResult
|
||||
|
||||
loop = _make_full_loop(tmp_path)
|
||||
session = loop.sessions.get_or_create("websocket:late-goal")
|
||||
session = await loop.sessions.state.get("websocket:late-goal")
|
||||
seen: dict[str, str | None] = {}
|
||||
|
||||
async def fake_run(spec):
|
||||
assert callable(spec.continuation_callback)
|
||||
session.metadata[GOAL_STATE_KEY] = {
|
||||
await loop.sessions.state.update_metadata(session.key, {GOAL_STATE_KEY: {
|
||||
"status": "active",
|
||||
"objective": "Goal created during this runner call.",
|
||||
}
|
||||
seen["goal_continue"] = spec.continuation_callback()
|
||||
}})
|
||||
seen["goal_continue"] = await spec.continuation_callback()
|
||||
return AgentRunResult(
|
||||
final_content="ok",
|
||||
messages=[{"role": "assistant", "content": "ok"}],
|
||||
@@ -1873,7 +1877,7 @@ async def test_stop_preserves_runtime_checkpoint_for_next_turn(tmp_path: Path) -
|
||||
|
||||
async def interrupted_run_agent_loop(_transcript_input, *, session=None, **_kwargs):
|
||||
assert session is not None
|
||||
loop._set_runtime_checkpoint(
|
||||
await loop._set_runtime_checkpoint(
|
||||
session,
|
||||
{
|
||||
"assistant_message": {
|
||||
@@ -1917,7 +1921,21 @@ async def test_stop_preserves_runtime_checkpoint_for_next_turn(tmp_path: Path) -
|
||||
first_msg = InboundMessage(channel="feishu", sender_id="u1", chat_id="c4", content="keep progress")
|
||||
task = asyncio.create_task(loop._process_message(first_msg))
|
||||
loop._active_tasks[first_msg.session_key] = {task}
|
||||
await asyncio.wait_for(checkpoint_saved.wait(), timeout=1.0)
|
||||
checkpoint_wait = asyncio.create_task(checkpoint_saved.wait())
|
||||
try:
|
||||
done, _ = await asyncio.wait(
|
||||
(checkpoint_wait, task), timeout=5, return_when=asyncio.FIRST_COMPLETED,
|
||||
)
|
||||
if task in done:
|
||||
await task
|
||||
assert checkpoint_wait in done, "the turn did not reach its durable checkpoint"
|
||||
except BaseException:
|
||||
task.cancel()
|
||||
await asyncio.gather(task, return_exceptions=True)
|
||||
raise
|
||||
finally:
|
||||
checkpoint_wait.cancel()
|
||||
await asyncio.gather(checkpoint_wait, return_exceptions=True)
|
||||
|
||||
stop_msg = InboundMessage(channel="feishu", sender_id="u1", chat_id="c4", content="/stop")
|
||||
stop_ctx = CommandContext(msg=stop_msg, session=None, key=stop_msg.session_key, raw="/stop", loop=loop)
|
||||
@@ -1976,7 +1994,7 @@ async def test_system_subagent_followup_is_persisted_before_prompt_assembly(tmp_
|
||||
session.add_message("user", "question")
|
||||
session.add_message("assistant", "working")
|
||||
loop.sessions.save(session)
|
||||
save_completed_subagent(loop, "sub-1", session.key)
|
||||
await save_completed_subagent(loop, "sub-1", session.key)
|
||||
|
||||
runtime = loop.llm_runtime()
|
||||
seen: dict[str, object] = {}
|
||||
@@ -2077,7 +2095,7 @@ async def test_turn_usage_is_persisted_with_the_saved_session(tmp_path: Path) ->
|
||||
@pytest.mark.asyncio
|
||||
async def test_system_subagent_followup_does_not_log_content(tmp_path: Path) -> None:
|
||||
loop = _make_full_loop(tmp_path)
|
||||
save_completed_subagent(loop, "sub-logs", "cli:logs")
|
||||
await save_completed_subagent(loop, "sub-logs", "cli:logs")
|
||||
|
||||
async def fake_run_agent_loop(transcript_input, **_kwargs):
|
||||
initial_messages = _assembled_messages(loop.context, transcript_input)
|
||||
@@ -2114,7 +2132,7 @@ async def test_system_subagent_followup_does_not_log_content(tmp_path: Path) ->
|
||||
@pytest.mark.asyncio
|
||||
async def test_system_subagent_followup_uses_common_turn_lifecycle(tmp_path: Path) -> None:
|
||||
loop = _make_full_loop(tmp_path)
|
||||
save_completed_subagent(loop, "sub-1", "cli:test")
|
||||
await save_completed_subagent(loop, "sub-1", "cli:test")
|
||||
visited: list[str] = []
|
||||
|
||||
for name in (
|
||||
@@ -2243,7 +2261,7 @@ async def test_multiple_subagent_followups_all_persist_as_standalone_history(tmp
|
||||
loop._run_agent_loop = fake_run_agent_loop # type: ignore[method-assign]
|
||||
|
||||
for idx in range(3):
|
||||
save_completed_subagent(loop, f"sub-{idx}", "cli:multi")
|
||||
await save_completed_subagent(loop, f"sub-{idx}", "cli:multi")
|
||||
await loop._process_message(
|
||||
InboundMessage(
|
||||
channel="system",
|
||||
@@ -2361,7 +2379,7 @@ async def test_system_subagent_followup_uses_thread_session_and_slack_metadata(t
|
||||
thread_session = loop.sessions.get_or_create("slack:C123:1700.42")
|
||||
thread_session.add_message("user", "thread question")
|
||||
loop.sessions.save(thread_session)
|
||||
save_completed_subagent(loop, "sub-1", thread_session.key)
|
||||
await save_completed_subagent(loop, "sub-1", thread_session.key)
|
||||
|
||||
seen: dict[str, object] = {}
|
||||
|
||||
|
||||
@@ -64,7 +64,7 @@ async def test_transient_session_keeps_history_without_persisting_or_durable_too
|
||||
default_restrict_to_workspace=True,
|
||||
),
|
||||
)
|
||||
key = f"websocket:{temporary_chats.create(object(), trusted_webui=True)}"
|
||||
key = f"websocket:{await temporary_chats.create(object(), trusted_webui=True)}"
|
||||
|
||||
await loop._process_message(_message(key, "first question"))
|
||||
await loop._process_message(_message(key, "second question"))
|
||||
@@ -111,8 +111,8 @@ async def test_turn_tool_selection_preserves_empty_registries(tmp_path, monkeypa
|
||||
if selection == "explicit_empty":
|
||||
kwargs["tools"] = ToolRegistry()
|
||||
elif selection == "disable_all":
|
||||
session = loop.sessions.get_or_create(key)
|
||||
session.policy = SessionPolicy(disabled_tools=frozenset(loop.tools.tool_names))
|
||||
await loop.sessions.state.get(key)
|
||||
await loop.sessions.state.set_policy(key, SessionPolicy(disabled_tools=frozenset(loop.tools.tool_names)))
|
||||
|
||||
try:
|
||||
response = await loop.process_direct("Handle this request", session_key=key, **kwargs)
|
||||
@@ -152,10 +152,10 @@ async def test_session_policy_controls_tool_logs_and_result_offload(
|
||||
loop.max_tool_result_chars = 2048
|
||||
key = "websocket:privacy-regression"
|
||||
if privacy == "temporary":
|
||||
loop.sessions.get_or_create_transient(key)
|
||||
await loop.sessions.state.register_transient(key)
|
||||
else:
|
||||
session = loop.sessions.get_or_create(key)
|
||||
session.policy = SessionPolicy(log_content=privacy != "quiet")
|
||||
await loop.sessions.state.get(key)
|
||||
await loop.sessions.state.set_policy(key, SessionPolicy(log_content=privacy != "quiet"))
|
||||
secret = "synthetic-private-query-测试"
|
||||
text = "synthetic-private-result-" * 1000
|
||||
image = {"type": "image_url", "image_url": {"url": "data:image/png;base64,c3ludGhldGlj"}}
|
||||
@@ -198,7 +198,7 @@ async def test_session_policy_controls_tool_logs_and_result_offload(
|
||||
|
||||
async def test_direct_transient_run_never_spills_before_cancellation(tmp_path) -> None:
|
||||
loop = _loop(tmp_path, [])
|
||||
session = loop.sessions.get_or_create_transient("websocket:cancel-private")
|
||||
session = await loop.sessions.state.register_transient("websocket:cancel-private")
|
||||
loop.max_tool_result_chars = 100
|
||||
loop.tools.prepare_call = MagicMock(return_value=(None, {}, None))
|
||||
loop.tools.execute = AsyncMock(return_value="synthetic large result" * 1000)
|
||||
@@ -244,9 +244,9 @@ async def test_session_worker_errors_keep_private_content_out_of_logs(
|
||||
loop = _loop(tmp_path, [])
|
||||
key = "websocket:synthetic-worker-error"
|
||||
if private:
|
||||
loop.sessions.get_or_create_transient(key)
|
||||
await loop.sessions.state.register_transient(key)
|
||||
else:
|
||||
loop.sessions.get_or_create(key)
|
||||
await loop.sessions.state.get(key)
|
||||
secret = "synthetic-private-worker-content"
|
||||
if failure == "runner":
|
||||
loop.provider.chat_stream_with_retry = AsyncMock(side_effect=ValueError(secret))
|
||||
@@ -278,10 +278,11 @@ async def test_transient_session_stays_outside_unified_session(tmp_path) -> None
|
||||
durable.add_message("user", "durable question")
|
||||
loop.sessions.save(durable)
|
||||
key = "websocket:transient-unified"
|
||||
transient = loop.sessions.get_or_create_transient(key)
|
||||
await loop.sessions.state.register_transient(key)
|
||||
|
||||
await run_session(loop, _message(key, "private question"))
|
||||
|
||||
transient = await loop.sessions.state.get(key)
|
||||
assert [public_history_message(message)["content"] for message in transient.messages] == [
|
||||
"private question",
|
||||
"private answer",
|
||||
@@ -294,7 +295,7 @@ async def test_transient_session_stays_outside_unified_session(tmp_path) -> None
|
||||
async def test_missing_required_session_cannot_fall_back_to_disk(tmp_path) -> None:
|
||||
loop = _loop(tmp_path, [])
|
||||
key = "websocket:transient-stale"
|
||||
loop.sessions.get_or_create_transient(key)
|
||||
await loop.sessions.state.register_transient(key)
|
||||
loop.sessions.invalidate(key)
|
||||
|
||||
with pytest.raises(RuntimeError, match="required session is not active"):
|
||||
@@ -331,12 +332,12 @@ async def test_deleted_child_cannot_notify_a_recreated_parent(tmp_path) -> None:
|
||||
task_id, = loop.subagents.statuses_for_session(key)
|
||||
notice = await asyncio.wait_for(loop.bus.consume_inbound(), timeout=2)
|
||||
assert notice.require_existing_session
|
||||
assert loop.sessions.delete_session(key)
|
||||
assert await loop.sessions.state.delete(key)
|
||||
assert loop.sessions.read_session_file(SubagentSessions.key(task_id)) is None
|
||||
loop.sessions.save(loop.sessions.get_or_create(key))
|
||||
await loop.sessions.state.get(key)
|
||||
|
||||
assert loop.subagents.statuses_for_session(key) == {}
|
||||
loop._enqueue_session_message(notice)
|
||||
await loop._enqueue_session_message(notice)
|
||||
assert key not in loop._pending_queues
|
||||
assert await loop._process_message(notice) is None
|
||||
loop.provider.chat_stream_with_retry.assert_not_awaited()
|
||||
@@ -370,7 +371,7 @@ async def test_session_discard_control_cancels_active_turn(tmp_path, monkeypatch
|
||||
)
|
||||
key = "websocket:transient-cancelled"
|
||||
previous_file_state = loop._file_state_store.for_session(key)
|
||||
loop.sessions.get_or_create_transient(
|
||||
await loop.sessions.state.register_transient(
|
||||
key,
|
||||
disabled_tools={"create_goal", "update_goal", "subagent", "cron"},
|
||||
)
|
||||
|
||||
@@ -65,12 +65,12 @@ async def test_goal_input_enters_running_turn_with_scoped_permission(tmp_path, c
|
||||
channel="cli", sender_id="user", chat_id="test", content=command,
|
||||
))
|
||||
async with asyncio.timeout(3):
|
||||
while loop._pending_queues["cli:test"].empty():
|
||||
while "cli:test" not in loop._pending_queues or loop._pending_queues["cli:test"].empty():
|
||||
await asyncio.sleep(0)
|
||||
assert len(calls) == 1
|
||||
release.set()
|
||||
await asyncio.wait_for(asyncio.gather(*loop._active_tasks["cli:test"]), 5)
|
||||
session = loop.sessions.get_or_create("cli:test")
|
||||
session = (await loop.sessions.state.get("cli:test"))
|
||||
assert process.await_count == 1
|
||||
assert permissions[:3] == [False, True, True]
|
||||
assert "Discuss the migration" in calls[1]
|
||||
@@ -105,7 +105,7 @@ async def test_scheduled_goal_command_cannot_generate_internal_input(tmp_path):
|
||||
assert "only be started by a user" in response.content
|
||||
assert loop._pending_queues == {}
|
||||
assert goal_mutation_allowed() is False
|
||||
assert loop.sessions.get_or_create(msg.session_key).messages == []
|
||||
assert (await loop.sessions.state.get(msg.session_key)).messages == []
|
||||
finally:
|
||||
await loop.aclose()
|
||||
|
||||
@@ -142,7 +142,7 @@ async def test_goal_at_iteration_limit_stays_queued_for_a_tool_capable_turn(tmp_
|
||||
if boundary == "empty":
|
||||
return LLMResponse(content="")
|
||||
return LLMResponse(content="The migration plan is ready.")
|
||||
if kwargs.get("tools") and GOAL_STATE_KEY not in loop.sessions.get_or_create("cli:test").metadata:
|
||||
if kwargs.get("tools") and GOAL_STATE_KEY not in (await loop.sessions.state.get("cli:test")).metadata:
|
||||
assert goal_mutation_allowed() is True
|
||||
return LLMResponse(content=None, tool_calls=[ToolCallRequest(
|
||||
id="create", name="create_goal",
|
||||
@@ -160,7 +160,7 @@ async def test_goal_at_iteration_limit_stays_queued_for_a_tool_capable_turn(tmp_
|
||||
await run_session(loop, InboundMessage(
|
||||
channel="cli", sender_id="user", chat_id="test", content="Discuss the migration.",
|
||||
))
|
||||
session = loop.sessions.get_or_create("cli:test")
|
||||
session = (await loop.sessions.state.get("cli:test"))
|
||||
assert session.metadata[GOAL_STATE_KEY]["status"] == "completed"
|
||||
goal_calls = [call for call in calls if "Goal Runtime Guidance" in call]
|
||||
assert goal_calls
|
||||
@@ -173,7 +173,7 @@ async def test_goal_at_iteration_limit_stays_queued_for_a_tool_capable_turn(tmp_
|
||||
|
||||
async def test_generated_goal_input_survives_pending_followup_recovery(tmp_path):
|
||||
from nanobot.command.router import CommandContext
|
||||
from nanobot.session.recovery import pending_followups, record_pending_followup
|
||||
from nanobot.session.recovery import pending_followups
|
||||
|
||||
provider = MagicMock(aclose=AsyncMock())
|
||||
provider.get_default_model.return_value = "test-model"
|
||||
@@ -189,14 +189,12 @@ async def test_generated_goal_input_survives_pending_followup_recovery(tmp_path)
|
||||
raw=message.content, loop=loop, is_user_turn=True,
|
||||
))
|
||||
assert isinstance(generated, InboundMessage)
|
||||
session = loop.sessions.get_or_create(message.session_key)
|
||||
assert record_pending_followup(session, generated)
|
||||
loop.sessions.save(session)
|
||||
assert await loop.sessions.state.queue_followup(message.session_key, generated)
|
||||
finally:
|
||||
await loop.aclose()
|
||||
|
||||
loop = AgentLoop(bus=MessageBus(), provider=provider, workspace=tmp_path, model="test-model")
|
||||
session = loop.sessions.get_or_create(message.session_key)
|
||||
session = (await loop.sessions.state.get(message.session_key))
|
||||
recovered, = pending_followups(session)
|
||||
responses = iter([
|
||||
LLMResponse(content=None, tool_calls=[ToolCallRequest(
|
||||
@@ -225,6 +223,7 @@ async def test_generated_goal_input_survives_pending_followup_recovery(tmp_path)
|
||||
async with asyncio.timeout(5):
|
||||
while (await loop.bus.consume_outbound()).content != "done":
|
||||
pass
|
||||
session = await loop.sessions.state.get(message.session_key)
|
||||
assert session.metadata[GOAL_STATE_KEY]["status"] == "completed"
|
||||
assert pending_followups(session) == []
|
||||
assert sum(row.get("content") == message.content for row in session.messages) == 1
|
||||
@@ -255,7 +254,7 @@ async def test_internal_continuation_cannot_inherit_goal_permission(tmp_path):
|
||||
with goal_mutation_permission(True):
|
||||
await loop._process_message(message, session_key="cli:test")
|
||||
assert goal_mutation_allowed() is True
|
||||
assert GOAL_STATE_KEY not in loop.sessions.get_or_create("cli:test").metadata
|
||||
assert GOAL_STATE_KEY not in (await loop.sessions.state.get("cli:test")).metadata
|
||||
final_request = provider.chat_stream_with_retry.await_args.kwargs["messages"]
|
||||
assert "create_goal is unavailable for this turn" in str(final_request)
|
||||
assert goal_mutation_allowed() is False
|
||||
|
||||
@@ -3,10 +3,12 @@
|
||||
import asyncio
|
||||
import threading
|
||||
from copy import deepcopy
|
||||
from unittest.mock import AsyncMock
|
||||
|
||||
import pytest
|
||||
|
||||
from nanobot.agent.hook import AgentHook
|
||||
from nanobot.agent.runner import AgentRunner
|
||||
from nanobot.agent.tools.context import current_request_context
|
||||
from nanobot.providers.base import LLMProvider, LLMResponse, LLMUsage
|
||||
from nanobot.runtime_context import public_history_message
|
||||
@@ -209,7 +211,7 @@ async def test_cancellation_during_run_cleanup_delivers_finally_once(
|
||||
loop.sessions.save(session)
|
||||
runtime_loop = asyncio.get_running_loop()
|
||||
entered = asyncio.Event()
|
||||
hook_returned = asyncio.Event()
|
||||
snapshot_entered = asyncio.Event()
|
||||
worker_finished = asyncio.Event()
|
||||
release = threading.Event()
|
||||
events = []
|
||||
@@ -223,7 +225,6 @@ async def test_cancellation_during_run_cleanup_delivers_finally_once(
|
||||
loop.process_direct("Blocked", session_key="cli:blocker"),
|
||||
))
|
||||
await asyncio.wait_for(entered.wait(), 5)
|
||||
hook_returned.set()
|
||||
|
||||
async def before_run(self, context):
|
||||
events.append("before_run")
|
||||
@@ -262,10 +263,22 @@ async def test_cancellation_during_run_cleanup_delivers_finally_once(
|
||||
return original_read(path, *args, **kwargs)
|
||||
|
||||
monkeypatch.setattr(type(prompt_file), "read_text", read_text)
|
||||
original_snapshot = loop.runner._run_context_snapshot
|
||||
snapshot_paused = False
|
||||
|
||||
async def snapshot(hook, messages):
|
||||
nonlocal snapshot_paused
|
||||
boundary = "after_iteration" if phase == "success_snapshot" else "after_run"
|
||||
if events and events[-1] == boundary and not snapshot_paused:
|
||||
snapshot_paused = True
|
||||
snapshot_entered.set()
|
||||
await asyncio.Event().wait()
|
||||
return await original_snapshot(hook, messages)
|
||||
|
||||
monkeypatch.setattr(loop.runner, "_run_context_snapshot", snapshot)
|
||||
first = asyncio.create_task(loop.process_direct("First", session_key="cli:first", hooks=[Lifecycle()]))
|
||||
try:
|
||||
await asyncio.wait_for(hook_returned.wait(), 5)
|
||||
await asyncio.sleep(0)
|
||||
await asyncio.wait_for(snapshot_entered.wait(), 5)
|
||||
first.cancel()
|
||||
with pytest.raises(asyncio.CancelledError):
|
||||
await asyncio.wait_for(first, 0.5)
|
||||
@@ -294,3 +307,178 @@ async def test_cancellation_during_run_cleanup_delivers_finally_once(
|
||||
if entered.is_set():
|
||||
await asyncio.wait_for(worker_finished.wait(), 5)
|
||||
await loop.aclose()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("cancel", [False, True])
|
||||
async def test_prompt_preparation_preserves_context_and_allows_cancellation(
|
||||
tmp_path, monkeypatch, loop_factory, cancel,
|
||||
) -> None:
|
||||
loop = loop_factory()
|
||||
loop.provider.provider_name = "prompt-test"
|
||||
loop.provider.chat_stream_with_retry = AsyncMock(return_value=LLMResponse(content="Done"))
|
||||
runtime_loop = asyncio.get_running_loop()
|
||||
entered = asyncio.Event()
|
||||
completed = asyncio.Event()
|
||||
release = threading.Event()
|
||||
original = loop.context.build_system_prompt
|
||||
captured = []
|
||||
finalized = []
|
||||
|
||||
class Lifecycle(AgentHook):
|
||||
async def on_finally(self, context):
|
||||
finalized.append((context.stop_reason, current_request_context(), asyncio.get_running_loop()))
|
||||
|
||||
loop._extra_hooks.append(Lifecycle())
|
||||
|
||||
def build(**kwargs):
|
||||
captured.append(current_request_context())
|
||||
runtime_loop.call_soon_threadsafe(entered.set)
|
||||
try:
|
||||
assert release.wait(5), "test did not release prompt filesystem work"
|
||||
return original(**kwargs)
|
||||
finally:
|
||||
runtime_loop.call_soon_threadsafe(completed.set)
|
||||
|
||||
monkeypatch.setattr(loop.context, "build_system_prompt", build)
|
||||
task = asyncio.create_task(loop.process_direct("Hello", session_key="cli:prompt-work"))
|
||||
try:
|
||||
await asyncio.wait_for(entered.wait(), timeout=5)
|
||||
assert captured[0] is not None
|
||||
assert captured[0].session_key == "cli:prompt-work"
|
||||
assert captured[0].workspace_scope.project_path == tmp_path.resolve()
|
||||
assert current_request_context() is None
|
||||
loop.provider.chat_stream_with_retry.assert_not_awaited()
|
||||
if cancel:
|
||||
task.cancel()
|
||||
with pytest.raises(asyncio.CancelledError):
|
||||
await asyncio.wait_for(task, timeout=5)
|
||||
loop.provider.chat_stream_with_retry.assert_not_awaited()
|
||||
assert len(finalized) == 1
|
||||
reason, request, final_loop = finalized[0]
|
||||
assert reason == "cancelled"
|
||||
assert request is not None and request.session_key == "cli:prompt-work"
|
||||
assert final_loop is runtime_loop
|
||||
release.set()
|
||||
await asyncio.wait_for(completed.wait(), timeout=5)
|
||||
if not cancel:
|
||||
result = await asyncio.wait_for(task, timeout=5)
|
||||
assert result is not None and result.content == "Done"
|
||||
saved = loop.sessions.read_session_snapshot("cli:prompt-work")
|
||||
assert [public_history_message(message)["content"] for message in saved.messages] == ["Hello", "Done"]
|
||||
assert current_request_context() is None
|
||||
finally:
|
||||
release.set()
|
||||
if not task.done():
|
||||
task.cancel()
|
||||
await asyncio.gather(task, return_exceptions=True)
|
||||
if captured:
|
||||
await asyncio.wait_for(completed.wait(), timeout=5)
|
||||
await loop.aclose()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_cancelled_prompt_keeps_its_worker_slot_until_read_finishes() -> None:
|
||||
runner = AgentRunner()
|
||||
runtime_loop = asyncio.get_running_loop()
|
||||
entered = {name: asyncio.Event() for name in ("first", "second")}
|
||||
released = {name: threading.Event() for name in entered}
|
||||
|
||||
def read(name):
|
||||
runtime_loop.call_soon_threadsafe(entered[name].set)
|
||||
assert released[name].wait(5), "test did not release prompt read"
|
||||
return name
|
||||
|
||||
first = asyncio.create_task(runner.prepare_prompt(read, "first"))
|
||||
tasks = [first]
|
||||
try:
|
||||
await asyncio.wait_for(entered["first"].wait(), timeout=5)
|
||||
first.cancel()
|
||||
with pytest.raises(asyncio.CancelledError):
|
||||
await asyncio.wait_for(first, timeout=5)
|
||||
second = asyncio.create_task(runner.prepare_prompt(read, "second"))
|
||||
tasks.append(second)
|
||||
await asyncio.sleep(0)
|
||||
# The cancelled caller's read keeps its slot until the worker exits.
|
||||
assert not entered["second"].is_set()
|
||||
released["first"].set()
|
||||
await asyncio.wait_for(entered["second"].wait(), timeout=5)
|
||||
released["second"].set()
|
||||
assert await asyncio.wait_for(second, timeout=5) == "second"
|
||||
finally:
|
||||
for release in released.values():
|
||||
release.set()
|
||||
for task in tasks:
|
||||
if not task.done():
|
||||
task.cancel()
|
||||
await asyncio.gather(*tasks, return_exceptions=True)
|
||||
await asyncio.gather(*tuple(runner.context_governor._preparation_jobs), return_exceptions=True)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("phase", ["request", "usage"])
|
||||
@pytest.mark.parametrize("cancel", [False, True])
|
||||
async def test_local_token_estimation_leaves_loop_available(
|
||||
tmp_path, monkeypatch, loop_factory, phase, cancel,
|
||||
) -> None:
|
||||
loop = loop_factory()
|
||||
loop.provider.provider_name = "token-test"
|
||||
loop.provider.chat_stream_with_retry = AsyncMock(return_value=LLMResponse(content="Done"))
|
||||
runtime_loop = asyncio.get_running_loop()
|
||||
entered = asyncio.Event()
|
||||
completed = asyncio.Event()
|
||||
release = threading.Event()
|
||||
captured = []
|
||||
finalized = []
|
||||
|
||||
class Lifecycle(AgentHook):
|
||||
async def on_finally(self, context):
|
||||
finalized.append((context.stop_reason, current_request_context(), asyncio.get_running_loop()))
|
||||
|
||||
loop._extra_hooks.append(Lifecycle())
|
||||
|
||||
def count(*_args, **_kwargs):
|
||||
captured.append(current_request_context())
|
||||
runtime_loop.call_soon_threadsafe(entered.set)
|
||||
try:
|
||||
assert release.wait(5), "test did not release local token estimation"
|
||||
return 10, "test-counter"
|
||||
finally:
|
||||
runtime_loop.call_soon_threadsafe(completed.set)
|
||||
|
||||
module = "context_governance" if phase == "request" else "runner"
|
||||
monkeypatch.setattr(f"nanobot.agent.{module}.estimate_prompt_tokens_chain", count)
|
||||
task = asyncio.create_task(loop.process_direct("Hello", session_key="cli:token-work"))
|
||||
try:
|
||||
await asyncio.wait_for(entered.wait(), timeout=5)
|
||||
assert captured[0] is not None
|
||||
assert captured[0].session_key == "cli:token-work"
|
||||
assert captured[0].workspace_scope.project_path == tmp_path.resolve()
|
||||
assert current_request_context() is None
|
||||
if phase == "request":
|
||||
loop.provider.chat_stream_with_retry.assert_not_awaited()
|
||||
else:
|
||||
loop.provider.chat_stream_with_retry.assert_awaited_once()
|
||||
if cancel:
|
||||
task.cancel()
|
||||
with pytest.raises(asyncio.CancelledError):
|
||||
await asyncio.wait_for(asyncio.shield(task), timeout=1)
|
||||
assert len(finalized) == 1
|
||||
reason, request, final_loop = finalized[0]
|
||||
assert reason == "cancelled"
|
||||
assert request is not None and request.session_key == "cli:token-work"
|
||||
assert final_loop is runtime_loop
|
||||
else:
|
||||
release.set()
|
||||
result = await asyncio.wait_for(task, timeout=5)
|
||||
assert result is not None and result.content == "Done"
|
||||
saved = loop.sessions.read_session_snapshot("cli:token-work")
|
||||
assert [public_history_message(message)["content"] for message in saved.messages] == ["Hello", "Done"]
|
||||
finally:
|
||||
release.set()
|
||||
if not task.done():
|
||||
task.cancel()
|
||||
await asyncio.gather(task, return_exceptions=True)
|
||||
if captured:
|
||||
await asyncio.wait_for(completed.wait(), timeout=5)
|
||||
await loop.aclose()
|
||||
@@ -811,7 +811,7 @@ async def test_runner_does_not_auto_continue_goal_after_policy_terminal(
|
||||
model="test-model",
|
||||
max_iterations=3,
|
||||
max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,
|
||||
continuation_callback=lambda: "Continue working.",
|
||||
continuation_callback=AsyncMock(return_value="Continue working."),
|
||||
terminal_injection_callback=terminal_injection_callback,
|
||||
))
|
||||
|
||||
|
||||
@@ -26,7 +26,7 @@ def run_spec():
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("callback", [None, lambda: None], ids=["absent", "no-request"])
|
||||
@pytest.mark.parametrize("callback", [None, AsyncMock(return_value=None)], ids=["absent", "no-request"])
|
||||
async def test_runner_completes_without_a_continuation_request(run_spec, callback):
|
||||
run_spec.continuation_callback = callback
|
||||
|
||||
@@ -42,7 +42,7 @@ async def test_continuation_injects_text_without_exceeding_budget(run_spec, max_
|
||||
continuation = "Continue working toward the active sustained goal."
|
||||
run_spec.max_iterations = max_iterations
|
||||
run_spec.finalize_on_max_iterations = finalize
|
||||
run_spec.continuation_callback = lambda: continuation
|
||||
run_spec.continuation_callback = AsyncMock(side_effect=lambda: continuation)
|
||||
|
||||
result = await AgentRunner().run(run_spec)
|
||||
|
||||
@@ -60,7 +60,7 @@ async def test_runner_does_not_request_continuation_on_error(run_spec):
|
||||
run_spec.runtime.provider.chat_stream_with_retry.return_value = LLMResponse(
|
||||
content=None, finish_reason="error",
|
||||
)
|
||||
callback = MagicMock(return_value="Continue working.")
|
||||
callback = AsyncMock(return_value="Continue working.")
|
||||
run_spec.continuation_callback = callback
|
||||
|
||||
result = await AgentRunner().run(run_spec)
|
||||
@@ -85,7 +85,7 @@ async def test_runner_reads_continuation_state_after_each_response(run_spec):
|
||||
return LLMResponse(content="The draft is complete.")
|
||||
|
||||
run_spec.runtime.provider.chat_stream_with_retry.side_effect = respond
|
||||
run_spec.continuation_callback = lambda: continuation
|
||||
run_spec.continuation_callback = AsyncMock(side_effect=lambda: continuation)
|
||||
|
||||
result = await AgentRunner().run(run_spec)
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@ from unittest.mock import AsyncMock, MagicMock, patch
|
||||
import pytest
|
||||
|
||||
from agent.runner_helpers import make_run_spec
|
||||
from agent.session_helpers import mock_session_manager
|
||||
from nanobot.agent.context import TranscriptInput
|
||||
from nanobot.agent.context_governance import (
|
||||
BACKFILL_CONTENT,
|
||||
@@ -80,7 +81,7 @@ def _make_loop(tmp_path):
|
||||
provider.get_default_model.return_value = "test-model"
|
||||
|
||||
with patch("nanobot.agent.loop.ContextBuilder"), \
|
||||
patch("nanobot.agent.loop.SessionManager"), \
|
||||
patch("nanobot.agent.loop.SessionManager", side_effect=mock_session_manager), \
|
||||
patch("nanobot.agent.loop.SubagentManager") as mock_sub_mgr:
|
||||
mock_sub_mgr.return_value.cancel_by_session = AsyncMock(return_value=0)
|
||||
loop = AgentLoop(bus=bus, provider=provider, workspace=tmp_path)
|
||||
|
||||
@@ -37,7 +37,6 @@ def _make_loop(tmp_path, *, recovery_admission=None):
|
||||
provider.get_default_model.return_value = "test-model"
|
||||
|
||||
with patch("nanobot.agent.loop.ContextBuilder"), \
|
||||
patch("nanobot.agent.loop.SessionManager"), \
|
||||
patch("nanobot.agent.loop.SubagentManager") as mock_sub_mgr:
|
||||
mock_sub_mgr.return_value.cancel_by_session = AsyncMock(return_value=0)
|
||||
mock_sub_mgr.return_value.close = AsyncMock()
|
||||
@@ -393,7 +392,7 @@ async def test_goal_continuation_precedes_terminal_wait():
|
||||
continuation_checks = 0
|
||||
terminal_waits = 0
|
||||
|
||||
def continue_goal() -> str | None:
|
||||
async def continue_goal() -> str | None:
|
||||
nonlocal continuation_checks
|
||||
continuation_checks += 1
|
||||
return "Continue the active goal." if continuation_checks == 1 else None
|
||||
@@ -749,7 +748,7 @@ async def test_pending_injection_resolves_its_own_runtime_context(tmp_path):
|
||||
)
|
||||
|
||||
loop.register_runtime_context_provider(provide_identity)
|
||||
session = loop.sessions.get_or_create("telegram:group-1")
|
||||
session = await loop.sessions.state.get("telegram:group-1")
|
||||
pending_queue = asyncio.Queue()
|
||||
await pending_queue.put(InboundMessage(
|
||||
channel="telegram",
|
||||
@@ -1444,9 +1443,9 @@ async def test_persistent_conversion_error_does_not_drop_later_session_inputs(tm
|
||||
calls += 1
|
||||
if calls == 1:
|
||||
for content in ["before", "bad", "after"]:
|
||||
loop._enqueue_session_message(InboundMessage(
|
||||
(await loop._enqueue_session_message(InboundMessage(
|
||||
channel="cli", sender_id="u", chat_id="c", content=content,
|
||||
))
|
||||
)))
|
||||
return LLMResponse(content="answer", finish_reason="stop")
|
||||
|
||||
async def context_provider(request):
|
||||
@@ -1472,16 +1471,25 @@ async def test_persistent_conversion_error_does_not_drop_later_session_inputs(tm
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_session_inbox_is_installed_before_worker_start(tmp_path):
|
||||
async def test_session_inbox_is_installed_before_worker_start(tmp_path, monkeypatch):
|
||||
"""A preloaded burst has one FIFO path before the worker can be scheduled."""
|
||||
from nanobot.bus.events import InboundMessage, OutboundMessage
|
||||
|
||||
loop = _make_loop(tmp_path)
|
||||
first_started = asyncio.Event()
|
||||
all_enqueued = asyncio.Event()
|
||||
release_first = asyncio.Event()
|
||||
all_processed = asyncio.Event()
|
||||
processed: list[str] = []
|
||||
followups = [f"follow-up-{index}" for index in range(40)]
|
||||
enqueue = loop._enqueue_session_message
|
||||
|
||||
async def capture_enqueue(msg):
|
||||
await enqueue(msg)
|
||||
if msg.content == followups[-1]:
|
||||
all_enqueued.set()
|
||||
|
||||
monkeypatch.setattr(loop, "_enqueue_session_message", capture_enqueue)
|
||||
|
||||
async def _process_message(msg, **_kwargs):
|
||||
processed.append(msg.content)
|
||||
@@ -1502,14 +1510,11 @@ async def test_session_inbox_is_installed_before_worker_start(tmp_path):
|
||||
)
|
||||
|
||||
run_task = asyncio.create_task(loop.run())
|
||||
await asyncio.wait_for(first_started.wait(), timeout=2)
|
||||
await asyncio.wait_for(
|
||||
asyncio.gather(first_started.wait(), all_enqueued.wait()), timeout=30,
|
||||
)
|
||||
|
||||
session_key = "cli:c"
|
||||
for _ in range(200):
|
||||
pending = loop._pending_queues.get(session_key)
|
||||
if pending is not None and pending.qsize() == len(followups):
|
||||
break
|
||||
await asyncio.sleep(0.01)
|
||||
assert len(loop._active_tasks[session_key]) == 1
|
||||
assert loop._pending_queues[session_key].qsize() == len(followups)
|
||||
|
||||
@@ -1562,7 +1567,8 @@ async def test_busy_session_burst_reaches_next_model_call_as_one_ordered_batch(
|
||||
model="test-model",
|
||||
)
|
||||
loop.tools.get_definitions = MagicMock(return_value=[])
|
||||
loop.sessions.get_or_create("cli:c").policy = SessionPolicy(log_content=log_content)
|
||||
await loop.sessions.state.get("cli:c")
|
||||
await loop.sessions.state.set_policy("cli:c", SessionPolicy(log_content=log_content))
|
||||
followups = [f"follow-up-{index:02}" for index in range(12)]
|
||||
|
||||
run_task = asyncio.create_task(loop.run())
|
||||
@@ -1594,7 +1600,8 @@ async def test_busy_session_burst_reaches_next_model_call_as_one_ordered_batch(
|
||||
break
|
||||
await asyncio.sleep(0.01)
|
||||
loop.stop()
|
||||
await asyncio.wait_for(run_task, timeout=2)
|
||||
# Shutdown drains accepted writes and closes the worker's WAL connection.
|
||||
await asyncio.wait_for(run_task, timeout=30)
|
||||
|
||||
assert len(captured_messages) == 2
|
||||
second_request = "\n".join(
|
||||
|
||||
@@ -20,7 +20,7 @@ from nanobot.runtime_context import (
|
||||
webui_quote_runtime_context,
|
||||
)
|
||||
from nanobot.sdk.types import snapshot_from_session
|
||||
from nanobot.session.manager import Session, _message_preview_text
|
||||
from nanobot.session.manager import Session, message_preview_text
|
||||
from nanobot.session.webui_turns import _title_inputs
|
||||
from nanobot.webui.transcript import _session_user_event
|
||||
|
||||
@@ -163,7 +163,7 @@ def test_webui_preview_title_and_backfill_hide_runtime_context() -> None:
|
||||
}
|
||||
session = Session(key="websocket:chat", messages=[persisted])
|
||||
|
||||
assert _message_preview_text(persisted) == "visible user text"
|
||||
assert message_preview_text(persisted) == "visible user text"
|
||||
assert _title_inputs(session) == ("visible user text", "")
|
||||
event = _session_user_event("websocket:chat", persisted)
|
||||
assert event is not None
|
||||
|
||||
@@ -148,7 +148,7 @@ def test_same_snapshot_default_clears_preset_and_publishes_update(tmp_path: Path
|
||||
assert published == [("fast-model", None)]
|
||||
|
||||
|
||||
def test_named_default_refresh_is_used_by_sessions_without_override(tmp_path: Path) -> None:
|
||||
async def test_named_default_refresh_is_used_by_sessions_without_override(tmp_path: Path) -> None:
|
||||
provider = _provider("shared-model")
|
||||
shared_signature = ("shared-model", "auto", "same-settings")
|
||||
snapshots = {
|
||||
@@ -189,7 +189,7 @@ def test_named_default_refresh_is_used_by_sessions_without_override(tmp_path: Pa
|
||||
session = loop.sessions.get_or_create("sdk:new-after-refresh")
|
||||
|
||||
assert runtime.model_preset == "deep"
|
||||
assert loop.runtime_for_session(session).model_preset == "deep"
|
||||
assert (await loop.runtime_for_session(session)).model_preset == "deep"
|
||||
assert model_preset_from_metadata(session.metadata) is None
|
||||
|
||||
|
||||
@@ -231,7 +231,7 @@ async def test_config_invalidation_defers_canonical_notification_until_default_r
|
||||
catalog["fast"] = ModelPresetConfig(model="model-b")
|
||||
|
||||
loop.invalidate_runtime_config()
|
||||
runtime = loop.runtime_for_session(session)
|
||||
runtime = (await loop.runtime_for_session(session))
|
||||
await asyncio.sleep(0)
|
||||
|
||||
assert published == []
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import MagicMock
|
||||
from unittest.mock import AsyncMock, MagicMock
|
||||
|
||||
import pytest
|
||||
|
||||
@@ -242,19 +242,19 @@ def test_self_tool_inspect_shows_model_preset(tmp_path) -> None:
|
||||
assert "model_preset: 'fast'" in output
|
||||
|
||||
|
||||
def test_self_tool_set_model_preset_via_modify(tmp_path) -> None:
|
||||
async def test_self_tool_set_model_preset_via_modify(tmp_path) -> None:
|
||||
presets = {
|
||||
"fast": ModelPresetConfig(model="openai/gpt-4.1"),
|
||||
}
|
||||
loop = _make_loop(tmp_path, presets=presets)
|
||||
tool = _my_tool(loop)
|
||||
result = tool._modify("model_preset", "fast")
|
||||
result = await tool._modify("model_preset", "fast")
|
||||
assert "Error" not in result
|
||||
assert loop.model_preset == "fast"
|
||||
assert loop.model == "openai/gpt-4.1"
|
||||
|
||||
|
||||
def test_self_tool_set_model_preset_switches_back_to_default(tmp_path) -> None:
|
||||
async def test_self_tool_set_model_preset_switches_back_to_default(tmp_path) -> None:
|
||||
presets = {
|
||||
"default": ModelPresetConfig(model="base-model", context_window_tokens=1000),
|
||||
"fast": ModelPresetConfig(model="openai/gpt-4.1", context_window_tokens=32_768),
|
||||
@@ -262,7 +262,7 @@ def test_self_tool_set_model_preset_switches_back_to_default(tmp_path) -> None:
|
||||
loop = _make_loop(tmp_path, presets=presets, active_preset="fast")
|
||||
tool = _my_tool(loop)
|
||||
|
||||
result = tool._modify("model_preset", "default")
|
||||
result = await tool._modify("model_preset", "default")
|
||||
|
||||
assert "Error" not in result
|
||||
assert "model is now 'base-model'" in result
|
||||
@@ -271,7 +271,7 @@ def test_self_tool_set_model_preset_switches_back_to_default(tmp_path) -> None:
|
||||
assert loop.context_window_tokens == 1000
|
||||
|
||||
|
||||
def test_self_tool_set_model_preset_unknown_lists_available(tmp_path) -> None:
|
||||
async def test_self_tool_set_model_preset_unknown_lists_available(tmp_path) -> None:
|
||||
presets = {
|
||||
"default": ModelPresetConfig(model="base-model"),
|
||||
"fast": ModelPresetConfig(model="openai/gpt-4.1"),
|
||||
@@ -279,14 +279,14 @@ def test_self_tool_set_model_preset_unknown_lists_available(tmp_path) -> None:
|
||||
loop = _make_loop(tmp_path, presets=presets)
|
||||
tool = _my_tool(loop)
|
||||
|
||||
result = tool._modify("model_preset", "missing")
|
||||
result = await tool._modify("model_preset", "missing")
|
||||
|
||||
assert result == "Error: model_preset 'missing' not found. Available: default, fast."
|
||||
assert loop.model_preset is None
|
||||
assert loop.model == "base-model"
|
||||
|
||||
|
||||
def test_self_tool_sets_model_preset_for_current_session(tmp_path) -> None:
|
||||
async def test_self_tool_sets_model_preset_for_current_session(tmp_path) -> None:
|
||||
presets = {
|
||||
"default": ModelPresetConfig(model="base-model"),
|
||||
"fast": ModelPresetConfig(model="openai/gpt-4.1"),
|
||||
@@ -300,7 +300,7 @@ def test_self_tool_sets_model_preset_for_current_session(tmp_path) -> None:
|
||||
session_key="cli:one",
|
||||
metadata={"source": "self-tool"},
|
||||
)):
|
||||
result = tool._modify("model_preset", "fast")
|
||||
result = await tool._modify("model_preset", "fast")
|
||||
|
||||
assert "for the next turn" in result
|
||||
assert model_preset_from_metadata(
|
||||
@@ -310,9 +310,9 @@ def test_self_tool_sets_model_preset_for_current_session(tmp_path) -> None:
|
||||
assert loop.model == "base-model"
|
||||
|
||||
|
||||
def test_self_tool_reports_session_preset_provider_configuration_error(tmp_path) -> None:
|
||||
async def test_self_tool_reports_session_preset_provider_configuration_error(tmp_path) -> None:
|
||||
loop = _make_loop(tmp_path)
|
||||
loop.set_session_model_preset = MagicMock(
|
||||
loop.set_session_model_preset = AsyncMock(
|
||||
side_effect=ValueError("No API key configured for provider 'openai'.")
|
||||
)
|
||||
tool = _my_tool(loop)
|
||||
@@ -322,7 +322,7 @@ def test_self_tool_reports_session_preset_provider_configuration_error(tmp_path)
|
||||
chat_id="one",
|
||||
session_key="cli:one",
|
||||
)):
|
||||
result = tool._modify("model_preset", "broken")
|
||||
result = await tool._modify("model_preset", "broken")
|
||||
|
||||
assert result == "Error: No API key configured for provider 'openai'."
|
||||
|
||||
@@ -334,7 +334,7 @@ def test_self_tool_reports_session_preset_provider_configuration_error(tmp_path)
|
||||
("context_window_tokens", 8_192),
|
||||
],
|
||||
)
|
||||
def test_self_tool_rejects_instance_runtime_changes_in_session(
|
||||
async def test_self_tool_rejects_instance_runtime_changes_in_session(
|
||||
tmp_path,
|
||||
key: str,
|
||||
value: object,
|
||||
@@ -347,24 +347,24 @@ def test_self_tool_rejects_instance_runtime_changes_in_session(
|
||||
channel="cli",
|
||||
chat_id="one",
|
||||
session_key=session.key,
|
||||
runtime=loop.runtime_for_session(session),
|
||||
runtime=(await loop.runtime_for_session(session)),
|
||||
)):
|
||||
result = tool._modify(key, value)
|
||||
result = await tool._modify(key, value)
|
||||
|
||||
other_runtime = loop.runtime_for_session(loop.sessions.get_or_create("cli:two"))
|
||||
other_runtime = (await loop.runtime_for_session(loop.sessions.get_or_create("cli:two")))
|
||||
assert "instance-wide and disabled" in result
|
||||
assert "model_preset" in result
|
||||
assert other_runtime.model == "base-model"
|
||||
assert other_runtime.context_window_tokens == 1000
|
||||
|
||||
|
||||
def test_self_tool_set_model_clears_active_preset(tmp_path) -> None:
|
||||
async def test_self_tool_set_model_clears_active_preset(tmp_path) -> None:
|
||||
presets = {
|
||||
"fast": ModelPresetConfig(model="openai/gpt-4.1"),
|
||||
}
|
||||
loop = _make_loop(tmp_path, presets=presets, active_preset="fast")
|
||||
tool = _my_tool(loop)
|
||||
result = tool._modify("model", "anthropic/claude-opus-4-5")
|
||||
result = await tool._modify("model", "anthropic/claude-opus-4-5")
|
||||
assert "Error" not in result
|
||||
assert loop.model_preset is None
|
||||
assert loop.model == "anthropic/claude-opus-4-5"
|
||||
|
||||
@@ -1,423 +1,87 @@
|
||||
"""Tests for atomic session save and corrupt-file repair."""
|
||||
"""Private continuation state stays outside public conversation history."""
|
||||
|
||||
import json
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from filelock import Timeout
|
||||
|
||||
from nanobot.providers.base import ProviderConversationState
|
||||
from nanobot.session.manager import Session, SessionManager
|
||||
|
||||
|
||||
class TestAtomicSave:
|
||||
def test_save_creates_valid_jsonl(self, tmp_path: Path):
|
||||
mgr = SessionManager(tmp_path)
|
||||
session = Session(key="test:1")
|
||||
session.add_message("user", "hello")
|
||||
session.add_message("assistant", "hi")
|
||||
|
||||
mgr.save(session)
|
||||
|
||||
path = mgr._get_session_path("test:1")
|
||||
lines = path.read_text(encoding="utf-8").strip().split("\n")
|
||||
assert len(lines) == 3
|
||||
|
||||
meta = json.loads(lines[0])
|
||||
assert meta["_type"] == "metadata"
|
||||
assert meta["key"] == "test:1"
|
||||
|
||||
msg1 = json.loads(lines[1])
|
||||
assert msg1["role"] == "user"
|
||||
assert msg1["content"] == "hello"
|
||||
|
||||
def test_no_tmp_file_left_after_successful_save(self, tmp_path: Path):
|
||||
mgr = SessionManager(tmp_path)
|
||||
session = Session(key="test:clean")
|
||||
mgr.save(session)
|
||||
|
||||
tmp_files = list(mgr.sessions_dir.glob("*.tmp"))
|
||||
assert tmp_files == []
|
||||
|
||||
def test_unique_tmp_file_cleaned_up_on_write_failure(
|
||||
self,
|
||||
tmp_path: Path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
):
|
||||
mgr = SessionManager(tmp_path)
|
||||
session = Session(key="test:fail")
|
||||
path = mgr._get_session_path("test:fail")
|
||||
stale_shared_tmp = path.with_suffix(".jsonl.tmp")
|
||||
unique_tmp = path.with_name(f".{path.name}.save-failure.tmp")
|
||||
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
stale_shared_tmp.write_text("stale", encoding="utf-8")
|
||||
monkeypatch.setattr(
|
||||
"nanobot.session.manager.secrets.token_hex",
|
||||
lambda _length: "save-failure",
|
||||
)
|
||||
|
||||
original_dumps = json.dumps
|
||||
|
||||
def failing_dumps(obj, **kwargs):
|
||||
if isinstance(obj, dict) and obj.get("role") == "assistant":
|
||||
raise OSError("simulated disk full")
|
||||
return original_dumps(obj, **kwargs)
|
||||
|
||||
session = Session(key="test:fail")
|
||||
session.messages = [
|
||||
{"role": "user", "content": "ok"},
|
||||
{"role": "assistant", "content": "will fail"},
|
||||
]
|
||||
|
||||
import unittest.mock
|
||||
with (
|
||||
unittest.mock.patch(
|
||||
"nanobot.session.manager.json.dumps",
|
||||
side_effect=failing_dumps,
|
||||
),
|
||||
pytest.raises(OSError, match="simulated disk full"),
|
||||
):
|
||||
mgr.save(session)
|
||||
|
||||
assert not unique_tmp.exists()
|
||||
assert stale_shared_tmp.read_text(encoding="utf-8") == "stale"
|
||||
|
||||
def test_overwrite_preserves_latest_data(self, tmp_path: Path):
|
||||
mgr = SessionManager(tmp_path)
|
||||
session = Session(key="test:overwrite")
|
||||
|
||||
session.add_message("user", "first")
|
||||
mgr.save(session)
|
||||
|
||||
session.add_message("user", "second")
|
||||
mgr.save(session)
|
||||
|
||||
mgr.invalidate("test:overwrite")
|
||||
loaded = mgr.get_or_create("test:overwrite")
|
||||
assert len(loaded.messages) == 2
|
||||
assert loaded.messages[0]["content"] == "first"
|
||||
assert loaded.messages[1]["content"] == "second"
|
||||
|
||||
def test_consecutive_saves_are_consistent(self, tmp_path: Path):
|
||||
mgr = SessionManager(tmp_path)
|
||||
session = Session(key="test:consistency")
|
||||
|
||||
for i in range(5):
|
||||
session.add_message("user", f"msg{i}")
|
||||
mgr.save(session)
|
||||
|
||||
mgr.invalidate("test:consistency")
|
||||
loaded = mgr.get_or_create("test:consistency")
|
||||
assert len(loaded.messages) == 5
|
||||
for i in range(5):
|
||||
assert loaded.messages[i]["content"] == f"msg{i}"
|
||||
|
||||
def test_managers_for_same_directory_coordinate_saves(self, tmp_path: Path):
|
||||
workspace = tmp_path / "workspace"
|
||||
sessions_root = tmp_path / "runtime"
|
||||
owner = SessionManager(workspace, sessions_root=sessions_root)
|
||||
peer = SessionManager(workspace, sessions_root=sessions_root)
|
||||
assert owner.sessions_dir == peer.sessions_dir
|
||||
|
||||
session = Session(key="test:peer-manager")
|
||||
peer._jsonl_store._session_files_lock.timeout = 0
|
||||
with owner.locked_session_files(), pytest.raises(Timeout):
|
||||
peer.save(session)
|
||||
|
||||
peer.save(session)
|
||||
assert peer._get_session_path(session.key).is_file()
|
||||
|
||||
def test_provider_state_round_trips_in_private_record_only(self, tmp_path: Path):
|
||||
mgr = SessionManager(tmp_path)
|
||||
secret = "encrypted-reasoning-blob"
|
||||
session = Session(
|
||||
key="test:provider-state",
|
||||
provider_state=ProviderConversationState(
|
||||
kind="openai_responses",
|
||||
provider="openai:https://api.openai.com/v1",
|
||||
model="gpt-5.6",
|
||||
version=1,
|
||||
payload={
|
||||
"items": [
|
||||
{
|
||||
"type": "reasoning",
|
||||
"encrypted_content": secret,
|
||||
}
|
||||
]
|
||||
},
|
||||
pending_messages=[{"role": "user", "content": "continue"}],
|
||||
),
|
||||
)
|
||||
session.add_message("user", "hello")
|
||||
mgr.save(session)
|
||||
|
||||
records = [
|
||||
json.loads(line)
|
||||
for line in mgr._get_session_path(session.key)
|
||||
.read_text(encoding="utf-8")
|
||||
.splitlines()
|
||||
]
|
||||
assert [record.get("_type") for record in records] == [
|
||||
"metadata",
|
||||
"provider_state",
|
||||
None,
|
||||
]
|
||||
assert secret in records[1]["state"]["payload"]["items"][0]["encrypted_content"]
|
||||
|
||||
mgr.invalidate(session.key)
|
||||
loaded = mgr.get_or_create(session.key)
|
||||
assert loaded.provider_state is not None
|
||||
assert loaded.provider_state.to_private_record() == session.provider_state.to_private_record()
|
||||
|
||||
public_payload = mgr.read_session_file(session.key)
|
||||
assert public_payload is not None
|
||||
assert public_payload["messages"] == [session.messages[0]]
|
||||
assert secret not in json.dumps(public_payload)
|
||||
assert secret not in json.dumps(mgr.list_sessions())
|
||||
|
||||
def test_provider_state_does_not_consume_list_preview_budget(
|
||||
self,
|
||||
tmp_path: Path,
|
||||
monkeypatch,
|
||||
):
|
||||
import nanobot.session.manager as session_manager
|
||||
|
||||
monkeypatch.setattr(session_manager, "_SESSION_LIST_PREVIEW_MAX_CHARS", 100)
|
||||
mgr = SessionManager(tmp_path)
|
||||
session = Session(
|
||||
key="test:provider-state-preview",
|
||||
provider_state=ProviderConversationState(
|
||||
kind="openai_responses",
|
||||
provider="openai:test",
|
||||
model="test-model",
|
||||
version=1,
|
||||
payload={"items": [{"encrypted_content": "x" * 200}]},
|
||||
),
|
||||
)
|
||||
session.add_message("user", "visible preview")
|
||||
mgr.save(session)
|
||||
|
||||
assert mgr.list_sessions()[0]["preview"] == "visible preview"
|
||||
|
||||
def test_clear_and_fork_discard_provider_state(self, tmp_path: Path):
|
||||
mgr = SessionManager(tmp_path)
|
||||
state = ProviderConversationState(
|
||||
def test_provider_state_round_trips_in_private_record_only(tmp_path: Path):
|
||||
mgr = SessionManager(tmp_path)
|
||||
secret = "encrypted-reasoning-blob"
|
||||
session = Session(
|
||||
key="test:provider-state",
|
||||
provider_state=ProviderConversationState(
|
||||
kind="openai_responses",
|
||||
provider="openai:test",
|
||||
provider="openai:https://api.openai.com/v1",
|
||||
model="gpt-5.6",
|
||||
version=1,
|
||||
payload={"items": []},
|
||||
)
|
||||
source = Session(key="test:state-source", provider_state=state)
|
||||
source.add_message("user", "hello")
|
||||
mgr.save(source)
|
||||
|
||||
fork = mgr.fork_session_before_user_index(
|
||||
source.key,
|
||||
"test:state-fork",
|
||||
1,
|
||||
)
|
||||
assert fork is not None
|
||||
assert fork.provider_state is None
|
||||
|
||||
source.clear()
|
||||
assert source.provider_state is None
|
||||
|
||||
def test_invalid_provider_state_record_is_not_public_history(self, tmp_path: Path):
|
||||
mgr = SessionManager(tmp_path)
|
||||
path = mgr._get_session_path("test:bad-provider-state")
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(
|
||||
"\n".join(
|
||||
[
|
||||
json.dumps(
|
||||
{
|
||||
"_type": "metadata",
|
||||
"key": "test:bad-provider-state",
|
||||
"created_at": datetime.now().isoformat(),
|
||||
"updated_at": datetime.now().isoformat(),
|
||||
"metadata": {},
|
||||
"last_consolidated": 0,
|
||||
}
|
||||
),
|
||||
json.dumps(
|
||||
{
|
||||
"_type": "provider_state",
|
||||
"state": {"kind": "openai_responses"},
|
||||
}
|
||||
),
|
||||
json.dumps({"role": "user", "content": "safe"}),
|
||||
payload={
|
||||
"items": [
|
||||
{
|
||||
"type": "reasoning",
|
||||
"encrypted_content": secret,
|
||||
}
|
||||
]
|
||||
)
|
||||
+ "\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
},
|
||||
pending_messages=[{"role": "user", "content": "continue"}],
|
||||
),
|
||||
)
|
||||
session.add_message("user", "hello")
|
||||
mgr.save(session)
|
||||
|
||||
loaded = mgr._load("test:bad-provider-state")
|
||||
assert loaded is not None
|
||||
assert loaded.provider_state is None
|
||||
assert loaded.messages == [{"role": "user", "content": "safe"}]
|
||||
mgr.invalidate(session.key)
|
||||
loaded = mgr.get_or_create(session.key)
|
||||
assert loaded.provider_state is not None
|
||||
assert loaded.provider_state.to_private_record() == session.provider_state.to_private_record()
|
||||
|
||||
public_payload = mgr.read_session_file(session.key)
|
||||
assert public_payload is not None
|
||||
assert public_payload["messages"] == [session.messages[0]]
|
||||
assert secret not in json.dumps(public_payload)
|
||||
assert secret not in json.dumps(mgr.list_sessions())
|
||||
|
||||
class TestRepairCorruptFile:
|
||||
def _write_corrupt_jsonl(self, path: Path, lines: list[str]) -> None:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text("\n".join(lines) + "\n", encoding="utf-8")
|
||||
def test_provider_state_does_not_consume_list_preview_budget(
|
||||
tmp_path: Path,
|
||||
monkeypatch,
|
||||
):
|
||||
mgr = SessionManager(tmp_path)
|
||||
session = Session(
|
||||
key="test:provider-state-preview",
|
||||
provider_state=ProviderConversationState(
|
||||
kind="openai_responses",
|
||||
provider="openai:test",
|
||||
model="test-model",
|
||||
version=1,
|
||||
payload={"items": [{"encrypted_content": "x" * 200}]},
|
||||
),
|
||||
)
|
||||
session.add_message("user", "visible preview")
|
||||
mgr.save(session)
|
||||
|
||||
def test_truncated_last_line_recovered(self, tmp_path: Path):
|
||||
mgr = SessionManager(tmp_path)
|
||||
path = mgr._get_session_path("test:trunc")
|
||||
assert mgr.list_sessions()[0]["preview"] == "visible preview"
|
||||
|
||||
valid_meta = json.dumps({
|
||||
"_type": "metadata",
|
||||
"key": "test:trunc",
|
||||
"created_at": datetime.now().isoformat(),
|
||||
"updated_at": datetime.now().isoformat(),
|
||||
"metadata": {},
|
||||
"last_consolidated": 0,
|
||||
})
|
||||
valid_msg = json.dumps({"role": "user", "content": "hello"})
|
||||
def test_clear_and_fork_discard_provider_state(tmp_path: Path):
|
||||
mgr = SessionManager(tmp_path)
|
||||
state = ProviderConversationState(
|
||||
kind="openai_responses",
|
||||
provider="openai:test",
|
||||
model="gpt-5.6",
|
||||
version=1,
|
||||
payload={"items": []},
|
||||
)
|
||||
source = Session(key="test:state-source", provider_state=state)
|
||||
source.add_message("user", "hello")
|
||||
mgr.save(source)
|
||||
|
||||
self._write_corrupt_jsonl(path, [
|
||||
valid_meta,
|
||||
valid_msg,
|
||||
'{"role": "assistant", "content": "partial...',
|
||||
])
|
||||
fork = mgr.fork_session_before_user_index(
|
||||
source.key,
|
||||
"test:state-fork",
|
||||
1,
|
||||
)
|
||||
assert fork is not None
|
||||
assert fork.provider_state is None
|
||||
|
||||
session = mgr._load("test:trunc")
|
||||
assert session is not None
|
||||
assert len(session.messages) == 1
|
||||
assert session.messages[0]["content"] == "hello"
|
||||
|
||||
def test_corrupt_metadata_line_skipped(self, tmp_path: Path):
|
||||
mgr = SessionManager(tmp_path)
|
||||
path = mgr._get_session_path("test:badmeta")
|
||||
|
||||
self._write_corrupt_jsonl(path, [
|
||||
"NOT VALID JSON!!!",
|
||||
'{"role": "user", "content": "survived"}',
|
||||
])
|
||||
|
||||
session = mgr._load("test:badmeta")
|
||||
assert session is not None
|
||||
assert len(session.messages) == 1
|
||||
assert session.messages[0]["content"] == "survived"
|
||||
|
||||
def test_all_corrupt_lines_returns_none(self, tmp_path: Path):
|
||||
mgr = SessionManager(tmp_path)
|
||||
path = mgr._get_session_path("test:allbad")
|
||||
|
||||
self._write_corrupt_jsonl(path, [
|
||||
"garbage line 1",
|
||||
"garbage line 2",
|
||||
"{{invalid json",
|
||||
])
|
||||
|
||||
session = mgr._load("test:allbad")
|
||||
assert session is None
|
||||
|
||||
def test_empty_file_returns_empty_session(self, tmp_path: Path):
|
||||
mgr = SessionManager(tmp_path)
|
||||
path = mgr._get_session_path("test:empty")
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text("", encoding="utf-8")
|
||||
|
||||
session = mgr._load("test:empty")
|
||||
assert session is not None
|
||||
assert session.messages == []
|
||||
assert session.key == "test:empty"
|
||||
|
||||
def test_repair_preserves_valid_messages_amid_corruption(self, tmp_path: Path):
|
||||
mgr = SessionManager(tmp_path)
|
||||
path = mgr._get_session_path("test:mixed")
|
||||
|
||||
self._write_corrupt_jsonl(path, [
|
||||
json.dumps({"_type": "metadata", "key": "test:mixed",
|
||||
"created_at": datetime.now().isoformat(),
|
||||
"updated_at": datetime.now().isoformat(),
|
||||
"metadata": {}, "last_consolidated": 0}),
|
||||
"BROKEN",
|
||||
json.dumps({"role": "user", "content": "msg1"}),
|
||||
'{"role": "assistant", "content": "broken',
|
||||
json.dumps({"role": "user", "content": "msg2"}),
|
||||
])
|
||||
|
||||
session = mgr._load("test:mixed")
|
||||
assert session is not None
|
||||
assert len(session.messages) == 2
|
||||
assert session.messages[0]["content"] == "msg1"
|
||||
assert session.messages[1]["content"] == "msg2"
|
||||
|
||||
def test_repair_with_bad_timestamp_uses_fallback(self, tmp_path: Path):
|
||||
mgr = SessionManager(tmp_path)
|
||||
path = mgr._get_session_path("test:badts")
|
||||
|
||||
self._write_corrupt_jsonl(path, [
|
||||
json.dumps({"_type": "metadata", "key": "test:badts",
|
||||
"created_at": "not-a-date",
|
||||
"updated_at": "also-bad",
|
||||
"metadata": {}, "last_consolidated": 5}),
|
||||
json.dumps({"role": "user", "content": "hi"}),
|
||||
])
|
||||
|
||||
session = mgr._load("test:badts")
|
||||
assert session is not None
|
||||
# offset 5 exceeds the single loaded message; reset to avoid hiding history (#4066)
|
||||
assert session.last_consolidated == 0
|
||||
assert isinstance(session.created_at, datetime)
|
||||
|
||||
def test_read_session_file_repairs_corrupt_jsonl(self, tmp_path: Path):
|
||||
mgr = SessionManager(tmp_path)
|
||||
path = mgr._get_session_path("test:read-repair")
|
||||
|
||||
self._write_corrupt_jsonl(path, [
|
||||
json.dumps({
|
||||
"_type": "metadata",
|
||||
"key": "test:read-repair",
|
||||
"created_at": datetime.now().isoformat(),
|
||||
"updated_at": datetime.now().isoformat(),
|
||||
"metadata": {"source": "repair"},
|
||||
"last_consolidated": 0,
|
||||
}),
|
||||
json.dumps({"role": "user", "content": "survived"}),
|
||||
'{"role": "assistant", "content": "partial...',
|
||||
])
|
||||
|
||||
payload = mgr.read_session_file("test:read-repair")
|
||||
assert payload is not None
|
||||
assert payload["key"] == "test:read-repair"
|
||||
assert payload["metadata"] == {"source": "repair"}
|
||||
assert payload["messages"] == [{"role": "user", "content": "survived"}]
|
||||
|
||||
def test_list_sessions_keeps_repaired_corrupt_file(self, tmp_path: Path):
|
||||
mgr = SessionManager(tmp_path)
|
||||
path = mgr._get_session_path("test:list-repair")
|
||||
|
||||
self._write_corrupt_jsonl(path, [
|
||||
"NOT VALID JSON",
|
||||
json.dumps({
|
||||
"_type": "metadata",
|
||||
"key": "test:list-repair",
|
||||
"created_at": datetime.now().isoformat(),
|
||||
"updated_at": datetime.now().isoformat(),
|
||||
"metadata": {},
|
||||
"last_consolidated": 0,
|
||||
}),
|
||||
json.dumps({"role": "user", "content": "hello"}),
|
||||
])
|
||||
|
||||
sessions = mgr.list_sessions()
|
||||
assert any(s["key"] == "test:list-repair" for s in sessions)
|
||||
|
||||
def test_get_or_create_returns_new_session_for_corrupt_file(self, tmp_path: Path):
|
||||
mgr = SessionManager(tmp_path)
|
||||
path = mgr._get_session_path("test:fallback")
|
||||
|
||||
self._write_corrupt_jsonl(path, ["{{{{"])
|
||||
|
||||
session = mgr.get_or_create("test:fallback")
|
||||
assert session is not None
|
||||
assert session.messages == []
|
||||
assert session.key == "test:fallback"
|
||||
source.clear()
|
||||
assert source.provider_state is None
|
||||
@@ -1,144 +1,18 @@
|
||||
"""Regression tests for collision-resistant session filenames."""
|
||||
|
||||
import json
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
"""Session keys remain distinct even when their display filenames collide."""
|
||||
|
||||
from nanobot.session.manager import Session, SessionManager
|
||||
from nanobot.utils.helpers import safe_filename
|
||||
|
||||
|
||||
def _manager(tmp_path: Path, monkeypatch) -> SessionManager:
|
||||
monkeypatch.setattr(
|
||||
"nanobot.session.manager.get_legacy_sessions_dir",
|
||||
lambda: tmp_path / "legacy_sessions",
|
||||
)
|
||||
return SessionManager(tmp_path / "workspace")
|
||||
|
||||
|
||||
def _write_session_file(path: Path, key: str, content: str) -> None:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
metadata = {
|
||||
"_type": "metadata",
|
||||
"key": key,
|
||||
"created_at": datetime(2025, 1, 1).isoformat(),
|
||||
"updated_at": datetime(2025, 1, 1).isoformat(),
|
||||
"metadata": {"source": "test"},
|
||||
"last_consolidated": 0,
|
||||
}
|
||||
message = {"role": "user", "content": content}
|
||||
path.write_text(
|
||||
json.dumps(metadata) + "\n" + json.dumps(message) + "\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
|
||||
def test_distinct_keys_have_distinct_filenames(tmp_path: Path, monkeypatch) -> None:
|
||||
sm = _manager(tmp_path, monkeypatch)
|
||||
|
||||
first = sm._get_session_path("telegram:a_b")
|
||||
second = sm._get_session_path("telegram:a:b")
|
||||
|
||||
assert first.name != second.name
|
||||
assert sm.safe_key("telegram:a_b") == sm.safe_key("telegram:a:b")
|
||||
assert sm._storage_key("telegram:a_b") != sm._storage_key("telegram:a:b")
|
||||
|
||||
|
||||
def test_save_uses_new_path_not_lossy(tmp_path: Path, monkeypatch) -> None:
|
||||
sm = _manager(tmp_path, monkeypatch)
|
||||
key = "telegram:a:b"
|
||||
session = Session(key=key)
|
||||
session.add_message("user", "first")
|
||||
sm.save(session)
|
||||
|
||||
new_path = sm._get_session_path(key)
|
||||
lossy_path = sm._get_legacy_lossy_path(key)
|
||||
_write_session_file(lossy_path, key, "stale lossy content")
|
||||
stale_lossy = lossy_path.read_text(encoding="utf-8")
|
||||
|
||||
session.add_message("assistant", "latest content")
|
||||
sm.save(session)
|
||||
|
||||
assert new_path.exists()
|
||||
assert lossy_path.exists()
|
||||
assert "latest content" in new_path.read_text(encoding="utf-8")
|
||||
assert lossy_path.read_text(encoding="utf-8") == stale_lossy
|
||||
|
||||
|
||||
def test_load_ignores_legacy_lossy_path(tmp_path: Path, monkeypatch) -> None:
|
||||
sm = _manager(tmp_path, monkeypatch)
|
||||
key = "telegram:legacy:lossy"
|
||||
lossy_path = sm._get_legacy_lossy_path(key)
|
||||
_write_session_file(lossy_path, key, "loaded from lossy")
|
||||
|
||||
session = sm._load(key)
|
||||
|
||||
assert session is None
|
||||
assert lossy_path.exists()
|
||||
assert not sm._get_session_path(key).exists()
|
||||
|
||||
|
||||
def test_load_ignores_legacy_global_path(tmp_path: Path, monkeypatch) -> None:
|
||||
sm = _manager(tmp_path, monkeypatch)
|
||||
key = "telegram:legacy:global"
|
||||
new_path = sm._get_session_path(key)
|
||||
legacy_path = sm._get_legacy_session_path(key)
|
||||
_write_session_file(legacy_path, key, "loaded from global")
|
||||
|
||||
session = sm._load(key)
|
||||
|
||||
assert session is None
|
||||
assert legacy_path.exists()
|
||||
assert not new_path.exists()
|
||||
|
||||
|
||||
def test_safe_key_is_lossy() -> None:
|
||||
assert SessionManager.safe_key("telegram:a_b") == SessionManager.safe_key("telegram:a:b")
|
||||
|
||||
|
||||
def test_storage_key_is_collision_resistant() -> None:
|
||||
encoded = {
|
||||
SessionManager._storage_key("a:b"),
|
||||
SessionManager._storage_key("a_b"),
|
||||
SessionManager._storage_key("a:b:c"),
|
||||
}
|
||||
|
||||
assert len(encoded) == 3
|
||||
assert SessionManager._storage_key("telegram:a_b") != SessionManager._storage_key("telegram:a:b")
|
||||
|
||||
|
||||
def test_lossy_path_helper_returns_expected_path(tmp_path: Path, monkeypatch) -> None:
|
||||
sm = _manager(tmp_path, monkeypatch)
|
||||
key = "telegram:a:b"
|
||||
expected = sm.sessions_dir / f"{safe_filename(key.replace(':', '_'))}.jsonl"
|
||||
|
||||
assert sm._get_legacy_lossy_path(key) == expected
|
||||
|
||||
|
||||
def test_storage_paths_are_distinct_when_keys_collide_under_safe_key(
|
||||
tmp_path: Path,
|
||||
monkeypatch,
|
||||
) -> None:
|
||||
sm = _manager(tmp_path, monkeypatch)
|
||||
first = Session(key="telegram:a_b")
|
||||
first.add_message("user", "underscore history")
|
||||
second = Session(key="telegram:a:b")
|
||||
second.add_message("user", "colon history")
|
||||
|
||||
sm.save(first)
|
||||
sm.save(second)
|
||||
|
||||
assert sm.safe_key(first.key) == sm.safe_key(second.key)
|
||||
assert sm._get_session_path(first.key).exists()
|
||||
assert sm._get_session_path(second.key).exists()
|
||||
assert sm._get_session_path(first.key) != sm._get_session_path(second.key)
|
||||
|
||||
sm.invalidate(first.key)
|
||||
sm.invalidate(second.key)
|
||||
loaded_first = sm._load(first.key)
|
||||
loaded_second = sm._load(second.key)
|
||||
|
||||
assert loaded_first is not None
|
||||
assert loaded_second is not None
|
||||
assert loaded_first.messages[0]["content"] == "underscore history"
|
||||
assert loaded_second.messages[0]["content"] == "colon history"
|
||||
def test_colliding_display_names_roundtrip_independently(tmp_path):
|
||||
manager = SessionManager(tmp_path)
|
||||
keys = ("telegram:a_b", "telegram:a:b", "telegram:a/b", "telegram:你好")
|
||||
for key in keys:
|
||||
session = Session(key=key)
|
||||
session.add_message("user", key)
|
||||
manager.save(session)
|
||||
assert manager.safe_key(keys[0]) == manager.safe_key(keys[1])
|
||||
assert len(manager.list_sessions()) == len(keys)
|
||||
for key in keys:
|
||||
assert manager.read_session_file(key)["messages"][0]["content"] == key
|
||||
manager.delete_session(keys[0])
|
||||
assert manager.read_session_snapshot(keys[1]) is not None
|
||||
@@ -16,14 +16,13 @@ def _seed(workspace: Path, key: str = "telegram:abc") -> SessionManager:
|
||||
|
||||
def test_delete_session_removes_file_and_invalidates_cache(tmp_path: Path) -> None:
|
||||
sm = _seed(tmp_path, "telegram:abc")
|
||||
file_path = sm._get_session_path("telegram:abc")
|
||||
assert file_path.exists()
|
||||
assert sm.read_session_snapshot("telegram:abc") is not None
|
||||
# Populate cache as a real consumer would.
|
||||
cached = sm.get_or_create("telegram:abc")
|
||||
assert cached.messages
|
||||
|
||||
assert sm.delete_session("telegram:abc") is True
|
||||
assert not file_path.exists()
|
||||
assert sm.read_session_snapshot("telegram:abc") is None
|
||||
# Subsequent get_or_create returns a fresh, empty Session (no stale cache).
|
||||
fresh = sm.get_or_create("telegram:abc")
|
||||
assert fresh.messages == []
|
||||
@@ -59,98 +58,11 @@ def test_read_session_file_returns_metadata_and_messages(tmp_path: Path) -> None
|
||||
def test_read_session_file_does_not_populate_cache(tmp_path: Path) -> None:
|
||||
sm = _seed(tmp_path, "telegram:abc")
|
||||
sm.invalidate("telegram:abc")
|
||||
assert "telegram:abc" not in sm._cache
|
||||
assert sm.get_cached("telegram:abc") is None
|
||||
sm.read_session_file("telegram:abc")
|
||||
assert "telegram:abc" not in sm._cache
|
||||
assert sm.get_cached("telegram:abc") is None
|
||||
|
||||
|
||||
def test_read_session_file_missing(tmp_path: Path) -> None:
|
||||
sm = SessionManager(tmp_path)
|
||||
assert sm.read_session_file("nope:none") is None
|
||||
|
||||
|
||||
def test_storage_key_matches_internal_path(tmp_path: Path) -> None:
|
||||
sm = SessionManager(tmp_path)
|
||||
key = "telegram:abc/def"
|
||||
expected = sm._get_session_path(key).name
|
||||
assert SessionManager._storage_key(key) + ".jsonl" == expected
|
||||
|
||||
|
||||
def _write_legacy_session(legacy_dir: Path, key: str, roles: list[str]) -> Path:
|
||||
legacy_dir.mkdir(parents=True, exist_ok=True)
|
||||
safe = SessionManager.safe_key(key)
|
||||
path = legacy_dir / f"{safe}.jsonl"
|
||||
metadata_line = (
|
||||
'{"_type":"metadata","key":"' + key + '",'
|
||||
'"created_at":"2025-01-01T00:00:00",'
|
||||
'"updated_at":"2025-01-01T00:00:00",'
|
||||
'"metadata":{}}'
|
||||
)
|
||||
lines = [metadata_line]
|
||||
for role in roles:
|
||||
lines.append('{"role":"' + role + '","content":"msg"}')
|
||||
path.write_text("\n".join(lines) + "\n", encoding="utf-8")
|
||||
return path
|
||||
|
||||
|
||||
def test_delete_session_cleans_legacy_file(tmp_path: Path, monkeypatch) -> None:
|
||||
"""A session that only exists at the legacy location must also be deleted."""
|
||||
legacy = tmp_path / "legacy_sessions"
|
||||
monkeypatch.setattr(
|
||||
"nanobot.session.manager.get_legacy_sessions_dir",
|
||||
lambda: legacy,
|
||||
)
|
||||
key = "telegram:only-legacy"
|
||||
legacy_path = _write_legacy_session(legacy, key, ["user", "assistant"])
|
||||
assert legacy_path.exists()
|
||||
|
||||
sm = SessionManager(tmp_path / "workspace")
|
||||
new_path = sm._get_session_path(key)
|
||||
assert not new_path.exists()
|
||||
|
||||
assert sm.delete_session(key) is True
|
||||
assert not legacy_path.exists(), "legacy session file should have been removed"
|
||||
|
||||
|
||||
def test_delete_session_cleans_both_locations(tmp_path: Path, monkeypatch) -> None:
|
||||
"""When files exist at both the new and legacy paths, both must be removed."""
|
||||
legacy = tmp_path / "legacy_sessions"
|
||||
monkeypatch.setattr(
|
||||
"nanobot.session.manager.get_legacy_sessions_dir",
|
||||
lambda: legacy,
|
||||
)
|
||||
workspace = tmp_path / "workspace"
|
||||
key = "telegram:both-paths"
|
||||
_write_legacy_session(legacy, key, ["user", "assistant"])
|
||||
|
||||
sm = SessionManager(workspace)
|
||||
session = Session(key=key)
|
||||
session.add_message("user", "recent")
|
||||
sm.save(session)
|
||||
|
||||
assert sm._get_session_path(key).exists()
|
||||
assert (legacy / f"{SessionManager.safe_key(key)}.jsonl").exists()
|
||||
|
||||
assert sm.delete_session(key) is True
|
||||
|
||||
assert not sm._get_session_path(key).exists()
|
||||
assert not (legacy / f"{SessionManager.safe_key(key)}.jsonl").exists()
|
||||
|
||||
|
||||
def test_delete_session_prevents_legacy_revival(tmp_path: Path, monkeypatch) -> None:
|
||||
"""After delete_session, a subsequent get_or_create must not resurrect history."""
|
||||
legacy = tmp_path / "legacy_sessions"
|
||||
monkeypatch.setattr(
|
||||
"nanobot.session.manager.get_legacy_sessions_dir",
|
||||
lambda: legacy,
|
||||
)
|
||||
workspace = tmp_path / "workspace"
|
||||
key = "telegram:no-revival"
|
||||
_write_legacy_session(legacy, key, ["user", "assistant"])
|
||||
|
||||
sm = SessionManager(workspace)
|
||||
assert sm.delete_session(key) is True
|
||||
assert not (legacy / f"{SessionManager.safe_key(key)}.jsonl").exists()
|
||||
|
||||
fresh = sm.get_or_create(key)
|
||||
assert fresh.messages == []
|
||||
@@ -1,6 +1,7 @@
|
||||
"""Independent turns and internal controls retain their session inbox semantics."""
|
||||
|
||||
import asyncio
|
||||
import threading
|
||||
from unittest.mock import AsyncMock, MagicMock
|
||||
|
||||
import pytest
|
||||
@@ -23,7 +24,6 @@ from nanobot.session.recovery import (
|
||||
PENDING_FOLLOWUPS_KEY,
|
||||
REQUEST_ORIGIN_METADATA_KEY,
|
||||
pending_followups,
|
||||
record_pending_followup,
|
||||
)
|
||||
from nanobot.triggers.local_session_turns import LOCAL_TRIGGER_META
|
||||
from nanobot.webui.recovery import RecoveryCoordinator
|
||||
@@ -46,6 +46,95 @@ async def loop(tmp_path):
|
||||
await agent.aclose()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("rejection", ["stop", "followup", "replaced-followup", "idle"])
|
||||
async def test_rejected_input_does_not_stop_other_sessions(loop, monkeypatch, rejection):
|
||||
state = loop.sessions.state
|
||||
session = await state.get("websocket:busy")
|
||||
model_started, release_model = asyncio.Event(), asyncio.Event()
|
||||
readers_started, release_readers = threading.Event(), threading.Event()
|
||||
idle_checked = asyncio.Event()
|
||||
active_turn = rejection in {"followup", "replaced-followup"}
|
||||
readers = []
|
||||
|
||||
async def chat(**kwargs):
|
||||
if active_turn and not model_started.is_set():
|
||||
model_started.set()
|
||||
await release_model.wait()
|
||||
return LLMResponse(content="still responsive")
|
||||
|
||||
async def reply(chat_id):
|
||||
async with asyncio.timeout(5):
|
||||
while True:
|
||||
message = await loop.bus.consume_outbound()
|
||||
if message.chat_id == chat_id and message.event is None:
|
||||
return message
|
||||
|
||||
original_list = loop.sessions._store.list_metadata
|
||||
|
||||
def blocked_list():
|
||||
readers_started.set()
|
||||
assert release_readers.wait(5)
|
||||
return original_list()
|
||||
|
||||
loop.provider.chat_stream_with_retry = chat
|
||||
if rejection == "idle":
|
||||
original_check = loop.auto_compact.check_expired
|
||||
|
||||
async def observed_check(*args, **kwargs):
|
||||
try:
|
||||
await original_check(*args, **kwargs)
|
||||
finally:
|
||||
idle_checked.set()
|
||||
|
||||
monkeypatch.setattr(loop.auto_compact, "check_expired", observed_check)
|
||||
loop._next_idle_compact_check_at = 0
|
||||
run_task = asyncio.create_task(loop.run())
|
||||
try:
|
||||
if active_turn:
|
||||
await loop.bus.publish_inbound(InboundMessage(
|
||||
channel="websocket", sender_id="u", chat_id="busy", content="first",
|
||||
metadata={"webui": True}, session_generation=session.generation,
|
||||
))
|
||||
await asyncio.wait_for(model_started.wait(), timeout=3)
|
||||
if rejection == "replaced-followup":
|
||||
await state.reset(session.key)
|
||||
else:
|
||||
monkeypatch.setattr(loop.sessions._store, "list_metadata", blocked_list)
|
||||
readers = [asyncio.create_task(state.list_metadata()) for _ in range(64)]
|
||||
assert await asyncio.to_thread(readers_started.wait, 2)
|
||||
|
||||
if rejection == "idle":
|
||||
await asyncio.wait_for(idle_checked.wait(), timeout=3)
|
||||
else:
|
||||
rejected = InboundMessage(
|
||||
channel="telegram" if rejection == "stop" else "websocket",
|
||||
sender_id="u", chat_id="busy",
|
||||
content="/stop" if rejection == "stop" else "rejected follow-up",
|
||||
metadata={"webui": True}, session_generation=session.generation,
|
||||
)
|
||||
await loop.bus.publish_inbound(rejected)
|
||||
assert (await reply("busy")).content == "Sorry, I encountered an error."
|
||||
assert not run_task.done()
|
||||
|
||||
release_readers.set()
|
||||
await asyncio.gather(*readers)
|
||||
await loop.bus.publish_inbound(InboundMessage(
|
||||
channel="telegram", sender_id="u", chat_id="other", content="hello",
|
||||
))
|
||||
assert (await reply("other")).content == "still responsive"
|
||||
if active_turn:
|
||||
assert not release_model.is_set()
|
||||
assert loop._pending_queues[session.key].empty()
|
||||
saved = await state.read(session.key)
|
||||
assert pending_followups(saved) == []
|
||||
finally:
|
||||
release_readers.set()
|
||||
await asyncio.gather(*readers, return_exceptions=True)
|
||||
loop.stop()
|
||||
run_task.cancel()
|
||||
await asyncio.gather(run_task, return_exceptions=True)
|
||||
|
||||
|
||||
def _automation_message(kind: str, name: str) -> InboundMessage:
|
||||
metadata = (
|
||||
{
|
||||
@@ -83,9 +172,6 @@ async def test_automation_turn_is_deferred_while_session_active(loop, kind):
|
||||
async with asyncio.timeout(3):
|
||||
while not coordinator.deferred_queues.get(key):
|
||||
await asyncio.sleep(0)
|
||||
loop.stop()
|
||||
await asyncio.wait_for(run_task, timeout=3)
|
||||
|
||||
assert pending.empty()
|
||||
assert loop._active_tasks == {}
|
||||
assert coordinator.deferred_queues[key] == [msg]
|
||||
@@ -106,7 +192,7 @@ async def test_automation_turn_is_deferred_while_session_active(loop, kind):
|
||||
@pytest.mark.parametrize("kind", ["cron", "local_trigger"])
|
||||
async def test_submitted_automation_reports_pending_until_completed(loop, kind):
|
||||
coordinator = loop._cron_turns if kind == "cron" else loop._local_trigger_turns
|
||||
coordinator._enqueue = MagicMock()
|
||||
coordinator._enqueue = AsyncMock()
|
||||
submit = loop.submit_cron_turn if kind == "cron" else loop.submit_local_trigger_turn
|
||||
pending_ids = (
|
||||
loop.pending_cron_job_ids_for_session
|
||||
@@ -256,15 +342,15 @@ async def test_stopped_followups_are_not_recovered_but_shutdown_preserves_them(
|
||||
|
||||
loop.provider.chat_stream_with_retry = chat
|
||||
key = "websocket:test"
|
||||
loop._enqueue_session_message(InboundMessage(
|
||||
(await loop._enqueue_session_message(InboundMessage(
|
||||
channel="websocket", sender_id="u", chat_id="test", content="first",
|
||||
metadata={"webui": True},
|
||||
))
|
||||
)))
|
||||
await asyncio.wait_for(started.wait(), timeout=3)
|
||||
loop._enqueue_session_message(InboundMessage(
|
||||
(await loop._enqueue_session_message(InboundMessage(
|
||||
channel="websocket", sender_id="u", chat_id="test", content="cancel me",
|
||||
metadata={"webui": True},
|
||||
))
|
||||
)))
|
||||
|
||||
if not followup_still_queued:
|
||||
consumed = loop._pending_queues[key].get_nowait()
|
||||
@@ -300,16 +386,15 @@ async def test_stopped_followups_are_not_recovered_but_shutdown_preserves_them(
|
||||
|
||||
async def test_cancel_preserves_followups_accepted_after_cancellation_started(loop):
|
||||
key = "websocket:test"
|
||||
session = loop.sessions.get_or_create(key)
|
||||
session = await loop.sessions.state.get(key)
|
||||
|
||||
def journal(content):
|
||||
record_pending_followup(session, InboundMessage(
|
||||
async def journal(content):
|
||||
await loop.sessions.state.queue_followup(key, InboundMessage(
|
||||
channel="websocket", sender_id="u", chat_id="test", content=content,
|
||||
metadata={"webui": True},
|
||||
metadata={"webui": True}, session_generation=session.generation,
|
||||
))
|
||||
loop.sessions.save(session)
|
||||
|
||||
journal("old followup")
|
||||
await journal("old followup")
|
||||
started = asyncio.Event()
|
||||
cancelling = asyncio.Event()
|
||||
release = asyncio.Event()
|
||||
@@ -328,7 +413,7 @@ async def test_cancel_preserves_followups_accepted_after_cancellation_started(lo
|
||||
stop = asyncio.create_task(loop._cancel_active_tasks(key))
|
||||
try:
|
||||
await asyncio.wait_for(cancelling.wait(), timeout=3)
|
||||
journal("new followup")
|
||||
await journal("new followup")
|
||||
finally:
|
||||
release.set()
|
||||
await stop
|
||||
@@ -422,7 +507,7 @@ async def test_ingress_sources_share_one_session_worker(loop, bus_running):
|
||||
if bus_running:
|
||||
await loop.bus.publish_inbound(first)
|
||||
else:
|
||||
loop._enqueue_session_message(first)
|
||||
(await loop._enqueue_session_message(first))
|
||||
await asyncio.wait_for(started.wait(), timeout=3)
|
||||
cron = asyncio.create_task(loop.submit_cron_turn(_automation_message("cron", "cron")))
|
||||
trigger = asyncio.create_task(loop.submit_local_trigger_turn(
|
||||
@@ -437,7 +522,7 @@ async def test_ingress_sources_share_one_session_worker(loop, bus_running):
|
||||
while loop._pending_queues[key].empty():
|
||||
await asyncio.sleep(0)
|
||||
else:
|
||||
loop._enqueue_session_message(second)
|
||||
(await loop._enqueue_session_message(second))
|
||||
compact = InboundMessage(channel="websocket", sender_id="u", chat_id="test", content="/compact")
|
||||
await loop._dispatch_command_inline(compact, key, compact.content, loop.commands.dispatch)
|
||||
assert len(loop._active_tasks[key]) == 1
|
||||
@@ -528,7 +613,9 @@ async def test_goal_continuation_after_followup_keeps_control_identity(loop, com
|
||||
while loop._pending_queues["cli:test"].empty():
|
||||
await asyncio.sleep(0)
|
||||
elif complete_on_followup or len(requests) == 3:
|
||||
session.metadata[GOAL_STATE_KEY]["status"] = "complete"
|
||||
await loop.sessions.state.update_metadata(session.key, {
|
||||
GOAL_STATE_KEY: {"status": "complete", "objective": "Finish the long goal"},
|
||||
})
|
||||
return LLMResponse(content="done")
|
||||
return LLMResponse(
|
||||
content="working", finish_reason="tool_calls",
|
||||
@@ -587,7 +674,9 @@ async def test_queued_continuation_keeps_its_origin_after_another_chat_runs(loop
|
||||
persisted = SessionManager(loop.workspace).get_or_create(key)
|
||||
persisted_origin = persisted.metadata[REQUEST_ORIGIN_METADATA_KEY]
|
||||
await loop.tools.get("message").execute(content="Continuation reply")
|
||||
session.metadata[GOAL_STATE_KEY]["status"] = "complete"
|
||||
await loop.sessions.state.mutate_metadata(
|
||||
key, lambda metadata: metadata[GOAL_STATE_KEY].update(status="complete"),
|
||||
)
|
||||
return LLMResponse(content="done")
|
||||
return LLMResponse(content="working", finish_reason="tool_calls", tool_calls=[
|
||||
ToolCallRequest(id=f"call-{len(requests)}", name="noop", arguments={}),
|
||||
|
||||
@@ -38,7 +38,7 @@ def _tool_turn(prefix: str, idx: int) -> list[dict]:
|
||||
]
|
||||
|
||||
|
||||
def test_list_sessions_includes_metadata_title(tmp_path):
|
||||
def test_list_sessions_includesmetadata_title(tmp_path):
|
||||
manager = SessionManager(tmp_path)
|
||||
session = manager.get_or_create("websocket:chat-title")
|
||||
session.metadata["title"] = "自动生成标题"
|
||||
|
||||
@@ -4,6 +4,7 @@ import pytest
|
||||
|
||||
from nanobot.agent.loop import AgentLoop
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.bus.runtime_events import RuntimeModelChanged
|
||||
from nanobot.config.schema import ModelPresetConfig
|
||||
from nanobot.nanobot import Nanobot
|
||||
from nanobot.providers.base import GenerationSettings, LLMProvider, LLMResponse
|
||||
@@ -69,8 +70,8 @@ async def test_sessions_run_concurrently_with_isolated_model_presets(tmp_path) -
|
||||
preset_snapshot_loader=load_preset,
|
||||
)
|
||||
loop.schedule_background = lambda coro: coro.close() # type: ignore[method-assign]
|
||||
loop.set_session_model_preset("sdk:fast", "fast")
|
||||
loop.set_session_model_preset("sdk:deep", "deep")
|
||||
(await loop.set_session_model_preset("sdk:fast", "fast"))
|
||||
(await loop.set_session_model_preset("sdk:deep", "deep"))
|
||||
|
||||
fast_reply, deep_reply = await asyncio.gather(
|
||||
loop.process_direct("hello", session_key="sdk:fast"),
|
||||
@@ -135,6 +136,31 @@ async def test_removed_session_model_preset_falls_back_and_clears_metadata(tmp_p
|
||||
assert model_preset_from_metadata(restored.metadata) is None
|
||||
|
||||
|
||||
async def test_async_runtime_resolution_publishes_model_refresh_on_event_loop(
|
||||
tmp_path,
|
||||
monkeypatch,
|
||||
) -> None:
|
||||
provider = RecordingProvider("base-model")
|
||||
loop = AgentLoop(bus=MessageBus(), provider=provider, workspace=tmp_path, model="base-model")
|
||||
session = loop.sessions.get_or_create("sdk:runtime-refresh")
|
||||
refreshed = LLMRuntime.capture(provider, "updated-model", context_window_tokens=16_000)
|
||||
monkeypatch.setattr(loop.runtime_resolver, "admit", lambda: refreshed)
|
||||
published = asyncio.Event()
|
||||
events: list[RuntimeModelChanged] = []
|
||||
|
||||
def on_changed(event: RuntimeModelChanged) -> None:
|
||||
events.append(event)
|
||||
published.set()
|
||||
|
||||
unsubscribe = loop.bus.subscribe(on_changed, RuntimeModelChanged)
|
||||
try:
|
||||
assert await loop.runtime_for_session(session) is refreshed
|
||||
await asyncio.wait_for(published.wait(), timeout=1)
|
||||
finally:
|
||||
unsubscribe()
|
||||
assert events[0].model == "updated-model"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_streamed_sdk_resolves_session_runtime_after_lock_admission(tmp_path) -> None:
|
||||
base = RecordingProvider("base-model")
|
||||
@@ -166,13 +192,13 @@ async def test_streamed_sdk_resolves_session_runtime_after_lock_admission(tmp_pa
|
||||
)
|
||||
loop.schedule_background = lambda coro: coro.close() # type: ignore[method-assign]
|
||||
session_key = "sdk:queued"
|
||||
loop.set_session_model_preset(session_key, "fast")
|
||||
(await loop.set_session_model_preset(session_key, "fast"))
|
||||
|
||||
lock = loop._session_locks.setdefault(session_key, asyncio.Lock())
|
||||
await lock.acquire()
|
||||
try:
|
||||
run = await Nanobot(loop).run_streamed("hello", session_key=session_key)
|
||||
loop.set_session_model_preset(session_key, "deep")
|
||||
(await loop.set_session_model_preset(session_key, "deep"))
|
||||
finally:
|
||||
lock.release()
|
||||
|
||||
@@ -210,7 +236,7 @@ async def test_sdk_custom_model_preset_metadata_does_not_select_runtime(
|
||||
metadata={"model_preset": custom_value},
|
||||
)
|
||||
ingested_result = await bot.run("hello", session_key="sdk:custom-metadata")
|
||||
exported = bot.sessions.export("sdk:custom-metadata")
|
||||
exported = (await bot.sessions.export("sdk:custom-metadata"))
|
||||
restored = await bot.sessions.restore(
|
||||
SessionSnapshot(
|
||||
key="sdk:restored-metadata",
|
||||
|
||||
@@ -16,7 +16,7 @@ from unittest.mock import AsyncMock, MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from agent.session_helpers import run_session
|
||||
from agent.session_helpers import mock_session_manager, run_session
|
||||
from nanobot.agent.loop import AgentLoop
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.session.recovery import RUNTIME_CHECKPOINT_KEY
|
||||
@@ -37,7 +37,7 @@ def _make_loop(tmp_path: Path) -> AgentLoop:
|
||||
bus = MessageBus()
|
||||
provider = _make_provider()
|
||||
with patch("nanobot.agent.loop.ContextBuilder"), \
|
||||
patch("nanobot.agent.loop.SessionManager"), \
|
||||
patch("nanobot.agent.loop.SessionManager", side_effect=mock_session_manager), \
|
||||
patch("nanobot.agent.loop.SubagentManager") as mock_subagent_manager:
|
||||
mock_subagent_manager.return_value.cancel_by_session = AsyncMock(return_value=0)
|
||||
return AgentLoop(bus=bus, provider=provider, workspace=tmp_path)
|
||||
@@ -60,7 +60,7 @@ async def test_dispatch_cancellation_restores_checkpoint():
|
||||
workspace.__truediv__ = MagicMock(return_value=MagicMock())
|
||||
|
||||
with patch("nanobot.agent.loop.ContextBuilder"), \
|
||||
patch("nanobot.agent.loop.SessionManager"), \
|
||||
patch("nanobot.agent.loop.SessionManager", side_effect=mock_session_manager), \
|
||||
patch("nanobot.agent.loop.SubagentManager") as mock_subagent_manager:
|
||||
mock_subagent_manager.return_value.cancel_by_session = AsyncMock(return_value=0)
|
||||
loop = AgentLoop(bus=bus, provider=provider, workspace=workspace)
|
||||
@@ -112,7 +112,7 @@ async def test_dispatch_cancellation_restores_checkpoint():
|
||||
)
|
||||
assert checkpoint_key not in session.metadata, \
|
||||
"Checkpoint metadata should be cleared after restore"
|
||||
assert loop.sessions.save.called, \
|
||||
assert loop.sessions.state.restore_interruption.await_count == 1, \
|
||||
"Session should be persisted so the restored state survives process restart"
|
||||
|
||||
|
||||
|
||||
@@ -28,7 +28,7 @@ from nanobot.bus.runtime_events import TurnRunStatusChanged
|
||||
from nanobot.config import Config
|
||||
from nanobot.nanobot import Nanobot
|
||||
from nanobot.providers.base import GenerationSettings, LLMProvider, LLMResponse, ToolCallRequest
|
||||
from nanobot.session.manager import SessionManager
|
||||
from nanobot.session.manager import SESSION_CACHE_MAX_SIZE, SessionManager
|
||||
from nanobot.session.webui_turns import WebuiTurnRoutePolicy
|
||||
from nanobot.utils.llm_runtime import LLMRuntime
|
||||
|
||||
@@ -101,7 +101,7 @@ async def test_sdk_ephemeral_delegation_never_persists_on_later_flush(
|
||||
if existing_parent:
|
||||
parent.add_message("user", "Earlier durable question")
|
||||
loop.sessions.save(parent)
|
||||
before = {path.name: path.read_bytes() for path in loop.sessions.sessions_dir.glob("*.jsonl")}
|
||||
before = loop.sessions.read_session_file(key)
|
||||
secret = "private-delegation-marker"
|
||||
source = loop.workspace / f"{secret}.txt"
|
||||
source.write_text(secret * 1000, encoding="utf-8")
|
||||
@@ -138,19 +138,18 @@ async def test_sdk_ephemeral_delegation_never_persists_on_later_flush(
|
||||
assert result.content == f"Parent conclusion: {secret}"
|
||||
assert all(ctx is not None and not ctx.log_content and not ctx.persist_session for ctx in requests)
|
||||
assert secret not in "\n".join(logs)
|
||||
assert {path.name: path.read_bytes() for path in loop.sessions.sessions_dir.glob("*.jsonl")} == before
|
||||
assert loop.sessions.read_session_file(key) == before
|
||||
assert not list(loop.sessions.sessions_dir.glob("*.checkpoint.json"))
|
||||
assert not (loop.workspace / ".nanobot" / "tool-results").exists()
|
||||
assert loop.bus.inbound_size == 0
|
||||
|
||||
loop.provider.chat_stream_with_retry = AsyncMock(return_value=LLMResponse(content="Durable answer"))
|
||||
await bot.run("Durable follow-up", session_key=key)
|
||||
bot.sessions.flush()
|
||||
saved = "\n".join(path.read_text() for path in loop.sessions.sessions_dir.glob("*.jsonl"))
|
||||
saved = json.dumps(loop.sessions.read_session_file(key))
|
||||
assert "Durable answer" in saved
|
||||
assert ("Earlier durable question" in saved) is existing_parent
|
||||
assert secret not in saved
|
||||
assert len(list(loop.sessions.sessions_dir.glob("*.jsonl"))) == 1
|
||||
assert [row["key"] for row in loop.sessions.list_sessions()] == [key]
|
||||
finally:
|
||||
loop.stop()
|
||||
await asyncio.wait_for(consumer, timeout=2)
|
||||
@@ -181,7 +180,10 @@ async def test_child_origin_uses_the_channel_turn_identity(loop_factory):
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_default_loop_keeps_slack_thread_for_late_subagent_result(tmp_path, monkeypatch):
|
||||
@pytest.mark.parametrize("cache_invalidation", ["handles", "eviction"])
|
||||
async def test_default_loop_keeps_slack_thread_for_late_subagent_result(
|
||||
tmp_path, monkeypatch, cache_invalidation,
|
||||
):
|
||||
monkeypatch.setattr("nanobot.agent.loop._SUBAGENT_TERMINAL_WAIT_SECONDS", 0.01)
|
||||
child_started, release_child, parent_idle = (asyncio.Event() for _ in range(3))
|
||||
|
||||
@@ -245,6 +247,11 @@ async def test_default_loop_keeps_slack_thread_for_late_subagent_result(tmp_path
|
||||
saved = SessionManager(workspace, sessions_root=sessions_root).get_existing(session_key)
|
||||
assert saved is not None
|
||||
saved_route = saved.metadata["_compaction_route"]
|
||||
if cache_invalidation == "handles":
|
||||
await sessions.state.ensure_session_handles()
|
||||
else:
|
||||
for i in range(SESSION_CACHE_MAX_SIZE + 1):
|
||||
await sessions.state.get_header(f"telegram:other-{i}")
|
||||
release_child.set()
|
||||
late_reply = await next_reply("Late follow-up")
|
||||
|
||||
@@ -265,7 +272,7 @@ async def test_owner_canonical_fallback_and_absent_context(tmp_path):
|
||||
manager, _, ctx = setup(tmp_path)
|
||||
manager.runner.run = AsyncMock(return_value=AgentRunResult(messages=[], final_content="private"))
|
||||
task_id = await spawn(manager, ctx)
|
||||
receipt = manager.send(task_id, "owner", "follow-up")
|
||||
receipt = await manager.send(task_id, "owner", "follow-up")
|
||||
snapshot = manager.statuses_for_session("owner")[task_id]
|
||||
snapshot.state = "cancelled"
|
||||
snapshot.owner = "other"
|
||||
|
||||
@@ -8,7 +8,7 @@ from unittest.mock import AsyncMock, MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from agent.session_helpers import run_session
|
||||
from agent.session_helpers import mock_session_manager, run_session
|
||||
from nanobot.agent.memory import Consolidator
|
||||
from nanobot.bus.outbound_events import StreamDeltaEvent, StreamEndEvent
|
||||
from nanobot.config.schema import AgentDefaults
|
||||
@@ -37,7 +37,7 @@ def _make_loop(*, tools_config=None):
|
||||
workspace.__truediv__ = MagicMock(return_value=MagicMock())
|
||||
|
||||
with patch("nanobot.agent.loop.ContextBuilder"), \
|
||||
patch("nanobot.agent.loop.SessionManager"), \
|
||||
patch("nanobot.agent.loop.SessionManager", side_effect=mock_session_manager), \
|
||||
patch("nanobot.agent.loop.SubagentManager") as mock_sub_mgr:
|
||||
mock_sub_mgr.return_value.cancel_by_session = AsyncMock(return_value=0)
|
||||
loop = AgentLoop(bus=bus, provider=provider, workspace=workspace, tools_config=tools_config)
|
||||
@@ -340,7 +340,7 @@ class TestDispatch:
|
||||
async def test_run_logs_and_continues_after_leaked_cancelled_error(self, monkeypatch):
|
||||
loop, bus = _make_loop()
|
||||
loop.aclose = AsyncMock()
|
||||
loop.auto_compact.check_expired = MagicMock()
|
||||
loop.auto_compact.check_expired = AsyncMock()
|
||||
warnings: list[str] = []
|
||||
calls = 0
|
||||
|
||||
|
||||
@@ -325,13 +325,14 @@ def test_websocket_lifecycle_reuses_registered_ingress_owner(tmp_path: Path) ->
|
||||
wth.clear_websocket_turn_if_current("chat-queued", owner)
|
||||
|
||||
|
||||
def test_internal_user_input_uses_the_persisted_webui_route(tmp_path: Path) -> None:
|
||||
async def test_internal_user_input_uses_the_persisted_webui_route(tmp_path: Path) -> None:
|
||||
from nanobot.session import webui_turns as wth
|
||||
|
||||
sessions = SessionManager(tmp_path / "sessions")
|
||||
target = sessions.get_or_create("websocket:target")
|
||||
target.metadata["webui"] = True
|
||||
sessions.save(target)
|
||||
await sessions.state.read(target.key)
|
||||
factory = TurnDeliveryFactory(
|
||||
MessageBus(),
|
||||
route_policy=WebuiTurnRoutePolicy(sessions),
|
||||
@@ -418,7 +419,7 @@ async def test_same_chat_different_sessions_restore_previous_active_projection(
|
||||
wth._WEBSOCKET_TURN_OWNERS.pop("shared-chat", None)
|
||||
|
||||
|
||||
def test_late_subagent_route_requires_webui_owned_session(tmp_path: Path) -> None:
|
||||
async def test_late_subagent_route_requires_webui_owned_session(tmp_path: Path) -> None:
|
||||
sessions = SessionManager(tmp_path)
|
||||
factory = TurnDeliveryFactory(
|
||||
MessageBus(),
|
||||
@@ -446,6 +447,8 @@ def test_late_subagent_route_requires_webui_owned_session(tmp_path: Path) -> Non
|
||||
|
||||
session = sessions.get_or_create(session_key)
|
||||
session.metadata["webui"] = True
|
||||
sessions.save(session)
|
||||
await sessions.state.read(session_key)
|
||||
first_visible_route = factory.create(msg, session_key).route
|
||||
second_visible_route = factory.create(msg, session_key).route
|
||||
|
||||
|
||||
@@ -19,7 +19,7 @@ from unittest.mock import AsyncMock, MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from agent.session_helpers import run_session
|
||||
from agent.session_helpers import mock_session_manager, run_session
|
||||
from nanobot.agent.loop import AgentLoop
|
||||
from nanobot.agent.tools.file_state import FileStateStore
|
||||
from nanobot.bus.events import InboundMessage
|
||||
@@ -42,7 +42,7 @@ def _make_loop(tmp_path: Path, unified_session: bool = False) -> AgentLoop:
|
||||
provider = MagicMock()
|
||||
provider.get_default_model.return_value = "test-model"
|
||||
|
||||
with patch("nanobot.agent.loop.SessionManager"), \
|
||||
with patch("nanobot.agent.loop.SessionManager", side_effect=mock_session_manager), \
|
||||
patch("nanobot.agent.loop.SubagentManager") as mock_sub_mgr:
|
||||
mock_sub_mgr.return_value.cancel_by_session = AsyncMock(return_value=0)
|
||||
loop = AgentLoop(
|
||||
@@ -317,7 +317,7 @@ class TestCmdNewUnifiedSession:
|
||||
consolidator=SimpleNamespace(archive_session=AsyncMock(return_value=True)),
|
||||
_cancel_active_tasks=AsyncMock(return_value=0),
|
||||
discard_session_file_state=MagicMock(),
|
||||
runtime_for_session=MagicMock(return_value=MagicMock()),
|
||||
runtime_for_session=AsyncMock(return_value=MagicMock()),
|
||||
schedule_background=lambda coro: asyncio.ensure_future(coro),
|
||||
)
|
||||
|
||||
@@ -351,7 +351,7 @@ class TestStopCommandWithUnifiedSession:
|
||||
msg = _make_msg(channel="telegram", chat_id="123456")
|
||||
|
||||
loop._process_message = AsyncMock(return_value=None)
|
||||
loop._enqueue_session_message(msg)
|
||||
(await loop._enqueue_session_message(msg))
|
||||
assert set(loop._active_tasks) == {UNIFIED_SESSION_KEY}
|
||||
await asyncio.gather(*loop._active_tasks[UNIFIED_SESSION_KEY])
|
||||
|
||||
|
||||
@@ -71,7 +71,8 @@ async def _execute(tool, ctx: RequestContext, *, allowed: bool = True, **kwargs)
|
||||
async def test_create_goal_records_goal_metadata(tmp_path):
|
||||
sm = SessionManager(tmp_path)
|
||||
create, _update, ctx = _tools(sm)
|
||||
sm.get_or_create("websocket:c1").metadata["_sustained_goal_continuation_rounds"] = 12
|
||||
await sm.state.get("websocket:c1")
|
||||
await sm.state.update_metadata("websocket:c1", {"_sustained_goal_continuation_rounds": 12})
|
||||
|
||||
out = await _execute(
|
||||
create,
|
||||
@@ -87,6 +88,7 @@ async def test_create_goal_records_goal_metadata(tmp_path):
|
||||
assert blob["status"] == "active"
|
||||
assert blob["objective"] == "Do the thing"
|
||||
assert blob["ui_summary"] == "thing"
|
||||
sess = sm.get_or_create("websocket:c1")
|
||||
assert "_sustained_goal_continuation_rounds" not in sess.metadata
|
||||
assert "_sustained_goal_continuation_rounds" not in (
|
||||
SessionManager(tmp_path).get_or_create("websocket:c1").metadata
|
||||
@@ -97,6 +99,36 @@ async def test_create_goal_records_goal_metadata(tmp_path):
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_goal_context_and_mutations_only_read_session_metadata(tmp_path, monkeypatch):
|
||||
sm = SessionManager(tmp_path)
|
||||
stored = sm.get_or_create("websocket:c1")
|
||||
stored.add_message("user", "Keep the previous conversation.")
|
||||
stored.add_message("assistant", "Previous answer.")
|
||||
sm.save(stored)
|
||||
create, update, ctx = _tools(sm)
|
||||
|
||||
def history_unavailable(*_args, **_kwargs):
|
||||
pytest.fail("goal metadata operations must not request conversation history")
|
||||
|
||||
monkeypatch.setattr(sm.state, "get", history_unavailable)
|
||||
monkeypatch.setattr(sm.state, "read", history_unavailable)
|
||||
ordinary = _request_context(metadata={}, original_user_text="Continue.")
|
||||
try:
|
||||
assert await create.runtime_context_provider()(ordinary) is None
|
||||
assert "Goal recorded" in await _execute(create, ctx, objective="Preserve history")
|
||||
context = await create.runtime_context_provider()(ordinary)
|
||||
assert context is not None and "Preserve history" in context.content
|
||||
assert "marked complete" in await _execute(update, ordinary, action="complete")
|
||||
assert await create.runtime_context_provider()(ordinary) is None
|
||||
|
||||
reopened = SessionManager(tmp_path).get_or_create(stored.key)
|
||||
assert reopened.messages == stored.messages
|
||||
assert reopened.metadata[GOAL_STATE_KEY]["status"] == "completed"
|
||||
finally:
|
||||
await sm.state.aclose()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_create_goal_rejects_without_explicit_goal_permission(tmp_path):
|
||||
sm = SessionManager(tmp_path)
|
||||
@@ -144,9 +176,10 @@ async def test_update_goal_replace_keeps_goal_active_with_new_objective(tmp_path
|
||||
create, update, ctx = _tools(sm)
|
||||
|
||||
await _execute(create, ctx, objective="Old")
|
||||
sess = sm.get_or_create("websocket:c1")
|
||||
sess.metadata["_sustained_goal_continuation_rounds"] = 12
|
||||
sm.save(sess)
|
||||
await sm.state.update_metadata(
|
||||
"websocket:c1",
|
||||
{"_sustained_goal_continuation_rounds": 12},
|
||||
)
|
||||
out = await _execute(
|
||||
update,
|
||||
_request_context(),
|
||||
@@ -161,6 +194,7 @@ async def test_update_goal_replace_keeps_goal_active_with_new_objective(tmp_path
|
||||
assert blob["objective"] == "New"
|
||||
assert blob["previous_objective"] == "Old"
|
||||
assert blob["ui_summary"] == "new"
|
||||
sess = sm.get_or_create("websocket:c1")
|
||||
assert "_sustained_goal_continuation_rounds" not in sess.metadata
|
||||
assert "_sustained_goal_continuation_rounds" not in (
|
||||
SessionManager(tmp_path).get_or_create("websocket:c1").metadata
|
||||
@@ -178,13 +212,14 @@ async def test_goal_state_mutations_roll_back_on_save_failure(tmp_path, monkeypa
|
||||
sess = sm.get_or_create("websocket:c1")
|
||||
sess.metadata["marker"] = {"keep": True}
|
||||
sess.metadata["_sustained_goal_continuation_rounds"] = 12
|
||||
original_save = sm.save
|
||||
sm.save(sess)
|
||||
original_save = sm._store.replace_metadata
|
||||
create_context = _request_context()
|
||||
|
||||
def fail_save(_session, **_kwargs):
|
||||
def fail_save(*_args, **_kwargs):
|
||||
raise OSError("disk unavailable")
|
||||
|
||||
monkeypatch.setattr(sm, "save", fail_save)
|
||||
monkeypatch.setattr(sm._store, "replace_metadata", fail_save)
|
||||
with pytest.raises(OSError, match="disk unavailable"):
|
||||
await _execute(create, create_context, objective="Old")
|
||||
|
||||
@@ -194,13 +229,16 @@ async def test_goal_state_mutations_roll_back_on_save_failure(tmp_path, monkeypa
|
||||
}
|
||||
assert GOAL_STATE_KEY not in SessionManager(tmp_path).get_or_create("websocket:c1").metadata
|
||||
|
||||
monkeypatch.setattr(sm, "save", original_save)
|
||||
monkeypatch.setattr(sm._store, "replace_metadata", original_save)
|
||||
assert "Goal recorded" in await _execute(create, create_context, objective="Old")
|
||||
sess.metadata["_sustained_goal_continuation_rounds"] = 12
|
||||
sm.save(sess)
|
||||
await sm.state.update_metadata(
|
||||
"websocket:c1",
|
||||
{"_sustained_goal_continuation_rounds": 12},
|
||||
)
|
||||
sess = sm.get_or_create("websocket:c1")
|
||||
replace_context = _request_context()
|
||||
|
||||
monkeypatch.setattr(sm, "save", fail_save)
|
||||
monkeypatch.setattr(sm._store, "replace_metadata", fail_save)
|
||||
with pytest.raises(OSError, match="disk unavailable"):
|
||||
await _execute(update, replace_context, action="replace", objective="New")
|
||||
|
||||
@@ -210,13 +248,14 @@ async def test_goal_state_mutations_roll_back_on_save_failure(tmp_path, monkeypa
|
||||
assert persisted[GOAL_STATE_KEY]["objective"] == "Old"
|
||||
assert persisted["_sustained_goal_continuation_rounds"] == 12
|
||||
|
||||
monkeypatch.setattr(sm, "save", original_save)
|
||||
monkeypatch.setattr(sm._store, "replace_metadata", original_save)
|
||||
assert "Goal replaced" in await _execute(
|
||||
update,
|
||||
replace_context,
|
||||
action="replace",
|
||||
objective="New",
|
||||
)
|
||||
sess = sm.get_or_create("websocket:c1")
|
||||
assert "_sustained_goal_continuation_rounds" not in sess.metadata
|
||||
assert (
|
||||
SessionManager(tmp_path).get_or_create("websocket:c1").metadata[GOAL_STATE_KEY]["objective"]
|
||||
@@ -372,7 +411,7 @@ async def test_registry_does_not_reuse_goal_context_after_request_scope(tmp_path
|
||||
leaked_out = await registry.execute("create_goal", {"objective": "Leaked"})
|
||||
|
||||
assert "missing routing context" in str(leaked_out)
|
||||
assert sess.metadata[GOAL_STATE_KEY]["status"] == "completed"
|
||||
assert sm.get_or_create(sess.key).metadata[GOAL_STATE_KEY]["status"] == "completed"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
|
||||
@@ -383,10 +383,10 @@ async def test_workspace_inspection_reaches_model_from_selected_chat(tmp_path: P
|
||||
]),
|
||||
LLMResponse(content="done", tool_calls=[]),
|
||||
])
|
||||
session = loop.sessions.get_or_create("websocket:inspection")
|
||||
session.metadata["workspace_scope"] = {
|
||||
session = await loop.sessions.state.get("websocket:inspection")
|
||||
await loop.sessions.state.update_metadata(session.key, {"workspace_scope": {
|
||||
"project_path": str(project), "access_mode": "restricted",
|
||||
}
|
||||
}})
|
||||
|
||||
response = await loop.process_direct(
|
||||
"Check the current directory and read marker.txt",
|
||||
@@ -475,9 +475,11 @@ async def test_access_changes_refresh_only_new_message_and_preserve_prefix(tmp_p
|
||||
provider = loop.provider
|
||||
provider.generation = GenerationSettings()
|
||||
provider.chat_stream_with_retry = AsyncMock(return_value=LLMResponse(content="done"))
|
||||
session = loop.sessions.get_or_create("websocket:scope-changes")
|
||||
session = await loop.sessions.state.get("websocket:scope-changes")
|
||||
for root, mode in [(project, "restricted"), (project, "full"), (other, "restricted")]:
|
||||
session.metadata["workspace_scope"] = {"project_path": str(root), "access_mode": mode}
|
||||
await loop.sessions.state.update_metadata(session.key, {"workspace_scope": {
|
||||
"project_path": str(root), "access_mode": mode,
|
||||
}})
|
||||
await loop.process_direct(
|
||||
"Check access", channel="websocket", chat_id="scope-changes", session_key=session.key,
|
||||
)
|
||||
@@ -497,9 +499,10 @@ async def test_access_changes_refresh_only_new_message_and_preserve_prefix(tmp_p
|
||||
assert {key: value for key, value in before.items() if key != "messages"} == {
|
||||
key: value for key, value in after.items() if key != "messages"
|
||||
}
|
||||
assert all(message["content"] == "Check access" for message in session.get_history(
|
||||
session = await loop.sessions.state.get(session.key)
|
||||
assert [message["content"] for message in session.get_history(
|
||||
include_runtime_context=False,
|
||||
) if message["role"] == "user")
|
||||
) if message["role"] == "user"] == ["Check access"] * 3
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -515,12 +518,14 @@ async def test_injected_channel_input_reports_active_tool_scope(tmp_path: Path)
|
||||
]),
|
||||
LLMResponse(content="done"),
|
||||
])
|
||||
session = loop.sessions.get_or_create(UNIFIED_SESSION_KEY)
|
||||
session = await loop.sessions.state.get(UNIFIED_SESSION_KEY)
|
||||
session.metadata["workspace_scope"] = {"project_path": str(project), "access_mode": "restricted"}
|
||||
session.add_message("user", "Start")
|
||||
await loop.sessions.state.prepare_input(session)
|
||||
pending = asyncio.Queue()
|
||||
await pending.put(InboundMessage("telegram", "user", "chat", "Read marker.txt"))
|
||||
await loop._run_agent_loop(
|
||||
TranscriptInput(history=[{"role": "user", "content": "Start"}], current_message=None),
|
||||
TranscriptInput(history=session.get_history(), current_message=None),
|
||||
runtime=loop.llm_runtime(), session=session, pending_queue=pending,
|
||||
request_context=RequestContext("websocket", "chat", session_key=session.key),
|
||||
)
|
||||
@@ -648,6 +653,8 @@ async def test_subagent_check_is_session_scoped(tmp_path, single_task, runtime):
|
||||
loop = _make_loop(tmp_path)
|
||||
manager = loop.subagents
|
||||
# Queued tasks must be scoped before their runner starts.
|
||||
for _ in range(manager.max_concurrent_subagents):
|
||||
await manager._run_slots.acquire()
|
||||
await manager.spawn("ALPHA_PRIVATE_TASK", label="ALPHA_LABEL", session_key="owner:a", runtime=runtime)
|
||||
await manager.spawn("BETA_PRIVATE_TASK", label="BETA_LABEL", session_key="owner:b", runtime=runtime)
|
||||
try:
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"""Tests for subagent tool registration and wiring."""
|
||||
|
||||
import asyncio
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
|
||||
import pytest
|
||||
@@ -767,12 +768,13 @@ async def test_terminal_drain_reuses_one_timeout_budget(tmp_path):
|
||||
content="result",
|
||||
)
|
||||
|
||||
loop.tools.get_runtime_context_providers = MagicMock(return_value=[])
|
||||
fake_loop = MagicMock(wraps=asyncio.get_running_loop())
|
||||
fake_loop.time = clock
|
||||
with (
|
||||
patch("nanobot.agent.loop.asyncio.get_running_loop", return_value=fake_loop),
|
||||
patch("nanobot.agent.loop.asyncio.wait_for", side_effect=_deliver),
|
||||
):
|
||||
loop_asyncio = SimpleNamespace(**vars(asyncio))
|
||||
loop_asyncio.get_running_loop = lambda: fake_loop
|
||||
loop_asyncio.wait_for = _deliver
|
||||
with patch("nanobot.agent.loop.asyncio", loop_asyncio):
|
||||
assert await terminal_injection_callback()
|
||||
assert await terminal_injection_callback()
|
||||
|
||||
|
||||
Reference in new issue
Block a user