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()
|
||||
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
"""Message tools preserve target identity through gateway delivery recording."""
|
||||
|
||||
from functools import partial
|
||||
|
||||
import pytest
|
||||
|
||||
from nanobot.agent.tools.context import RequestContext, request_context
|
||||
from nanobot.agent.tools.message import MessageTool
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.cli.gateway_runtime import _deliver_to_channel
|
||||
from nanobot.session.manager import SessionManager
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
async def delivery(tmp_path):
|
||||
workspace = tmp_path / "workspace"
|
||||
workspace.mkdir()
|
||||
(workspace / "attachment.txt").write_text("attachment", encoding="utf-8")
|
||||
sessions = SessionManager(workspace, sessions_root=tmp_path / "sessions")
|
||||
bus = MessageBus()
|
||||
tool = MessageTool(
|
||||
send_callback=partial(_deliver_to_channel, bus=bus, session_manager=sessions),
|
||||
workspace=workspace,
|
||||
)
|
||||
try:
|
||||
yield sessions, bus, tool
|
||||
finally:
|
||||
await sessions.state.aclose()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("channel,chat_id,key,metadata", [
|
||||
("slack", "C123", "slack:C123:111.222", {"slack": {"thread_ts": "111.222"}}),
|
||||
("telegram", "-100123", "telegram:-100123:topic:42", {"message_thread_id": 42}),
|
||||
])
|
||||
async def test_thread_media_is_recorded_in_its_admitted_session(delivery, channel, chat_id, key, metadata):
|
||||
sessions, bus, tool = delivery
|
||||
session = await sessions.state.get(key)
|
||||
coarse_key = f"{channel}:{chat_id}"
|
||||
await sessions.state.get(coarse_key)
|
||||
with request_context(RequestContext(
|
||||
channel, chat_id, session_key=key, session_generation=session.generation, metadata=metadata,
|
||||
)):
|
||||
result = await tool.execute(content="caption", media=["attachment.txt"])
|
||||
|
||||
assert result == f"Message sent to {channel}:{chat_id} with 1 attachments"
|
||||
sent = bus.outbound.get_nowait()
|
||||
assert sent.metadata == metadata
|
||||
assert len(sent.media) == 1
|
||||
assert [message["content"] for message in (await sessions.state.read(key)).messages] == ["caption"]
|
||||
assert (await sessions.state.read(coarse_key)).messages == []
|
||||
|
||||
|
||||
async def test_first_cross_target_media_creates_its_own_session(delivery):
|
||||
sessions, bus, tool = delivery
|
||||
origin = await sessions.state.get("websocket:origin")
|
||||
with request_context(RequestContext(
|
||||
"websocket", "origin", session_key=origin.key, session_generation=origin.generation,
|
||||
)):
|
||||
result = await tool.execute(
|
||||
content="caption", channel="email", chat_id="fresh@example.invalid",
|
||||
media=["attachment.txt"],
|
||||
)
|
||||
|
||||
assert result == "Message sent to email:fresh@example.invalid with 1 attachments"
|
||||
sent = bus.outbound.get_nowait()
|
||||
assert sent.metadata == {}
|
||||
target = await sessions.state.read("email:fresh@example.invalid")
|
||||
assert [message["content"] for message in target.messages] == ["caption"]
|
||||
assert (await sessions.state.read(origin.key)).messages == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize("operation", ["reset", "delete"])
|
||||
async def test_old_turn_media_cannot_recreate_or_write_a_replaced_target(delivery, operation):
|
||||
sessions, bus, tool = delivery
|
||||
session = await sessions.state.get("slack:C123:111.222")
|
||||
await getattr(sessions.state, operation)(session.key)
|
||||
with request_context(RequestContext(
|
||||
"slack", "C123", session_key=session.key, session_generation=session.generation,
|
||||
)):
|
||||
result = await tool.execute(content="late caption", media=["attachment.txt"])
|
||||
|
||||
assert result.startswith("Error sending message:")
|
||||
assert bus.outbound.empty()
|
||||
target = await sessions.state.read(session.key)
|
||||
assert target is None or target.messages == []
|
||||
assert await sessions.state.read("slack:C123") is None
|
||||
|
||||
|
||||
async def test_cross_target_reset_after_admission_revokes_media(delivery, monkeypatch):
|
||||
sessions, bus, tool = delivery
|
||||
original = sessions.state.record_delivery
|
||||
|
||||
async def reset_before_recording(key, *args, **kwargs):
|
||||
await sessions.state.reset(key)
|
||||
await original(key, *args, **kwargs)
|
||||
|
||||
monkeypatch.setattr(sessions.state, "record_delivery", reset_before_recording)
|
||||
result = await tool.execute(
|
||||
content="late caption", channel="email", chat_id="fresh@example.invalid",
|
||||
media=["attachment.txt"],
|
||||
)
|
||||
assert "replaced session" in result
|
||||
assert bus.outbound.empty()
|
||||
assert (await sessions.state.read("email:fresh@example.invalid")).messages == []
|
||||
+17
-15
@@ -124,8 +124,16 @@ class _EmptyGatewaySessionManager:
|
||||
def list_sessions(self) -> list[dict[str, object]]:
|
||||
return []
|
||||
|
||||
def flush_all(self) -> int:
|
||||
return 0
|
||||
def list_session_metadata(self) -> list[dict[str, object]]:
|
||||
return []
|
||||
|
||||
@property
|
||||
def state(self):
|
||||
return SimpleNamespace(
|
||||
list_sessions=AsyncMock(return_value=[]),
|
||||
record_delivery=AsyncMock(),
|
||||
aclose=AsyncMock(),
|
||||
)
|
||||
|
||||
|
||||
def test_gateway_signal_handler_first_signal_stops_and_second_forces() -> None:
|
||||
@@ -2157,7 +2165,7 @@ def test_heartbeat_empty_response_is_not_evaluated(
|
||||
bus.publish_outbound = AsyncMock()
|
||||
seen: dict[str, object] = {}
|
||||
|
||||
class _FakeSessionManager:
|
||||
class _FakeSessionManager(_EmptyGatewaySessionManager):
|
||||
def __init__(self, _workspace: Path) -> None:
|
||||
pass
|
||||
|
||||
@@ -3197,7 +3205,7 @@ def test_gateway_unbound_agent_cron_is_skipped(
|
||||
def add_message(self, role: str, content: str, **kwargs) -> None:
|
||||
self.messages.append({"role": role, "content": content, **kwargs})
|
||||
|
||||
class _FakeSessionManager:
|
||||
class _FakeSessionManager(_EmptyGatewaySessionManager):
|
||||
def __init__(self, _workspace: Path) -> None:
|
||||
self.session = _FakeSession()
|
||||
seen["session_manager"] = self
|
||||
@@ -3318,7 +3326,7 @@ def test_gateway_bound_cron_runs_as_session_turn(
|
||||
)
|
||||
monkeypatch.setattr("nanobot.bus.queue.MessageBus", lambda: bus)
|
||||
|
||||
class _FakeSessionManager:
|
||||
class _FakeSessionManager(_EmptyGatewaySessionManager):
|
||||
def __init__(self, _workspace: Path) -> None:
|
||||
pass
|
||||
|
||||
@@ -3533,7 +3541,7 @@ def test_gateway_local_trigger_queue_submits_agent_turns(
|
||||
class _FakeContext:
|
||||
memory = _FakeMemory()
|
||||
|
||||
class _FakeSessionManager:
|
||||
class _FakeSessionManager(_EmptyGatewaySessionManager):
|
||||
def flush_all(self) -> int:
|
||||
return 0
|
||||
|
||||
@@ -3833,7 +3841,7 @@ def test_gateway_health_endpoint_binds_and_serves_expected_responses(
|
||||
config.gateway.port = 18791
|
||||
captured: dict[str, object] = {}
|
||||
|
||||
class _FakeSessionManager:
|
||||
class _FakeSessionManager(_EmptyGatewaySessionManager):
|
||||
def flush_all(self) -> int:
|
||||
return 0
|
||||
|
||||
@@ -4036,7 +4044,7 @@ def test_gateway_agent_task_owns_initial_mcp_provider_close(
|
||||
config.gateway.port = 18791
|
||||
seen: dict[str, object] = {}
|
||||
|
||||
class _FakeSessionManager:
|
||||
class _FakeSessionManager(_EmptyGatewaySessionManager):
|
||||
def flush_all(self) -> int:
|
||||
return 0
|
||||
|
||||
@@ -4190,11 +4198,6 @@ def test_gateway_shutdown_event_exits_forever_runtime_tasks(
|
||||
channel_finished = asyncio.Event()
|
||||
channels_stopping = asyncio.Event()
|
||||
|
||||
class _FakeSessionManager:
|
||||
def flush_all(self) -> int:
|
||||
seen["sessions_flushed"] = True
|
||||
return 0
|
||||
|
||||
class _FakeAgentLoop(_GatewayAgentContractStub):
|
||||
@classmethod
|
||||
def from_config(cls, config, bus=None, **extra):
|
||||
@@ -4203,7 +4206,7 @@ def test_gateway_shutdown_event_exits_forever_runtime_tasks(
|
||||
def __init__(self, **_kwargs) -> None:
|
||||
self.model = "test-model"
|
||||
self.provider = object()
|
||||
self.sessions = _FakeSessionManager()
|
||||
self.sessions = _EmptyGatewaySessionManager()
|
||||
self.runtime_resolver = MagicMock()
|
||||
|
||||
def llm_runtime(self) -> None:
|
||||
@@ -4326,7 +4329,6 @@ def test_gateway_shutdown_event_exits_forever_runtime_tasks(
|
||||
assert seen["channel_task_cleaned_up"] is True
|
||||
assert seen["channels_stopped"] is True
|
||||
assert seen["cron_stopped"] is True
|
||||
assert seen["sessions_flushed"] is True
|
||||
assert seen["shutdown_handlers_restored"] is True
|
||||
if shutdown_signal is not None:
|
||||
assert seen["graceful_shutdown_requested"] is True
|
||||
|
||||
@@ -14,6 +14,8 @@ import pytest
|
||||
from nanobot.agent.context import TranscriptInput
|
||||
from nanobot.bus.events import InboundMessage
|
||||
from nanobot.providers.base import LLMResponse, LLMUsage
|
||||
from nanobot.session.manager import Session
|
||||
from nanobot.session.state import SessionState
|
||||
|
||||
|
||||
def _make_loop():
|
||||
@@ -28,8 +30,11 @@ def _make_loop():
|
||||
workspace.__truediv__ = MagicMock(return_value=MagicMock())
|
||||
|
||||
with patch("nanobot.agent.loop.ContextBuilder"), \
|
||||
patch("nanobot.agent.loop.SessionManager"), \
|
||||
patch("nanobot.agent.loop.SessionManager") as mock_sessions, \
|
||||
patch("nanobot.agent.loop.SubagentManager") as mock_sub_mgr:
|
||||
mock_sessions.return_value.state = MagicMock(spec=SessionState)
|
||||
mock_sessions.return_value.state.get = AsyncMock(side_effect=lambda key: Session(key))
|
||||
mock_sessions.return_value.state.peek.return_value = None
|
||||
mock_sub_mgr.return_value.close = AsyncMock()
|
||||
loop = AgentLoop(bus=bus, provider=provider, workspace=workspace)
|
||||
return loop, bus
|
||||
@@ -240,7 +245,7 @@ class TestRestartCommand:
|
||||
session.metadata = {
|
||||
"_last_usage": LLMUsage.reported(input_tokens=0, output_tokens=0).to_dict()
|
||||
}
|
||||
loop.sessions.get_or_create.return_value = session
|
||||
loop.sessions.state.get = AsyncMock(return_value=session)
|
||||
loop._start_time = time.time() - 125
|
||||
loop.consolidator.estimate_session_prompt_tokens = MagicMock(
|
||||
return_value=(20500, "tiktoken")
|
||||
@@ -277,7 +282,7 @@ class TestRestartCommand:
|
||||
loop, _bus = _make_loop()
|
||||
session = MagicMock()
|
||||
session.get_history.return_value = [{"role": "user"}]
|
||||
loop.sessions.get_or_create.return_value = session
|
||||
loop.sessions.state.get = AsyncMock(return_value=session)
|
||||
loop.consolidator.estimate_session_prompt_tokens = MagicMock(
|
||||
return_value=(1000, "tiktoken")
|
||||
)
|
||||
@@ -332,7 +337,7 @@ class TestRestartCommand:
|
||||
session.metadata = {
|
||||
"_last_usage": LLMUsage.reported(input_tokens=1200, output_tokens=34).to_dict()
|
||||
}
|
||||
loop.sessions.get_or_create.return_value = session
|
||||
loop.sessions.state.get = AsyncMock(return_value=session)
|
||||
loop.consolidator.estimate_session_prompt_tokens = MagicMock(
|
||||
return_value=(0, "none")
|
||||
)
|
||||
@@ -358,7 +363,7 @@ class TestRestartCommand:
|
||||
{"role": "user", "content": "How are you?"},
|
||||
{"role": "assistant", "content": "I am doing well."},
|
||||
]
|
||||
loop.sessions.get_or_create.return_value = session
|
||||
loop.sessions.state.get = AsyncMock(return_value=session)
|
||||
|
||||
msg = InboundMessage(channel="telegram", sender_id="u1", chat_id="c1", content="/history")
|
||||
response = await loop._process_message(msg)
|
||||
@@ -376,7 +381,7 @@ class TestRestartCommand:
|
||||
session.get_history.return_value = [
|
||||
{"role": "user", "content": f"message {i}"} for i in range(20)
|
||||
]
|
||||
loop.sessions.get_or_create.return_value = session
|
||||
loop.sessions.state.get = AsyncMock(return_value=session)
|
||||
|
||||
msg = InboundMessage(channel="telegram", sender_id="u1", chat_id="c1", content="/history 3")
|
||||
response = await loop._process_message(msg)
|
||||
@@ -400,7 +405,7 @@ class TestRestartCommand:
|
||||
},
|
||||
*({"role": "assistant", "content": f"reply {i}"} for i in range(60)),
|
||||
]
|
||||
loop.sessions.get_or_create.return_value = session
|
||||
loop.sessions.state.get = AsyncMock(return_value=session)
|
||||
|
||||
msg = InboundMessage(channel="telegram", sender_id="u1", chat_id="c1", content="/history 999")
|
||||
response = await loop._process_message(msg)
|
||||
@@ -426,7 +431,7 @@ class TestRestartCommand:
|
||||
loop, _bus = _make_loop()
|
||||
session = MagicMock()
|
||||
session.get_history.return_value = []
|
||||
loop.sessions.get_or_create.return_value = session
|
||||
loop.sessions.state.get = AsyncMock(return_value=session)
|
||||
|
||||
msg = InboundMessage(channel="telegram", sender_id="u1", chat_id="c1", content="/history")
|
||||
response = await loop._process_message(msg)
|
||||
@@ -439,7 +444,7 @@ class TestRestartCommand:
|
||||
loop, _bus = _make_loop()
|
||||
session = MagicMock()
|
||||
session.get_history.return_value = []
|
||||
loop.sessions.get_or_create.return_value = session
|
||||
loop.sessions.state.get = AsyncMock(return_value=session)
|
||||
loop.subagents.get_running_count.return_value = 0
|
||||
loop.subagents.get_running_count_by_session.return_value = 0
|
||||
|
||||
|
||||
@@ -1,31 +0,0 @@
|
||||
from pathlib import Path
|
||||
|
||||
from typer.testing import CliRunner
|
||||
|
||||
from nanobot.cli import commands
|
||||
from nanobot.config.loader import load_config
|
||||
from nanobot.session.manager import SessionManager
|
||||
|
||||
|
||||
def test_sessions_restore_workspace_command_prepares_downgrade(
|
||||
tmp_path: Path,
|
||||
monkeypatch,
|
||||
) -> None:
|
||||
workspace = tmp_path / "workspace"
|
||||
config_path = tmp_path / "instance" / "config.json"
|
||||
config = load_config(config_path)
|
||||
config.agents.defaults.workspace = str(workspace)
|
||||
manager = SessionManager(workspace, sessions_root=config_path.parent / "sessions")
|
||||
session = manager.get_or_create("cli:rollback")
|
||||
session.add_message("user", "restore-me")
|
||||
manager.save(session, fsync=True)
|
||||
monkeypatch.setattr(commands, "_load_runtime_config", lambda *_args: config)
|
||||
|
||||
result = CliRunner().invoke(commands.app, ["sessions", "restore-workspace"])
|
||||
|
||||
assert result.exit_code == 0, result.output
|
||||
assert "Restored 1 session file(s)" in result.output
|
||||
restored = workspace / "sessions" / manager._get_session_path(session.key).name
|
||||
assert restored.exists()
|
||||
assert "restore-me" in restored.read_text(encoding="utf-8")
|
||||
assert manager._get_session_path(session.key).exists()
|
||||
@@ -141,12 +141,21 @@ def _make_dream_prompt_ctx(tmp_path, raw: str = "/dream-prompt", args: str = "")
|
||||
return CommandContext(msg=msg, session=None, key=msg.session_key, raw=raw, args=args, loop=loop)
|
||||
|
||||
|
||||
async def _run_dream_command(ctx: CommandContext) -> OutboundMessage:
|
||||
before = asyncio.all_tasks()
|
||||
immediate = await cmd_dream(ctx)
|
||||
try:
|
||||
await asyncio.gather(*(asyncio.all_tasks() - before))
|
||||
finally:
|
||||
await ctx.loop.sessions.state.aclose()
|
||||
return immediate
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_dream_no_history_explains_how_to_create_input(tmp_path) -> None:
|
||||
ctx, bus = _make_dream_ctx(tmp_path)
|
||||
|
||||
immediate = await cmd_dream(ctx)
|
||||
await asyncio.sleep(0)
|
||||
immediate = await _run_dream_command(ctx)
|
||||
|
||||
assert immediate.content == "Dreaming..."
|
||||
assert len(bus.outbound) == 1
|
||||
@@ -185,8 +194,7 @@ async def test_dream_internal_run_silences_progress(tmp_path) -> None:
|
||||
)
|
||||
ctx = CommandContext(msg=msg, session=None, key=msg.session_key, raw="/dream", args="", loop=loop)
|
||||
|
||||
await cmd_dream(ctx)
|
||||
await asyncio.sleep(0)
|
||||
await _run_dream_command(ctx)
|
||||
|
||||
assert len(calls) == 1
|
||||
assert callable(calls[0][1]["on_progress"])
|
||||
@@ -243,8 +251,7 @@ def _build_runnable_dream(
|
||||
async def test_dream_advances_cursor_when_diff_nonempty(tmp_path) -> None:
|
||||
"""A completed run with a real file delta advances the cursor."""
|
||||
ctx, store = _build_runnable_dream(tmp_path, initialized=True, content_diff="SOUL.md: +1 -0")
|
||||
await cmd_dream(ctx)
|
||||
await asyncio.sleep(0)
|
||||
await _run_dream_command(ctx)
|
||||
assert store._last_dream_cursor == 42
|
||||
|
||||
|
||||
@@ -252,8 +259,7 @@ async def test_dream_advances_cursor_when_diff_nonempty(tmp_path) -> None:
|
||||
async def test_dream_advances_cursor_on_completed_noop(tmp_path) -> None:
|
||||
"""A completed no-op has processed the batch and must not repeat it."""
|
||||
ctx, store = _build_runnable_dream(tmp_path, initialized=True, content_diff="")
|
||||
await cmd_dream(ctx)
|
||||
await asyncio.sleep(0)
|
||||
await _run_dream_command(ctx)
|
||||
assert store._last_dream_cursor == 42
|
||||
assert "no memory changes" in ctx.loop.bus.outbound[0].content
|
||||
|
||||
@@ -267,8 +273,7 @@ async def test_dream_keeps_cursor_when_incomplete_with_diff(tmp_path) -> None:
|
||||
content_diff="SOUL.md: +1 -0",
|
||||
stop_reason="length",
|
||||
)
|
||||
await cmd_dream(ctx)
|
||||
await asyncio.sleep(0)
|
||||
await _run_dream_command(ctx)
|
||||
assert store._last_dream_cursor == 5
|
||||
assert "did not complete" in ctx.loop.bus.outbound[0].content
|
||||
|
||||
@@ -282,8 +287,7 @@ async def test_dream_advances_cursor_when_completed_after_tool_error(tmp_path) -
|
||||
content_diff="",
|
||||
tool_error=True,
|
||||
)
|
||||
await cmd_dream(ctx)
|
||||
await asyncio.sleep(0)
|
||||
await _run_dream_command(ctx)
|
||||
assert store._last_dream_cursor == 42
|
||||
assert "no memory changes" in ctx.loop.bus.outbound[0].content
|
||||
|
||||
@@ -322,8 +326,7 @@ async def test_dream_noop_batch_unlocks_following_history(tmp_path) -> None:
|
||||
)
|
||||
ctx = CommandContext(msg=msg, session=None, key=msg.session_key, raw="/dream", args="", loop=loop)
|
||||
|
||||
await cmd_dream(ctx)
|
||||
await asyncio.sleep(0)
|
||||
await _run_dream_command(ctx)
|
||||
|
||||
assert len(processed_prompts) == 1
|
||||
assert "entry-20" in processed_prompts[0]
|
||||
@@ -343,8 +346,7 @@ async def test_dream_non_git_falls_back_to_completion_gate(tmp_path) -> None:
|
||||
ctx, store = _build_runnable_dream(
|
||||
tmp_path, initialized=False, content_diff="", stop_reason="completed",
|
||||
)
|
||||
await cmd_dream(ctx)
|
||||
await asyncio.sleep(0)
|
||||
await _run_dream_command(ctx)
|
||||
assert store._last_dream_cursor == 42 # advanced via completion fallback
|
||||
|
||||
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
"""Manual context compaction command behavior."""
|
||||
|
||||
import asyncio
|
||||
import sqlite3
|
||||
import threading
|
||||
from datetime import datetime, timedelta
|
||||
from unittest.mock import AsyncMock, MagicMock
|
||||
|
||||
@@ -45,6 +47,61 @@ async def loop(tmp_path):
|
||||
await loop.aclose()
|
||||
|
||||
|
||||
async def test_compact_session_io_runs_outside_event_loop(loop, monkeypatch) -> None:
|
||||
key = "cli:test"
|
||||
session = loop.sessions.get_or_create(key)
|
||||
session.add_message("user", "summarize this conversation")
|
||||
session.provider_state = ProviderConversationState(
|
||||
kind="openai_responses", provider="openai:test", model="test-model",
|
||||
version=1, payload={"items": []},
|
||||
)
|
||||
loop.sessions.save(session)
|
||||
|
||||
event_loop_thread = threading.get_ident()
|
||||
calls = []
|
||||
|
||||
def observe(name, operation):
|
||||
def checked(*args, **kwargs):
|
||||
assert threading.get_ident() != event_loop_thread
|
||||
calls.append(name)
|
||||
return operation(*args, **kwargs)
|
||||
return checked
|
||||
|
||||
for name in ("load", "save"):
|
||||
monkeypatch.setattr(loop.sessions._store, name, observe(name, getattr(loop.sessions._store, name)))
|
||||
|
||||
msg = InboundMessage(channel="cli", sender_id="user", chat_id="test", content="/compact")
|
||||
await loop.commands.dispatch(CommandContext(
|
||||
msg=msg, session=None, key=key, raw="/compact", loop=loop,
|
||||
))
|
||||
|
||||
assert "load" in calls and "save" in calls
|
||||
monkeypatch.undo()
|
||||
assert loop.sessions.get_or_create(key).provider_state is None
|
||||
|
||||
|
||||
async def test_compact_lock_contention_keeps_heartbeat_running(loop) -> None:
|
||||
key = "cli:test"
|
||||
session = loop.sessions.get_or_create(key)
|
||||
session.add_message("user", "summarize this conversation")
|
||||
loop.sessions.save(session)
|
||||
|
||||
msg = InboundMessage(channel="cli", sender_id="user", chat_id="test", content="/compact")
|
||||
blocker = sqlite3.connect(loop.sessions._store.path)
|
||||
blocker.execute("BEGIN IMMEDIATE")
|
||||
task = asyncio.create_task(loop.commands.dispatch(CommandContext(
|
||||
msg=msg, session=session, key=key, raw="/compact", loop=loop,
|
||||
)))
|
||||
try:
|
||||
for _ in range(5):
|
||||
await asyncio.sleep(0.01)
|
||||
assert not task.done(), "compaction must wait for storage without blocking the loop"
|
||||
finally:
|
||||
blocker.rollback()
|
||||
blocker.close()
|
||||
await asyncio.wait_for(task, timeout=2)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("command", ["/compact", " /COMPACT@nanobot ", "/summarize"])
|
||||
async def test_compact_emits_one_lifecycle_and_keeps_the_session(loop, command) -> None:
|
||||
@@ -165,6 +222,7 @@ async def test_empty_compact_finishes_silently_and_does_not_schedule_idle_archiv
|
||||
if legacy_commands:
|
||||
session.add_message("user", "/compact", _command=True)
|
||||
session.add_message("assistant", "Nothing to compact.", _command=True)
|
||||
session.updated_at = datetime.now() - timedelta(minutes=30)
|
||||
loop.sessions.save(session)
|
||||
completions = []
|
||||
loop.bus.subscribe(completions.append, TurnCompleted)
|
||||
@@ -183,11 +241,10 @@ async def test_empty_compact_finishes_silently_and_does_not_schedule_idle_archiv
|
||||
assert reloaded.last_archived == 2
|
||||
assert loop.consolidator.store.read_unprocessed_history(0) == []
|
||||
|
||||
reloaded.updated_at = datetime.now() - timedelta(minutes=30)
|
||||
loop.sessions.save(reloaded)
|
||||
loop.auto_compact._ttl = 1
|
||||
assert loop.auto_compact._is_expired(reloaded.updated_at)
|
||||
schedule = MagicMock()
|
||||
loop.auto_compact.check_expired(schedule, loop.runtime_for_session)
|
||||
await loop.auto_compact.check_expired(schedule, loop.runtime_for_session)
|
||||
schedule.assert_not_called()
|
||||
|
||||
|
||||
@@ -267,17 +324,18 @@ async def test_compact_is_a_fifo_barrier_during_an_active_turn(loop, command_tex
|
||||
channel="cli", sender_id="u", chat_id="test", content="initial question",
|
||||
)))
|
||||
try:
|
||||
await asyncio.wait_for(started.wait(), timeout=5)
|
||||
loop._enqueue_session_message(InboundMessage(
|
||||
# Include cold context initialization and durable commits on slower CI disks.
|
||||
await asyncio.wait_for(started.wait(), timeout=30)
|
||||
(await loop._enqueue_session_message(InboundMessage(
|
||||
channel="cli", sender_id="u", chat_id="test", content="before compaction",
|
||||
))
|
||||
)))
|
||||
command = InboundMessage(channel="cli", sender_id="u", chat_id="test", content=command_text)
|
||||
await loop._dispatch_command_inline(command, key, command.content, loop.commands.dispatch)
|
||||
loop._enqueue_session_message(InboundMessage(
|
||||
(await loop._enqueue_session_message(InboundMessage(
|
||||
channel="cli", sender_id="u", chat_id="test", content="after compaction",
|
||||
))
|
||||
)))
|
||||
release.set()
|
||||
await asyncio.wait_for(task, timeout=5)
|
||||
await asyncio.wait_for(task, timeout=30)
|
||||
finally:
|
||||
release.set()
|
||||
if not task.done():
|
||||
@@ -308,9 +366,9 @@ async def test_stop_completes_compact_queued_behind_an_active_turn(loop, command
|
||||
loop.provider.chat_stream_with_retry = chat
|
||||
completions = []
|
||||
loop.bus.subscribe(completions.append, TurnCompleted)
|
||||
loop._enqueue_session_message(InboundMessage(
|
||||
(await loop._enqueue_session_message(InboundMessage(
|
||||
channel="websocket", sender_id="u", chat_id="test", content="question",
|
||||
))
|
||||
)))
|
||||
task = next(iter(loop._active_tasks[key]))
|
||||
await asyncio.wait_for(started.wait(), timeout=5)
|
||||
command = InboundMessage(
|
||||
@@ -348,7 +406,7 @@ async def test_stop_finishes_inflight_compaction_as_cancelled(loop, command) ->
|
||||
channel="websocket", sender_id="user", chat_id="test", content=command,
|
||||
metadata={"webui_turn_id": "compact-turn"},
|
||||
)
|
||||
loop._enqueue_session_message(msg)
|
||||
(await loop._enqueue_session_message(msg))
|
||||
task = next(iter(loop._active_tasks[key]))
|
||||
await asyncio.wait_for(entered.wait(), timeout=5)
|
||||
|
||||
@@ -402,9 +460,10 @@ async def test_idle_and_manual_compact_share_persisted_checkpoint(loop) -> None:
|
||||
assert reloaded.get_history() == []
|
||||
assert reloaded.metadata["_last_summary"]["text"] == "Portable checkpoint."
|
||||
|
||||
reloaded = await loop.sessions.state.get(key)
|
||||
reloaded.add_message("user", "next question")
|
||||
reloaded.add_message("assistant", "next answer")
|
||||
loop.sessions.save(reloaded)
|
||||
await loop.sessions.state.finish_turn(reloaded)
|
||||
await loop.consolidator.compact_idle_session(key, runtime=runtime)
|
||||
loop.sessions.invalidate(key)
|
||||
reloaded = loop.sessions.get_or_create(key)
|
||||
|
||||
@@ -163,6 +163,7 @@ async def test_model_command_reports_provider_configuration_errors(tmp_path) ->
|
||||
switched = await cmd_model(_ctx(loop, "/model fast", args="fast"))
|
||||
session = loop.sessions.get_or_create("cli:direct")
|
||||
session.metadata[SESSION_MODEL_PRESET_METADATA_KEY] = "fast"
|
||||
loop.sessions.save(session)
|
||||
status = await cmd_model(_ctx(loop, "/model"))
|
||||
|
||||
assert "Could not switch model preset" in switched.content
|
||||
@@ -264,8 +265,7 @@ async def test_goal_command_preserves_task_and_visible_command(tmp_path, with_se
|
||||
task = "检查 /tmp/project\n保留现有文件。"
|
||||
command = f"/goal {task}"
|
||||
ctx = _ctx_session(loop, command, args=task)
|
||||
if not with_session:
|
||||
ctx.session = None
|
||||
ctx.session = await loop.sessions.state.get(ctx.key) if with_session else None
|
||||
out = await cmd_goal(ctx)
|
||||
assert isinstance(out, InboundMessage)
|
||||
assert ctx.msg.content == command
|
||||
@@ -287,6 +287,7 @@ async def test_goal_command_registered_on_router(tmp_path) -> None:
|
||||
register_builtin_commands(router)
|
||||
loop = _make_loop(tmp_path)
|
||||
ctx = _ctx_session(loop, "/goal ship it", args="ship it")
|
||||
ctx.session = await loop.sessions.state.get(ctx.key)
|
||||
out = await router.dispatch(ctx)
|
||||
assert isinstance(out, InboundMessage)
|
||||
assert out.content == "ship it"
|
||||
|
||||
@@ -110,8 +110,8 @@ class TestMidTurnCommandDispatchedDirectly:
|
||||
def fake_loop(self) -> MagicMock:
|
||||
loop = MagicMock()
|
||||
loop.sessions = MagicMock()
|
||||
loop.sessions.get_or_create = MagicMock(return_value=MagicMock(
|
||||
messages=[], last_archived=0, clear=MagicMock(),
|
||||
loop.sessions.state.get = AsyncMock(return_value=MagicMock(
|
||||
key="test:chat1", messages=[], last_archived=0, clear=MagicMock(),
|
||||
))
|
||||
loop.sessions.save = MagicMock()
|
||||
loop.sessions.invalidate = MagicMock()
|
||||
@@ -137,10 +137,11 @@ class TestMidTurnCommandDispatchedDirectly:
|
||||
msg=fake_msg, session=None,
|
||||
key="test:chat1", raw="/new", loop=fake_loop,
|
||||
)
|
||||
fake_loop.sessions.state.reset = AsyncMock()
|
||||
result = await router.dispatch(ctx)
|
||||
assert result is not None
|
||||
assert "New session" in result.content
|
||||
fake_loop.sessions.get_or_create.assert_called_once_with("test:chat1")
|
||||
fake_loop.sessions.state.reset.assert_awaited_once_with("test:chat1")
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_help_dispatched_with_session_none(
|
||||
|
||||
@@ -64,7 +64,7 @@ async def test_user_shell_uses_exec_tool_with_workspace_scope(
|
||||
scope = SimpleNamespace(project_path=tmp_path)
|
||||
loop = MagicMock()
|
||||
loop.tools.get.return_value = tool
|
||||
loop.sessions.get_or_create.return_value = session
|
||||
loop.sessions.state.get = AsyncMock(return_value=session)
|
||||
loop.workspace_scopes.for_turn.return_value = scope
|
||||
ctx = _context(loop, trusted=True)
|
||||
if context_session:
|
||||
|
||||
@@ -159,6 +159,7 @@ async def test_codex_title_omits_effort_even_with_high_chat_reasoning(monkeypatc
|
||||
session = sessions.get_or_create("websocket:default-effort-title")
|
||||
session.metadata["webui"] = True
|
||||
session.add_message("user", "Explain context compaction.")
|
||||
sessions.save(session)
|
||||
|
||||
assert await maybe_generate_webui_title(
|
||||
sessions=sessions, session_key=session.key,
|
||||
@@ -166,7 +167,9 @@ async def test_codex_title_omits_effort_even_with_high_chat_reasoning(monkeypatc
|
||||
)
|
||||
assert len(requests) == 1
|
||||
assert "effort" not in requests[0].get("reasoning", {})
|
||||
assert session.metadata["title"] == "Context Compaction"
|
||||
persisted = await sessions.state.read(session.key)
|
||||
assert persisted is not None
|
||||
assert persisted.metadata["title"] == "Context Compaction"
|
||||
assert provider.generation.reasoning_effort == "high"
|
||||
|
||||
|
||||
@@ -207,6 +210,7 @@ async def test_codex_title_failure_logs_request_purpose_and_safe_upstream_detail
|
||||
session = sessions.get_or_create("websocket:diagnostic-title")
|
||||
session.metadata["webui"] = True
|
||||
session.add_message("user", "PRIVATE PROMPT MUST NOT APPEAR")
|
||||
sessions.save(session)
|
||||
sink = io.StringIO()
|
||||
logger.enable("nanobot")
|
||||
handler_id = add_console_log_sink(sink)
|
||||
@@ -221,7 +225,9 @@ async def test_codex_title_failure_logs_request_purpose_and_safe_upstream_detail
|
||||
logger.remove(handler_id)
|
||||
|
||||
assert generated is False
|
||||
assert "title" not in session.metadata
|
||||
persisted = await sessions.state.read(session.key)
|
||||
assert persisted is not None
|
||||
assert "title" not in persisted.metadata
|
||||
log, outside_log = sink.getvalue().splitlines()
|
||||
assert "purpose=webui_title" not in outside_log
|
||||
assert f"session={session.key}" not in outside_log
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
CREATE TABLE storage_meta (key TEXT PRIMARY KEY, value TEXT NOT NULL);
|
||||
CREATE TABLE sessions (
|
||||
key TEXT PRIMARY KEY, created_at TEXT NOT NULL, updated_at TEXT NOT NULL,
|
||||
metadata TEXT NOT NULL, provider_state TEXT, last_archived INTEGER NOT NULL,
|
||||
revision INTEGER NOT NULL, generation TEXT NOT NULL,
|
||||
title TEXT NOT NULL, preview TEXT NOT NULL, visible_updated_at TEXT
|
||||
);
|
||||
CREATE TABLE messages (
|
||||
session_key TEXT NOT NULL REFERENCES sessions(key) ON DELETE CASCADE,
|
||||
position INTEGER NOT NULL, record TEXT NOT NULL,
|
||||
PRIMARY KEY (session_key, position)
|
||||
);
|
||||
CREATE TABLE checkpoints (
|
||||
session_key TEXT PRIMARY KEY REFERENCES sessions(key) ON DELETE CASCADE,
|
||||
record TEXT NOT NULL
|
||||
);
|
||||
CREATE TABLE pending_inputs (
|
||||
session_key TEXT NOT NULL REFERENCES sessions(key) ON DELETE CASCADE,
|
||||
kind TEXT NOT NULL, position INTEGER NOT NULL, record TEXT NOT NULL,
|
||||
PRIMARY KEY (session_key, kind, position)
|
||||
);
|
||||
CREATE INDEX sessions_updated ON sessions(updated_at DESC);
|
||||
INSERT INTO storage_meta (key, value) VALUES ('jsonl_import', 'complete');
|
||||
PRAGMA user_version = 1;
|
||||
@@ -30,8 +30,8 @@ def test_loaded_corrupt_offset_keeps_messages(tmp_path: Path):
|
||||
}
|
||||
|
||||
for name, offset in offsets.items():
|
||||
manager = SessionManager(tmp_path / name)
|
||||
path = manager._get_session_path("chan:chat")
|
||||
workspace = tmp_path / name
|
||||
path = workspace / "sessions" / "old.jsonl"
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
message = {"role": "user", "content": f"survived {name}"}
|
||||
path.write_text(
|
||||
@@ -47,7 +47,7 @@ def test_loaded_corrupt_offset_keeps_messages(tmp_path: Path):
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
session = manager.get_or_create("chan:chat")
|
||||
session = SessionManager(workspace).get_or_create("chan:chat")
|
||||
|
||||
assert session.messages == [message]
|
||||
assert session.last_consolidated == 0
|
||||
@@ -64,8 +64,7 @@ def test_valid_offset_is_preserved():
|
||||
|
||||
|
||||
def test_last_archived_field_migrates_with_legacy_alias(tmp_path: Path):
|
||||
manager = SessionManager(tmp_path)
|
||||
path = manager._get_session_path("chan:chat")
|
||||
path = tmp_path / "sessions" / "old.jsonl"
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
messages = [
|
||||
{"role": "user", "content": "first"},
|
||||
@@ -84,20 +83,18 @@ def test_last_archived_field_migrates_with_legacy_alias(tmp_path: Path):
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
manager = SessionManager(tmp_path)
|
||||
session = manager.get_or_create("chan:chat")
|
||||
|
||||
assert session.last_archived == 1
|
||||
assert session.last_consolidated == 1
|
||||
manager.save(session)
|
||||
metadata = json.loads(path.read_text(encoding="utf-8").splitlines()[0])
|
||||
assert metadata["last_archived"] == 1
|
||||
assert metadata["last_consolidated"] == 1
|
||||
assert manager.read_session_snapshot("chan:chat").last_archived == 1
|
||||
|
||||
|
||||
def test_loaded_null_metadata_becomes_empty_dict(tmp_path: Path):
|
||||
"""Session jsonl metadata:null must load as {} so agent .pop/.get work."""
|
||||
manager = SessionManager(tmp_path)
|
||||
path = manager._get_session_path("chan:chat")
|
||||
path = tmp_path / "sessions" / "old.jsonl"
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(
|
||||
json.dumps({
|
||||
@@ -110,6 +107,7 @@ def test_loaded_null_metadata_becomes_empty_dict(tmp_path: Path):
|
||||
}) + "\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
manager = SessionManager(tmp_path)
|
||||
session = manager.get_or_create("chan:chat")
|
||||
assert session.metadata == {}
|
||||
session.metadata["title"] = "ok"
|
||||
|
||||
@@ -177,13 +177,13 @@ async def test_scan_loads_only_sessions_that_need_webui_recovery(
|
||||
|
||||
coordinator, _, restarted = _coordinator(tmp_path)
|
||||
loaded: list[str] = []
|
||||
get_or_create = restarted.get_or_create
|
||||
get_or_create = restarted.state.get
|
||||
|
||||
def tracked_get_or_create(key: str) -> Session:
|
||||
async def tracked_get_or_create(key: str) -> Session:
|
||||
loaded.append(key)
|
||||
return get_or_create(key)
|
||||
return await get_or_create(key)
|
||||
|
||||
monkeypatch.setattr(restarted, "get_or_create", tracked_get_or_create)
|
||||
monkeypatch.setattr(restarted.state, "get", tracked_get_or_create)
|
||||
monkeypatch.setattr(
|
||||
"nanobot.webui.transcript.has_unfinished_transcript_tail",
|
||||
lambda _key: False,
|
||||
|
||||
@@ -0,0 +1,443 @@
|
||||
"""Admission, ordering, and shutdown at the asynchronous session boundary."""
|
||||
|
||||
import asyncio
|
||||
import sqlite3
|
||||
import threading
|
||||
|
||||
import pytest
|
||||
|
||||
from nanobot.bus.events import InboundMessage
|
||||
from nanobot.session.manager import SessionManager
|
||||
from nanobot.session.state import SessionOperationQueueFullError, SessionState
|
||||
|
||||
|
||||
@pytest.mark.parametrize("channel", ["cli", "telegram", "system"])
|
||||
async def test_non_websocket_followup_does_not_access_storage(tmp_path, monkeypatch, channel):
|
||||
manager = SessionManager(tmp_path)
|
||||
|
||||
def unexpected_transaction(*args, **kwargs):
|
||||
pytest.fail("a non-recoverable follow-up must not access session storage")
|
||||
|
||||
monkeypatch.setattr(manager._store, "transaction", unexpected_transaction)
|
||||
state = manager.state
|
||||
try:
|
||||
assert await state.queue_followup(
|
||||
f"{channel}:chat",
|
||||
InboundMessage(channel=channel, sender_id="u", chat_id="chat", content="follow-up"),
|
||||
) is None
|
||||
finally:
|
||||
await state.aclose()
|
||||
|
||||
|
||||
async def test_writes_run_in_submission_order(tmp_path):
|
||||
state = SessionManager(tmp_path).state
|
||||
await state.get("chat:a")
|
||||
await asyncio.gather(*(state.update_metadata("chat:a", {"title": str(i)}) for i in range(50)))
|
||||
assert (await state.get("chat:a")).metadata["title"] == "49"
|
||||
await state.aclose()
|
||||
|
||||
|
||||
async def test_close_drains_accepted_operations(tmp_path, monkeypatch):
|
||||
manager = SessionManager(tmp_path)
|
||||
state = manager.state
|
||||
await state.get("chat:a")
|
||||
started, release = threading.Event(), threading.Event()
|
||||
original = manager._store.replace_metadata
|
||||
|
||||
def blocked(key, metadata, **kwargs):
|
||||
started.set()
|
||||
release.wait(5)
|
||||
return original(key, metadata, **kwargs)
|
||||
|
||||
monkeypatch.setattr(manager._store, "replace_metadata", blocked)
|
||||
task = asyncio.create_task(state.update_metadata("chat:a", {"title": "committed"}))
|
||||
assert await asyncio.to_thread(started.wait, 2)
|
||||
close = asyncio.create_task(state.aclose())
|
||||
await asyncio.sleep(0)
|
||||
assert not close.done()
|
||||
release.set()
|
||||
await asyncio.gather(task, close)
|
||||
assert manager.get_or_create("chat:a").metadata["title"] == "committed"
|
||||
with pytest.raises(RuntimeError, match="closed"):
|
||||
await state.update_metadata("chat:a", {"title": "late"})
|
||||
|
||||
|
||||
async def test_full_owner_rejects_without_creating_waiters(tmp_path, monkeypatch):
|
||||
manager = SessionManager(tmp_path)
|
||||
state = SessionState(manager._store, capacity=1, workers=1)
|
||||
await state.get("chat:a")
|
||||
started, release = threading.Event(), threading.Event()
|
||||
original = manager._store.replace_metadata
|
||||
|
||||
def blocked(key, metadata, **kwargs):
|
||||
started.set()
|
||||
release.wait(5)
|
||||
return original(key, metadata, **kwargs)
|
||||
|
||||
monkeypatch.setattr(manager._store, "replace_metadata", blocked)
|
||||
accepted = asyncio.create_task(state.update_metadata("chat:a", {"title": "accepted"}))
|
||||
assert await asyncio.to_thread(started.wait, 2)
|
||||
|
||||
with pytest.raises(SessionOperationQueueFullError, match="queue is full"):
|
||||
await state.update_metadata("chat:b", {"title": "rejected"})
|
||||
|
||||
release.set()
|
||||
await accepted
|
||||
assert await state.read("chat:b") is None
|
||||
await state.aclose()
|
||||
|
||||
|
||||
async def test_slow_session_does_not_block_unrelated_session(tmp_path, monkeypatch):
|
||||
manager = SessionManager(tmp_path)
|
||||
state = SessionState(manager._store, capacity=4, workers=2)
|
||||
await state.get("chat:a")
|
||||
await state.get("chat:b")
|
||||
await state.update_metadata("chat:b", {"title": "ready"})
|
||||
started, release = threading.Event(), threading.Event()
|
||||
original = manager._store.replace_metadata
|
||||
|
||||
def blocked(key, metadata, **kwargs):
|
||||
if key == "chat:a":
|
||||
started.set()
|
||||
release.wait(5)
|
||||
return original(key, metadata, **kwargs)
|
||||
|
||||
monkeypatch.setattr(manager._store, "replace_metadata", blocked)
|
||||
slow = asyncio.create_task(state.update_metadata("chat:a", {"title": "slow"}))
|
||||
assert await asyncio.to_thread(started.wait, 2)
|
||||
other = await asyncio.wait_for(state.read("chat:b"), timeout=0.25)
|
||||
assert other is not None and other.metadata["title"] == "ready"
|
||||
release.set()
|
||||
await slow
|
||||
await state.aclose()
|
||||
|
||||
|
||||
async def test_close_timeout_does_not_cancel_internal_drain(tmp_path, monkeypatch):
|
||||
manager = SessionManager(tmp_path)
|
||||
state = manager.state
|
||||
await state.get("chat:a")
|
||||
started, release = threading.Event(), threading.Event()
|
||||
original = manager._store.replace_metadata
|
||||
|
||||
def blocked(key, metadata, **kwargs):
|
||||
started.set()
|
||||
release.wait(5)
|
||||
return original(key, metadata, **kwargs)
|
||||
|
||||
monkeypatch.setattr(manager._store, "replace_metadata", blocked)
|
||||
accepted = asyncio.create_task(state.update_metadata("chat:a", {"title": "committed"}))
|
||||
assert await asyncio.to_thread(started.wait, 2)
|
||||
with pytest.raises(TimeoutError):
|
||||
await asyncio.wait_for(state.aclose(), timeout=0.05)
|
||||
with pytest.raises(RuntimeError, match="closed"):
|
||||
await state.update_metadata("chat:b", {"title": "late"})
|
||||
release.set()
|
||||
await accepted
|
||||
await state.aclose()
|
||||
assert manager.get_or_create("chat:a").metadata["title"] == "committed"
|
||||
|
||||
|
||||
async def test_global_barrier_orders_both_sides_of_admission(tmp_path):
|
||||
state = SessionManager(tmp_path).state
|
||||
started, release = threading.Event(), threading.Event()
|
||||
order = []
|
||||
|
||||
def first():
|
||||
started.set()
|
||||
assert release.wait(5)
|
||||
order.append("first")
|
||||
|
||||
first_task = asyncio.create_task(state._execute("chat:a", first))
|
||||
tasks = [first_task]
|
||||
try:
|
||||
assert await asyncio.to_thread(started.wait, 2)
|
||||
tasks.append(asyncio.create_task(state._execute(None, lambda: order.append("barrier"))))
|
||||
await asyncio.sleep(0)
|
||||
tasks.append(asyncio.create_task(state._execute("chat:b", lambda: order.append("later"))))
|
||||
await asyncio.sleep(0)
|
||||
assert state._admitted == 3
|
||||
assert order == []
|
||||
release.set()
|
||||
await asyncio.gather(*tasks)
|
||||
assert order == ["first", "barrier", "later"]
|
||||
finally:
|
||||
release.set()
|
||||
await asyncio.gather(*tasks, return_exceptions=True)
|
||||
await state.aclose()
|
||||
|
||||
|
||||
async def test_fork_waits_for_target_and_blocks_later_target_read(tmp_path, monkeypatch):
|
||||
state = SessionManager(tmp_path).state
|
||||
await state.import_messages("chat:source", [{"role": "user", "content": "kept"}])
|
||||
target_started, target_release = threading.Event(), threading.Event()
|
||||
fork_started, fork_release = threading.Event(), threading.Event()
|
||||
original_load = state._load
|
||||
|
||||
def paused_source(key, *, history=True):
|
||||
if key == "chat:source":
|
||||
fork_started.set()
|
||||
assert fork_release.wait(5)
|
||||
return original_load(key, history=history)
|
||||
|
||||
def target_operation():
|
||||
target_started.set()
|
||||
assert target_release.wait(5)
|
||||
|
||||
monkeypatch.setattr(state, "_load", paused_source)
|
||||
tasks = [asyncio.create_task(state._execute("chat:target", target_operation))]
|
||||
try:
|
||||
assert await asyncio.to_thread(target_started.wait, 2)
|
||||
fork = asyncio.create_task(state.fork("chat:source", "chat:target", 1))
|
||||
tasks.append(fork)
|
||||
await asyncio.sleep(0)
|
||||
read = asyncio.create_task(state.read("chat:target"))
|
||||
tasks.append(read)
|
||||
await asyncio.sleep(0)
|
||||
assert state._admitted == 3
|
||||
assert not fork_started.is_set()
|
||||
target_release.set()
|
||||
assert await asyncio.to_thread(fork_started.wait, 2)
|
||||
assert not read.done()
|
||||
fork_release.set()
|
||||
result = await fork
|
||||
snapshot = await read
|
||||
assert result is not None and snapshot is not None
|
||||
assert result.generation == snapshot.generation
|
||||
assert snapshot.messages[0]["content"] == "kept"
|
||||
finally:
|
||||
target_release.set()
|
||||
fork_release.set()
|
||||
await asyncio.gather(*tasks, return_exceptions=True)
|
||||
await state.aclose()
|
||||
|
||||
|
||||
async def test_failed_predecessor_does_not_poison_key_or_global_barrier(tmp_path):
|
||||
state = SessionManager(tmp_path).state
|
||||
order = []
|
||||
|
||||
def fail():
|
||||
raise ValueError("injected")
|
||||
|
||||
failed = asyncio.create_task(state._execute("chat:a", fail))
|
||||
same_key = asyncio.create_task(state._execute("chat:a", lambda: order.append("same")))
|
||||
barrier = asyncio.create_task(state._execute(None, lambda: order.append("barrier")))
|
||||
results = await asyncio.gather(failed, same_key, barrier, return_exceptions=True)
|
||||
assert isinstance(results[0], ValueError)
|
||||
assert results[1:] == [None, None]
|
||||
assert order == ["same", "barrier"]
|
||||
assert state._admitted == 0
|
||||
assert state._key_tails == {}
|
||||
assert state._global_tail is None
|
||||
await state.aclose()
|
||||
|
||||
|
||||
async def test_cancel_before_coroutine_starts_submits_no_command(tmp_path):
|
||||
state = SessionManager(tmp_path).state
|
||||
task = asyncio.create_task(state.get("chat:unaccepted"))
|
||||
task.cancel()
|
||||
with pytest.raises(asyncio.CancelledError):
|
||||
await task
|
||||
assert state._admitted == 0
|
||||
assert await state.read("chat:unaccepted") is None
|
||||
await state.aclose()
|
||||
|
||||
|
||||
async def test_followup_can_initialize_first_turn_but_cannot_revive_deleted_session(tmp_path):
|
||||
from nanobot.session.recovery import pending_followups
|
||||
from nanobot.session.sqlite_store import SessionConflictError
|
||||
|
||||
state = SessionManager(tmp_path).state
|
||||
message = InboundMessage(channel="websocket", sender_id="u", chat_id="a", content="second")
|
||||
assert await state.queue_followup("websocket:a", message)
|
||||
session = await state.get("websocket:a")
|
||||
assert [item.content for item in pending_followups(session)] == ["second"]
|
||||
await state.delete(session.key)
|
||||
with pytest.raises(SessionConflictError, match="existing session"):
|
||||
await state.queue_followup(session.key, message)
|
||||
assert await state.read(session.key) is None
|
||||
await state.aclose()
|
||||
|
||||
|
||||
async def test_followup_rejects_discarded_or_replaced_generation(tmp_path):
|
||||
from nanobot.session.sqlite_store import SessionConflictError
|
||||
|
||||
state = SessionManager(tmp_path).state
|
||||
session = await state.register_transient("websocket:private")
|
||||
message = InboundMessage(
|
||||
channel="websocket", sender_id="u", chat_id="private", content="private",
|
||||
require_existing_session=True, session_generation=session.generation,
|
||||
)
|
||||
await state.discard(session.key)
|
||||
with pytest.raises(SessionConflictError, match="existing session"):
|
||||
await state.queue_followup(session.key, message)
|
||||
replacement = await state.register_transient(session.key)
|
||||
with pytest.raises(SessionConflictError, match="replaced session"):
|
||||
await state.queue_followup(session.key, message)
|
||||
assert (await state.get(replacement.key)).metadata == {}
|
||||
await state.aclose()
|
||||
|
||||
|
||||
async def test_display_metadata_reads_committed_snapshot_during_write(tmp_path, monkeypatch):
|
||||
manager = SessionManager(tmp_path)
|
||||
state = manager.state
|
||||
await state.get("websocket:busy")
|
||||
await state.update_metadata("websocket:busy", {"title": "committed"})
|
||||
started, release = threading.Event(), threading.Event()
|
||||
original = manager._store.replace_metadata
|
||||
|
||||
def blocked(key, metadata, **kwargs):
|
||||
started.set()
|
||||
assert release.wait(5)
|
||||
return original(key, metadata, **kwargs)
|
||||
|
||||
monkeypatch.setattr(manager._store, "replace_metadata", blocked)
|
||||
write = asyncio.create_task(state.update_metadata("websocket:busy", {"title": "next"}))
|
||||
try:
|
||||
assert await asyncio.to_thread(started.wait, 2)
|
||||
rows = await asyncio.wait_for(state.list_metadata(), timeout=0.5)
|
||||
assert rows[0]["metadata"]["title"] == "committed"
|
||||
rows[0]["metadata"]["title"] = "local edit"
|
||||
finally:
|
||||
release.set()
|
||||
await write
|
||||
assert (await state.list_metadata())[0]["metadata"]["title"] == "next"
|
||||
await state.aclose()
|
||||
|
||||
|
||||
async def test_cached_header_preserves_policy_and_offsets_without_history(tmp_path):
|
||||
state = SessionManager(tmp_path).state
|
||||
await state.import_messages("chat:header", [
|
||||
{"role": "user", "content": "input"}, {"role": "assistant", "content": "answer"},
|
||||
])
|
||||
draft = await state.get("chat:header")
|
||||
draft.last_archived = 1
|
||||
draft.metadata["nested"] = {"value": "committed"}
|
||||
await state.prepare_input(draft)
|
||||
header = state.peek_header("chat:header")
|
||||
assert header is not None
|
||||
assert header.messages == []
|
||||
assert header.last_archived == 1
|
||||
assert header.generation == draft.generation
|
||||
assert header.policy == draft.policy
|
||||
header.metadata["nested"]["value"] = "local edit"
|
||||
assert state.peek_metadata("chat:header")["nested"]["value"] == "committed"
|
||||
assert len(state.peek("chat:header").messages) == 2
|
||||
await state.aclose()
|
||||
|
||||
|
||||
async def test_missing_get_keeps_creation_before_a_later_delete(tmp_path, monkeypatch):
|
||||
state = SessionManager(tmp_path).state
|
||||
started, release = threading.Event(), threading.Event()
|
||||
original = state._load
|
||||
first = True
|
||||
|
||||
def paused_read(key, *, history=True):
|
||||
nonlocal first
|
||||
if first:
|
||||
first = False
|
||||
started.set()
|
||||
assert release.wait(5)
|
||||
return original(key, history=history)
|
||||
|
||||
monkeypatch.setattr(state, "_load", paused_read)
|
||||
get = asyncio.create_task(state.get("chat:new"))
|
||||
tasks = [get]
|
||||
try:
|
||||
assert await asyncio.to_thread(started.wait, 2)
|
||||
deleted = asyncio.create_task(state.delete("chat:new"))
|
||||
tasks.append(deleted)
|
||||
await asyncio.sleep(0)
|
||||
assert not deleted.done()
|
||||
release.set()
|
||||
assert (await get).persisted
|
||||
assert await deleted
|
||||
assert await state.read("chat:new") is None
|
||||
finally:
|
||||
release.set()
|
||||
await asyncio.gather(*tasks, return_exceptions=True)
|
||||
await state.aclose()
|
||||
|
||||
|
||||
async def test_metadata_peek_and_header_do_not_expose_history_or_shared_metadata(tmp_path):
|
||||
state = SessionManager(tmp_path).state
|
||||
try:
|
||||
assert state.peek_metadata("chat:missing") is None
|
||||
empty = await state.get_header("chat:empty")
|
||||
assert empty.messages == [] and empty.persisted
|
||||
assert state.peek_metadata(empty.key) == {}
|
||||
assert empty._baseline is None
|
||||
await state.import_messages("chat:history", [{"role": "user", "content": "retained"}])
|
||||
await state.update_metadata("chat:history", {"custom": {"values": ["saved"]}})
|
||||
await state.commit_summary(await state.get("chat:history"), "Saved context", archive_end=1)
|
||||
header = await state.get_header("chat:history")
|
||||
assert header.messages == [] and header._baseline is None
|
||||
assert header.last_archived > 0
|
||||
header.metadata["custom"]["values"].append("header edit")
|
||||
metadata = state.peek_metadata("chat:history")
|
||||
metadata["custom"]["values"].append("peek edit")
|
||||
loaded = await state.get("chat:history")
|
||||
assert loaded.generation == header.generation
|
||||
assert loaded.last_archived == header.last_archived
|
||||
assert loaded.messages[0]["content"] == "retained"
|
||||
assert loaded.metadata["custom"]["values"] == ["saved"]
|
||||
await state.register_transient("chat:private")
|
||||
assert state.peek_metadata("chat:private") == {}
|
||||
await state.update_metadata("chat:private", {"custom": {"values": ["private"]}})
|
||||
private = state.peek_metadata("chat:private")
|
||||
private["custom"]["values"].append("peek edit")
|
||||
assert state.peek_metadata("chat:private")["custom"]["values"] == ["private"]
|
||||
finally:
|
||||
await state.aclose()
|
||||
|
||||
|
||||
async def test_connection_open_failure_does_not_poison_the_owner(tmp_path, monkeypatch):
|
||||
state = SessionManager(tmp_path).state
|
||||
connect = sqlite3.connect
|
||||
first = True
|
||||
|
||||
def fail_first(*args, **kwargs):
|
||||
nonlocal first
|
||||
if first:
|
||||
first = False
|
||||
raise sqlite3.OperationalError("database is locked")
|
||||
return connect(*args, **kwargs)
|
||||
|
||||
monkeypatch.setattr(sqlite3, "connect", fail_first)
|
||||
try:
|
||||
with pytest.raises(sqlite3.OperationalError, match="database is locked"):
|
||||
await state.get("chat:retry")
|
||||
assert state._admitted == 0
|
||||
draft = await state.get("chat:retry")
|
||||
draft.add_message("user", "accepted after lock was released")
|
||||
await state.prepare_input(draft)
|
||||
assert (await state.get(draft.key)).messages[-1]["content"] == "accepted after lock was released"
|
||||
finally:
|
||||
await state.aclose()
|
||||
|
||||
|
||||
async def test_history_peek_does_not_hold_the_metadata_control_lock(tmp_path, monkeypatch):
|
||||
import nanobot.session.state as owner
|
||||
from nanobot.session.manager import Session
|
||||
|
||||
state = SessionManager(tmp_path).state
|
||||
await state.import_messages("chat:child", [{"role": "user", "content": "history"}])
|
||||
await state.update_metadata("chat:child", {"title": "committed"})
|
||||
started, release = threading.Event(), threading.Event()
|
||||
deepcopy = owner.deepcopy
|
||||
|
||||
def paused_copy(value):
|
||||
if isinstance(value, Session):
|
||||
started.set()
|
||||
assert release.wait(5)
|
||||
return deepcopy(value)
|
||||
|
||||
monkeypatch.setattr(owner, "deepcopy", paused_copy)
|
||||
history = asyncio.create_task(asyncio.to_thread(state.peek, "chat:child"))
|
||||
try:
|
||||
assert await asyncio.to_thread(started.wait, 2)
|
||||
assert state.peek_metadata("chat:child")["title"] == "committed"
|
||||
assert not history.done()
|
||||
finally:
|
||||
release.set()
|
||||
await history
|
||||
await state.aclose()
|
||||
@@ -1,89 +1,46 @@
|
||||
import gc
|
||||
import weakref
|
||||
"""Detached views and transient session lifetime."""
|
||||
|
||||
from nanobot.session.manager import SESSION_CACHE_MAX_SIZE, SessionManager
|
||||
import pytest
|
||||
|
||||
from nanobot.session.manager import SessionManager
|
||||
from nanobot.session.sqlite_store import SessionConflictError
|
||||
|
||||
|
||||
def _bounded_manager(tmp_path, limit: int) -> SessionManager:
|
||||
async def test_committed_view_cache_is_bounded(tmp_path):
|
||||
state = SessionManager(tmp_path).state
|
||||
for i in range(140):
|
||||
await state.get(str(i))
|
||||
await state.update_metadata(str(i), {"title": str(i)})
|
||||
assert len(state._snapshots) <= 128
|
||||
assert state.peek("0") is None
|
||||
assert (await state.get("0")).metadata["title"] == "0"
|
||||
await state.aclose()
|
||||
|
||||
|
||||
async def test_cached_views_are_detached(tmp_path):
|
||||
state = SessionManager(tmp_path).state
|
||||
await state.get("chat:a")
|
||||
await state.update_metadata("chat:a", {"title": "saved"})
|
||||
cached = state.peek("chat:a")
|
||||
cached.metadata["title"] = "unsaved"
|
||||
assert state.peek("chat:a").metadata["title"] == "saved"
|
||||
await state.aclose()
|
||||
|
||||
|
||||
async def test_transient_session_never_reaches_storage(tmp_path):
|
||||
manager = SessionManager(tmp_path)
|
||||
manager._max_cached_sessions = limit
|
||||
return manager
|
||||
|
||||
|
||||
def test_default_session_cache_is_bounded(tmp_path) -> None:
|
||||
manager = SessionManager(tmp_path)
|
||||
|
||||
for index in range(SESSION_CACHE_MAX_SIZE + 1):
|
||||
manager.get_or_create(f"test:{index}")
|
||||
|
||||
assert len(manager._cache) == SESSION_CACHE_MAX_SIZE
|
||||
|
||||
|
||||
def test_session_cache_releases_inactive_lru_entries(tmp_path) -> None:
|
||||
manager = _bounded_manager(tmp_path, 1)
|
||||
first = manager.get_or_create("test:first")
|
||||
first.add_message("user", "persist me")
|
||||
manager.save(first)
|
||||
first_ref = weakref.ref(first)
|
||||
|
||||
second = manager.get_or_create("test:second")
|
||||
manager.save(second)
|
||||
del first
|
||||
gc.collect()
|
||||
|
||||
assert len(manager._cache) == 1
|
||||
assert first_ref() is None
|
||||
assert manager.get_or_create("test:first").messages[0]["content"] == "persist me"
|
||||
|
||||
|
||||
def test_session_cache_keeps_identity_for_evicted_active_sessions(tmp_path) -> None:
|
||||
manager = _bounded_manager(tmp_path, 1)
|
||||
active = manager.get_or_create("test:active")
|
||||
manager.save(active)
|
||||
|
||||
manager.save(manager.get_or_create("test:other"))
|
||||
|
||||
assert manager.get_or_create("test:active") is active
|
||||
|
||||
|
||||
def test_session_cache_refreshes_lru_order_on_access(tmp_path) -> None:
|
||||
manager = _bounded_manager(tmp_path, 2)
|
||||
manager.save(manager.get_or_create("test:first"))
|
||||
manager.save(manager.get_or_create("test:second"))
|
||||
|
||||
manager.get_or_create("test:first")
|
||||
manager.save(manager.get_or_create("test:third"))
|
||||
|
||||
assert list(manager._cache) == ["test:first", "test:third"]
|
||||
|
||||
|
||||
def test_flush_all_includes_live_sessions_outside_strong_cache(tmp_path, monkeypatch) -> None:
|
||||
manager = _bounded_manager(tmp_path, 1)
|
||||
active = manager.get_or_create("test:active")
|
||||
manager.save(active)
|
||||
manager.save(manager.get_or_create("test:other"))
|
||||
saved: list[tuple[str, bool]] = []
|
||||
original_save = manager.save
|
||||
|
||||
def recording_save(session, *, fsync=False):
|
||||
saved.append((session.key, fsync))
|
||||
original_save(session, fsync=fsync)
|
||||
|
||||
monkeypatch.setattr(manager, "save", recording_save)
|
||||
|
||||
assert manager.flush_all() == 2
|
||||
assert set(saved) == {("test:active", True), ("test:other", True)}
|
||||
|
||||
|
||||
def test_transient_session_never_reaches_storage(tmp_path) -> None:
|
||||
manager = SessionManager(tmp_path)
|
||||
session = manager.get_or_create_transient("websocket:temporary-test")
|
||||
session.add_message("user", "secret")
|
||||
|
||||
manager.save(session, fsync=True)
|
||||
|
||||
assert manager.get_cached(session.key) is session
|
||||
assert manager.read_session_file(session.key) is None
|
||||
assert list(manager.sessions_dir.glob("*.jsonl")) == []
|
||||
manager.invalidate(session.key)
|
||||
assert manager.get_cached(session.key) is None
|
||||
state = manager.state
|
||||
draft = await state.register_transient(
|
||||
"temporary:a", disabled_tools=frozenset({"create_goal"})
|
||||
)
|
||||
draft.add_message("user", "private")
|
||||
await state.prepare_input(draft)
|
||||
draft.add_message("assistant", "answer")
|
||||
await state.finish_turn(draft)
|
||||
assert len((await state.get(draft.key)).messages) == 2
|
||||
assert manager.read_session_snapshot(draft.key) is None
|
||||
assert manager.list_sessions() == []
|
||||
state.forget_transient(draft.key)
|
||||
with pytest.raises(SessionConflictError):
|
||||
await state.finish_turn(draft)
|
||||
await state.aclose()
|
||||
@@ -1,198 +1,12 @@
|
||||
"""Tests for session fsync and flush_all on graceful shutdown."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import errno
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from unittest.mock import call, patch
|
||||
|
||||
import pytest
|
||||
"""Durability configuration is applied to every SQLite connection."""
|
||||
|
||||
from nanobot.session.manager import SessionManager
|
||||
|
||||
_IS_WINDOWS = sys.platform == "win32"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def sessions_dir(tmp_path: Path) -> Path:
|
||||
d = tmp_path / "sessions"
|
||||
d.mkdir()
|
||||
return tmp_path
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def manager(sessions_dir: Path) -> SessionManager:
|
||||
return SessionManager(workspace=sessions_dir)
|
||||
|
||||
|
||||
class TestSaveFsync:
|
||||
"""Verify that save(fsync=True) calls os.fsync."""
|
||||
|
||||
def test_save_without_fsync_does_not_call_fsync(self, manager: SessionManager):
|
||||
session = manager.get_or_create("test:no-fsync")
|
||||
session.add_message("user", "hello")
|
||||
|
||||
with patch("os.fsync") as mock_fsync:
|
||||
manager.save(session, fsync=False)
|
||||
mock_fsync.assert_not_called()
|
||||
|
||||
def test_save_with_fsync_calls_fsync(self, manager: SessionManager):
|
||||
session = manager.get_or_create("test:with-fsync")
|
||||
session.add_message("user", "hello")
|
||||
|
||||
with patch("os.fsync") as mock_fsync:
|
||||
manager.save(session, fsync=True)
|
||||
# File fsync always runs; directory fsync only on non-Windows.
|
||||
expected = 1 if _IS_WINDOWS else 2
|
||||
assert mock_fsync.call_count == expected
|
||||
|
||||
def test_save_default_no_fsync(self, manager: SessionManager):
|
||||
"""Default save() should not fsync (backward compat)."""
|
||||
session = manager.get_or_create("test:default")
|
||||
session.add_message("user", "hello")
|
||||
|
||||
with patch("os.fsync") as mock_fsync:
|
||||
manager.save(session)
|
||||
mock_fsync.assert_not_called()
|
||||
|
||||
def test_save_ignores_unsupported_directory_fsync(
|
||||
self, manager: SessionManager
|
||||
) -> None:
|
||||
"""Shared filesystems may open directories but reject directory fsync."""
|
||||
session = manager.get_or_create("test:unsupported-directory-fsync")
|
||||
session.add_message("user", "hello")
|
||||
directory_fd = 987654
|
||||
with (
|
||||
manager.locked_session_files(),
|
||||
patch("nanobot.utils.helpers.os.open", return_value=directory_fd) as open_dir,
|
||||
patch(
|
||||
"nanobot.utils.helpers.os.fsync",
|
||||
side_effect=[None, OSError(errno.EINVAL, "Invalid argument")],
|
||||
),
|
||||
patch("nanobot.utils.helpers.os.close") as close_dir,
|
||||
):
|
||||
manager.save(session, fsync=True)
|
||||
|
||||
assert manager._get_session_path(session.key).exists()
|
||||
open_dir.assert_called_once_with(str(manager.sessions_dir), os.O_RDONLY)
|
||||
assert close_dir.call_args_list.count(call(directory_fd)) == 1
|
||||
|
||||
def test_save_propagates_other_directory_fsync_errors(
|
||||
self, manager: SessionManager
|
||||
) -> None:
|
||||
"""Only EINVAL is an expected unsupported-directory-fsync result."""
|
||||
session = manager.get_or_create("test:directory-fsync-io-error")
|
||||
directory_fd = 987654
|
||||
with (
|
||||
manager.locked_session_files(),
|
||||
patch("nanobot.utils.helpers.os.open", return_value=directory_fd),
|
||||
patch(
|
||||
"nanobot.utils.helpers.os.fsync",
|
||||
side_effect=[None, OSError(errno.EIO, "I/O error")],
|
||||
),
|
||||
patch("nanobot.utils.helpers.os.close") as close_dir,
|
||||
pytest.raises(OSError, match="I/O error"),
|
||||
):
|
||||
manager.save(session, fsync=True)
|
||||
|
||||
assert close_dir.call_args_list.count(call(directory_fd)) == 1
|
||||
|
||||
|
||||
class TestFlushAll:
|
||||
"""Verify flush_all re-saves all cached sessions with fsync."""
|
||||
|
||||
def test_flush_all_empty_cache(self, manager: SessionManager):
|
||||
assert manager.flush_all() == 0
|
||||
|
||||
def test_flush_all_saves_cached_sessions(self, manager: SessionManager):
|
||||
s1 = manager.get_or_create("test:session-1")
|
||||
s1.add_message("user", "msg 1")
|
||||
manager.save(s1)
|
||||
|
||||
s2 = manager.get_or_create("test:session-2")
|
||||
s2.add_message("user", "msg 2")
|
||||
manager.save(s2)
|
||||
|
||||
flushed = manager.flush_all()
|
||||
assert flushed == 2
|
||||
|
||||
def test_flush_all_uses_fsync(self, manager: SessionManager):
|
||||
session = manager.get_or_create("test:fsync-check")
|
||||
session.add_message("user", "important")
|
||||
manager.save(session)
|
||||
|
||||
with patch("os.fsync") as mock_fsync:
|
||||
manager.flush_all()
|
||||
# file fsync always; directory fsync only on non-Windows
|
||||
expected = 1 if _IS_WINDOWS else 2
|
||||
assert mock_fsync.call_count == expected
|
||||
|
||||
def test_flush_all_continues_on_error(self, manager: SessionManager):
|
||||
"""One broken session should not prevent others from flushing."""
|
||||
s1 = manager.get_or_create("test:good")
|
||||
s1.add_message("user", "ok")
|
||||
manager.save(s1)
|
||||
|
||||
s2 = manager.get_or_create("test:bad")
|
||||
s2.add_message("user", "ok")
|
||||
manager.save(s2)
|
||||
|
||||
original_save = manager.save
|
||||
call_count = {"n": 0}
|
||||
|
||||
def patched_save(session, *, fsync=False):
|
||||
call_count["n"] += 1
|
||||
if session.key == "test:bad":
|
||||
raise OSError("disk on fire")
|
||||
original_save(session, fsync=fsync)
|
||||
|
||||
manager.save = patched_save
|
||||
flushed = manager.flush_all()
|
||||
|
||||
# One succeeded, one failed — flush_all returns successful count
|
||||
assert flushed == 1
|
||||
assert call_count["n"] == 2
|
||||
|
||||
def test_flush_all_data_survives_reload(self, sessions_dir: Path):
|
||||
"""Data flushed by flush_all should survive a fresh SessionManager load."""
|
||||
mgr1 = SessionManager(workspace=sessions_dir)
|
||||
session = mgr1.get_or_create("test:persist")
|
||||
session.add_message("user", "remember this")
|
||||
session.add_message("assistant", "noted")
|
||||
mgr1.save(session)
|
||||
mgr1.flush_all()
|
||||
|
||||
# Simulate process restart — new manager, cold cache
|
||||
mgr2 = SessionManager(workspace=sessions_dir)
|
||||
reloaded = mgr2.get_or_create("test:persist")
|
||||
history = reloaded.get_history(max_messages=100)
|
||||
|
||||
assert len(history) == 2
|
||||
assert history[0]["content"] == "remember this"
|
||||
assert history[1]["content"] == "noted"
|
||||
|
||||
|
||||
class TestLoadErrors:
|
||||
@pytest.mark.parametrize(
|
||||
"operation",
|
||||
("get_or_create", "read_session_file", "read_session_metadata", "list_sessions"),
|
||||
)
|
||||
def test_permission_error_is_not_treated_as_corrupt_data(
|
||||
self,
|
||||
sessions_dir: Path,
|
||||
operation: str,
|
||||
) -> None:
|
||||
writer = SessionManager(workspace=sessions_dir)
|
||||
session = writer.get_or_create("test:permission")
|
||||
session.add_message("user", "must not disappear")
|
||||
writer.save(session)
|
||||
|
||||
reader = SessionManager(workspace=sessions_dir)
|
||||
with patch("builtins.open", side_effect=PermissionError("access denied")):
|
||||
with pytest.raises(PermissionError, match="access denied"):
|
||||
if operation == "list_sessions":
|
||||
reader.list_sessions()
|
||||
else:
|
||||
getattr(reader, operation)("test:permission")
|
||||
def test_every_transaction_uses_full_synchronous_and_foreign_keys(tmp_path):
|
||||
manager = SessionManager(tmp_path)
|
||||
for _ in range(2):
|
||||
with manager._store.transaction() as db:
|
||||
assert db.execute("PRAGMA synchronous").fetchone()[0] == 2
|
||||
assert db.execute("PRAGMA foreign_keys").fetchone()[0] == 1
|
||||
assert db.execute("PRAGMA journal_mode").fetchone()[0] == "wal"
|
||||
@@ -1,7 +1,9 @@
|
||||
import asyncio
|
||||
import sqlite3
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from concurrent.futures import TimeoutError as FutureTimeout
|
||||
from pathlib import Path
|
||||
from threading import Event
|
||||
from threading import Event, Thread
|
||||
|
||||
import pytest
|
||||
|
||||
@@ -138,7 +140,7 @@ def test_session_snapshot_and_handle_sync_share_one_lock(
|
||||
resolver.list_all()
|
||||
snapshot_taken = Event()
|
||||
release_snapshot = Event()
|
||||
original_list = manager.list_sessions
|
||||
original_list = manager._store.list_metadata
|
||||
|
||||
def paused_list():
|
||||
rows = original_list()
|
||||
@@ -146,7 +148,7 @@ def test_session_snapshot_and_handle_sync_share_one_lock(
|
||||
assert release_snapshot.wait(timeout=2)
|
||||
return rows
|
||||
|
||||
monkeypatch.setattr(manager, "list_sessions", paused_list)
|
||||
monkeypatch.setattr(manager._store, "list_metadata", paused_list)
|
||||
with ThreadPoolExecutor(max_workers=2) as pool:
|
||||
old_sync = pool.submit(resolver.list_all)
|
||||
assert snapshot_taken.wait(timeout=2)
|
||||
@@ -219,3 +221,27 @@ def test_private_type_cannot_be_resolved_through_an_existing_handle(tmp_path: Pa
|
||||
|
||||
reopened = SessionManager(tmp_path)
|
||||
assert SessionHandleResolver(reopened).list_all() == []
|
||||
|
||||
|
||||
async def test_runtime_existing_handles_do_not_wait_for_an_external_write_lock(tmp_path):
|
||||
manager = SessionManager(tmp_path)
|
||||
state = manager.state
|
||||
await state.get("websocket:existing")
|
||||
expected = await state.ensure_session_handles()
|
||||
ready, release = Event(), Event()
|
||||
|
||||
def hold():
|
||||
with sqlite3.connect(manager._store.path) as db:
|
||||
db.execute("BEGIN IMMEDIATE")
|
||||
ready.set()
|
||||
assert release.wait(5)
|
||||
|
||||
thread = Thread(target=hold)
|
||||
thread.start()
|
||||
try:
|
||||
assert await asyncio.to_thread(ready.wait, 2)
|
||||
assert await asyncio.wait_for(state.ensure_session_handles(), timeout=2) == expected
|
||||
finally:
|
||||
release.set()
|
||||
thread.join()
|
||||
await state.aclose()
|
||||
@@ -0,0 +1,216 @@
|
||||
"""Incremental storage must preserve snapshot isolation and cross-process conflicts."""
|
||||
|
||||
import asyncio
|
||||
import sqlite3
|
||||
import threading
|
||||
|
||||
import pytest
|
||||
|
||||
from nanobot.bus.events import InboundMessage
|
||||
from nanobot.session.manager import SessionManager
|
||||
from nanobot.session.sqlite_store import SessionConflictError
|
||||
|
||||
|
||||
async def test_append_does_not_resubmit_committed_rows(tmp_path):
|
||||
manager = SessionManager(tmp_path)
|
||||
state = manager.state
|
||||
draft = await state.import_messages("chat:a", [
|
||||
{"role": "user", "content": str(i)} for i in range(100)
|
||||
])
|
||||
with sqlite3.connect(manager._store.path) as db:
|
||||
db.execute("""CREATE TRIGGER reject_prefix BEFORE INSERT ON messages
|
||||
WHEN NEW.position < 100 BEGIN SELECT RAISE(ABORT, 'prefix'); END""")
|
||||
draft.add_message("user", "new input")
|
||||
await state.prepare_input(draft)
|
||||
draft.add_message("assistant", "new answer")
|
||||
await state.finish_turn(draft)
|
||||
stored = manager.read_session_snapshot(draft.key)
|
||||
assert [m["content"] for m in stored.messages] == [str(i) for i in range(100)] + ["new input", "new answer"]
|
||||
await state.aclose()
|
||||
|
||||
|
||||
async def test_metadata_checkpoint_and_followups_do_not_read_history(tmp_path):
|
||||
manager = SessionManager(tmp_path)
|
||||
state = manager.state
|
||||
draft = await state.import_messages("websocket:a", [
|
||||
{"role": "user", "content": str(i)} for i in range(100)
|
||||
])
|
||||
|
||||
def deny_history(action, table, *_args):
|
||||
return sqlite3.SQLITE_DENY if action == sqlite3.SQLITE_READ and table == "messages" else sqlite3.SQLITE_OK
|
||||
|
||||
def protect():
|
||||
with manager._store.transaction() as db:
|
||||
db.set_authorizer(deny_history)
|
||||
|
||||
await state._execute(draft.key, protect)
|
||||
await state.update_metadata(draft.key, {"title": "new"})
|
||||
await state.checkpoint_view(draft, {"step": 1})
|
||||
before_followup = manager.read_session_snapshot(draft.key).updated_at
|
||||
identifier = await state.queue_followup(draft.key, InboundMessage(
|
||||
channel="websocket", sender_id="u", chat_id="a", content="follow-up",
|
||||
))
|
||||
assert identifier
|
||||
assert manager.read_session_snapshot(draft.key).updated_at > before_followup
|
||||
await state.acknowledge_followups(draft.key, [identifier])
|
||||
await state.aclose()
|
||||
stored = manager.read_session_snapshot(draft.key)
|
||||
assert len(stored.messages) == 100
|
||||
assert stored.metadata["title"] == "new"
|
||||
assert stored.metadata["runtime_checkpoint"] == {"step": 1}
|
||||
assert not stored.metadata.get("pending_user_followups")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("transient", [False, True])
|
||||
async def test_nested_draft_edits_and_failed_commits_remain_private(tmp_path, transient):
|
||||
manager = SessionManager(tmp_path)
|
||||
state = manager.state
|
||||
draft = (
|
||||
await state.register_transient("chat:a")
|
||||
if transient
|
||||
else await state.get("chat:a")
|
||||
)
|
||||
draft.messages.append({"role": "user", "content": [{"type": "text", "text": "original"}]})
|
||||
await state.prepare_input(draft)
|
||||
peer = await state.get(draft.key)
|
||||
draft.messages[0]["content"][0]["text"] = "edited"
|
||||
assert state.peek(draft.key).messages[0]["content"][0]["text"] == "original"
|
||||
await state.finish_turn(draft)
|
||||
# Previously issued drafts still represent their old revision.
|
||||
assert peer.messages[0]["content"][0]["text"] == "original"
|
||||
peer.add_message("assistant", "stale append")
|
||||
with pytest.raises(SessionConflictError):
|
||||
await state.finish_turn(peer)
|
||||
draft.messages[0]["content"][0]["text"] = "unsaved after commit"
|
||||
assert (await state.get(draft.key)).messages[0]["content"][0]["text"] == "edited"
|
||||
await state.aclose()
|
||||
|
||||
|
||||
async def test_import_and_fork_returns_do_not_alias_committed_records(tmp_path):
|
||||
state = SessionManager(tmp_path).state
|
||||
source = await state.import_messages("chat:a", [
|
||||
{"role": "user", "content": [{"type": "text", "text": "original"}]},
|
||||
{"role": "user", "content": "next"},
|
||||
])
|
||||
fork = await state.fork(source.key, "chat:b", 1)
|
||||
source.messages[0]["content"][0]["text"] = "import edit"
|
||||
fork.messages[0]["content"][0]["text"] = "fork edit"
|
||||
for key in (source.key, fork.key):
|
||||
assert (await state.get(key)).messages[0]["content"][0]["text"] == "original"
|
||||
await state.aclose()
|
||||
|
||||
|
||||
async def test_external_append_merges_and_external_edit_conflicts(tmp_path):
|
||||
manager = SessionManager(tmp_path)
|
||||
state = manager.state
|
||||
draft = await state.import_messages("chat:a", [{"role": "user", "content": "first"}])
|
||||
other = SessionManager(tmp_path)
|
||||
external = other.get_or_create(draft.key)
|
||||
external.add_message("assistant", "external")
|
||||
other.save(external)
|
||||
draft.add_message("assistant", "local")
|
||||
await state.finish_turn(draft)
|
||||
assert [m["content"] for m in draft.messages] == ["first", "external", "local"]
|
||||
external = other.get_or_create(draft.key)
|
||||
external.messages[0]["content"] = "replaced"
|
||||
other.save(external)
|
||||
# A metadata-only command must not revalidate stale cached history accidentally.
|
||||
await state.update_metadata(draft.key, {"title": "new"})
|
||||
draft.add_message("assistant", "stale")
|
||||
with pytest.raises(SessionConflictError):
|
||||
await state.finish_turn(draft)
|
||||
assert (await state.get(draft.key)).messages[0]["content"] == "replaced"
|
||||
await state.aclose()
|
||||
|
||||
|
||||
async def test_rejected_write_does_not_change_cached_snapshot(tmp_path):
|
||||
manager = SessionManager(tmp_path)
|
||||
state = manager.state
|
||||
draft = await state.import_messages("chat:a", [{"role": "user", "content": "first"}])
|
||||
with sqlite3.connect(manager._store.path) as db:
|
||||
db.execute("""CREATE TRIGGER reject_append BEFORE INSERT ON messages
|
||||
WHEN NEW.position > 0 BEGIN SELECT RAISE(ABORT, 'injected'); END""")
|
||||
draft.add_message("assistant", "rejected")
|
||||
draft.metadata["title"] = "rejected"
|
||||
with pytest.raises(sqlite3.IntegrityError, match="injected"):
|
||||
await state.finish_turn(draft)
|
||||
cached = state.peek(draft.key)
|
||||
assert len(cached.messages) == 1
|
||||
assert "title" not in cached.metadata
|
||||
assert manager.read_session_snapshot(draft.key).messages == cached.messages
|
||||
await state.aclose()
|
||||
|
||||
|
||||
async def test_truncation_and_summary_keep_storage_and_cache_in_sync(tmp_path):
|
||||
manager = SessionManager(tmp_path)
|
||||
state = manager.state
|
||||
draft = await state.import_messages("chat:a", [
|
||||
{"role": "user", "content": str(i)} for i in range(5)
|
||||
])
|
||||
draft.messages = draft.messages[:3]
|
||||
await state.finish_turn(draft)
|
||||
await state.commit_summary(draft, "summary", archive_end=2)
|
||||
current = await state.get(draft.key)
|
||||
await state.update_metadata(draft.key, {"title": "after summary"})
|
||||
stored = manager.read_session_snapshot(draft.key)
|
||||
assert len(stored.messages) == 4
|
||||
assert stored.last_archived == current.last_archived == 2
|
||||
assert stored.messages == current.messages == state.peek(draft.key).messages
|
||||
await state.aclose()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("transient", [False, True])
|
||||
async def test_metadata_callback_result_is_detached(tmp_path, transient):
|
||||
state = SessionManager(tmp_path).state
|
||||
if transient:
|
||||
await state.register_transient("chat:a")
|
||||
else:
|
||||
await state.get("chat:a")
|
||||
shared = {"nested": ["saved"]}
|
||||
|
||||
def change(metadata):
|
||||
metadata["custom"] = shared
|
||||
return shared
|
||||
|
||||
result, metadata = await state.mutate_metadata("chat:a", change)
|
||||
result["nested"].append("result mutation")
|
||||
metadata["custom"]["nested"].append("metadata mutation")
|
||||
shared["nested"].append("callback mutation")
|
||||
assert state.peek("chat:a").metadata["custom"] == {"nested": ["saved"]}
|
||||
assert (await state.get("chat:a")).metadata["custom"] == {"nested": ["saved"]}
|
||||
await state.aclose()
|
||||
|
||||
|
||||
async def test_owner_reuses_worker_connections_and_closes_them_after_drain(tmp_path, monkeypatch):
|
||||
manager = SessionManager(tmp_path)
|
||||
connections = []
|
||||
closed = []
|
||||
original_connect = sqlite3.connect
|
||||
|
||||
class TrackedConnection(sqlite3.Connection):
|
||||
def execute(self, *args, **kwargs):
|
||||
assert threading.get_ident() == self.owner_thread
|
||||
return super().execute(*args, **kwargs)
|
||||
|
||||
def close(self):
|
||||
closed.append((id(self), threading.get_ident()))
|
||||
return super().close()
|
||||
|
||||
def connect(*args, **kwargs):
|
||||
connection = original_connect(*args, **kwargs, factory=TrackedConnection)
|
||||
connection.owner_thread = threading.get_ident()
|
||||
connections.append((id(connection), threading.get_ident()))
|
||||
return connection
|
||||
|
||||
monkeypatch.setattr(sqlite3, "connect", connect)
|
||||
state = manager.state
|
||||
await state.get("chat:a")
|
||||
await state.update_metadata("chat:a", {"title": "new"})
|
||||
await state.get("chat:a")
|
||||
assert len(connections) == 2
|
||||
assert all(thread_id != threading.get_ident() for _, thread_id in connections)
|
||||
assert closed == []
|
||||
await asyncio.gather(state.aclose(), state.aclose())
|
||||
assert {identifier for identifier, _ in closed} == {identifier for identifier, _ in connections}
|
||||
assert len(closed) == len(connections)
|
||||
assert all(thread_id != threading.get_ident() for _, thread_id in closed)
|
||||
@@ -1,66 +1,11 @@
|
||||
"""Tests for retired legacy session storage paths."""
|
||||
|
||||
import json
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
"""Completed migration makes legacy JSONL files inert."""
|
||||
|
||||
from nanobot.session.manager import SessionManager
|
||||
|
||||
|
||||
def test_list_sessions_ignores_legacy_stem(tmp_path: Path) -> None:
|
||||
manager = SessionManager(tmp_path / "workspace")
|
||||
|
||||
# A legacy lossy-path filename must not be treated as current session storage,
|
||||
# even when the file contains otherwise recoverable records.
|
||||
legacy_stem = "telegram_12345"
|
||||
corrupt_path = manager.sessions_dir / f"{legacy_stem}.jsonl"
|
||||
corrupt_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
metadata = json.dumps({
|
||||
"_type": "metadata",
|
||||
"key": "telegram:12345",
|
||||
"created_at": datetime(2025, 1, 1).isoformat(),
|
||||
"updated_at": datetime(2025, 1, 1).isoformat(),
|
||||
})
|
||||
corrupt_path.write_text(
|
||||
metadata + "\n{INVALID JSON LINE\n"
|
||||
+ json.dumps({"role": "user", "content": "recoverable message"}) + "\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
sessions = manager.list_sessions()
|
||||
|
||||
assert sessions == []
|
||||
assert corrupt_path.exists()
|
||||
|
||||
|
||||
def test_read_session_methods_ignore_legacy_lossy_stem(
|
||||
tmp_path: Path,
|
||||
monkeypatch,
|
||||
) -> None:
|
||||
monkeypatch.setattr(
|
||||
"nanobot.session.manager.get_legacy_sessions_dir",
|
||||
lambda: tmp_path / "legacy_sessions",
|
||||
)
|
||||
manager = SessionManager(tmp_path / "workspace")
|
||||
session_id = "123e4567-e89b-12d3-a456-426614174000"
|
||||
key = f"websocket:{session_id}"
|
||||
legacy_path = manager._get_legacy_lossy_path(key)
|
||||
assert legacy_path.name == f"websocket_{session_id}.jsonl"
|
||||
|
||||
metadata = {
|
||||
"_type": "metadata",
|
||||
"key": key,
|
||||
"created_at": datetime(2025, 1, 1).isoformat(),
|
||||
"updated_at": datetime(2025, 1, 1).isoformat(),
|
||||
"metadata": {
|
||||
"workspace_scope": "project",
|
||||
"project_path": "/tmp/example-project",
|
||||
},
|
||||
}
|
||||
legacy_path.write_text(json.dumps(metadata) + "\n", encoding="utf-8")
|
||||
|
||||
metadata_result = manager.read_session_metadata(key)
|
||||
file_result = manager.read_session_file(key)
|
||||
|
||||
assert metadata_result is None
|
||||
assert file_result is None
|
||||
def test_list_and_reads_ignore_files_created_after_migration(tmp_path):
|
||||
manager = SessionManager(tmp_path)
|
||||
(manager.sessions_dir / "cli_test.jsonl").write_text("invalid JSON")
|
||||
assert manager.list_sessions() == []
|
||||
assert manager.read_session_metadata("cli:test") is None
|
||||
assert manager.read_session_file("cli:test") is None
|
||||
@@ -8,12 +8,13 @@ import shutil
|
||||
import subprocess
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
|
||||
from nanobot.config.loader import load_config
|
||||
from nanobot.session.manager import JsonlSessionStore, SessionManager
|
||||
from nanobot.session.jsonl_migration import WORKSPACE_BACKUP_DIR
|
||||
from nanobot.session.location import SessionLocation
|
||||
from nanobot.session.manager import SessionManager
|
||||
|
||||
|
||||
def _write_legacy_session(
|
||||
@@ -25,7 +26,7 @@ def _write_legacy_session(
|
||||
) -> Path:
|
||||
"""Write a valid session file in the legacy in-workspace location."""
|
||||
old_dir.mkdir(parents=True, exist_ok=True)
|
||||
path = old_dir / f"{JsonlSessionStore.storage_key(key)}.jsonl"
|
||||
path = old_dir / f"{SessionLocation.storage_key(key)}.jsonl"
|
||||
path.write_text(
|
||||
json.dumps(
|
||||
{
|
||||
@@ -126,7 +127,7 @@ def test_sessions_follow_active_custom_config_data_root(
|
||||
manager.save(session)
|
||||
|
||||
assert manager.sessions_dir.parent == custom_instance / "sessions"
|
||||
assert manager._get_session_path(session.key).exists()
|
||||
assert (manager.sessions_dir / "sessions.sqlite3").exists()
|
||||
assert not (default_home / ".nanobot" / "sessions").exists()
|
||||
|
||||
|
||||
@@ -220,126 +221,43 @@ def test_equivalent_workspace_paths_share_one_store(tmp_path: Path) -> None:
|
||||
assert via_link.messages[-1]["content"] == "via-real"
|
||||
|
||||
|
||||
def test_legacy_in_workspace_sessions_are_migrated(tmp_path: Path) -> None:
|
||||
def test_migration_rejects_symlinked_session_file(tmp_path, create_symlink):
|
||||
workspace = tmp_path / "workspace"
|
||||
key = "telegram:1"
|
||||
old_file = _write_legacy_session(workspace / "sessions", key, "migrated-msg")
|
||||
|
||||
manager = SessionManager(workspace=workspace)
|
||||
|
||||
# The session is readable through the normal store.
|
||||
loaded = manager.get_or_create(key)
|
||||
assert loaded.messages[-1]["content"] == "migrated-msg"
|
||||
# The legacy in-workspace file has been moved away...
|
||||
assert not old_file.exists()
|
||||
# ...into the out-of-workspace store.
|
||||
assert (manager.sessions_dir / old_file.name).exists()
|
||||
|
||||
# Migration is idempotent: a second construction must not corrupt anything.
|
||||
again = SessionManager(workspace=workspace).get_or_create(key)
|
||||
assert again.messages[-1]["content"] == "migrated-msg"
|
||||
path = _write_legacy_session(workspace / "sessions", "cli:test", "original")
|
||||
target = tmp_path / "outside.jsonl"
|
||||
path.rename(target)
|
||||
create_symlink(path, target)
|
||||
with pytest.raises(RuntimeError, match="migration failed"):
|
||||
SessionManager(workspace)
|
||||
assert "original" in target.read_text()
|
||||
|
||||
|
||||
def test_migration_keeps_source_when_install_fails(tmp_path: Path) -> None:
|
||||
def test_migration_rejects_symlinked_source_directory(tmp_path, create_symlink):
|
||||
workspace = tmp_path / "workspace"
|
||||
key = "telegram:partial"
|
||||
old_file = _write_legacy_session(workspace / "sessions", key, "still-safe")
|
||||
|
||||
with patch.object(JsonlSessionStore, "_install_snapshot", side_effect=OSError("disk full")):
|
||||
manager = SessionManager(workspace=workspace)
|
||||
|
||||
assert old_file.exists()
|
||||
assert not (manager.sessions_dir / old_file.name).exists()
|
||||
|
||||
retried = SessionManager(workspace=workspace)
|
||||
assert retried.get_or_create(key).messages[-1]["content"] == "still-safe"
|
||||
assert not old_file.exists()
|
||||
|
||||
|
||||
def test_migration_preserves_newest_valid_conflict(tmp_path: Path) -> None:
|
||||
workspace = tmp_path / "workspace"
|
||||
key = "telegram:conflict"
|
||||
old_file = _write_legacy_session(workspace / "sessions", key, "newer-workspace")
|
||||
manager = SessionManager(workspace=workspace)
|
||||
|
||||
# Recreate an older legacy source while a newer destination already exists.
|
||||
manager_session = manager.get_or_create(key)
|
||||
manager_session.add_message("assistant", "newer-destination")
|
||||
manager.save(manager_session)
|
||||
_write_legacy_session(
|
||||
workspace / "sessions",
|
||||
key,
|
||||
"older-workspace",
|
||||
updated_at="2025-01-01T00:00:00",
|
||||
)
|
||||
|
||||
retried = SessionManager(workspace=workspace)
|
||||
loaded = retried.get_or_create(key)
|
||||
|
||||
assert loaded.messages[-1]["content"] == "newer-destination"
|
||||
conflicts = list((retried.sessions_dir / ".migration-conflicts").glob("*.jsonl"))
|
||||
assert len(conflicts) == 1
|
||||
assert "older-workspace" in conflicts[0].read_text(encoding="utf-8")
|
||||
assert not old_file.exists()
|
||||
|
||||
|
||||
def test_explicit_rollback_restore_copies_sessions_back_without_deleting_new_store(
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
workspace = tmp_path / "workspace"
|
||||
manager = SessionManager(workspace=workspace)
|
||||
session = manager.get_or_create("telegram:rollback")
|
||||
session.add_message("user", "available-to-old-version")
|
||||
manager.save(session, fsync=True)
|
||||
|
||||
result = manager.restore_sessions_to_workspace()
|
||||
legacy_file = workspace / "sessions" / manager._get_session_path(session.key).name
|
||||
|
||||
assert result.restored == 1
|
||||
assert result.unchanged == 0
|
||||
assert result.conflicts == ()
|
||||
assert legacy_file.exists()
|
||||
assert manager._get_session_path(session.key).exists()
|
||||
assert "available-to-old-version" in legacy_file.read_text(encoding="utf-8")
|
||||
|
||||
repeated = manager.restore_sessions_to_workspace()
|
||||
assert repeated.restored == 0
|
||||
assert repeated.unchanged == 1
|
||||
assert repeated.conflicts == ()
|
||||
|
||||
|
||||
def test_legacy_migration_rejects_symlinked_session_file(tmp_path: Path) -> None:
|
||||
workspace = tmp_path / "workspace"
|
||||
old_dir = workspace / "sessions"
|
||||
old_dir.mkdir(parents=True)
|
||||
key = "telegram:symlink"
|
||||
outside = _write_legacy_session(tmp_path / "outside", key, "outside-secret")
|
||||
source = old_dir / outside.name
|
||||
try:
|
||||
source.symlink_to(outside)
|
||||
except OSError as exc:
|
||||
pytest.skip(f"file symlink unavailable: {exc}")
|
||||
|
||||
manager = SessionManager(workspace=workspace)
|
||||
|
||||
assert source.is_symlink()
|
||||
assert not (manager.sessions_dir / source.name).exists()
|
||||
assert manager.get_or_create(key).messages == []
|
||||
|
||||
|
||||
def test_legacy_migration_rejects_symlinked_sessions_directory(tmp_path: Path) -> None:
|
||||
workspace = tmp_path / "workspace"
|
||||
outside = tmp_path / "outside"
|
||||
key = "telegram:directory-symlink"
|
||||
outside_file = _write_legacy_session(outside, key, "outside-secret")
|
||||
workspace.mkdir()
|
||||
try:
|
||||
(workspace / "sessions").symlink_to(outside, target_is_directory=True)
|
||||
except OSError as exc:
|
||||
pytest.skip(f"directory symlink unavailable: {exc}")
|
||||
outside = tmp_path / "outside"
|
||||
outside.mkdir()
|
||||
create_symlink(workspace / "sessions", outside, target_is_directory=True)
|
||||
with pytest.raises(ValueError, match="symlink"):
|
||||
SessionManager(workspace)
|
||||
|
||||
manager = SessionManager(workspace=workspace)
|
||||
|
||||
assert outside_file.exists()
|
||||
assert not (manager.sessions_dir / outside_file.name).exists()
|
||||
assert manager.get_or_create(key).messages == []
|
||||
def test_workspace_migration_rejects_symlinked_backup_directory(tmp_path, create_symlink):
|
||||
workspace = tmp_path / "workspace"
|
||||
root = tmp_path / "root"
|
||||
source = _write_legacy_session(workspace / "sessions", "cli:test", "original")
|
||||
original = source.read_bytes()
|
||||
location = SessionLocation(workspace, sessions_root=root)
|
||||
outside = tmp_path / "outside"
|
||||
outside.mkdir()
|
||||
backup = location.sessions_dir / WORKSPACE_BACKUP_DIR
|
||||
create_symlink(backup, outside, target_is_directory=True)
|
||||
|
||||
with pytest.raises(RuntimeError, match="Could not move legacy sessions"):
|
||||
SessionManager(workspace, sessions_root=root)
|
||||
assert source.read_bytes() == original
|
||||
assert list(outside.iterdir()) == []
|
||||
backup.unlink()
|
||||
manager = SessionManager(workspace, sessions_root=root)
|
||||
assert not source.exists()
|
||||
assert (manager.sessions_dir / WORKSPACE_BACKUP_DIR / source.name).read_bytes() == original
|
||||
@@ -1,210 +1,98 @@
|
||||
from unittest.mock import MagicMock
|
||||
"""Administrative SQLite repository operations."""
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
from nanobot.providers.base import ProviderConversationState
|
||||
from nanobot.session import Session, SessionManager
|
||||
from nanobot.session.manager import SessionStore
|
||||
from nanobot.session.manager import Session, SessionManager
|
||||
from nanobot.session.model_selection import SESSION_MODEL_PRESET_METADATA_KEY
|
||||
from nanobot.session.types import PARENT_SESSION_KEY, SESSION_TYPE_KEY
|
||||
|
||||
|
||||
def test_manager_delegates_persistence_to_store(tmp_path) -> None:
|
||||
stored = Session(key="cli:test")
|
||||
stored.add_message("user", "hello")
|
||||
payload = {
|
||||
"key": stored.key,
|
||||
"created_at": stored.created_at.isoformat(),
|
||||
"updated_at": stored.updated_at.isoformat(),
|
||||
"metadata": {},
|
||||
"messages": stored.messages,
|
||||
def test_manager_roundtrips_full_history_and_private_state(tmp_path):
|
||||
manager = SessionManager(tmp_path)
|
||||
session = Session(key="cli:test", messages=[{"role": "user", "content": str(i)} for i in range(2001)])
|
||||
session.provider_state = ProviderConversationState(kind="openai_responses", provider="openai:test",
|
||||
model="test-model", version=1, payload={"response_id": "private"})
|
||||
manager.save(session)
|
||||
loaded = manager.read_session_snapshot(session.key)
|
||||
assert loaded is not session
|
||||
assert loaded.messages == session.messages
|
||||
assert loaded.provider_state == session.provider_state
|
||||
assert "provider_state" not in manager.read_session_file(session.key)
|
||||
assert manager.list_sessions()[0]["preview"] == "0"
|
||||
|
||||
|
||||
def test_rename_model_preset_is_atomic(tmp_path, monkeypatch):
|
||||
manager = SessionManager(tmp_path)
|
||||
for key in ("cli:one", "cli:two"):
|
||||
manager.save(Session(key=key, metadata={SESSION_MODEL_PRESET_METADATA_KEY: "old"}))
|
||||
original = manager._store.update_metadata
|
||||
def fail_second(key, values, **kwargs):
|
||||
if key == "cli:two":
|
||||
raise OSError("disk full")
|
||||
return original(key, values, **kwargs)
|
||||
import pytest
|
||||
with monkeypatch.context() as patch:
|
||||
patch.setattr(manager._store, "update_metadata", fail_second)
|
||||
with pytest.raises(OSError):
|
||||
manager.rename_model_preset("old", "new")
|
||||
assert all(manager.get_or_create(key).metadata[SESSION_MODEL_PRESET_METADATA_KEY] == "old"
|
||||
for key in ("cli:one", "cli:two"))
|
||||
assert manager.rename_model_preset("old", "new") == 2
|
||||
assert all(manager.get_or_create(key).metadata[SESSION_MODEL_PRESET_METADATA_KEY] == "new"
|
||||
for key in ("cli:one", "cli:two"))
|
||||
|
||||
|
||||
def test_metadata_updates_do_not_replace_messages(tmp_path):
|
||||
manager = SessionManager(tmp_path)
|
||||
manager.save(Session(key="cli:test", messages=[{"role": "user", "content": "hello"}]))
|
||||
assert manager.update_session_metadata("cli:test", {"title": "new"})
|
||||
assert manager.read_session_file("cli:test")["messages"] == [{"role": "user", "content": "hello"}]
|
||||
assert manager.read_session_metadata("cli:test")["metadata"]["title"] == "new"
|
||||
assert not manager.update_session_metadata("cli:missing", {"title": "x"})
|
||||
assert manager.delete_session("cli:test")
|
||||
assert manager.read_session_file("cli:test") is None
|
||||
|
||||
|
||||
def test_child_headers_select_declared_children_and_preserve_descendant_deletion(tmp_path, monkeypatch):
|
||||
manager = SessionManager(tmp_path)
|
||||
parent = "chat:项目'\"\\root"
|
||||
manager.save(Session(key=parent))
|
||||
manager.save(Session(key="chat:unrelated", metadata={"title": "unrelated"}))
|
||||
for key, kind, parent_key, second in (
|
||||
("subagent:first", "subagent", parent, 1),
|
||||
("extension:child", "extension", parent, 2),
|
||||
("extension:grandchild", "extension", "extension:child", 3),
|
||||
):
|
||||
manager.save(Session(
|
||||
key=key, updated_at=datetime(2026, 1, 1, 0, 0, second),
|
||||
messages=[{"role": "user", "content": "private transcript"}],
|
||||
metadata={
|
||||
PARENT_SESSION_KEY: parent_key, SESSION_TYPE_KEY: kind,
|
||||
"nested": {"value": key}, "runtime_checkpoint": {"step": 1},
|
||||
"pending_user_followups": [{"id": "queued"}],
|
||||
},
|
||||
))
|
||||
|
||||
def prohibit_full_listing():
|
||||
raise AssertionError("child queries must not materialize unrelated session headers")
|
||||
|
||||
monkeypatch.setattr(manager._store, "list_metadata", prohibit_full_listing)
|
||||
assert manager.child_session_keys(parent) == ["extension:child", "subagent:first"]
|
||||
rows = manager.list_child_session_metadata(parent)
|
||||
assert [row["key"] for row in rows] == ["extension:child", "subagent:first"]
|
||||
assert rows[0]["updated_at"] == "2026-01-01T00:00:02"
|
||||
assert rows[0]["metadata"] == {
|
||||
PARENT_SESSION_KEY: parent, SESSION_TYPE_KEY: "extension",
|
||||
"nested": {"value": "extension:child"},
|
||||
}
|
||||
metadata = {
|
||||
"key": stored.key,
|
||||
"created_at": stored.created_at.isoformat(),
|
||||
"updated_at": stored.updated_at.isoformat(),
|
||||
"metadata": {},
|
||||
}
|
||||
listing = [
|
||||
{
|
||||
"key": stored.key,
|
||||
"created_at": stored.created_at.isoformat(),
|
||||
"updated_at": stored.updated_at.isoformat(),
|
||||
"title": "",
|
||||
"preview": "hello",
|
||||
"path": "session.db",
|
||||
}
|
||||
]
|
||||
store = MagicMock(spec=SessionStore)
|
||||
store.load.return_value = stored
|
||||
store.read.return_value = payload
|
||||
store.read_metadata.return_value = metadata
|
||||
store.list_sessions.return_value = listing
|
||||
store.delete.return_value = True
|
||||
manager = SessionManager(tmp_path, store=store)
|
||||
rows[0]["metadata"]["nested"]["value"] = "detached edit"
|
||||
assert manager.list_child_session_metadata(parent)[0]["metadata"]["nested"]["value"] == "extension:child"
|
||||
assert manager.read_session_metadata("extension:child")["metadata"]["runtime_checkpoint"] == {"step": 1}
|
||||
|
||||
assert manager.get_or_create(stored.key) is stored
|
||||
assert manager.get_or_create(stored.key) is stored
|
||||
store.load.assert_called_once_with(stored.key)
|
||||
|
||||
manager.save(stored, fsync=True)
|
||||
store.save.assert_called_once_with(stored, fsync=True)
|
||||
assert manager.read_session_file(stored.key) == payload
|
||||
assert manager.read_session_metadata(stored.key) == metadata
|
||||
assert manager.list_sessions() == listing
|
||||
|
||||
assert manager.delete_session(stored.key) is True
|
||||
store.delete.assert_called_once_with(stored.key)
|
||||
assert manager.get_cached(stored.key) is None
|
||||
|
||||
|
||||
def test_manager_renames_model_preset_in_live_and_persisted_sessions(tmp_path) -> None:
|
||||
workspace = tmp_path / "workspace"
|
||||
sessions_root = tmp_path / "sessions"
|
||||
manager = SessionManager(workspace, sessions_root=sessions_root)
|
||||
selected = manager.get_or_create("websocket:selected")
|
||||
selected.metadata[SESSION_MODEL_PRESET_METADATA_KEY] = "openai"
|
||||
manager.save(selected)
|
||||
other = manager.get_or_create("websocket:other")
|
||||
other.metadata[SESSION_MODEL_PRESET_METADATA_KEY] = "backup"
|
||||
manager.save(other)
|
||||
transient = manager.get_or_create_transient("websocket:temporary")
|
||||
transient.metadata[SESSION_MODEL_PRESET_METADATA_KEY] = "openai"
|
||||
|
||||
assert manager.rename_model_preset("openai", "Codex") == 2
|
||||
assert selected.metadata[SESSION_MODEL_PRESET_METADATA_KEY] == "Codex"
|
||||
assert transient.metadata[SESSION_MODEL_PRESET_METADATA_KEY] == "Codex"
|
||||
|
||||
reloaded = SessionManager(workspace, sessions_root=sessions_root)
|
||||
assert (
|
||||
reloaded.get_or_create("websocket:selected").metadata[
|
||||
SESSION_MODEL_PRESET_METADATA_KEY
|
||||
]
|
||||
== "Codex"
|
||||
)
|
||||
assert (
|
||||
reloaded.get_or_create("websocket:other").metadata[
|
||||
SESSION_MODEL_PRESET_METADATA_KEY
|
||||
]
|
||||
== "backup"
|
||||
)
|
||||
|
||||
|
||||
def test_read_session_snapshot_does_not_populate_runtime_cache(tmp_path) -> None:
|
||||
stored = Session(key="websocket:context")
|
||||
store = MagicMock(spec=SessionStore)
|
||||
store.load.return_value = stored
|
||||
manager = SessionManager(tmp_path, store=store)
|
||||
|
||||
assert manager.read_session_snapshot(stored.key) is stored
|
||||
assert manager.get_cached(stored.key) is None
|
||||
store.load.assert_called_once_with(stored.key)
|
||||
|
||||
|
||||
def test_manager_preserves_full_session_before_store_save(tmp_path) -> None:
|
||||
store = MagicMock(spec=SessionStore)
|
||||
manager = SessionManager(tmp_path, store=store)
|
||||
session = Session(
|
||||
key="cli:large",
|
||||
messages=[
|
||||
{
|
||||
"role": "user" if index % 2 == 0 else "assistant",
|
||||
"content": str(index),
|
||||
}
|
||||
for index in range(2_001)
|
||||
],
|
||||
)
|
||||
|
||||
manager.save(session)
|
||||
|
||||
assert len(session.messages) == 2_001
|
||||
assert session.messages[0]["content"] == "0"
|
||||
assert session.messages[-1]["content"] == "2000"
|
||||
store.save.assert_called_once_with(session, fsync=False)
|
||||
|
||||
|
||||
def test_runtime_checkpoint_does_not_rewrite_long_session(tmp_path) -> None:
|
||||
manager = SessionManager(tmp_path)
|
||||
session = manager.get_or_create("websocket:long")
|
||||
for index in range(256):
|
||||
session.add_message("user", f"{index}:" + "x" * 4096)
|
||||
manager.save(session)
|
||||
|
||||
main_path = manager._get_session_path(session.key)
|
||||
main_before = main_path.read_bytes()
|
||||
stat_before = main_path.stat()
|
||||
session.metadata["runtime_checkpoint"] = {
|
||||
"phase": "tools_completed",
|
||||
"assistant_message": {"role": "assistant", "content": "working"},
|
||||
"completed_tool_results": [],
|
||||
"pending_tool_calls": [],
|
||||
}
|
||||
session.provider_state = ProviderConversationState(
|
||||
kind="openai_responses",
|
||||
provider="openai:test",
|
||||
model="test-model",
|
||||
version=1,
|
||||
payload={"response_id": "private-response"},
|
||||
)
|
||||
|
||||
manager.save_runtime_checkpoint(session)
|
||||
|
||||
checkpoint_path = manager._get_runtime_checkpoint_path(session.key)
|
||||
assert main_path.read_bytes() == main_before
|
||||
assert main_path.stat().st_ino == stat_before.st_ino
|
||||
assert main_path.stat().st_mtime_ns == stat_before.st_mtime_ns
|
||||
assert checkpoint_path.stat().st_size < len(main_before) // 100
|
||||
|
||||
restored = SessionManager(tmp_path).get_or_create(session.key)
|
||||
assert restored.metadata["runtime_checkpoint"]["phase"] == "tools_completed"
|
||||
assert restored.provider_state is not None
|
||||
assert restored.provider_state.payload == {"response_id": "private-response"}
|
||||
|
||||
|
||||
def test_completed_session_supersedes_stale_checkpoint(tmp_path) -> None:
|
||||
manager = SessionManager(tmp_path)
|
||||
session = manager.get_or_create("websocket:completed")
|
||||
session.add_message("user", "question")
|
||||
manager.save(session)
|
||||
session.metadata["runtime_checkpoint"] = {"phase": "awaiting_tools"}
|
||||
manager.save_runtime_checkpoint(session)
|
||||
checkpoint_path = manager._get_runtime_checkpoint_path(session.key)
|
||||
stale_checkpoint = checkpoint_path.read_bytes()
|
||||
|
||||
session.metadata.pop("runtime_checkpoint")
|
||||
session.add_message("assistant", "answer")
|
||||
manager.save(session)
|
||||
assert not checkpoint_path.exists()
|
||||
|
||||
# Emulate a process dying after the main record was committed but before an
|
||||
# obsolete sidecar could be removed. The base fingerprint keeps it stale.
|
||||
checkpoint_path.write_bytes(stale_checkpoint)
|
||||
restored = SessionManager(tmp_path).get_or_create(session.key)
|
||||
assert "runtime_checkpoint" not in restored.metadata
|
||||
assert restored.messages[-1]["content"] == "answer"
|
||||
assert not checkpoint_path.exists()
|
||||
|
||||
|
||||
def test_delete_session_removes_runtime_checkpoint(tmp_path) -> None:
|
||||
manager = SessionManager(tmp_path)
|
||||
session = manager.get_or_create("websocket:delete")
|
||||
session.add_message("user", "question")
|
||||
manager.save(session)
|
||||
session.metadata["runtime_checkpoint"] = {"phase": "awaiting_tools"}
|
||||
manager.save_runtime_checkpoint(session)
|
||||
checkpoint_path = manager._get_runtime_checkpoint_path(session.key)
|
||||
assert checkpoint_path.exists()
|
||||
|
||||
assert manager.delete_session(session.key) is True
|
||||
assert not checkpoint_path.exists()
|
||||
|
||||
|
||||
def test_invalid_runtime_checkpoint_is_discarded(tmp_path) -> None:
|
||||
manager = SessionManager(tmp_path)
|
||||
session = manager.get_or_create("websocket:invalid-checkpoint")
|
||||
session.add_message("user", "question")
|
||||
manager.save(session)
|
||||
checkpoint_path = manager._get_runtime_checkpoint_path(session.key)
|
||||
checkpoint_path.write_text("{truncated", encoding="utf-8")
|
||||
|
||||
restored = SessionManager(tmp_path).get_or_create(session.key)
|
||||
|
||||
assert "runtime_checkpoint" not in restored.metadata
|
||||
assert not checkpoint_path.exists()
|
||||
deleted = []
|
||||
manager.set_delete_observer(deleted.append)
|
||||
assert manager.delete_session(parent)
|
||||
assert set(deleted) == {parent, "subagent:first", "extension:child", "extension:grandchild"}
|
||||
assert [row["key"] for row in manager.list_sessions()] == ["chat:unrelated"]
|
||||
assert manager.list_child_session_metadata(parent) == []
|
||||
@@ -0,0 +1,236 @@
|
||||
"""Session schema upgrades preserve records and fail atomically."""
|
||||
|
||||
import json
|
||||
import sqlite3
|
||||
from contextlib import closing
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
import nanobot.session.sqlite_store as sqlite_store
|
||||
from nanobot.providers.base import ProviderConversationState
|
||||
from nanobot.session.manager import Session
|
||||
from nanobot.session.sqlite_store import SqliteSessionStore
|
||||
|
||||
|
||||
def _session() -> Session:
|
||||
return Session(
|
||||
key="chat:extensions",
|
||||
messages=[{"role": "user", "content": "hello", "extension": {"source": "import"}}],
|
||||
metadata={
|
||||
"title": "Extended session",
|
||||
"extension": {"enabled": True},
|
||||
"runtime_checkpoint": {
|
||||
"phase": "final_response", "iteration": 1, "model": "gpt-test",
|
||||
"assistant_message": {"role": "assistant", "content": "checkpoint answer"},
|
||||
"completed_tool_results": [], "pending_tool_calls": [], "extension": {"step": 2},
|
||||
},
|
||||
"pending_user_followups": [{
|
||||
"id": "followup", "sender_id": "user", "chat_id": "extensions", "content": "next",
|
||||
"media": [], "metadata": {}, "extension": True,
|
||||
}],
|
||||
},
|
||||
provider_state=ProviderConversationState(
|
||||
kind="openai_responses", provider="openai", model="gpt-test", version=1,
|
||||
payload={"items": [], "extension": {"cursor": "opaque"}},
|
||||
pending_messages=[{"role": "assistant", "content": "pending", "extension": True}],
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def _write_legacy(workspace: Path, session: Session) -> Path:
|
||||
directory = workspace / "sessions"
|
||||
directory.mkdir(parents=True)
|
||||
path = directory / "session.jsonl"
|
||||
assert session.provider_state is not None
|
||||
records = [
|
||||
{"_type": "metadata", "key": session.key, "metadata": session.metadata,
|
||||
"created_at": session.created_at.isoformat(), "updated_at": session.updated_at.isoformat(),
|
||||
"last_archived": session.last_archived},
|
||||
{"_type": "provider_state", "state": session.provider_state.to_private_record()},
|
||||
*session.messages,
|
||||
]
|
||||
path.write_text("\n".join(json.dumps(record) for record in records) + "\n", encoding="utf-8")
|
||||
return path
|
||||
|
||||
|
||||
def _database_snapshot(path: Path) -> tuple[int, str, str]:
|
||||
with closing(sqlite3.connect(path)) as db:
|
||||
return (
|
||||
db.execute("PRAGMA user_version").fetchone()[0],
|
||||
db.execute("PRAGMA journal_mode").fetchone()[0],
|
||||
"\n".join(db.iterdump()),
|
||||
)
|
||||
|
||||
|
||||
def test_ordered_upgrades_preserve_records_and_do_not_repeat_import(tmp_path, monkeypatch):
|
||||
workspace = tmp_path / "workspace"
|
||||
original = _session()
|
||||
source = _write_legacy(workspace, original)
|
||||
store = SqliteSessionStore(tmp_path)
|
||||
with closing(sqlite3.connect(store.path)) as db:
|
||||
schema = Path(__file__).with_name("fixtures") / "sqlite_v1.sql"
|
||||
db.executescript(schema.read_text(encoding="utf-8"))
|
||||
store.save(original)
|
||||
assert _database_snapshot(store.path)[0] == 1
|
||||
|
||||
def add_archived(db: sqlite3.Connection) -> None:
|
||||
db.execute("ALTER TABLE sessions ADD COLUMN archived INTEGER NOT NULL DEFAULT 0")
|
||||
|
||||
def index_archived(db: sqlite3.Connection) -> None:
|
||||
db.execute("CREATE INDEX sessions_archived ON sessions(archived)")
|
||||
|
||||
monkeypatch.setattr(sqlite_store, "_SCHEMA_MIGRATIONS", (
|
||||
*sqlite_store._SCHEMA_MIGRATIONS, add_archived, index_archived,
|
||||
))
|
||||
source.write_text("stale malformed source must not be imported again", encoding="utf-8")
|
||||
upgraded = SqliteSessionStore(tmp_path)
|
||||
upgraded.initialize(workspace)
|
||||
assert _database_snapshot(store.path)[0] == 3
|
||||
loaded = upgraded.load(original.key)
|
||||
assert loaded is not None
|
||||
assert loaded.messages == original.messages
|
||||
assert loaded.metadata == original.metadata
|
||||
assert loaded.provider_state == original.provider_state
|
||||
upgraded.save(loaded)
|
||||
|
||||
reopened = SqliteSessionStore(tmp_path)
|
||||
reopened.initialize(workspace)
|
||||
roundtrip = reopened.load(original.key)
|
||||
assert roundtrip is not None
|
||||
assert roundtrip.messages == original.messages
|
||||
assert roundtrip.metadata == original.metadata
|
||||
assert roundtrip.provider_state == original.provider_state
|
||||
with closing(sqlite3.connect(store.path)) as db:
|
||||
assert db.execute("SELECT archived FROM sessions").fetchall() == [(0,)]
|
||||
assert db.execute("SELECT name FROM sqlite_master WHERE name='sessions_archived'").fetchone()
|
||||
assert db.execute("SELECT value FROM storage_meta WHERE key='jsonl_import'").fetchone() == ("complete",)
|
||||
|
||||
|
||||
def test_failed_upgrade_rolls_back_schema_version_and_records_then_can_retry(tmp_path, monkeypatch):
|
||||
workspace = tmp_path / "workspace"
|
||||
store = SqliteSessionStore(tmp_path)
|
||||
store.initialize(workspace)
|
||||
original = _session()
|
||||
store.save(original)
|
||||
before = _database_snapshot(store.path)
|
||||
migrations = sqlite_store._SCHEMA_MIGRATIONS
|
||||
|
||||
def add_archived(db: sqlite3.Connection) -> None:
|
||||
db.execute("ALTER TABLE sessions ADD COLUMN archived INTEGER NOT NULL DEFAULT 0")
|
||||
|
||||
def fail_upgrade(db: sqlite3.Connection) -> None:
|
||||
db.execute("UPDATE sessions SET title='partial migration'")
|
||||
db.execute("CREATE TABLE migration_partial (value TEXT)")
|
||||
raise RuntimeError("migration interrupted")
|
||||
|
||||
monkeypatch.setattr(sqlite_store, "_SCHEMA_MIGRATIONS", (
|
||||
*migrations, add_archived, fail_upgrade,
|
||||
))
|
||||
with pytest.raises(RuntimeError, match="migration interrupted"):
|
||||
store.initialize(workspace)
|
||||
assert _database_snapshot(store.path) == before
|
||||
|
||||
def complete_upgrade(db: sqlite3.Connection) -> None:
|
||||
db.execute("CREATE INDEX sessions_archived ON sessions(archived)")
|
||||
|
||||
monkeypatch.setattr(sqlite_store, "_SCHEMA_MIGRATIONS", (
|
||||
*migrations, add_archived, complete_upgrade,
|
||||
))
|
||||
store.initialize(workspace)
|
||||
assert _database_snapshot(store.path)[0] == 3
|
||||
loaded = store.load(original.key)
|
||||
assert loaded is not None
|
||||
assert loaded.messages == original.messages
|
||||
assert loaded.metadata == original.metadata
|
||||
assert loaded.provider_state == original.provider_state
|
||||
|
||||
|
||||
def test_added_columns_allow_import_and_all_session_write_paths(tmp_path, monkeypatch):
|
||||
def add_optional_columns(db: sqlite3.Connection) -> None:
|
||||
for table in ("storage_meta", "sessions", "messages", "checkpoints", "pending_inputs"):
|
||||
db.execute(f"ALTER TABLE {table} ADD COLUMN extension TEXT")
|
||||
db.execute(f"ALTER TABLE {table} ADD COLUMN format_version INTEGER NOT NULL DEFAULT 1")
|
||||
|
||||
monkeypatch.setattr(sqlite_store, "_SCHEMA_MIGRATIONS", (
|
||||
*sqlite_store._SCHEMA_MIGRATIONS, add_optional_columns,
|
||||
))
|
||||
workspace = tmp_path / "workspace"
|
||||
imported = _session()
|
||||
_write_legacy(workspace, imported)
|
||||
store = SqliteSessionStore(tmp_path)
|
||||
store.initialize(workspace)
|
||||
loaded = store.load(imported.key)
|
||||
assert loaded is not None
|
||||
assert loaded.messages == imported.messages
|
||||
assert loaded.metadata == imported.metadata
|
||||
assert loaded.provider_state == imported.provider_state
|
||||
|
||||
created = _session()
|
||||
created.key = "chat:new"
|
||||
store.save(created)
|
||||
created.add_message("assistant", "answer", extension={"keep": True})
|
||||
store.save(created, message_start=1)
|
||||
assert store.update_metadata(created.key, {"title": "Changed title"})
|
||||
current = store.load(created.key)
|
||||
assert current is not None
|
||||
current.metadata["runtime_checkpoint"]["extension"] = {"step": 3}
|
||||
store.save_runtime_checkpoint(current)
|
||||
store.replace_metadata(current.key, current.metadata)
|
||||
roundtrip = store.load(current.key)
|
||||
assert roundtrip is not None
|
||||
assert roundtrip.messages == created.messages
|
||||
assert roundtrip.metadata == current.metadata
|
||||
assert roundtrip.provider_state == current.provider_state
|
||||
with closing(sqlite3.connect(store.path)) as db:
|
||||
for table in ("storage_meta", "sessions", "messages", "checkpoints", "pending_inputs"):
|
||||
rows = db.execute(f"SELECT extension, format_version FROM {table}").fetchall()
|
||||
assert rows and all(row == (None, 1) for row in rows)
|
||||
|
||||
|
||||
def test_future_schema_is_rejected_without_modifying_database(tmp_path):
|
||||
workspace = tmp_path / "workspace"
|
||||
store = SqliteSessionStore(tmp_path)
|
||||
store.initialize(workspace)
|
||||
store.save(_session())
|
||||
future_version = len(sqlite_store._SCHEMA_MIGRATIONS) + 1
|
||||
with closing(sqlite3.connect(store.path)) as db:
|
||||
db.execute("PRAGMA journal_mode = DELETE")
|
||||
db.execute(f"PRAGMA user_version = {future_version}")
|
||||
before = _database_snapshot(store.path)
|
||||
before_bytes = store.path.read_bytes()
|
||||
before_files = {path.name for path in tmp_path.iterdir()}
|
||||
|
||||
with pytest.raises(RuntimeError, match=f"unsupported session database schema: {future_version}"):
|
||||
store.initialize(workspace)
|
||||
assert _database_snapshot(store.path) == before
|
||||
assert store.path.read_bytes() == before_bytes
|
||||
assert {path.name for path in tmp_path.iterdir()} == before_files
|
||||
|
||||
|
||||
def test_missing_sqlite_json_support_is_rejected_before_database_changes(tmp_path, monkeypatch):
|
||||
workspace = tmp_path / "workspace"
|
||||
store = SqliteSessionStore(tmp_path)
|
||||
store.initialize(workspace)
|
||||
store.save(_session())
|
||||
with closing(sqlite3.connect(store.path)) as db:
|
||||
db.execute("PRAGMA journal_mode = DELETE")
|
||||
before = _database_snapshot(store.path)
|
||||
before_bytes = store.path.read_bytes()
|
||||
native_connect = sqlite3.connect
|
||||
|
||||
class WithoutJson(sqlite3.Connection):
|
||||
def execute(self, sql, parameters=()):
|
||||
if "json_extract(" in sql:
|
||||
raise sqlite3.OperationalError("no such function: json_extract")
|
||||
return super().execute(sql, parameters)
|
||||
|
||||
def connect(*args, **kwargs):
|
||||
return native_connect(*args, factory=WithoutJson, **kwargs)
|
||||
|
||||
with monkeypatch.context() as patch:
|
||||
patch.setattr(sqlite3, "connect", connect)
|
||||
with pytest.raises(RuntimeError, match="requires SQLite JSON support"):
|
||||
store.initialize(workspace)
|
||||
assert _database_snapshot(store.path) == before
|
||||
assert store.path.read_bytes() == before_bytes
|
||||
@@ -0,0 +1,727 @@
|
||||
"""SQLite durability, migration, and asynchronous state ownership contracts."""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import shutil
|
||||
import sqlite3
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import tomllib
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from packaging.version import Version
|
||||
|
||||
import nanobot.session.jsonl_migration as jsonl_migration
|
||||
from nanobot.session.jsonl_migration import SUNSET_VERSION, WORKSPACE_BACKUP_DIR
|
||||
from nanobot.session.location import SessionLocation
|
||||
from nanobot.session.manager import Session, SessionManager
|
||||
from nanobot.session.sqlite_store import SessionConflictError
|
||||
|
||||
|
||||
def legacy(workspace: Path, key: str = "websocket:old", *, content: str = "hello") -> Path:
|
||||
directory = workspace / "sessions"
|
||||
directory.mkdir(parents=True, exist_ok=True)
|
||||
path = directory / f"{SessionLocation.storage_key(key)}.jsonl"
|
||||
path.write_text(json.dumps({"_type": "metadata", "key": key, "metadata": {"title": "old"},
|
||||
"last_archived": 0, "created_at": "2026-01-01T00:00:00",
|
||||
"updated_at": "2026-01-01T00:00:00"}) + "\n" +
|
||||
json.dumps({"role": "user", "content": content}) + "\n")
|
||||
return path
|
||||
|
||||
|
||||
def test_migration_must_be_removed_at_declared_sunset():
|
||||
version = tomllib.loads((Path(__file__).parents[2] / "pyproject.toml").read_text())["project"]["version"]
|
||||
assert SUNSET_VERSION == "0.5.0"
|
||||
assert Version(Version(version).base_version) < Version(SUNSET_VERSION), (
|
||||
"Remove jsonl_migration, its initialization hook, and migration-only tests before 0.5.0"
|
||||
)
|
||||
|
||||
|
||||
def test_import_is_once_and_private_sources_are_unchanged(tmp_path):
|
||||
workspace = tmp_path / "workspace"
|
||||
path = legacy(workspace)
|
||||
location = SessionLocation(workspace)
|
||||
path = path.replace(location.sessions_dir / path.name)
|
||||
original = path.read_bytes()
|
||||
manager = SessionManager(workspace)
|
||||
assert manager.read_session_snapshot("websocket:old").messages[0]["content"] == "hello"
|
||||
assert path.read_bytes() == original
|
||||
manager.delete_session("websocket:old")
|
||||
# Reopening must not resurrect deleted conversations, even if the source changes.
|
||||
path.write_text("broken legacy file")
|
||||
assert SessionManager(workspace).read_session_snapshot("websocket:old") is None
|
||||
|
||||
|
||||
def test_invalid_source_rolls_back_entire_migration(tmp_path):
|
||||
workspace = tmp_path / "workspace"
|
||||
path = legacy(workspace)
|
||||
original = path.read_bytes()
|
||||
bad = path.parent / "zz-invalid.jsonl"
|
||||
bad.write_text("not json")
|
||||
with pytest.raises(RuntimeError, match="migration failed"):
|
||||
SessionManager(workspace)
|
||||
assert path.read_bytes() == original
|
||||
bad.unlink()
|
||||
manager = SessionManager(workspace)
|
||||
assert len(manager.list_sessions()) == 1
|
||||
assert not path.exists()
|
||||
assert (manager.sessions_dir / WORKSPACE_BACKUP_DIR / path.name).read_bytes() == original
|
||||
|
||||
|
||||
def test_migration_preserves_checkpoint_and_pending_inputs(tmp_path):
|
||||
workspace = tmp_path / "workspace"
|
||||
path = legacy(workspace)
|
||||
checkpoint = {"version": 1, "session_key": "websocket:old", "base_message_count": 1,
|
||||
"base_updated_at": "2026-01-01T00:00:00", "checkpoint": {"messages": [{"role": "assistant", "content": "partial"}]},
|
||||
"provider_state": None}
|
||||
checkpoint_path = path.with_suffix(".checkpoint.json")
|
||||
checkpoint_path.write_text(json.dumps(checkpoint))
|
||||
original, original_checkpoint = path.read_bytes(), checkpoint_path.read_bytes()
|
||||
original_mtime, checkpoint_mtime = path.stat().st_mtime_ns, checkpoint_path.stat().st_mtime_ns
|
||||
manager = SessionManager(workspace)
|
||||
assert manager.get_or_create("websocket:old").metadata["runtime_checkpoint"] == checkpoint["checkpoint"]
|
||||
backup = manager.sessions_dir / WORKSPACE_BACKUP_DIR
|
||||
assert (backup / path.name).read_bytes() == original
|
||||
assert (backup / checkpoint_path.name).read_bytes() == original_checkpoint
|
||||
assert (backup / path.name).stat().st_mtime_ns == original_mtime
|
||||
assert (backup / checkpoint_path.name).stat().st_mtime_ns == checkpoint_mtime
|
||||
assert not path.exists() and not checkpoint_path.exists()
|
||||
|
||||
|
||||
async def test_workspace_migration_isolates_raw_private_records(tmp_path):
|
||||
from nanobot.agent.tools.filesystem import ReadFileTool
|
||||
from nanobot.agent.tools.sessions import ReadSessionTool
|
||||
from nanobot.providers.base import ProviderConversationState
|
||||
|
||||
workspace = tmp_path / "workspace"
|
||||
path = legacy(workspace)
|
||||
provider = ProviderConversationState(
|
||||
kind="openai_responses", provider="openai", model="gpt-test", version=1,
|
||||
payload={"items": [{"encrypted_content": "private-provider-state"}]},
|
||||
)
|
||||
with path.open("a", encoding="utf-8") as handle:
|
||||
handle.write(json.dumps({"_type": "provider_state", "state": provider.to_private_record()}) + "\n")
|
||||
handle.write(json.dumps({"role": "tool", "tool_call_id": "call", "content": "private-tool-output"}) + "\n")
|
||||
original = path.read_bytes()
|
||||
manager = SessionManager(workspace)
|
||||
backup = manager.sessions_dir / WORKSPACE_BACKUP_DIR / path.name
|
||||
assert not path.exists()
|
||||
assert backup.read_bytes() == original
|
||||
if sys.platform != "win32":
|
||||
assert backup.stat().st_mode & 0o777 == 0o600
|
||||
assert backup.parent.stat().st_mode & 0o777 == 0o700
|
||||
|
||||
public = await ReadSessionTool(manager).execute(session_key="websocket:old")
|
||||
assert "private-provider-state" not in public and "private-tool-output" not in public
|
||||
tool = ReadFileTool(workspace=workspace, allowed_dir=workspace, restrict_to_workspace=True)
|
||||
assert (await tool.execute(path=str(path))).is_error
|
||||
blocked = await tool.execute(path=str(backup))
|
||||
assert blocked.is_error and "outside allowed directory" in blocked
|
||||
manager.delete_session("websocket:old")
|
||||
assert SessionManager(workspace).read_session_snapshot("websocket:old") is None
|
||||
assert backup.read_bytes() == original
|
||||
|
||||
|
||||
def test_restart_finishes_workspace_isolation_after_import_commit(tmp_path, monkeypatch):
|
||||
workspace = tmp_path / "workspace"
|
||||
root = tmp_path / "root"
|
||||
path = legacy(workspace)
|
||||
original = path.read_bytes()
|
||||
location = SessionLocation(workspace, sessions_root=root)
|
||||
|
||||
def interrupted(*_args):
|
||||
raise RuntimeError("interrupted after import commit")
|
||||
|
||||
with monkeypatch.context() as patch:
|
||||
patch.setattr(jsonl_migration, "finish_workspace_migration", interrupted)
|
||||
with pytest.raises(RuntimeError, match="interrupted after import commit"):
|
||||
SessionManager(workspace, sessions_root=root)
|
||||
assert path.read_bytes() == original
|
||||
with sqlite3.connect(location.sessions_dir / "sessions.sqlite3") as db:
|
||||
assert db.execute("SELECT count(*) FROM sessions").fetchone()[0] == 1
|
||||
assert db.execute("SELECT value FROM storage_meta WHERE key='jsonl_import'").fetchone()[0] == "complete"
|
||||
|
||||
manager = SessionManager(workspace, sessions_root=root)
|
||||
assert len(manager.list_sessions()) == 1
|
||||
assert not path.exists()
|
||||
assert (manager.sessions_dir / WORKSPACE_BACKUP_DIR / path.name).read_bytes() == original
|
||||
|
||||
|
||||
def test_workspace_backup_failure_retains_sources_and_retries(tmp_path, monkeypatch):
|
||||
workspace = tmp_path / "workspace"
|
||||
path = legacy(workspace)
|
||||
original = path.read_bytes()
|
||||
|
||||
def failed_backup(*_args):
|
||||
raise OSError("backup storage unavailable")
|
||||
|
||||
with monkeypatch.context() as patch:
|
||||
patch.setattr(jsonl_migration, "_write_backup", failed_backup)
|
||||
with pytest.raises(RuntimeError, match="Could not move legacy sessions"):
|
||||
SessionManager(workspace)
|
||||
assert path.read_bytes() == original
|
||||
manager = SessionManager(workspace)
|
||||
assert not path.exists()
|
||||
assert (manager.sessions_dir / WORKSPACE_BACKUP_DIR / path.name).read_bytes() == original
|
||||
|
||||
|
||||
def test_restart_finishes_partial_workspace_source_removal(tmp_path, monkeypatch):
|
||||
workspace = tmp_path / "workspace"
|
||||
path = legacy(workspace)
|
||||
checkpoint_path = path.with_suffix(".checkpoint.json")
|
||||
checkpoint_path.write_text(json.dumps({"version": 1}))
|
||||
original, original_checkpoint = path.read_bytes(), checkpoint_path.read_bytes()
|
||||
original_unlink = Path.unlink
|
||||
|
||||
def interrupted_unlink(target, *args, **kwargs):
|
||||
if target == checkpoint_path:
|
||||
raise OSError("interrupted checkpoint removal")
|
||||
return original_unlink(target, *args, **kwargs)
|
||||
|
||||
with monkeypatch.context() as patch:
|
||||
patch.setattr(Path, "unlink", interrupted_unlink)
|
||||
with pytest.raises(RuntimeError, match="Could not move legacy sessions"):
|
||||
SessionManager(workspace)
|
||||
assert not path.exists()
|
||||
assert checkpoint_path.read_bytes() == original_checkpoint
|
||||
manager = SessionManager(workspace)
|
||||
assert len(manager.list_sessions()) == 1
|
||||
assert not checkpoint_path.exists()
|
||||
backup = manager.sessions_dir / WORKSPACE_BACKUP_DIR
|
||||
assert (backup / path.name).read_bytes() == original
|
||||
assert (backup / checkpoint_path.name).read_bytes() == original_checkpoint
|
||||
|
||||
|
||||
def test_restart_requires_durable_workspace_source_removal(tmp_path, monkeypatch):
|
||||
workspace = tmp_path / "workspace"
|
||||
path = legacy(workspace)
|
||||
original = path.read_bytes()
|
||||
original_sync = SessionLocation.fsync_directory
|
||||
|
||||
def unavailable_directory_sync(directory):
|
||||
if directory == path.parent:
|
||||
raise OSError("source directory flush unavailable")
|
||||
original_sync(directory)
|
||||
|
||||
with monkeypatch.context() as patch:
|
||||
patch.setattr(SessionLocation, "fsync_directory", staticmethod(unavailable_directory_sync))
|
||||
for _ in range(2):
|
||||
with pytest.raises(RuntimeError, match="Could not move legacy sessions"):
|
||||
SessionManager(workspace)
|
||||
assert not path.exists()
|
||||
manager = SessionManager(workspace)
|
||||
assert len(manager.list_sessions()) == 1
|
||||
assert (manager.sessions_dir / WORKSPACE_BACKUP_DIR / path.name).read_bytes() == original
|
||||
|
||||
|
||||
def test_stale_administrative_save_is_rejected(tmp_path):
|
||||
manager = SessionManager(tmp_path)
|
||||
session = Session(key="chat:a")
|
||||
manager.save(session)
|
||||
old = manager.get_or_create(session.key)
|
||||
session.add_message("user", "new")
|
||||
manager.save(session)
|
||||
old.add_message("user", "stale")
|
||||
with pytest.raises(SessionConflictError):
|
||||
manager.save(old)
|
||||
assert manager.get_or_create(session.key).messages[-1]["content"] == "new"
|
||||
|
||||
|
||||
def test_transaction_rolls_back_all_rows(tmp_path):
|
||||
manager = SessionManager(tmp_path)
|
||||
def write_then_fail() -> None:
|
||||
session = Session(key="chat:a", metadata={"runtime_checkpoint": {"step": 1}, "pending_user_followups": [{"id": "x"}]})
|
||||
session.add_message("user", "hello")
|
||||
manager.save(session)
|
||||
raise RuntimeError("injected failure")
|
||||
|
||||
with pytest.raises(RuntimeError):
|
||||
manager._store.run_write(write_then_fail)
|
||||
assert manager.list_sessions() == []
|
||||
with sqlite3.connect(manager.sessions_dir / "sessions.sqlite3") as db:
|
||||
for table in ("sessions", "messages", "checkpoints", "pending_inputs"):
|
||||
assert db.execute(f"SELECT count(*) FROM {table}").fetchone()[0] == 0
|
||||
|
||||
|
||||
async def test_metadata_updates_preserve_running_turn(tmp_path):
|
||||
manager = SessionManager(tmp_path)
|
||||
state = manager.state
|
||||
draft = await state.get("chat:a")
|
||||
draft.add_message("user", "hello")
|
||||
draft.metadata["pending_user_turn"] = True
|
||||
await state.prepare_input(draft)
|
||||
await state.update_metadata(draft.key, {"title": "new title"})
|
||||
draft.add_message("assistant", "answer")
|
||||
await state.finish_turn(draft)
|
||||
loaded = await state.get(draft.key)
|
||||
assert loaded.metadata["title"] == "new title"
|
||||
assert [row["content"] for row in loaded.messages] == ["hello", "answer"]
|
||||
assert "pending_user_turn" not in loaded.metadata
|
||||
await state.aclose()
|
||||
|
||||
|
||||
async def test_reset_rejects_late_result_and_checkpoint(tmp_path):
|
||||
state = SessionManager(tmp_path).state
|
||||
draft = await state.get("chat:a")
|
||||
draft.add_message("user", "hello")
|
||||
await state.prepare_input(draft)
|
||||
await state.reset(draft.key)
|
||||
draft.add_message("assistant", "late")
|
||||
with pytest.raises(SessionConflictError):
|
||||
await state.finish_turn(draft)
|
||||
with pytest.raises(SessionConflictError):
|
||||
await state.checkpoint_view(draft, {"step": 2})
|
||||
assert (await state.get(draft.key)).messages == []
|
||||
await state.aclose()
|
||||
|
||||
|
||||
async def test_detached_reads_do_not_publish_mutations(tmp_path):
|
||||
state = SessionManager(tmp_path).state
|
||||
await state.import_messages("chat:a", [{"role": "user", "content": "hello"}])
|
||||
draft = await state.get("chat:a")
|
||||
draft.messages[0]["content"] = "edited"
|
||||
draft.metadata["title"] = "unsaved"
|
||||
loaded = await state.get("chat:a")
|
||||
assert loaded.messages[0]["content"] == "hello"
|
||||
assert "title" not in loaded.metadata
|
||||
await state.aclose()
|
||||
|
||||
|
||||
async def test_checkpoint_does_not_rewrite_messages(tmp_path):
|
||||
manager = SessionManager(tmp_path)
|
||||
state = manager.state
|
||||
draft = await state.get("chat:a")
|
||||
draft.add_message("user", "hello")
|
||||
await state.prepare_input(draft)
|
||||
path = manager.sessions_dir / "sessions.sqlite3"
|
||||
with sqlite3.connect(path) as db:
|
||||
db.execute("CREATE TRIGGER prohibit_rewrite BEFORE UPDATE ON messages BEGIN SELECT RAISE(ABORT, 'rewritten'); END")
|
||||
await state.checkpoint_view(draft, {"step": 1})
|
||||
assert (await state.get(draft.key)).metadata["runtime_checkpoint"] == {"step": 1}
|
||||
await state.aclose()
|
||||
|
||||
|
||||
async def test_database_lock_does_not_block_event_loop(tmp_path):
|
||||
manager = SessionManager(tmp_path)
|
||||
state = manager.state
|
||||
await state.get("chat:a")
|
||||
await state.update_metadata("chat:a", {"title": "old"})
|
||||
ready = threading.Event()
|
||||
release = threading.Event()
|
||||
def hold():
|
||||
with sqlite3.connect(manager.sessions_dir / "sessions.sqlite3") as db:
|
||||
db.execute("BEGIN IMMEDIATE")
|
||||
ready.set()
|
||||
release.wait(5)
|
||||
thread = threading.Thread(target=hold)
|
||||
thread.start()
|
||||
await asyncio.to_thread(ready.wait, 2)
|
||||
task = asyncio.create_task(state.update_metadata("chat:a", {"title": "new"}))
|
||||
try:
|
||||
start = time.monotonic()
|
||||
await asyncio.sleep(0.03)
|
||||
assert time.monotonic() - start < 0.3
|
||||
assert not task.done()
|
||||
finally:
|
||||
release.set()
|
||||
await task
|
||||
thread.join()
|
||||
await state.aclose()
|
||||
|
||||
|
||||
async def test_existing_reads_do_not_wait_for_another_sessions_write_lock(tmp_path):
|
||||
manager = SessionManager(tmp_path)
|
||||
state = manager.state
|
||||
await state.get("chat:write")
|
||||
await state.get("chat:read")
|
||||
await state.update_metadata("chat:read", {"title": "committed"})
|
||||
ready, release = threading.Event(), threading.Event()
|
||||
|
||||
def hold():
|
||||
with sqlite3.connect(manager._store.path) as db:
|
||||
db.execute("BEGIN IMMEDIATE")
|
||||
ready.set()
|
||||
assert release.wait(5)
|
||||
|
||||
thread = threading.Thread(target=hold)
|
||||
thread.start()
|
||||
await asyncio.to_thread(ready.wait, 2)
|
||||
write = asyncio.create_task(state.update_metadata("chat:write", {"title": "waiting"}))
|
||||
try:
|
||||
await asyncio.sleep(0)
|
||||
metadata = await asyncio.wait_for(state.read_metadata("chat:read"), timeout=2)
|
||||
draft = await asyncio.wait_for(state.get("chat:read"), timeout=2)
|
||||
header = await asyncio.wait_for(state.get_header("chat:read"), timeout=2)
|
||||
assert metadata["metadata"]["title"] == draft.metadata["title"] == header.metadata["title"] == "committed"
|
||||
assert not write.done()
|
||||
finally:
|
||||
release.set()
|
||||
await write
|
||||
thread.join()
|
||||
await state.aclose()
|
||||
|
||||
|
||||
async def test_closing_one_owner_preserves_another_owners_connections(tmp_path):
|
||||
from nanobot.session.state import SessionState
|
||||
|
||||
manager = SessionManager(tmp_path)
|
||||
first = SessionState(manager._store)
|
||||
second = SessionState(manager._store)
|
||||
try:
|
||||
await first.get("chat:first")
|
||||
await second.get("chat:second")
|
||||
await first.aclose()
|
||||
await second.update_metadata("chat:second", {"title": "still open"})
|
||||
assert (await second.get("chat:second")).metadata["title"] == "still open"
|
||||
finally:
|
||||
await first.aclose()
|
||||
await second.aclose()
|
||||
|
||||
|
||||
async def test_cancellation_settles_accepted_write(tmp_path, monkeypatch):
|
||||
manager = SessionManager(tmp_path)
|
||||
state = manager.state
|
||||
ready = threading.Event()
|
||||
release = threading.Event()
|
||||
original = manager._store.save
|
||||
def blocked(session, **kwargs):
|
||||
ready.set()
|
||||
release.wait(5)
|
||||
return original(session, **kwargs)
|
||||
monkeypatch.setattr(manager._store, "save", blocked)
|
||||
task = asyncio.create_task(state.import_messages("chat:a", [{"role": "user", "content": "accepted"}]))
|
||||
await asyncio.to_thread(ready.wait, 2)
|
||||
task.cancel()
|
||||
await asyncio.sleep(0)
|
||||
assert not task.done()
|
||||
release.set()
|
||||
with pytest.raises(asyncio.CancelledError):
|
||||
await task
|
||||
assert (await state.get("chat:a")).messages[0]["content"] == "accepted"
|
||||
await state.aclose()
|
||||
with pytest.raises(RuntimeError, match="closed"):
|
||||
await state.get("chat:a")
|
||||
|
||||
|
||||
def test_committed_checkpoint_survives_process_exit(tmp_path):
|
||||
workspace, root = tmp_path / "workspace", tmp_path / "storage"
|
||||
script = '''
|
||||
import asyncio, os, sys
|
||||
from pathlib import Path
|
||||
from nanobot.session.manager import SessionManager
|
||||
async def main():
|
||||
state = SessionManager(Path(sys.argv[1]), sessions_root=Path(sys.argv[2])).state
|
||||
draft = await state.get("chat:a")
|
||||
draft.add_message("user", "accepted")
|
||||
draft.metadata["pending_user_turn"] = True
|
||||
await state.prepare_input(draft)
|
||||
await state.checkpoint_view(draft, {"step": "tool-finished"})
|
||||
os._exit(0)
|
||||
asyncio.run(main())
|
||||
'''
|
||||
subprocess.run([sys.executable, "-c", script, str(workspace), str(root)], check=True, timeout=15)
|
||||
manager = SessionManager(workspace, sessions_root=root)
|
||||
session = manager.get_or_create("chat:a")
|
||||
assert session.messages[0]["content"] == "accepted"
|
||||
assert session.metadata["runtime_checkpoint"] == {"step": "tool-finished"}
|
||||
|
||||
|
||||
async def test_late_metadata_and_summary_cannot_resurrect_deleted_session(tmp_path):
|
||||
state = SessionManager(tmp_path).state
|
||||
draft = await state.get("chat:deleted")
|
||||
await state.delete(draft.key)
|
||||
with pytest.raises(SessionConflictError):
|
||||
await state.mutate_metadata(
|
||||
draft.key, lambda metadata: metadata.update(title="late title"),
|
||||
expected_generation=draft.generation,
|
||||
)
|
||||
with pytest.raises(SessionConflictError):
|
||||
await state.commit_summary(draft, "late summary", archive_end=0)
|
||||
assert await state.read(draft.key) is None
|
||||
await state.aclose()
|
||||
|
||||
|
||||
async def test_large_draft_copy_and_publication_run_on_owner_worker(tmp_path, monkeypatch):
|
||||
import nanobot.session.state as owner
|
||||
|
||||
state = SessionManager(tmp_path).state
|
||||
draft = await state.get("chat:copy")
|
||||
draft.add_message("user", "large transcript" * 10000)
|
||||
loop_thread = threading.get_ident()
|
||||
original_copy = owner.deepcopy
|
||||
copied = threading.Event()
|
||||
|
||||
def checked_copy(value):
|
||||
if isinstance(value, Session) or (isinstance(value, dict) and "role" in value):
|
||||
assert threading.get_ident() != loop_thread
|
||||
copied.set()
|
||||
return original_copy(value)
|
||||
|
||||
monkeypatch.setattr(owner, "deepcopy", checked_copy)
|
||||
await state.prepare_input(draft)
|
||||
await state.checkpoint_view(draft, {"step": 1})
|
||||
await state.finish_turn(draft)
|
||||
assert copied.is_set()
|
||||
assert (await state.read(draft.key)).messages == draft.messages
|
||||
await state.aclose()
|
||||
|
||||
|
||||
def test_duplicate_json_keys_abort_entire_migration(tmp_path):
|
||||
workspace = tmp_path / "workspace"
|
||||
path = legacy(workspace)
|
||||
path.write_text(
|
||||
'{"_type":"metadata","key":"chat:a","key":"chat:b",'
|
||||
'"metadata":{},"created_at":"2026-01-01T00:00:00",'
|
||||
'"updated_at":"2026-01-01T00:00:00"}\n',
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
with pytest.raises(RuntimeError, match="migration failed"):
|
||||
SessionManager(workspace, sessions_root=tmp_path / "root")
|
||||
|
||||
database = next((tmp_path / "root").glob("*/sessions.sqlite3"))
|
||||
with sqlite3.connect(database) as db:
|
||||
tables = {
|
||||
row[0]
|
||||
for row in db.execute(
|
||||
"SELECT name FROM sqlite_master WHERE type='table'"
|
||||
)
|
||||
}
|
||||
assert "sessions" not in tables
|
||||
assert "storage_meta" not in tables
|
||||
|
||||
|
||||
def test_nested_duplicate_json_keys_abort_migration(tmp_path):
|
||||
workspace = tmp_path / "workspace"
|
||||
path = legacy(workspace)
|
||||
path.write_text(
|
||||
'{"_type":"metadata","key":"chat:a","metadata":{"title":"a","title":"b"},'
|
||||
'"created_at":"2026-01-01T00:00:00",'
|
||||
'"updated_at":"2026-01-01T00:00:00"}\n',
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
with pytest.raises(RuntimeError, match="migration failed"):
|
||||
SessionManager(workspace, sessions_root=tmp_path / "root")
|
||||
|
||||
|
||||
def test_second_provider_state_aborts_migration(tmp_path):
|
||||
workspace = tmp_path / "workspace"
|
||||
path = legacy(workspace)
|
||||
state = {
|
||||
"kind": "responses",
|
||||
"provider": "openai",
|
||||
"model": "gpt-test",
|
||||
"version": 1,
|
||||
"payload": {"secret": "opaque"},
|
||||
"pending_messages": [],
|
||||
}
|
||||
with path.open("a", encoding="utf-8") as handle:
|
||||
record = json.dumps({"_type": "provider_state", "state": state})
|
||||
handle.write(record + "\n" + record + "\n")
|
||||
|
||||
with pytest.raises(RuntimeError, match="migration failed"):
|
||||
SessionManager(workspace, sessions_root=tmp_path / "root")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("with_checkpoint", [False, True])
|
||||
def test_identical_migration_copies_are_imported_once_and_cleaned_up(tmp_path, with_checkpoint):
|
||||
workspace = tmp_path / "workspace"
|
||||
root = tmp_path / "root"
|
||||
source = legacy(workspace, key="chat:a")
|
||||
sources = [source]
|
||||
if with_checkpoint:
|
||||
checkpoint = source.with_suffix(".checkpoint.json")
|
||||
checkpoint.write_text(json.dumps({
|
||||
"version": 1, "session_key": "chat:a", "base_message_count": 1,
|
||||
"base_updated_at": "2026-01-01T00:00:00",
|
||||
"checkpoint": {"messages": [{"role": "assistant", "content": "partial"}]},
|
||||
}))
|
||||
sources.append(checkpoint)
|
||||
location = SessionLocation(workspace, sessions_root=root)
|
||||
originals = {path.name: path.read_bytes() for path in sources}
|
||||
for path in sources:
|
||||
shutil.copy2(path, location.sessions_dir / path.name)
|
||||
|
||||
for _ in range(2):
|
||||
manager = SessionManager(workspace, sessions_root=root)
|
||||
assert len(manager.list_sessions()) == 1
|
||||
session = manager.read_session_snapshot("chat:a")
|
||||
assert [message["content"] for message in session.messages] == ["hello"]
|
||||
if with_checkpoint:
|
||||
assert session.metadata["runtime_checkpoint"]["messages"][0]["content"] == "partial"
|
||||
for path in sources:
|
||||
assert not path.exists()
|
||||
assert (location.sessions_dir / path.name).read_bytes() == originals[path.name]
|
||||
assert (location.sessions_dir / WORKSPACE_BACKUP_DIR / path.name).read_bytes() == originals[path.name]
|
||||
|
||||
|
||||
def test_duplicate_sources_with_different_timestamps_abort_migration(tmp_path):
|
||||
workspace = tmp_path / "workspace"
|
||||
root = tmp_path / "root"
|
||||
source = legacy(workspace, key="chat:a")
|
||||
location = SessionLocation(workspace, sessions_root=root)
|
||||
duplicate = location.sessions_dir / source.name
|
||||
duplicate.write_text(
|
||||
source.read_text(encoding="utf-8").replace(
|
||||
'"updated_at": "2026-01-01T00:00:00"',
|
||||
'"updated_at": "2026-01-02T00:00:00"',
|
||||
),
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
with pytest.raises(RuntimeError, match="migration failed"):
|
||||
SessionManager(workspace, sessions_root=root)
|
||||
duplicate.unlink()
|
||||
manager = SessionManager(workspace, sessions_root=root)
|
||||
assert manager.read_session_snapshot("chat:a") is not None
|
||||
|
||||
|
||||
def test_invalid_migration_marker_fails_closed(tmp_path):
|
||||
workspace = tmp_path / "workspace"
|
||||
root = tmp_path / "root"
|
||||
manager = SessionManager(workspace, sessions_root=root)
|
||||
with sqlite3.connect(manager._store.path) as db:
|
||||
db.execute(
|
||||
"UPDATE storage_meta SET value='corrupt' WHERE key='jsonl_import'"
|
||||
)
|
||||
legacy(workspace, key="chat:must-not-import")
|
||||
|
||||
with pytest.raises(RuntimeError, match="invalid JSONL migration marker"):
|
||||
SessionManager(workspace, sessions_root=root)
|
||||
with sqlite3.connect(manager._store.path) as db:
|
||||
assert db.execute(
|
||||
"SELECT count(*) FROM sessions WHERE key='chat:must-not-import'"
|
||||
).fetchone()[0] == 0
|
||||
|
||||
|
||||
async def test_missing_update_commands_do_not_create_sessions(tmp_path):
|
||||
manager = SessionManager(tmp_path)
|
||||
state = manager.state
|
||||
with pytest.raises(SessionConflictError, match="does not exist"):
|
||||
await state.update_metadata("chat:missing", {"title": "late"})
|
||||
with pytest.raises(SessionConflictError, match="does not exist"):
|
||||
await state.record_delivery(
|
||||
"chat:missing", "late", {}, expected_generation="deleted-generation",
|
||||
)
|
||||
assert manager.read_session_snapshot("chat:missing") is None
|
||||
await state.aclose()
|
||||
|
||||
|
||||
async def test_delete_rejects_late_delivery_and_metadata(tmp_path):
|
||||
manager = SessionManager(tmp_path)
|
||||
state = manager.state
|
||||
session = await state.get("chat:a")
|
||||
assert await state.delete(session.key, expected_generation=session.generation)
|
||||
|
||||
with pytest.raises(SessionConflictError):
|
||||
await state.record_delivery(
|
||||
session.key,
|
||||
"deleted-secret",
|
||||
{},
|
||||
expected_generation=session.generation,
|
||||
)
|
||||
with pytest.raises(SessionConflictError):
|
||||
await state.update_metadata(
|
||||
session.key,
|
||||
{"secret": "deleted-secret"},
|
||||
expected_generation=session.generation,
|
||||
)
|
||||
assert manager.read_session_snapshot(session.key) is None
|
||||
await state.aclose()
|
||||
|
||||
|
||||
async def test_old_generation_cannot_write_into_recreated_key(tmp_path):
|
||||
manager = SessionManager(tmp_path)
|
||||
state = manager.state
|
||||
old = await state.get("chat:a")
|
||||
assert await state.delete(old.key, expected_generation=old.generation)
|
||||
current = await state.get(old.key)
|
||||
assert current.generation != old.generation
|
||||
|
||||
with pytest.raises(SessionConflictError, match="replaced session"):
|
||||
await state.record_delivery(
|
||||
old.key,
|
||||
"old result",
|
||||
{},
|
||||
expected_generation=old.generation,
|
||||
)
|
||||
loaded = await state.read(old.key)
|
||||
assert loaded is not None and loaded.messages == []
|
||||
await state.aclose()
|
||||
|
||||
|
||||
async def test_discarded_transient_late_delivery_never_becomes_durable(tmp_path):
|
||||
manager = SessionManager(tmp_path)
|
||||
state = manager.state
|
||||
transient = await state.register_transient("temporary:a")
|
||||
await state.discard(transient.key)
|
||||
|
||||
with pytest.raises(SessionConflictError):
|
||||
await state.record_delivery(
|
||||
transient.key,
|
||||
"private late result",
|
||||
{},
|
||||
expected_generation=transient.generation,
|
||||
)
|
||||
assert manager.read_session_snapshot(transient.key) is None
|
||||
await state.aclose()
|
||||
|
||||
|
||||
async def test_read_and_delete_are_serialized_without_cache_ghost(tmp_path, monkeypatch):
|
||||
manager = SessionManager(tmp_path)
|
||||
state = manager.state
|
||||
await state.get("chat:a")
|
||||
loaded, release = threading.Event(), threading.Event()
|
||||
original = state._load
|
||||
first = True
|
||||
|
||||
def paused_load(key, *, history=True):
|
||||
nonlocal first
|
||||
session = original(key, history=history)
|
||||
if first and key == "chat:a":
|
||||
first = False
|
||||
loaded.set()
|
||||
release.wait(5)
|
||||
return session
|
||||
|
||||
monkeypatch.setattr(state, "_load", paused_load)
|
||||
read = asyncio.create_task(state.read("chat:a"))
|
||||
assert await asyncio.to_thread(loaded.wait, 2)
|
||||
deletion = asyncio.create_task(state.delete("chat:a"))
|
||||
await asyncio.sleep(0.05)
|
||||
assert not deletion.done()
|
||||
release.set()
|
||||
assert await read is not None
|
||||
assert await deletion
|
||||
assert state.peek("chat:a") is None
|
||||
assert manager.read_session_snapshot("chat:a") is None
|
||||
await state.aclose()
|
||||
|
||||
|
||||
async def test_synchronous_mutation_is_rejected_after_owner_binds(tmp_path):
|
||||
manager = SessionManager(tmp_path)
|
||||
state = manager.state
|
||||
await state.get("chat:a")
|
||||
with pytest.raises(RuntimeError, match="async owner"):
|
||||
manager.delete_session("chat:a")
|
||||
with pytest.raises(RuntimeError, match="async owner"):
|
||||
manager.update_session_metadata("chat:a", {"title": "bypass"})
|
||||
await state.aclose()
|
||||
|
||||
|
||||
async def test_delivery_requires_explicit_nonempty_generation(tmp_path):
|
||||
state = SessionManager(tmp_path).state
|
||||
session = await state.get("chat:a")
|
||||
with pytest.raises(ValueError, match="requires a session generation"):
|
||||
await state.record_delivery(session.key, "unguarded", {}, expected_generation="")
|
||||
await state.record_delivery(
|
||||
session.key, "current", {}, expected_generation=session.generation,
|
||||
)
|
||||
assert [message["content"] for message in (await state.get(session.key)).messages] == [
|
||||
"current",
|
||||
]
|
||||
await state.aclose()
|
||||
@@ -73,7 +73,7 @@ async def test_maybe_continue_turn_queues_internal_message():
|
||||
visible_run_started_at=1234.5,
|
||||
)
|
||||
|
||||
assert await maybe_continue_turn(ctx) is True
|
||||
assert await maybe_continue_turn(ctx, session_metadata=ctx.session.metadata) is True
|
||||
|
||||
queued = pending.get_nowait()
|
||||
assert queued.sender_id == "system:continuation"
|
||||
@@ -126,7 +126,7 @@ async def test_internal_continuation_respects_round_limit():
|
||||
pending_queue_available=True,
|
||||
session_metadata=meta,
|
||||
)
|
||||
assert await maybe_continue_turn(ctx) is False
|
||||
assert await maybe_continue_turn(ctx, session_metadata=ctx.session.metadata) is False
|
||||
|
||||
|
||||
def test_internal_continuation_requires_budget_boundary_and_queue():
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def test_session_storage_benchmark_emits_auditable_windows_safe_result(tmp_path: Path) -> None:
|
||||
repo = Path(__file__).parents[1]
|
||||
output = tmp_path / "result.json"
|
||||
subprocess.run(
|
||||
[
|
||||
sys.executable,
|
||||
str(repo / "scripts" / "benchmark_session_storage.py"),
|
||||
"--repo",
|
||||
str(repo),
|
||||
"--variant",
|
||||
"sqlite",
|
||||
"--output",
|
||||
str(output),
|
||||
"--iterations",
|
||||
"1",
|
||||
"--sizes",
|
||||
"1",
|
||||
"--list-count",
|
||||
"1",
|
||||
"--concurrency",
|
||||
"1",
|
||||
"--turns",
|
||||
"1",
|
||||
],
|
||||
cwd=repo,
|
||||
check=True,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=120,
|
||||
)
|
||||
|
||||
result = json.loads(output.read_text(encoding="utf-8"))
|
||||
head = subprocess.run(
|
||||
["git", "rev-parse", "HEAD"],
|
||||
cwd=repo,
|
||||
check=True,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
).stdout.strip()
|
||||
assert result["correctness"] == "PASS"
|
||||
assert result["git"]["commit"] == head
|
||||
assert isinstance(result["git"]["dirty"], bool)
|
||||
assert result["dependencies"]["uv_lock_sha256"]
|
||||
assert result["dependencies"]["installed_sha256"]
|
||||
assert result["python"]["executable"] == sys.executable
|
||||
assert result["target_module"].startswith(str(repo.resolve()))
|
||||
assert result["data_filesystem"]["collector"]
|
||||
assert result["data_filesystem"]["filesystem_type"]
|
||||
assert result["harness"]["sha256"]
|
||||
assert result["parameters"] == {
|
||||
"iterations": 1,
|
||||
"sizes": [1],
|
||||
"list_count": 1,
|
||||
"concurrency": 1,
|
||||
"turns": 1,
|
||||
"content_bytes": 512,
|
||||
}
|
||||
@@ -65,9 +65,9 @@ def _fake_provider(name: str, *, max_tokens: int = 8192) -> MagicMock:
|
||||
|
||||
|
||||
async def _admit_fake_runtime(bot, session_key, callback, runtime=None) -> None:
|
||||
admitted = runtime or bot._loop.runtime_for_session(
|
||||
admitted = runtime or (await bot._loop.runtime_for_session(
|
||||
bot._loop.sessions.get_or_create(session_key)
|
||||
)
|
||||
))
|
||||
await callback(admitted)
|
||||
|
||||
|
||||
@@ -308,7 +308,8 @@ async def test_run_custom_session_key(tmp_path):
|
||||
)
|
||||
|
||||
|
||||
def test_request_context_preserves_legacy_positional_arguments(tmp_path):
|
||||
@pytest.mark.parametrize("generation_kwargs", [{}, {"session_generation": "generation-1"}])
|
||||
def test_request_context_preserves_legacy_positional_arguments(tmp_path, generation_kwargs):
|
||||
from nanobot.agent.tools.context import RequestContext
|
||||
|
||||
context = RequestContext(
|
||||
@@ -322,13 +323,20 @@ def test_request_context_preserves_legacy_positional_arguments(tmp_path):
|
||||
"alice",
|
||||
"turn-1",
|
||||
tmp_path,
|
||||
{"source": "sdk"},
|
||||
False,
|
||||
**generation_kwargs,
|
||||
)
|
||||
|
||||
assert context.original_user_text == "hello"
|
||||
assert context.runtime is None
|
||||
assert context.session_generation == generation_kwargs.get("session_generation")
|
||||
assert context.metadata == {"trusted": True}
|
||||
assert context.sender_id == "alice"
|
||||
assert context.turn_id == "turn-1"
|
||||
assert context.workspace == tmp_path
|
||||
assert context.attributes == {}
|
||||
assert context.attributes == {"source": "sdk"}
|
||||
assert context.log_content is False
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -365,7 +373,7 @@ async def test_run_exposes_attributes_to_context_provider_without_persisting_the
|
||||
assert result.content == "done"
|
||||
assert seen[0].attributes == {"tenant": "acme"}
|
||||
assert seen[0].metadata == {}
|
||||
snapshot = bot.sessions.export("sdk:attributes")
|
||||
snapshot = (await bot.sessions.export("sdk:attributes"))
|
||||
assert snapshot is not None
|
||||
assert all("attributes" not in message for message in snapshot.messages)
|
||||
|
||||
@@ -414,8 +422,8 @@ async def test_persisted_turn_callback_is_best_effort_and_reads_display_safe_ses
|
||||
failed_sync_attempts += 1
|
||||
raise RuntimeError("host sync failed")
|
||||
|
||||
def on_persisted(event: SessionTurnPersisted) -> None:
|
||||
seen.append((event, bot.sessions.get(event.context.session_key)))
|
||||
async def on_persisted(event: SessionTurnPersisted) -> None:
|
||||
seen.append((event, (await bot.sessions.get(event.context.session_key))))
|
||||
|
||||
remove_context = bot.runtime.add_context_provider(provide_context)
|
||||
remove_failure = bot.runtime.on_session_turn_persisted(fail_sync)
|
||||
@@ -437,7 +445,7 @@ async def test_persisted_turn_callback_is_best_effort_and_reads_display_safe_ses
|
||||
assert snapshot.messages[-1]["content"] == "saved reply"
|
||||
assert result.content == "saved reply"
|
||||
assert failed_sync_attempts == 1
|
||||
trusted_snapshot = bot.sessions.export("sdk:persisted")
|
||||
trusted_snapshot = (await bot.sessions.export("sdk:persisted"))
|
||||
assert trusted_snapshot is not None
|
||||
assert "model-only context" in trusted_snapshot.messages[-2]["content"]
|
||||
|
||||
@@ -466,7 +474,7 @@ async def test_persisted_turn_callback_observes_saved_command_turn(tmp_path):
|
||||
await bot.run("/skill", session_key="sdk:command")
|
||||
|
||||
assert len(seen) == 1
|
||||
snapshot = bot.sessions.export("sdk:command")
|
||||
snapshot = (await bot.sessions.export("sdk:command"))
|
||||
assert snapshot is not None
|
||||
assert [message["role"] for message in snapshot.messages[-2:]] == [
|
||||
"user",
|
||||
@@ -1462,17 +1470,17 @@ async def test_sessions_ingest_imports_transcript_without_running_model(tmp_path
|
||||
assert snapshot.messages[1]["source"] == "original-source"
|
||||
bot._loop.process_direct.assert_not_called()
|
||||
|
||||
reloaded = bot.sessions.get("sdk:history")
|
||||
reloaded = (await bot.sessions.get("sdk:history"))
|
||||
assert reloaded is not None
|
||||
assert reloaded.messages == snapshot.messages
|
||||
|
||||
await bot.aclose()
|
||||
async with Nanobot.from_config(config_path, workspace=tmp_path) as restarted:
|
||||
assert restarted.sessions.export("sdk:history") == snapshot
|
||||
assert await restarted.sessions.export("sdk:history") == snapshot
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_sessions_ingest_without_save_detaches_inputs_and_can_be_flushed(tmp_path):
|
||||
async def test_sessions_ingest_detaches_inputs_and_is_immediately_durable(tmp_path):
|
||||
config_path = _write_config(tmp_path)
|
||||
metadata = {"import": {"dataset": "original"}}
|
||||
messages = [{
|
||||
@@ -1482,7 +1490,7 @@ async def test_sessions_ingest_without_save_detaches_inputs_and_can_be_flushed(t
|
||||
}]
|
||||
async with Nanobot.from_config(config_path, workspace=tmp_path) as bot:
|
||||
snapshot = await bot.sessions.ingest(
|
||||
"sdk:unsaved", iter(messages), metadata=metadata, save=False,
|
||||
"sdk:imported", iter(messages), metadata=metadata,
|
||||
)
|
||||
metadata["import"]["dataset"] = "changed"
|
||||
messages[0]["content"][0]["text"] = "changed"
|
||||
@@ -1492,13 +1500,12 @@ async def test_sessions_ingest_without_save_detaches_inputs_and_can_be_flushed(t
|
||||
assert snapshot.messages[0]["role"] == "user"
|
||||
assert snapshot.messages[0]["content"] == [{"type": "text", "text": "hello"}]
|
||||
assert snapshot.messages[0]["import_info"] == {"index": 1}
|
||||
assert bot.sessions.get("sdk:unsaved") == snapshot
|
||||
assert await bot.sessions.get("sdk:imported") == snapshot
|
||||
async with Nanobot.from_config(config_path, workspace=tmp_path) as reader:
|
||||
assert reader.sessions.export("sdk:unsaved") is None
|
||||
assert bot.sessions.flush() == 1
|
||||
assert await reader.sessions.export("sdk:imported") == snapshot
|
||||
|
||||
async with Nanobot.from_config(config_path, workspace=tmp_path) as restarted:
|
||||
assert restarted.sessions.export("sdk:unsaved") == snapshot
|
||||
assert await restarted.sessions.export("sdk:imported") == snapshot
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -1518,7 +1525,7 @@ async def test_sessions_ingest_rejects_batch_without_session_changes(
|
||||
key, [{"role": "user", "content": "original history"}],
|
||||
metadata={"title": "Original", "import": {"dataset": "original"}},
|
||||
)
|
||||
before = bot.sessions.export(key)
|
||||
before = await bot.sessions.export(key)
|
||||
|
||||
with pytest.raises(ValueError, match="role|content"):
|
||||
await bot.sessions.ingest(
|
||||
@@ -1527,12 +1534,11 @@ async def test_sessions_ingest_rejects_batch_without_session_changes(
|
||||
metadata={"title": "Changed", "new_field": "must not leak"},
|
||||
)
|
||||
|
||||
assert bot.sessions.get(key) == before
|
||||
assert bot.sessions.export(key) == before
|
||||
bot.sessions.flush()
|
||||
assert await bot.sessions.get(key) == before
|
||||
assert await bot.sessions.export(key) == before
|
||||
|
||||
async with Nanobot.from_config(config_path, workspace=tmp_path) as restarted:
|
||||
assert restarted.sessions.export(key) == before
|
||||
assert await restarted.sessions.export(key) == before
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -1573,33 +1579,31 @@ async def test_session_helpers_get_list_export_clear_delete_flush(tmp_path):
|
||||
|
||||
await bot.sessions.ingest("sdk:first", [{"role": "user", "content": "hello"}])
|
||||
|
||||
listed = bot.sessions.list()
|
||||
listed = (await bot.sessions.list())
|
||||
assert listed
|
||||
assert isinstance(listed[0], SessionInfo)
|
||||
assert {row.key for row in listed} == {"sdk:first"}
|
||||
|
||||
exported = bot.sessions.export("sdk:first")
|
||||
exported = (await bot.sessions.export("sdk:first"))
|
||||
assert exported is not None
|
||||
exported.messages[0]["content"] = "mutated copy"
|
||||
assert bot.sessions.get("sdk:first").messages[0]["content"] == "hello"
|
||||
assert (await bot.sessions.get("sdk:first")).messages[0]["content"] == "hello"
|
||||
|
||||
state_before_clear = bot._loop._file_state_store.for_session("sdk:first")
|
||||
cleared = bot.sessions.clear("sdk:first")
|
||||
cleared = (await bot.sessions.clear("sdk:first"))
|
||||
assert cleared.messages == []
|
||||
state_after_clear = bot._loop._file_state_store.for_session("sdk:first")
|
||||
assert state_after_clear is not state_before_clear
|
||||
assert bot.sessions.flush() >= 1
|
||||
state_before_delete = state_after_clear
|
||||
assert bot.sessions.delete("sdk:first") is True
|
||||
assert (await bot.sessions.delete("sdk:first")) is True
|
||||
assert bot._loop._file_state_store.for_session("sdk:first") is not state_before_delete
|
||||
assert bot.sessions.get("sdk:first") is None
|
||||
assert (await bot.sessions.get("sdk:first")) is None
|
||||
|
||||
|
||||
def test_session_helpers_read_live_session_outside_strong_cache(tmp_path):
|
||||
async def test_session_helpers_read_only_committed_state(tmp_path):
|
||||
config_path = _write_config(tmp_path)
|
||||
bot = Nanobot.from_config(config_path, workspace=tmp_path)
|
||||
sessions = bot._loop.sessions
|
||||
sessions._max_cached_sessions = 1
|
||||
active = sessions.get_or_create("sdk:active")
|
||||
active.add_message("user", "persisted")
|
||||
sessions.save(active)
|
||||
@@ -1607,13 +1611,12 @@ def test_session_helpers_read_live_session_outside_strong_cache(tmp_path):
|
||||
sessions.save(sessions.get_or_create("sdk:other"))
|
||||
active.add_message("assistant", "not saved yet")
|
||||
|
||||
visible = bot.sessions.get("sdk:active")
|
||||
exported = bot.sessions.export("sdk:active")
|
||||
visible = (await bot.sessions.get("sdk:active"))
|
||||
exported = (await bot.sessions.export("sdk:active"))
|
||||
assert visible is not None
|
||||
assert exported is not None
|
||||
assert [message["content"] for message in visible.messages] == [
|
||||
"persisted",
|
||||
"not saved yet",
|
||||
]
|
||||
assert exported.messages == visible.messages
|
||||
|
||||
@@ -1633,14 +1636,14 @@ async def test_session_export_and_restore_preserve_runtime_context(tmp_path):
|
||||
**{RUNTIME_CONTEXT_HISTORY_META: marker},
|
||||
)
|
||||
bot._loop.sessions.save(source)
|
||||
bot._loop.sessions._cache.pop("sdk:source")
|
||||
bot._loop.sessions.invalidate("sdk:source")
|
||||
|
||||
public = bot.sessions.get("sdk:source")
|
||||
public = (await bot.sessions.get("sdk:source"))
|
||||
assert public is not None
|
||||
assert public.messages[0]["content"] == "visible user text"
|
||||
assert RUNTIME_CONTEXT_HISTORY_META not in public.messages[0]
|
||||
|
||||
exported = bot.sessions.export("sdk:source")
|
||||
exported = (await bot.sessions.export("sdk:source"))
|
||||
assert exported is not None
|
||||
assert exported.messages[0]["content"] == content
|
||||
assert exported.messages[0][RUNTIME_CONTEXT_HISTORY_META] == marker
|
||||
@@ -1653,7 +1656,7 @@ async def test_session_export_and_restore_preserve_runtime_context(tmp_path):
|
||||
restored = bot._loop.sessions.get_or_create("sdk:restored")
|
||||
assert restored.get_history() == source.get_history()
|
||||
|
||||
with pytest.raises(ValueError, match="not empty"):
|
||||
with pytest.raises(RuntimeError, match="not empty"):
|
||||
await bot.sessions.restore(exported, session_key="sdk:restored")
|
||||
|
||||
|
||||
@@ -1719,7 +1722,7 @@ async def test_runtime_helpers_expose_model_workspace_and_compact(tmp_path):
|
||||
bot = Nanobot.from_config(config_path, workspace=tmp_path)
|
||||
await bot.sessions.ingest("sdk:history", [{"role": "user", "content": "hello"}])
|
||||
runtime = bot._loop.llm_runtime()
|
||||
bot._loop.runtime_for_session = MagicMock(return_value=runtime) # type: ignore[method-assign]
|
||||
bot._loop.runtime_for_session = AsyncMock(return_value=runtime) # type: ignore[method-assign]
|
||||
|
||||
compact_session = AsyncMock()
|
||||
bot._loop.consolidator.compact_idle_session = compact_session
|
||||
|
||||
@@ -904,6 +904,7 @@ def test_agent_loop_shutdown_closes_exec_sessions(tmp_path):
|
||||
process = manager._sessions[sid].process
|
||||
|
||||
loop = object.__new__(AgentLoop)
|
||||
loop.sessions = SimpleNamespace(state=SimpleNamespace(aclose=AsyncMock()))
|
||||
loop._background_tasks = set()
|
||||
loop._exec_session_manager = manager
|
||||
loop.runtime_resolver = SimpleNamespace(aclose=AsyncMock())
|
||||
@@ -922,6 +923,7 @@ def test_agent_loop_shutdown_closes_exec_sessions(tmp_path):
|
||||
def test_agent_loop_shutdown_attempts_all_cleanup_after_errors():
|
||||
async def run() -> None:
|
||||
loop = object.__new__(AgentLoop)
|
||||
loop.sessions = SimpleNamespace(state=SimpleNamespace(aclose=AsyncMock()))
|
||||
loop._background_tasks = set()
|
||||
loop.runtime_resolver = SimpleNamespace(aclose=AsyncMock())
|
||||
loop.subagents = SimpleNamespace(
|
||||
@@ -1094,6 +1096,7 @@ def test_terminate_by_owner_skips_sessions_without_owner_key(tmp_path):
|
||||
def test_agent_loop_shutdown_preserves_single_cleanup_error():
|
||||
async def run() -> None:
|
||||
loop = object.__new__(AgentLoop)
|
||||
loop.sessions = SimpleNamespace(state=SimpleNamespace(aclose=AsyncMock()))
|
||||
loop._background_tasks = set()
|
||||
loop.runtime_resolver = SimpleNamespace(aclose=AsyncMock())
|
||||
loop.subagents = SimpleNamespace(
|
||||
|
||||
@@ -77,6 +77,10 @@ async def test_list_sessions_includes_all_persisted_channels_except_current(
|
||||
sessions = SessionManager(tmp_path)
|
||||
_persist(sessions, "websocket:current", "telegram:other", "slack:team")
|
||||
tool = ListSessionsTool(sessions)
|
||||
expected = {
|
||||
f"@{_handle(sessions, 'telegram:other').name}",
|
||||
f"@{_handle(sessions, 'slack:team').name}",
|
||||
}
|
||||
|
||||
with request_context(RequestContext(
|
||||
channel="websocket",
|
||||
@@ -85,10 +89,7 @@ async def test_list_sessions_includes_all_persisted_channels_except_current(
|
||||
)):
|
||||
result = json.loads(await tool.execute())
|
||||
|
||||
assert set(result) == {
|
||||
f"@{_handle(sessions, 'telegram:other').name}",
|
||||
f"@{_handle(sessions, 'slack:team').name}",
|
||||
}
|
||||
assert set(result) == expected
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -366,9 +367,12 @@ async def test_reply_follows_a_recycled_handle(tmp_path: Path) -> None:
|
||||
expect_reply=False,
|
||||
)
|
||||
received = await bus.consume_inbound()
|
||||
assert sessions.delete_session(source.session_key)
|
||||
_persist(sessions, "websocket:replacement")
|
||||
replacement = _handle(sessions, "websocket:replacement")
|
||||
assert await sessions.state.delete(source.session_key)
|
||||
await sessions.state.get("websocket:replacement")
|
||||
replacement = await SessionHandleResolver(sessions).ahandle_for_session(
|
||||
"websocket:replacement"
|
||||
)
|
||||
assert replacement is not None
|
||||
assert replacement.name == source.name
|
||||
|
||||
with request_context(RequestContext(
|
||||
|
||||
@@ -1126,3 +1126,37 @@ def test_cast_nullable_param_no_crash() -> None:
|
||||
assert result["name"] == "hello"
|
||||
result = tool.cast_params({"name": None})
|
||||
assert result["name"] is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize("command", [
|
||||
"cat ~unknown/file.txt",
|
||||
"cat --config=~unknown/file.txt",
|
||||
"cat <~unknown/file.txt",
|
||||
"cat ~/file.txt",
|
||||
])
|
||||
def test_exec_guard_rejects_unresolvable_home_path(tmp_path, monkeypatch, command) -> None:
|
||||
original = Path.expanduser
|
||||
|
||||
def expanduser(path):
|
||||
if str(path).startswith("~"):
|
||||
raise RuntimeError("Could not determine home directory.")
|
||||
return original(path)
|
||||
|
||||
monkeypatch.setattr(Path, "expanduser", expanduser)
|
||||
tool = ExecTool(restrict_to_workspace=True)
|
||||
error = tool._guard_command(command, str(tmp_path))
|
||||
assert error is not None
|
||||
assert error.startswith("Error: Command blocked by safety guard (path outside working dir)")
|
||||
|
||||
|
||||
def test_exec_guard_allows_resolved_home_inside_workspace(tmp_path, monkeypatch) -> None:
|
||||
original = Path.expanduser
|
||||
|
||||
def expanduser(path):
|
||||
if str(path).startswith("~"):
|
||||
return tmp_path / "file.txt"
|
||||
return original(path)
|
||||
|
||||
monkeypatch.setattr(Path, "expanduser", expanduser)
|
||||
tool = ExecTool(restrict_to_workspace=True)
|
||||
assert tool._guard_command("cat ~/file.txt", str(tmp_path)) is None
|
||||
@@ -7,7 +7,8 @@ from nanobot.security.workspace_access import (
|
||||
WorkspaceScopeError,
|
||||
default_workspace_scope,
|
||||
)
|
||||
from nanobot.session.manager import SessionManager, SessionStore
|
||||
from nanobot.session.manager import SessionManager
|
||||
from nanobot.session.sqlite_store import SqliteSessionStore
|
||||
from nanobot.webui.workspaces import (
|
||||
WebUIWorkspaceController,
|
||||
read_webui_default_access_mode,
|
||||
@@ -87,7 +88,7 @@ def test_legacy_restricted_webui_default_access_mode_maps_to_default(tmp_path, m
|
||||
assert read_webui_default_access_mode() == "default"
|
||||
|
||||
|
||||
def test_webui_default_access_applies_to_unscoped_old_sessions(tmp_path, monkeypatch) -> None:
|
||||
async def test_webui_default_access_applies_to_unscoped_old_sessions(tmp_path, monkeypatch) -> None:
|
||||
monkeypatch.setattr("nanobot.webui.workspaces.get_webui_dir", lambda: tmp_path / "webui")
|
||||
default = tmp_path / "default"
|
||||
default.mkdir()
|
||||
@@ -101,7 +102,7 @@ def test_webui_default_access_applies_to_unscoped_old_sessions(tmp_path, monkeyp
|
||||
)
|
||||
|
||||
scope = controller.scope_for_session_key("websocket:old-chat")
|
||||
new_scope = controller.scope_for_new_chat(
|
||||
new_scope = await controller.scope_for_new_chat(
|
||||
{},
|
||||
can_change_project=True,
|
||||
)
|
||||
@@ -138,7 +139,7 @@ def test_indexed_scope_preserves_missing_and_explicit_null_semantics(tmp_path, m
|
||||
assert explicit_null.access_mode == "restricted"
|
||||
|
||||
|
||||
def test_webui_default_access_does_not_override_explicit_session_scope(tmp_path, monkeypatch) -> None:
|
||||
async def test_webui_default_access_does_not_override_explicit_session_scope(tmp_path, monkeypatch) -> None:
|
||||
monkeypatch.setattr("nanobot.webui.workspaces.get_webui_dir", lambda: tmp_path / "webui")
|
||||
default = tmp_path / "default"
|
||||
project = tmp_path / "project"
|
||||
@@ -151,7 +152,7 @@ def test_webui_default_access_does_not_override_explicit_session_scope(tmp_path,
|
||||
default_restrict_to_workspace=True,
|
||||
)
|
||||
explicit = default_workspace_scope(project, restrict_to_workspace=False)
|
||||
controller.persist_scope("explicit-chat", explicit)
|
||||
await controller.persist_scope("explicit-chat", explicit)
|
||||
|
||||
scope = controller.scope_for_session_key("websocket:explicit-chat")
|
||||
|
||||
@@ -159,7 +160,7 @@ def test_webui_default_access_does_not_override_explicit_session_scope(tmp_path,
|
||||
assert scope.access_mode == "full"
|
||||
|
||||
|
||||
def test_scope_for_session_key_reads_metadata_without_full_history(
|
||||
async def test_scope_for_session_key_reads_metadata_without_full_history(
|
||||
tmp_path,
|
||||
monkeypatch,
|
||||
) -> None:
|
||||
@@ -175,7 +176,7 @@ def test_scope_for_session_key_reads_metadata_without_full_history(
|
||||
default_restrict_to_workspace=True,
|
||||
)
|
||||
explicit = default_workspace_scope(project, restrict_to_workspace=False)
|
||||
controller.persist_scope("metadata-only", explicit)
|
||||
await controller.persist_scope("metadata-only", explicit)
|
||||
|
||||
def fail_full_read(_key: str) -> None:
|
||||
raise AssertionError("scope lookup should not read full session history")
|
||||
@@ -188,7 +189,7 @@ def test_scope_for_session_key_reads_metadata_without_full_history(
|
||||
assert scope.access_mode == "full"
|
||||
|
||||
|
||||
def test_new_chat_scope_is_persisted_only_after_first_message(tmp_path, monkeypatch) -> None:
|
||||
async def test_new_chat_scope_is_persisted_only_after_first_message(tmp_path, monkeypatch) -> None:
|
||||
monkeypatch.setattr("nanobot.webui.workspaces.get_webui_dir", lambda: tmp_path / "webui")
|
||||
default = tmp_path / "default"
|
||||
project = tmp_path / "project"
|
||||
@@ -202,12 +203,12 @@ def test_new_chat_scope_is_persisted_only_after_first_message(tmp_path, monkeypa
|
||||
)
|
||||
scope = default_workspace_scope(project, restrict_to_workspace=False)
|
||||
|
||||
controller.stage_scope("draft-chat", scope)
|
||||
await controller.stage_scope("draft-chat", scope)
|
||||
|
||||
assert sessions.list_sessions() == []
|
||||
assert controller.scope_for_session_key("websocket:draft-chat") == scope
|
||||
|
||||
controller.persist_scope("draft-chat", scope)
|
||||
await controller.persist_scope("draft-chat", scope)
|
||||
|
||||
assert [item["key"] for item in sessions.list_sessions()] == ["websocket:draft-chat"]
|
||||
|
||||
@@ -227,7 +228,7 @@ def test_scope_for_session_key_always_reads_the_active_store(tmp_path, monkeypat
|
||||
residual.metadata[WORKSPACE_SCOPE_METADATA_KEY] = full_scope.metadata()
|
||||
residual_sessions.save(residual)
|
||||
|
||||
store = MagicMock(spec=SessionStore)
|
||||
store = MagicMock(spec=SqliteSessionStore)
|
||||
store.read_metadata.side_effect = [
|
||||
{
|
||||
"key": "websocket:cached",
|
||||
@@ -242,7 +243,8 @@ def test_scope_for_session_key_always_reads_the_active_store(tmp_path, monkeypat
|
||||
"metadata": {WORKSPACE_SCOPE_METADATA_KEY: restricted_scope.metadata()},
|
||||
},
|
||||
]
|
||||
sessions = SessionManager(workspace, store=store)
|
||||
sessions = SessionManager(workspace)
|
||||
monkeypatch.setattr(sessions._store, "read_metadata", store.read_metadata)
|
||||
controller = WebUIWorkspaceController(
|
||||
session_manager=sessions,
|
||||
default_workspace=default,
|
||||
@@ -259,7 +261,7 @@ def test_scope_for_session_key_always_reads_the_active_store(tmp_path, monkeypat
|
||||
assert store.read_metadata.call_count == 2
|
||||
|
||||
|
||||
def test_remote_existing_chat_can_reduce_its_workspace_access(tmp_path, monkeypatch) -> None:
|
||||
async def test_remote_existing_chat_can_reduce_its_workspace_access(tmp_path, monkeypatch) -> None:
|
||||
monkeypatch.setattr("nanobot.webui.workspaces.get_webui_dir", lambda: tmp_path / "webui")
|
||||
default = tmp_path / "default"
|
||||
project = tmp_path / "project"
|
||||
@@ -271,12 +273,12 @@ def test_remote_existing_chat_can_reduce_its_workspace_access(tmp_path, monkeypa
|
||||
default_workspace=default,
|
||||
default_restrict_to_workspace=True,
|
||||
)
|
||||
controller.persist_scope(
|
||||
await controller.persist_scope(
|
||||
"remote-chat",
|
||||
default_workspace_scope(project, restrict_to_workspace=False),
|
||||
)
|
||||
|
||||
scope = controller.scope_for_set_request(
|
||||
scope = await controller.scope_for_set_request(
|
||||
{
|
||||
"workspace_scope": {
|
||||
"project_path": str(project),
|
||||
@@ -301,7 +303,7 @@ def test_remote_existing_chat_can_reduce_its_workspace_access(tmp_path, monkeypa
|
||||
(False, "other", "full"),
|
||||
],
|
||||
)
|
||||
def test_new_chat_allows_project_selection_in_either_access_mode(
|
||||
async def test_new_chat_allows_project_selection_in_either_access_mode(
|
||||
tmp_path,
|
||||
monkeypatch,
|
||||
default_restricted: bool,
|
||||
@@ -320,7 +322,7 @@ def test_new_chat_allows_project_selection_in_either_access_mode(
|
||||
)
|
||||
requested_path = tmp_path / project_name
|
||||
|
||||
scope = controller.scope_for_new_chat(
|
||||
scope = await controller.scope_for_new_chat(
|
||||
{
|
||||
"workspace_scope": {
|
||||
"project_path": str(requested_path),
|
||||
@@ -333,7 +335,7 @@ def test_new_chat_allows_project_selection_in_either_access_mode(
|
||||
assert scope.access_mode == access_mode
|
||||
|
||||
|
||||
def test_project_selection_can_remain_disabled_for_untrusted_connections(
|
||||
async def test_project_selection_can_remain_disabled_for_untrusted_connections(
|
||||
tmp_path,
|
||||
monkeypatch,
|
||||
) -> None:
|
||||
@@ -352,7 +354,7 @@ def test_project_selection_can_remain_disabled_for_untrusted_connections(
|
||||
WorkspaceScopeError,
|
||||
match="project selection is unavailable for this connection",
|
||||
):
|
||||
controller.scope_for_new_chat(
|
||||
await controller.scope_for_new_chat(
|
||||
{
|
||||
"workspace_scope": {
|
||||
"project_path": str(other),
|
||||
@@ -363,7 +365,7 @@ def test_project_selection_can_remain_disabled_for_untrusted_connections(
|
||||
)
|
||||
|
||||
|
||||
def test_recent_projects_survive_controller_restart_without_changing_access(tmp_path, monkeypatch) -> None:
|
||||
async def test_recent_projects_survive_controller_restart_without_changing_access(tmp_path, monkeypatch) -> None:
|
||||
monkeypatch.setattr("nanobot.webui.workspaces.get_webui_dir", lambda: tmp_path / "webui")
|
||||
default = tmp_path / "default"
|
||||
project = tmp_path / "project"
|
||||
@@ -372,12 +374,12 @@ def test_recent_projects_survive_controller_restart_without_changing_access(tmp_
|
||||
controller = WebUIWorkspaceController(
|
||||
session_manager=None, default_workspace=default, default_restrict_to_workspace=True,
|
||||
)
|
||||
scope = controller.scope_for_new_chat(
|
||||
scope = await controller.scope_for_new_chat(
|
||||
{WORKSPACE_SCOPE_METADATA_KEY: {"project_path": str(project), "access_mode": "restricted"}},
|
||||
can_change_project=True,
|
||||
)
|
||||
controller.stage_scope("first", scope)
|
||||
controller.stage_scope("second", scope)
|
||||
await controller.stage_scope("first", scope)
|
||||
await controller.stage_scope("second", scope)
|
||||
restarted = WebUIWorkspaceController(
|
||||
session_manager=None, default_workspace=default, default_restrict_to_workspace=True,
|
||||
)
|
||||
|
||||
@@ -140,7 +140,8 @@ async def test_legacy_run_identity_is_captured_before_the_first_move(tmp_path):
|
||||
cron.stop()
|
||||
|
||||
|
||||
def test_target_identity_scope_and_channel_lifecycle(tmp_path):
|
||||
@pytest.mark.asyncio
|
||||
async def test_target_identity_scope_and_channel_lifecycle(tmp_path):
|
||||
sessions, _, job = seed(tmp_path)
|
||||
(tmp_path / "other").mkdir()
|
||||
workspaces = WebUIWorkspaceController(session_manager=sessions,
|
||||
@@ -154,41 +155,40 @@ def test_target_identity_scope_and_channel_lifecycle(tmp_path):
|
||||
session = sessions.get_or_create(key)
|
||||
session.metadata.update(metadata)
|
||||
sessions.save(session)
|
||||
chats = automation_chats(job, sessions, workspaces, {"telegram": {"running": True}})
|
||||
chats = await automation_chats(job, sessions, workspaces, {"telegram": {"running": True}})
|
||||
assert {chat.binding.session_key for chat in chats} == {"websocket:source", "telegram:-100:topic:42"}
|
||||
target = next(chat for chat in chats if chat.title == "Product team")
|
||||
assert target.binding == target_binding()
|
||||
assert set(target.public_payload()) == {"id", "title", "channel"}
|
||||
assert "-100" not in json.dumps(target.public_payload())
|
||||
assert len(automation_chats(job, sessions, workspaces, {})) == 1
|
||||
assert len(await automation_chats(job, sessions, workspaces, {})) == 1
|
||||
job.payload.session_key = "telegram:-100:topic:42"
|
||||
job.payload.origin_channel = "telegram"
|
||||
job.payload.origin_chat_id = "-100"
|
||||
offline = automation_chats(job, sessions, workspaces, {})
|
||||
offline = await automation_chats(job, sessions, workspaces, {})
|
||||
current = next(chat for chat in offline if chat.title == "Product team")
|
||||
assert current.public_payload()["unavailable"] is True
|
||||
# Only identical display names need a visible disambiguator.
|
||||
session = sessions.get_or_create("websocket:source")
|
||||
session.metadata["title"] = "Product team"
|
||||
sessions.save(session)
|
||||
duplicates = automation_chats(job, sessions, workspaces, {})
|
||||
await sessions.state.update_metadata(session.key, {"title": "Product team"})
|
||||
duplicates = await automation_chats(job, sessions, workspaces, {})
|
||||
assert len({chat.title for chat in duplicates}) == 2
|
||||
assert all(" · @" in chat.title for chat in duplicates)
|
||||
|
||||
|
||||
def test_untitled_chat_uses_message_preview_until_renamed(tmp_path):
|
||||
@pytest.mark.asyncio
|
||||
async def test_untitled_chat_uses_message_preview_until_renamed(tmp_path):
|
||||
sessions, _, job = seed(tmp_path)
|
||||
chat = sessions.get_or_create("websocket:reminder")
|
||||
chat.add_message("user", "十分钟后提醒我喝水")
|
||||
sessions.save(chat)
|
||||
workspaces = WebUIWorkspaceController(session_manager=sessions,
|
||||
default_workspace=tmp_path / "workspace", default_restrict_to_workspace=False)
|
||||
chats = automation_chats(job, sessions, workspaces, {})
|
||||
chats = await automation_chats(job, sessions, workspaces, {})
|
||||
choice = next(item for item in chats if item.binding.session_key == chat.key)
|
||||
assert choice.public_payload()["title"] == "十分钟后提醒我喝水"
|
||||
chat.metadata.update(title="My reminders", title_user_edited=True)
|
||||
sessions.save(chat)
|
||||
renamed = next(item for item in automation_chats(job, sessions, workspaces, {})
|
||||
await sessions.state.update_metadata(chat.key, {"title": "My reminders", "title_user_edited": True})
|
||||
renamed = next(item for item in await automation_chats(job, sessions, workspaces, {})
|
||||
if item.binding.session_key == chat.key)
|
||||
assert renamed.id == choice.id
|
||||
assert renamed.title == "My reminders"
|
||||
|
||||
@@ -38,12 +38,15 @@ def test_file_reference_outside_project_has_no_relative_path(tmp_path) -> None:
|
||||
|
||||
|
||||
@pytest.mark.parametrize("target", ["../elsewhere.txt", "linked.txt"])
|
||||
def test_file_reference_rejects_traversal_and_symlink_escape(tmp_path, target) -> None:
|
||||
def test_file_reference_rejects_traversal_and_symlink_escape(
|
||||
tmp_path, target, create_symlink,
|
||||
) -> None:
|
||||
workspace = tmp_path / "workspace"
|
||||
workspace.mkdir()
|
||||
outside = tmp_path / "elsewhere.txt"
|
||||
outside.write_text("example")
|
||||
(workspace / "linked.txt").symlink_to(outside)
|
||||
if target == "linked.txt":
|
||||
create_symlink(workspace / "linked.txt", outside)
|
||||
scope = default_workspace_scope(workspace, restrict_to_workspace=True)
|
||||
with pytest.raises(WebUIFilePreviewError) as error:
|
||||
file_reference_payload(target, scope=scope)
|
||||
@@ -106,12 +109,12 @@ def test_text_truncation_is_unchanged(tmp_path: Path) -> None:
|
||||
assert result["truncated"] is True
|
||||
|
||||
|
||||
def test_raster_symlink_cannot_escape_workspace(tmp_path: Path) -> None:
|
||||
def test_raster_symlink_cannot_escape_workspace(tmp_path: Path, create_symlink) -> None:
|
||||
workspace = tmp_path / "workspace"
|
||||
workspace.mkdir()
|
||||
image = tmp_path / "outside.png"
|
||||
image.write_bytes(PNG)
|
||||
(workspace / "linked.png").symlink_to(image)
|
||||
create_symlink(workspace / "linked.png", image)
|
||||
with pytest.raises(WebUIFilePreviewError) as error:
|
||||
file_preview_payload(
|
||||
"linked.png", scope=default_workspace_scope(workspace, restrict_to_workspace=True),
|
||||
|
||||
+15
-19
@@ -6,15 +6,14 @@ from unittest.mock import ANY, AsyncMock, MagicMock
|
||||
import pytest
|
||||
|
||||
import nanobot.webui.forking as forking
|
||||
from nanobot.session.webui_turns import WEBUI_TITLE_METADATA_KEY
|
||||
|
||||
|
||||
def test_create_fork_rebuilds_missing_transcript_and_saves_clean_title(
|
||||
async def test_create_fork_rebuilds_missing_transcript_and_saves_clean_title(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
forked = SimpleNamespace(messages=[{"role": "user", "content": "hello"}], metadata={})
|
||||
manager = MagicMock()
|
||||
manager.fork_session_before_user_index.return_value = forked
|
||||
manager.state.fork = AsyncMock(return_value=forked)
|
||||
rebuild = MagicMock()
|
||||
marker = MagicMock()
|
||||
monkeypatch.setattr(forking.uuid, "uuid4", lambda: "fork-id")
|
||||
@@ -22,7 +21,7 @@ def test_create_fork_rebuilds_missing_transcript_and_saves_clean_title(
|
||||
monkeypatch.setattr(forking, "write_session_messages_as_transcript", rebuild)
|
||||
monkeypatch.setattr(forking, "append_fork_marker", marker)
|
||||
|
||||
result = forking.create_webui_chat_fork(
|
||||
result = await forking.create_webui_chat_fork(
|
||||
manager,
|
||||
source_chat_id="source",
|
||||
before_user_index=2,
|
||||
@@ -30,25 +29,22 @@ def test_create_fork_rebuilds_missing_transcript_and_saves_clean_title(
|
||||
)
|
||||
|
||||
assert result == ("fork-id", "websocket:fork-id")
|
||||
manager.fork_session_before_user_index.assert_called_once_with(
|
||||
manager.state.fork.assert_awaited_once_with(
|
||||
"websocket:source",
|
||||
"websocket:fork-id",
|
||||
2,
|
||||
title="Useful fork",
|
||||
)
|
||||
rebuild.assert_called_once_with("websocket:fork-id", forked.messages)
|
||||
marker.assert_called_once_with("websocket:fork-id")
|
||||
assert forked.metadata[WEBUI_TITLE_METADATA_KEY] == "Useful fork"
|
||||
manager.save.assert_called_once_with(forked, fsync=True)
|
||||
|
||||
|
||||
def test_create_fork_rolls_back_session_and_transcript_together(
|
||||
async def test_create_fork_rolls_back_session_and_transcript_together(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
manager = MagicMock()
|
||||
manager.fork_session_before_user_index.return_value = SimpleNamespace(
|
||||
messages=[],
|
||||
metadata={},
|
||||
)
|
||||
manager.state.fork = AsyncMock(return_value=SimpleNamespace(messages=[], metadata={}))
|
||||
manager.state.delete = AsyncMock()
|
||||
delete_transcript = MagicMock()
|
||||
monkeypatch.setattr(forking.uuid, "uuid4", lambda: "failed-fork")
|
||||
monkeypatch.setattr(
|
||||
@@ -59,25 +55,25 @@ def test_create_fork_rolls_back_session_and_transcript_together(
|
||||
monkeypatch.setattr(forking, "delete_webui_transcript", delete_transcript)
|
||||
|
||||
with pytest.raises(OSError, match="disk full"):
|
||||
forking.create_webui_chat_fork(
|
||||
await forking.create_webui_chat_fork(
|
||||
manager,
|
||||
source_chat_id="source",
|
||||
before_user_index=1,
|
||||
)
|
||||
|
||||
delete_transcript.assert_called_once_with("websocket:failed-fork")
|
||||
manager.delete_session.assert_called_once_with("websocket:failed-fork")
|
||||
manager.state.delete.assert_awaited_once_with("websocket:failed-fork")
|
||||
|
||||
|
||||
def test_create_fork_stops_before_transcript_work_when_source_is_invalid(
|
||||
async def test_create_fork_stops_before_transcript_work_when_source_is_invalid(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
manager = MagicMock()
|
||||
manager.fork_session_before_user_index.return_value = None
|
||||
manager.state.fork = AsyncMock(return_value=None)
|
||||
fork_transcript = MagicMock()
|
||||
monkeypatch.setattr(forking, "fork_transcript_before_user_index", fork_transcript)
|
||||
|
||||
result = forking.create_webui_chat_fork(
|
||||
result = await forking.create_webui_chat_fork(
|
||||
manager,
|
||||
source_chat_id="missing",
|
||||
before_user_index=1,
|
||||
@@ -143,7 +139,7 @@ async def test_fork_handler_maps_invalid_source_and_internal_failure_to_stable_e
|
||||
warning = MagicMock()
|
||||
monkeypatch.setattr(forking, "logger", SimpleNamespace(warning=warning))
|
||||
envelope = {"source_chat_id": "source", "before_user_index": 0}
|
||||
monkeypatch.setattr(forking, "create_webui_chat_fork", lambda *_args, **_kwargs: None)
|
||||
monkeypatch.setattr(forking, "create_webui_chat_fork", AsyncMock(return_value=None))
|
||||
|
||||
await forking.handle_webui_fork_chat(channel, connection, envelope)
|
||||
channel.send_webui_protocol_error.assert_awaited_once_with(
|
||||
@@ -155,7 +151,7 @@ async def test_fork_handler_maps_invalid_source_and_internal_failure_to_stable_e
|
||||
monkeypatch.setattr(
|
||||
forking,
|
||||
"create_webui_chat_fork",
|
||||
MagicMock(side_effect=RuntimeError("broken transcript")),
|
||||
AsyncMock(side_effect=RuntimeError("broken transcript")),
|
||||
)
|
||||
await forking.handle_webui_fork_chat(channel, connection, envelope)
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import signal
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
@@ -144,6 +145,7 @@ def _start_gateway(config_path: Path, log_path: Path) -> subprocess.Popen[bytes]
|
||||
cwd=Path(__file__).resolve().parents[2],
|
||||
stdout=log_file,
|
||||
stderr=subprocess.STDOUT,
|
||||
creationflags=subprocess.CREATE_NEW_PROCESS_GROUP if sys.platform == "win32" else 0,
|
||||
)
|
||||
finally:
|
||||
log_file.close()
|
||||
@@ -153,12 +155,19 @@ def _start_gateway(config_path: Path, log_path: Path) -> subprocess.Popen[bytes]
|
||||
def _stop_gateway(process: subprocess.Popen[bytes]) -> None:
|
||||
if process.poll() is not None:
|
||||
return
|
||||
process.terminate()
|
||||
if sys.platform == "win32":
|
||||
# Target only this gateway's console group and let it close its SQLite worker.
|
||||
# TerminateProcess also races the child behind a venv's Python launcher.
|
||||
process.send_signal(signal.CTRL_BREAK_EVENT)
|
||||
else:
|
||||
process.terminate()
|
||||
try:
|
||||
process.wait(timeout=10)
|
||||
returncode = process.wait(timeout=30)
|
||||
except subprocess.TimeoutExpired:
|
||||
process.kill()
|
||||
process.wait(timeout=10)
|
||||
pytest.fail("gateway did not shut down gracefully within 30s")
|
||||
assert returncode == 0, f"gateway shutdown failed with exit code {returncode}"
|
||||
|
||||
|
||||
def _get_json(url: str, *, token: str | None = None) -> dict:
|
||||
@@ -195,13 +204,14 @@ def _wait_for_bootstrap(base_url: str, process: subprocess.Popen[bytes], log_pat
|
||||
|
||||
|
||||
async def _recv_until(ws: websockets.WebSocketClientProtocol, event: str) -> dict:
|
||||
deadline = time.monotonic() + 20
|
||||
while time.monotonic() < deadline:
|
||||
raw = await asyncio.wait_for(ws.recv(), timeout=5)
|
||||
payload = json.loads(raw)
|
||||
if payload.get("event") == event:
|
||||
return payload
|
||||
raise AssertionError(f"websocket event {event!r} was not received")
|
||||
try:
|
||||
async with asyncio.timeout(20):
|
||||
while True:
|
||||
payload = json.loads(await ws.recv())
|
||||
if payload.get("event") == event:
|
||||
return payload
|
||||
except TimeoutError as exc:
|
||||
raise AssertionError(f"websocket event {event!r} was not received within 20s") from exc
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -295,11 +305,11 @@ async def test_gateway_recovers_private_children_and_deletes_them_with_parent(tm
|
||||
sessions.save(parent)
|
||||
children = SubagentSessions(sessions)
|
||||
now = time.monotonic()
|
||||
children.create(SubagentStatus(
|
||||
await children.create(SubagentStatus(
|
||||
task_id="finished", label="Finished", task_description="inspect", owner=parent.key,
|
||||
started_at=now, finished_at=now, completed_at=time.time(), state="done", phase="done", result="Verified",
|
||||
))
|
||||
children.create(SubagentStatus(
|
||||
await children.create(SubagentStatus(
|
||||
task_id="abandoned", label="Abandoned", task_description="inspect", owner=parent.key,
|
||||
started_at=now, state="running", phase="thinking", result="Partial findings", partial=True,
|
||||
receipts={"follow-up": "accepted"},
|
||||
@@ -425,7 +435,7 @@ def test_gateway_restart_restores_a_completed_answer_without_replaying_model(
|
||||
"completed_tool_results": [],
|
||||
"pending_tool_calls": [],
|
||||
}
|
||||
sessions.save(session, fsync=True)
|
||||
sessions.save(session)
|
||||
|
||||
second = _start_gateway(config_path, second_log)
|
||||
try:
|
||||
|
||||
@@ -3,7 +3,6 @@ from __future__ import annotations
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import threading
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
@@ -19,6 +18,7 @@ from nanobot.session.history_visibility import HIDDEN_HISTORY_META
|
||||
from nanobot.session.manager import SessionManager
|
||||
from nanobot.session.model_selection import SESSION_MODEL_PRESET_METADATA_KEY
|
||||
from nanobot.session.recovery import RECOVERY_METADATA_KEY
|
||||
from nanobot.session.types import SESSION_TYPE_KEY, SessionType
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
@@ -28,31 +28,176 @@ def _isolate_webui_dir(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
monkeypatch.setattr(session_list_index, "get_webui_dir", lambda: webui_dir)
|
||||
|
||||
|
||||
def test_webui_session_list_reuses_valid_index_without_scanning_files(
|
||||
tmp_path: Path,
|
||||
monkeypatch,
|
||||
) -> None:
|
||||
def test_webui_session_list_reads_previews_without_loading_history(tmp_path, monkeypatch):
|
||||
manager = SessionManager(tmp_path)
|
||||
session = manager.get_or_create("websocket:indexed")
|
||||
session.metadata[SESSION_MODEL_PRESET_METADATA_KEY] = "fast"
|
||||
session.add_message("user", "indexed preview")
|
||||
manager.save(session)
|
||||
|
||||
assert list_webui_sessions(manager)[0]["preview"] == "indexed preview"
|
||||
assert list_webui_sessions(manager)[0]["model_preset"] == "fast"
|
||||
|
||||
def fail_scan(session_manager: SessionManager, path: Path, webui_dir: Path) -> None:
|
||||
raise AssertionError(f"unexpected session file scan: {path}")
|
||||
|
||||
monkeypatch.setattr(session_list_index, "_scan_session_row", fail_scan)
|
||||
def fail_load(*args, **kwargs):
|
||||
raise AssertionError("sidebar must not load conversation history or rewrite unchanged cache")
|
||||
|
||||
monkeypatch.setattr(manager._store, "load", fail_load)
|
||||
monkeypatch.setattr(manager, "read_session_metadata", fail_load)
|
||||
monkeypatch.setattr(session_list_index, "_read_index_rows", fail_load)
|
||||
monkeypatch.setattr(session_list_index, "_write_index_rows", fail_load)
|
||||
rows = list_webui_sessions(manager)
|
||||
|
||||
assert rows[0]["key"] == "websocket:indexed"
|
||||
assert rows[0]["preview"] == "indexed preview"
|
||||
assert rows[0]["model_preset"] == "fast"
|
||||
|
||||
|
||||
def test_webui_session_list_private_rows_suppress_transcript_fallback(tmp_path, monkeypatch):
|
||||
manager = SessionManager(tmp_path)
|
||||
manager.types.register(SessionType("internal", needs_handle=False, public_history=False))
|
||||
webui_dir = tmp_path / "webui"
|
||||
private_key, transcript_key = "websocket:internal", "websocket:transcript-only"
|
||||
for key in (private_key, transcript_key):
|
||||
(webui_dir / f"{SessionManager.safe_key(key)}.jsonl").write_text(
|
||||
json.dumps({"event": "user", "chat_id": key.removeprefix("websocket:"),
|
||||
"text": "transcript preview"}) + "\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
assert {row["key"] for row in list_webui_sessions(manager)} == {private_key, transcript_key}
|
||||
|
||||
public = manager.get_or_create("websocket:public")
|
||||
public.add_message("user", "public preview")
|
||||
manager.save(public)
|
||||
private = manager.get_or_create(private_key)
|
||||
private.metadata[SESSION_TYPE_KEY] = "internal"
|
||||
private.add_message("user", "private preview")
|
||||
manager.save(private)
|
||||
unknown = manager.get_or_create("websocket:unregistered")
|
||||
unknown.metadata[SESSION_TYPE_KEY] = "unregistered"
|
||||
manager.save(unknown)
|
||||
|
||||
def individual_metadata_unavailable(*_args, **_kwargs):
|
||||
pytest.fail("sidebar visibility must use the existing metadata query snapshot")
|
||||
|
||||
monkeypatch.setattr(manager, "read_session_metadata", individual_metadata_unavailable)
|
||||
rows = {row["key"]: row for row in list_webui_sessions(manager)}
|
||||
assert set(rows) == {public.key, transcript_key}
|
||||
assert rows[public.key]["preview"] == "public preview"
|
||||
assert rows[transcript_key]["preview"] == "transcript preview"
|
||||
assert {row["key"] for row in list_webui_sessions(manager)} == set(rows)
|
||||
|
||||
|
||||
def test_webui_session_list_scans_empty_display_directory_once_per_request(tmp_path, monkeypatch):
|
||||
manager = SessionManager(tmp_path)
|
||||
keys = {"websocket:first", "websocket:second", "websocket:third"}
|
||||
for key in keys:
|
||||
manager.save(manager.get_or_create(key))
|
||||
list_webui_sessions(manager)
|
||||
webui_dir = tmp_path / "webui"
|
||||
original_stat, original_scandir = Path.stat, os.scandir
|
||||
scans = []
|
||||
|
||||
def stored_files_only(path, *args, **kwargs):
|
||||
assert path.parent != webui_dir, "sidebar must not probe absent per-session display files"
|
||||
return original_stat(path, *args, **kwargs)
|
||||
|
||||
def scan(path):
|
||||
scans.append(Path(path))
|
||||
return original_scandir(path)
|
||||
|
||||
monkeypatch.setattr(Path, "stat", stored_files_only)
|
||||
monkeypatch.setattr(session_list_index.os, "scandir", scan)
|
||||
for _ in range(2):
|
||||
assert {row["key"] for row in list_webui_sessions(manager)} == keys
|
||||
assert scans == [webui_dir, webui_dir]
|
||||
|
||||
|
||||
def test_webui_session_list_snapshot_tracks_all_display_artifacts(tmp_path):
|
||||
manager = SessionManager(tmp_path)
|
||||
webui_dir = tmp_path / "webui"
|
||||
key = "websocket:artifacts"
|
||||
stem = SessionManager.safe_key(key)
|
||||
segments = webui_dir / f"{stem}.segments"
|
||||
segments.mkdir()
|
||||
active = webui_dir / f"{stem}.jsonl"
|
||||
active.write_text('{"event":"user","chat_id":"artifacts","text":"active question"}\n', encoding="utf-8")
|
||||
segment = segments / "000001.jsonl"
|
||||
segment.write_text('{"event":"user","chat_id":"artifacts","text":"older question"}\n', encoding="utf-8")
|
||||
other_files = [webui_dir / f"{stem}.json", segments / "manifest.json",
|
||||
segments / "state.json", segments / "delivery.json"]
|
||||
for path in other_files:
|
||||
path.write_text("{}\n", encoding="utf-8")
|
||||
all_files = [active, segment, *other_files]
|
||||
base_ns = int(datetime(2026, 1, 1).timestamp() * 1_000_000_000)
|
||||
for path in all_files:
|
||||
os.utime(path, ns=(base_ns, base_ns))
|
||||
|
||||
row, = list_webui_sessions(manager)
|
||||
assert row["preview"] == "older question"
|
||||
cache = json.loads((manager.sessions_dir / ".webui_session_index.json").read_text(encoding="utf-8"))
|
||||
cached, = cache["sessions"]
|
||||
assert cached["webui_activity_files"] == len(all_files)
|
||||
assert cached["webui_activity_size"] == sum(path.stat().st_size for path in all_files)
|
||||
state_file = segments / "state.json"
|
||||
state_file.write_text('{"active":true}\n', encoding="utf-8")
|
||||
newer_ns = base_ns + 1_000_000_000
|
||||
os.utime(state_file, ns=(newer_ns, newer_ns))
|
||||
refreshed, = list_webui_sessions(manager)
|
||||
assert refreshed["updated_at"] == datetime.fromtimestamp(newer_ns / 1_000_000_000).isoformat()
|
||||
other_files[0].unlink()
|
||||
other_files[-1].unlink()
|
||||
list_webui_sessions(manager)
|
||||
cached, = json.loads((manager.sessions_dir / ".webui_session_index.json").read_text(encoding="utf-8"))["sessions"]
|
||||
assert cached["webui_activity_files"] == len(all_files) - 2
|
||||
assert cached["webui_activity_size"] == sum(path.stat().st_size for path in all_files if path.exists())
|
||||
|
||||
|
||||
def test_webui_session_list_activity_uses_host_filename_case_semantics(tmp_path):
|
||||
manager = SessionManager(tmp_path)
|
||||
key = "websocket:MixedCase"
|
||||
session = manager.get_or_create(key)
|
||||
session.add_message("user", "stored question")
|
||||
session.messages[0]["timestamp"] = "2026-01-01T00:00:00"
|
||||
session.updated_at = datetime(2026, 1, 1)
|
||||
manager.save(session)
|
||||
path = tmp_path / "webui" / f"{SessionManager.safe_key(key).swapcase()}.jsonl"
|
||||
path.write_text('{"event":"turn_end","chat_id":"MixedCase"}\n', encoding="utf-8")
|
||||
activity = datetime(2026, 1, 2)
|
||||
activity_ns = int(activity.timestamp() * 1_000_000_000)
|
||||
os.utime(path, ns=(activity_ns, activity_ns))
|
||||
row, = list_webui_sessions(manager)
|
||||
assert row["updated_at"] == (activity.isoformat() if os.name == "nt" else "2026-01-01T00:00:00")
|
||||
|
||||
|
||||
def test_webui_session_list_keeps_transcript_only_key_case(tmp_path):
|
||||
key = "websocket:MixedCase"
|
||||
path = tmp_path / "webui" / f"{SessionManager.safe_key(key)}.jsonl"
|
||||
path.write_text('{"event":"user","chat_id":"MixedCase","text":"question"}\n', encoding="utf-8")
|
||||
row, = list_webui_sessions(SessionManager(tmp_path))
|
||||
assert row["key"] == key and row["preview"] == "question"
|
||||
|
||||
|
||||
def test_webui_session_list_rejects_display_file_and_segment_symlinks(tmp_path):
|
||||
manager = SessionManager(tmp_path)
|
||||
webui_dir = tmp_path / "webui"
|
||||
outside = tmp_path / "outside"
|
||||
outside.mkdir()
|
||||
target = outside / "000000.jsonl"
|
||||
target.write_text('{"event":"user","chat_id":"linked","text":"outside secret"}\n', encoding="utf-8")
|
||||
safe_segments = webui_dir / "websocket_safe.segments"
|
||||
safe_segments.mkdir()
|
||||
(safe_segments / "000001.jsonl").write_text(
|
||||
'{"event":"user","chat_id":"safe","text":"safe question"}\n', encoding="utf-8",
|
||||
)
|
||||
try:
|
||||
(webui_dir / "websocket_linked.jsonl").symlink_to(target)
|
||||
(webui_dir / "websocket_directory.segments").symlink_to(outside, target_is_directory=True)
|
||||
(safe_segments / "000000.jsonl").symlink_to(target)
|
||||
except OSError:
|
||||
pytest.skip("symlink creation is unavailable")
|
||||
|
||||
row, = list_webui_sessions(manager)
|
||||
assert row["key"] == "websocket:safe" and row["preview"] == "safe question"
|
||||
|
||||
|
||||
|
||||
def test_webui_session_list_refreshes_after_model_preset_rename(tmp_path: Path) -> None:
|
||||
manager = SessionManager(tmp_path)
|
||||
session = manager.get_or_create("websocket:renamed-preset")
|
||||
@@ -143,131 +288,44 @@ def test_webui_session_list_indexes_workspace_scope_and_preserves_null(
|
||||
}
|
||||
|
||||
|
||||
def test_webui_session_list_does_not_cache_old_snapshot_with_new_signature(
|
||||
tmp_path: Path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
def test_webui_session_list_refreshes_after_concurrent_metadata_change(tmp_path, monkeypatch):
|
||||
manager = SessionManager(tmp_path)
|
||||
session_key = "websocket:scope-race"
|
||||
session = manager.get_or_create(session_key)
|
||||
session.metadata[WORKSPACE_SCOPE_METADATA_KEY] = {
|
||||
"project_path": str(tmp_path),
|
||||
"access_mode": "full",
|
||||
}
|
||||
session.add_message("user", "hello")
|
||||
key = "websocket:scope-race"
|
||||
session = manager.get_or_create(key)
|
||||
session.metadata[WORKSPACE_SCOPE_METADATA_KEY] = {"project_path": str(tmp_path), "access_mode": "full"}
|
||||
manager.save(session)
|
||||
session_path = manager._get_session_path(session_key)
|
||||
original_open = open
|
||||
scope_changed = False
|
||||
original = manager.list_session_metadata
|
||||
|
||||
class RacingReader(io.StringIO):
|
||||
def __next__(self) -> str:
|
||||
nonlocal scope_changed
|
||||
if not scope_changed:
|
||||
scope_changed = True
|
||||
current = manager.get_or_create(session_key)
|
||||
current.metadata[WORKSPACE_SCOPE_METADATA_KEY] = {
|
||||
"project_path": str(tmp_path),
|
||||
"access_mode": "restricted",
|
||||
}
|
||||
manager.save(current)
|
||||
return super().__next__()
|
||||
|
||||
def racing_open(path, *args, **kwargs):
|
||||
if Path(path) == session_path:
|
||||
with original_open(path, *args, **kwargs) as source:
|
||||
return RacingReader(source.read())
|
||||
return original_open(path, *args, **kwargs)
|
||||
|
||||
monkeypatch.setattr(session_list_index, "open", racing_open, raising=False)
|
||||
def racing_read():
|
||||
snapshot = original()
|
||||
manager.update_session_metadata(key, {WORKSPACE_SCOPE_METADATA_KEY: {
|
||||
"project_path": str(tmp_path), "access_mode": "restricted",
|
||||
}})
|
||||
return snapshot
|
||||
|
||||
monkeypatch.setattr(manager, "list_session_metadata", racing_read)
|
||||
first = list_webui_sessions(manager)[0]
|
||||
second = list_webui_sessions(manager)[0]
|
||||
|
||||
assert session_list_index.indexed_workspace_scope(first)[1]["access_mode"] == "full"
|
||||
assert session_list_index.indexed_workspace_scope(second)[1]["access_mode"] == "restricted"
|
||||
|
||||
|
||||
def test_webui_session_scan_does_not_overlap_session_save(
|
||||
tmp_path: Path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
manager = SessionManager(
|
||||
tmp_path / "workspace",
|
||||
sessions_root=tmp_path / "runtime",
|
||||
)
|
||||
session = manager.get_or_create("websocket:windows-reader")
|
||||
|
||||
def test_webui_session_list_sees_committed_snapshot_during_write(tmp_path):
|
||||
manager = SessionManager(tmp_path)
|
||||
session = manager.get_or_create("websocket:concurrent")
|
||||
session.add_message("user", "before")
|
||||
manager.save(session)
|
||||
session_path = manager._get_session_path(session.key)
|
||||
session.messages[0]["content"] = "after"
|
||||
with ThreadPoolExecutor(max_workers=1) as executor:
|
||||
def write() -> None:
|
||||
manager.save(session)
|
||||
rows = executor.submit(list_webui_sessions, manager).result(timeout=3)
|
||||
assert rows[0]["preview"] == "before"
|
||||
|
||||
reader_open = threading.Event()
|
||||
release_reader = threading.Event()
|
||||
save_started = threading.Event()
|
||||
save_lock_attempted = threading.Event()
|
||||
write_entered = threading.Event()
|
||||
original_open = open
|
||||
store = manager._jsonl_store
|
||||
original_acquire = store._session_files_lock.acquire
|
||||
original_save_unlocked = store._save_unlocked
|
||||
manager._store.run_write(write)
|
||||
assert list_webui_sessions(manager)[0]["preview"] == "after"
|
||||
|
||||
class BlockingReader:
|
||||
def __init__(self, file):
|
||||
self.file = file
|
||||
|
||||
def __enter__(self):
|
||||
entered = self.file.__enter__()
|
||||
reader_open.set()
|
||||
if not release_reader.wait(5):
|
||||
raise AssertionError("timed out waiting to release the session reader")
|
||||
return entered
|
||||
|
||||
def __exit__(self, *args):
|
||||
try:
|
||||
return self.file.__exit__(*args)
|
||||
finally:
|
||||
reader_open.clear()
|
||||
|
||||
def blocking_open(path, *args, **kwargs):
|
||||
file = original_open(path, *args, **kwargs)
|
||||
if Path(path) == session_path:
|
||||
return BlockingReader(file)
|
||||
return file
|
||||
|
||||
def observed_acquire(*args, **kwargs):
|
||||
if save_started.is_set():
|
||||
save_lock_attempted.set()
|
||||
return original_acquire(*args, **kwargs)
|
||||
|
||||
def observed_save_unlocked(session, *, fsync=False):
|
||||
write_entered.set()
|
||||
assert not reader_open.is_set(), "save entered while the canonical file was open"
|
||||
return original_save_unlocked(session, fsync=fsync)
|
||||
|
||||
monkeypatch.setattr(session_list_index, "open", blocking_open, raising=False)
|
||||
monkeypatch.setattr(store._session_files_lock, "acquire", observed_acquire)
|
||||
monkeypatch.setattr(store, "_save_unlocked", observed_save_unlocked)
|
||||
|
||||
def save_session() -> None:
|
||||
save_started.set()
|
||||
manager.save(session)
|
||||
|
||||
with ThreadPoolExecutor(max_workers=2) as executor:
|
||||
list_future = executor.submit(list_webui_sessions, manager)
|
||||
try:
|
||||
assert reader_open.wait(5)
|
||||
save_future = executor.submit(save_session)
|
||||
assert save_lock_attempted.wait(5)
|
||||
assert not write_entered.is_set()
|
||||
finally:
|
||||
release_reader.set()
|
||||
|
||||
assert list_future.result(timeout=5)[0]["preview"] == "before"
|
||||
save_future.result(timeout=5)
|
||||
|
||||
assert write_entered.is_set()
|
||||
assert list_webui_sessions(manager)[0]["preview"] == "after"
|
||||
|
||||
|
||||
def test_webui_session_list_rejects_invalid_internal_model_preset_metadata(
|
||||
@@ -286,7 +344,7 @@ def test_webui_session_list_rejects_invalid_internal_model_preset_metadata(
|
||||
assert manager.get_or_create(session.key).metadata["model_preset"] == 7
|
||||
|
||||
|
||||
def test_webui_session_list_rescans_only_changed_file(tmp_path: Path, monkeypatch) -> None:
|
||||
def test_webui_session_list_reflects_changed_preview(tmp_path: Path, monkeypatch) -> None:
|
||||
manager = SessionManager(tmp_path)
|
||||
first = manager.get_or_create("websocket:first")
|
||||
first.add_message("user", "first")
|
||||
@@ -301,22 +359,8 @@ def test_webui_session_list_rescans_only_changed_file(tmp_path: Path, monkeypatc
|
||||
second.add_message("user", "second after")
|
||||
manager.save(second)
|
||||
|
||||
original_scan = session_list_index._scan_session_row
|
||||
scanned: list[str] = []
|
||||
|
||||
def record_scan(
|
||||
session_manager: SessionManager,
|
||||
path: Path,
|
||||
webui_dir: Path,
|
||||
) -> dict | None:
|
||||
scanned.append(path.name)
|
||||
return original_scan(session_manager, path, webui_dir)
|
||||
|
||||
monkeypatch.setattr(session_list_index, "_scan_session_row", record_scan)
|
||||
|
||||
rows = list_webui_sessions(manager)
|
||||
|
||||
assert scanned == [manager._get_session_path("websocket:second").name]
|
||||
assert {row["preview"] for row in rows} == {"first", "second after"}
|
||||
|
||||
|
||||
@@ -377,7 +421,7 @@ def test_webui_session_list_recovers_transcript_without_canonical_session(
|
||||
assert row["key"] == key
|
||||
assert row["preview"] == "original question"
|
||||
assert row["created_at"] == datetime.fromtimestamp(1785502800).isoformat()
|
||||
assert not manager._get_session_path(key).exists()
|
||||
assert manager.read_session_snapshot(key) is None
|
||||
assert manager.list_sessions() == []
|
||||
|
||||
reloaded = SessionManager(tmp_path / "workspace")
|
||||
@@ -741,22 +785,8 @@ def test_webui_session_list_rescans_when_transcript_changes(
|
||||
activity_ns = int(datetime(2026, 6, 15, 12, 30, 0).timestamp() * 1_000_000_000)
|
||||
os.utime(transcript, ns=(activity_ns, activity_ns))
|
||||
|
||||
original_scan = session_list_index._scan_session_row
|
||||
scanned: list[str] = []
|
||||
|
||||
def record_scan(
|
||||
session_manager: SessionManager,
|
||||
path: Path,
|
||||
webui_dir: Path,
|
||||
) -> dict | None:
|
||||
scanned.append(path.name)
|
||||
return original_scan(session_manager, path, webui_dir)
|
||||
|
||||
monkeypatch.setattr(session_list_index, "_scan_session_row", record_scan)
|
||||
|
||||
rows = list_webui_sessions(manager)
|
||||
|
||||
assert scanned == [manager._get_session_path("websocket:transcript-change").name]
|
||||
assert rows[0]["updated_at"].startswith("2026-06-15T12:30:00")
|
||||
|
||||
|
||||
@@ -790,14 +820,74 @@ def list_webui_sessions(manager: SessionManager) -> list[dict]:
|
||||
return session_list_index.list_webui_sessions(manager)
|
||||
|
||||
|
||||
async def test_sidebar_allocates_handles_then_reads_during_pending_write(tmp_path, monkeypatch):
|
||||
import asyncio
|
||||
import threading
|
||||
from types import SimpleNamespace
|
||||
|
||||
from websockets.datastructures import Headers
|
||||
from websockets.http11 import Request
|
||||
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.channels.websocket.runtime import WebSocketConfig
|
||||
from nanobot.webui.gateway_services import build_gateway_services
|
||||
|
||||
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path / "data")
|
||||
manager = SessionManager(tmp_path / "workspace")
|
||||
state = manager.state
|
||||
key = "websocket:busy"
|
||||
await state.get(key)
|
||||
await state.update_metadata(key, {"title": "committed"})
|
||||
gateway = build_gateway_services(
|
||||
config=WebSocketConfig(), bus=MessageBus(), session_manager=manager,
|
||||
static_dist_path=None, workspace_path=tmp_path / "workspace",
|
||||
default_restrict_to_workspace=True, runtime_model_name=lambda: "test-model",
|
||||
runtime_surface="gateway", runtime_capabilities_overrides=None,
|
||||
)
|
||||
token = gateway.tokens.issue_api_token(60)
|
||||
connection = SimpleNamespace(remote_address=("127.0.0.1", 12345))
|
||||
request = Request("/api/sessions", Headers({"Authorization": f"Bearer {token}"}))
|
||||
started, release = threading.Event(), threading.Event()
|
||||
original = manager._store.replace_metadata
|
||||
|
||||
def blocked(session_key, metadata, **kwargs):
|
||||
started.set()
|
||||
assert release.wait(5)
|
||||
return original(session_key, metadata, **kwargs)
|
||||
|
||||
try:
|
||||
first = await gateway.http.dispatch(connection, request)
|
||||
assert first.status_code == 200
|
||||
first_row, = json.loads(first.body)["sessions"]
|
||||
persisted = await state.read_metadata(key)
|
||||
assert first_row["handle"]["name"] == persisted["metadata"]["session_handle"]
|
||||
monkeypatch.setattr(manager._store, "replace_metadata", blocked)
|
||||
write = asyncio.create_task(state.update_metadata(key, {"title": "next"}))
|
||||
try:
|
||||
assert await asyncio.to_thread(started.wait, 2)
|
||||
response = await asyncio.wait_for(gateway.http.dispatch(connection, request), 0.5)
|
||||
assert response.status_code == 200
|
||||
row, = json.loads(response.body)["sessions"]
|
||||
assert row["title"] == "committed"
|
||||
assert row["handle"] == first_row["handle"]
|
||||
finally:
|
||||
release.set()
|
||||
await write
|
||||
finally:
|
||||
release.set()
|
||||
await state.aclose()
|
||||
|
||||
|
||||
def test_webui_session_list_fallback_time_when_missing(tmp_path: Path) -> None:
|
||||
manager = SessionManager(tmp_path)
|
||||
path = manager._get_session_path("websocket:missing-time")
|
||||
legacy = tmp_path / "sessions"
|
||||
legacy.mkdir()
|
||||
path = legacy / "websocket_missing-time.jsonl"
|
||||
path.write_text(
|
||||
'{"_type": "metadata", "key": "websocket:missing-time"}\n'
|
||||
'{"_type": "message", "role": "user", "content": "hello"}\n',
|
||||
encoding="utf-8",
|
||||
)
|
||||
manager = SessionManager(tmp_path)
|
||||
|
||||
rows = list_webui_sessions(manager)
|
||||
assert len(rows) == 1
|
||||
@@ -809,13 +899,15 @@ def test_webui_session_list_fallback_time_when_missing(tmp_path: Path) -> None:
|
||||
|
||||
|
||||
def test_session_manager_list_sessions_fallback_time_when_missing(tmp_path: Path) -> None:
|
||||
manager = SessionManager(tmp_path)
|
||||
path = manager._get_session_path("websocket:missing-time2")
|
||||
legacy = tmp_path / "sessions"
|
||||
legacy.mkdir()
|
||||
path = legacy / "websocket_missing-time2.jsonl"
|
||||
path.write_text(
|
||||
'{"_type": "metadata", "key": "websocket:missing-time2"}\n'
|
||||
'{"_type": "message", "role": "user", "content": "hello"}\n',
|
||||
encoding="utf-8",
|
||||
)
|
||||
manager = SessionManager(tmp_path)
|
||||
|
||||
sessions = manager.list_sessions()
|
||||
assert len(sessions) == 1
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import threading
|
||||
|
||||
import pytest
|
||||
|
||||
from nanobot.session.manager import SessionManager
|
||||
from nanobot.session.session_handles import (
|
||||
@@ -28,7 +32,33 @@ def _handle(manager: SessionManager, key: str) -> SessionHandle:
|
||||
return handle
|
||||
|
||||
|
||||
def test_normalize_session_mentions_keeps_only_existing_distinct_other_targets(
|
||||
@pytest.mark.parametrize("raw", [None, []], ids=["missing", "empty"])
|
||||
async def test_empty_mentions_do_not_wait_for_unrelated_storage(tmp_path, monkeypatch, raw):
|
||||
manager = SessionManager(tmp_path)
|
||||
state = manager.state
|
||||
await state.get("websocket:busy")
|
||||
started, release = threading.Event(), threading.Event()
|
||||
original = manager._store.replace_metadata
|
||||
|
||||
def blocked(key, metadata, **kwargs):
|
||||
started.set()
|
||||
assert release.wait(5)
|
||||
return original(key, metadata, **kwargs)
|
||||
|
||||
monkeypatch.setattr(manager._store, "replace_metadata", blocked)
|
||||
busy = asyncio.create_task(state.update_metadata("websocket:busy", {"title": "busy"}))
|
||||
try:
|
||||
assert await asyncio.to_thread(started.wait, 2)
|
||||
assert await asyncio.wait_for(WebuiSessionAccess(manager).normalize_mentions(raw), 1) == []
|
||||
assert not busy.done()
|
||||
finally:
|
||||
release.set()
|
||||
await busy
|
||||
await state.aclose()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_normalize_session_mentions_keeps_only_existing_distinct_other_targets(
|
||||
tmp_path,
|
||||
monkeypatch,
|
||||
) -> None:
|
||||
@@ -39,7 +69,7 @@ def test_normalize_session_mentions_keeps_only_existing_distinct_other_targets(
|
||||
_save_session(manager, "websocket:street", "Straße")
|
||||
_save_session(manager, "websocket:upper", "STRASSE")
|
||||
_save_session(manager, "telegram:history", "Telegram history")
|
||||
mentions = WebuiSessionAccess(manager).normalize_mentions(
|
||||
mentions = await WebuiSessionAccess(manager).normalize_mentions(
|
||||
[
|
||||
{
|
||||
"name": "pricing",
|
||||
@@ -57,6 +87,7 @@ def test_normalize_session_mentions_keeps_only_existing_distinct_other_targets(
|
||||
exclude_session_key="websocket:current",
|
||||
)
|
||||
|
||||
handles = await SessionHandleResolver(manager).alist_all_by_key()
|
||||
assert mentions == [
|
||||
{
|
||||
"id": handle.id,
|
||||
@@ -71,7 +102,7 @@ def test_normalize_session_mentions_keeps_only_existing_distinct_other_targets(
|
||||
("websocket:upper", "STRASSE"),
|
||||
("telegram:history", "Telegram history"),
|
||||
)
|
||||
for handle in (_handle(manager, key),)
|
||||
for handle in (handles[key],)
|
||||
]
|
||||
|
||||
|
||||
@@ -91,7 +122,11 @@ def test_session_mention_context_treats_titles_as_data() -> None:
|
||||
assert json.loads(block.content.splitlines()[2])[0]["session_key"] == "websocket:history"
|
||||
|
||||
|
||||
def test_session_mentions_do_not_isolate_workspaces(tmp_path) -> None:
|
||||
@pytest.mark.asyncio
|
||||
async def test_session_mentions_do_not_isolate_workspaces(tmp_path, monkeypatch) -> None:
|
||||
webui_dir = tmp_path / "webui"
|
||||
monkeypatch.setattr("nanobot.webui.transcript.get_webui_dir", lambda: webui_dir)
|
||||
monkeypatch.setattr("nanobot.webui.session_list_index.get_webui_dir", lambda: webui_dir)
|
||||
manager = SessionManager(tmp_path)
|
||||
project_b = tmp_path / "b"
|
||||
project_b.mkdir()
|
||||
@@ -106,12 +141,13 @@ def test_session_mentions_do_not_isolate_workspaces(tmp_path) -> None:
|
||||
manager.save(session)
|
||||
|
||||
access = WebuiSessionAccess(manager)
|
||||
mentions = access.normalize_mentions(
|
||||
mentions = await access.normalize_mentions(
|
||||
[{"name": "other", "session_key": "websocket:other"}],
|
||||
exclude_session_key="websocket:current",
|
||||
)
|
||||
|
||||
handle = _handle(manager, "websocket:other")
|
||||
handle = await SessionHandleResolver(manager).ahandle_for_session("websocket:other")
|
||||
assert handle is not None
|
||||
assert mentions == [{
|
||||
"id": handle.id,
|
||||
"name": handle.name,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from unittest.mock import MagicMock
|
||||
from unittest.mock import AsyncMock, MagicMock
|
||||
|
||||
import pytest
|
||||
|
||||
@@ -8,9 +8,10 @@ from nanobot.session.recovery import RECOVERY_METADATA_KEY
|
||||
from nanobot.webui.session_projection import WebUISessionProjection
|
||||
|
||||
|
||||
def test_attach_fields_restore_session_runtime_metadata() -> None:
|
||||
async def test_attach_fields_restore_session_runtime_metadata() -> None:
|
||||
usage = LLMUsage.reported(input_tokens=120, output_tokens=8, total_tokens=175)
|
||||
sessions = MagicMock()
|
||||
sessions.state.read_metadata = AsyncMock(side_effect=lambda key: sessions.read_session_metadata(key))
|
||||
sessions.read_session_metadata.return_value = {
|
||||
"metadata": {
|
||||
SESSION_MODEL_PRESET_METADATA_KEY: "Deep Research",
|
||||
@@ -25,7 +26,7 @@ def test_attach_fields_restore_session_runtime_metadata() -> None:
|
||||
|
||||
projection = WebUISessionProjection(sessions)
|
||||
|
||||
assert projection.attach_fields("websocket:chat-1") == {
|
||||
assert await projection.attach_fields("websocket:chat-1") == {
|
||||
"model_preset": "Deep Research",
|
||||
"recovery_state": {
|
||||
"status": "recovered",
|
||||
@@ -37,23 +38,25 @@ def test_attach_fields_restore_session_runtime_metadata() -> None:
|
||||
sessions.read_session_metadata.assert_called_once_with("websocket:chat-1")
|
||||
|
||||
|
||||
def test_attach_fields_tolerate_missing_or_invalid_session_metadata() -> None:
|
||||
async def test_attach_fields_tolerate_missing_or_invalid_session_metadata() -> None:
|
||||
sessions = MagicMock()
|
||||
sessions.state.read_metadata = AsyncMock(side_effect=lambda key: sessions.read_session_metadata(key))
|
||||
sessions.read_session_metadata.return_value = {
|
||||
"metadata": {SESSION_MODEL_PRESET_METADATA_KEY: 42}
|
||||
}
|
||||
log = MagicMock()
|
||||
projection = WebUISessionProjection(sessions, log=log)
|
||||
|
||||
assert projection.attach_fields("websocket:invalid") == {"model_preset": None}
|
||||
assert await projection.attach_fields("websocket:invalid") == {"model_preset": None}
|
||||
log.warning.assert_called_once()
|
||||
assert WebUISessionProjection(None).attach_fields("websocket:missing") == {}
|
||||
assert await WebUISessionProjection(None).attach_fields("websocket:missing") == {}
|
||||
|
||||
|
||||
def test_hydration_events_restore_goal_and_running_turn(
|
||||
async def test_hydration_events_restore_goal_and_running_turn(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
sessions = MagicMock()
|
||||
sessions.state.read_metadata = AsyncMock(side_effect=lambda key: sessions.read_session_metadata(key))
|
||||
sessions.read_session_metadata.return_value = {
|
||||
"metadata": {
|
||||
"goal_state": {
|
||||
@@ -72,7 +75,7 @@ def test_hydration_events_restore_goal_and_running_turn(
|
||||
lambda _chat_id: "turn-1",
|
||||
)
|
||||
|
||||
events = WebUISessionProjection(sessions).hydration_events(
|
||||
events = await WebUISessionProjection(sessions).hydration_events(
|
||||
"websocket:chat-1",
|
||||
"chat-1",
|
||||
)
|
||||
@@ -98,17 +101,60 @@ def test_hydration_events_restore_goal_and_running_turn(
|
||||
)
|
||||
|
||||
|
||||
def test_hydration_events_are_quiet_without_actionable_state(
|
||||
async def test_hydration_events_are_quiet_without_actionable_state(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
sessions = MagicMock()
|
||||
sessions.state.read_metadata = AsyncMock(side_effect=lambda key: sessions.read_session_metadata(key))
|
||||
sessions.read_session_metadata.return_value = {"metadata": {}}
|
||||
monkeypatch.setattr(
|
||||
"nanobot.webui.session_projection.websocket_turn_wall_started_at",
|
||||
lambda _chat_id: None,
|
||||
)
|
||||
|
||||
assert WebUISessionProjection(sessions).hydration_events(
|
||||
assert await WebUISessionProjection(sessions).hydration_events(
|
||||
"websocket:chat-1",
|
||||
"chat-1",
|
||||
) == ()
|
||||
|
||||
|
||||
async def test_hydration_yields_during_metadata_read_and_reads_live_turn_on_loop(
|
||||
tmp_path, monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
import asyncio
|
||||
import threading
|
||||
|
||||
loop_thread = threading.get_ident()
|
||||
entered = threading.Event()
|
||||
release = threading.Event()
|
||||
from nanobot.session.manager import SessionManager
|
||||
sessions = SessionManager(tmp_path)
|
||||
|
||||
def read_metadata(_key):
|
||||
assert threading.get_ident() != loop_thread
|
||||
entered.set()
|
||||
assert release.wait(timeout=3)
|
||||
return {"metadata": {}}
|
||||
|
||||
def active_turn(_chat_id):
|
||||
assert threading.get_ident() == loop_thread
|
||||
return 42.5
|
||||
|
||||
monkeypatch.setattr(sessions._store, "read_metadata", read_metadata)
|
||||
monkeypatch.setattr(
|
||||
"nanobot.webui.session_projection.websocket_turn_wall_started_at", active_turn,
|
||||
)
|
||||
projection = WebUISessionProjection(sessions)
|
||||
task = asyncio.create_task(projection.hydration_events("websocket:chat-io", "chat-io"))
|
||||
try:
|
||||
async with asyncio.timeout(2):
|
||||
while not entered.is_set() and not task.done():
|
||||
await asyncio.sleep(0)
|
||||
assert entered.is_set()
|
||||
for _ in range(5):
|
||||
await asyncio.sleep(0)
|
||||
assert not task.done()
|
||||
finally:
|
||||
release.set()
|
||||
events = await task
|
||||
assert events[0]["status"] == "running"
|
||||
@@ -1,10 +1,12 @@
|
||||
"""A restarted host replays task observations without recovering execution."""
|
||||
|
||||
import asyncio
|
||||
import hashlib
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
import textwrap
|
||||
import threading
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import AsyncMock, MagicMock
|
||||
from urllib.parse import quote
|
||||
@@ -20,6 +22,7 @@ from nanobot.agent.subagent_sessions import SUBAGENT, TASK_METADATA_KEY, Subagen
|
||||
from nanobot.agent.tools.context import RequestContext, current_request_context, request_context
|
||||
from nanobot.agent.tools.session_messages import ListSessionsTool, SendSessionMessageTool
|
||||
from nanobot.agent.tools.sessions import ReadSessionTool, SearchSessionsTool
|
||||
from nanobot.agent.tools.subagent import SubagentTool
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.bus.runtime_events import SubagentTaskChanged
|
||||
from nanobot.channels.websocket.runtime import WebSocketChannel, WebSocketConfig
|
||||
@@ -30,6 +33,8 @@ from nanobot.providers.base import (
|
||||
ProviderConversationState,
|
||||
ToolCallRequest,
|
||||
)
|
||||
from nanobot.session.jsonl_migration import WORKSPACE_BACKUP_DIR
|
||||
from nanobot.session.location import SessionLocation
|
||||
from nanobot.session.manager import SessionManager
|
||||
from nanobot.session.session_handles import SessionHandleResolver
|
||||
from nanobot.session.summary import SessionSummaryCheckpoint, is_summary_checkpoint
|
||||
@@ -62,6 +67,57 @@ def gateway_for(manager, sessions, workspace):
|
||||
return gateway, SimpleNamespace(remote_address=("127.0.0.1", 12345)), Headers({"Authorization": f"Bearer {token}"})
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("wait", [False, True])
|
||||
async def test_cancelled_task_creation_removes_committed_child(tmp_path, monkeypatch, wait):
|
||||
manager, sessions, runtime = manager_with_storage(tmp_path / "agent", tmp_path / "sessions")
|
||||
owner = "websocket:parent"
|
||||
await sessions.state.get(owner)
|
||||
entered, release = asyncio.Event(), threading.Event()
|
||||
loop = asyncio.get_running_loop()
|
||||
save = sessions._store.save
|
||||
children = []
|
||||
|
||||
def blocked_save(session, **kwargs):
|
||||
save(session, **kwargs)
|
||||
if session.key.startswith("subagent:"):
|
||||
children.append(session.key)
|
||||
loop.call_soon_threadsafe(entered.set)
|
||||
assert release.wait(5), "test did not release child persistence"
|
||||
|
||||
monkeypatch.setattr(sessions._store, "save", blocked_save)
|
||||
manager.runner.run = AsyncMock()
|
||||
|
||||
async def create():
|
||||
with request_context(RequestContext(
|
||||
channel="websocket", chat_id="parent", session_key=owner,
|
||||
runtime=runtime, can_receive_background_results=True,
|
||||
)):
|
||||
return await SubagentTool(manager).execute(action="create", task="Inspect config", wait=wait)
|
||||
|
||||
task = asyncio.create_task(create())
|
||||
try:
|
||||
await asyncio.wait_for(entered.wait(), 5)
|
||||
task.cancel()
|
||||
release.set()
|
||||
with pytest.raises(asyncio.CancelledError):
|
||||
await asyncio.wait_for(task, 5)
|
||||
assert len(children) == 1
|
||||
assert await sessions.state.read(children[0]) is None
|
||||
assert sessions.child_session_keys(owner) == []
|
||||
assert manager.statuses_for_session(owner) == {}
|
||||
assert manager.get_running_count() == 0
|
||||
manager.runner.run.assert_not_awaited()
|
||||
assert await sessions.state.read(owner) is not None
|
||||
finally:
|
||||
release.set()
|
||||
if not task.done():
|
||||
task.cancel()
|
||||
await asyncio.gather(task, return_exceptions=True)
|
||||
await manager.close()
|
||||
await sessions.state.aclose()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_child_thread_reads_real_session_through_parent_without_new_persistence(tmp_path):
|
||||
workspace, root = tmp_path / "agent", tmp_path / "sessions"
|
||||
@@ -162,7 +218,8 @@ async def test_child_activity_replays_real_tool_errors_and_file_diffs(tmp_path):
|
||||
workspace.mkdir()
|
||||
(workspace / "example.txt").write_text("before\n", encoding="utf-8")
|
||||
manager, sessions, runtime = manager_with_storage(workspace, root)
|
||||
entered, release = asyncio.Event(), asyncio.Event()
|
||||
model_requests = asyncio.Queue()
|
||||
release = asyncio.Event()
|
||||
responses = iter([
|
||||
LLMResponse(content="Read the file", tool_calls=[
|
||||
ToolCallRequest("read", "read_file", {"path": "example.txt"}),
|
||||
@@ -181,9 +238,9 @@ async def test_child_activity_replays_real_tool_errors_and_file_diffs(tmp_path):
|
||||
for message in kwargs["messages"]:
|
||||
assert not ({"tool_events", "file_edit_events"} & message.keys())
|
||||
response = next(responses, None)
|
||||
model_requests.put_nowait(None)
|
||||
if response is not None:
|
||||
return response
|
||||
entered.set()
|
||||
await release.wait()
|
||||
return LLMResponse(content="Edited the file; the other file does not exist.")
|
||||
|
||||
@@ -191,8 +248,26 @@ async def test_child_activity_replays_real_tool_errors_and_file_diffs(tmp_path):
|
||||
gateway, connection, headers = gateway_for(manager, sessions, workspace)
|
||||
try:
|
||||
await manager.spawn("Edit and inspect files", session_key="websocket:parent", runtime=runtime)
|
||||
await asyncio.wait_for(entered.wait(), 5)
|
||||
task_id, = manager.statuses_for_session("websocket:parent")
|
||||
task = manager._running_tasks[task_id]
|
||||
# Each tool's persisted activity completes before the next model request.
|
||||
for _ in range(4):
|
||||
request = asyncio.create_task(model_requests.get())
|
||||
try:
|
||||
done, _ = await asyncio.wait(
|
||||
(request, task), timeout=5, return_when=asyncio.FIRST_COMPLETED,
|
||||
)
|
||||
if task in done:
|
||||
result = task.result()
|
||||
status = manager.check(task_id, "websocket:parent")
|
||||
pytest.fail(
|
||||
"subagent ended before its activity was ready: "
|
||||
f"state={status.state}, error={status.error!r}, result={result!r}"
|
||||
)
|
||||
assert request in done, "subagent made no progress to its next model request"
|
||||
finally:
|
||||
request.cancel()
|
||||
await asyncio.gather(request, return_exceptions=True)
|
||||
path = f"/api/sessions/websocket%3Aparent/subagents/{task_id}/webui-thread"
|
||||
|
||||
async def assert_activity(gateway, connection, headers):
|
||||
@@ -320,9 +395,9 @@ async def test_task_changes_use_parent_chat_events_and_saved_child_observations(
|
||||
await asyncio.wait_for(entered.get(), 2)
|
||||
first, sibling = manager.statuses_for_session("websocket:parent")
|
||||
foreign, = manager.statuses_for_session("websocket:other")
|
||||
parent = sessions.get_existing("websocket:parent")
|
||||
parent = await sessions.state.read("websocket:parent")
|
||||
parent.add_message("assistant", "Parent reply already delivered")
|
||||
sessions.save(parent)
|
||||
await sessions.state.finish_turn(parent)
|
||||
original_messages = parent.messages.copy()
|
||||
routed = await deliver()
|
||||
assert {payload["task"]["task_id"] for conn, payload in routed if conn is parent_connection} == {first, sibling}
|
||||
@@ -358,7 +433,7 @@ async def test_task_changes_use_parent_chat_events_and_saved_child_observations(
|
||||
)
|
||||
await manager.bus.drain()
|
||||
assert manager.bus.outbound_size > 0
|
||||
sessions.delete_session("websocket:parent")
|
||||
await sessions.state.delete("websocket:parent")
|
||||
assert await deliver() == []
|
||||
finally:
|
||||
await manager.close()
|
||||
@@ -390,7 +465,7 @@ async def test_abrupt_process_exit_preserves_terminal_records_and_interrupts_pen
|
||||
sessions = SessionManager(workspace, sessions_root=Path(sys.argv[2]))
|
||||
parent = sessions.get_or_create("websocket:parent")
|
||||
parent.add_message("user", "Delegate the inspection", webui_turn_id="turn-1")
|
||||
sessions.save(parent, fsync=True)
|
||||
sessions.save(parent)
|
||||
manager = SubagentManager(workspace=workspace, bus=MessageBus(), max_tool_result_chars=16000,
|
||||
max_concurrent_subagents=1, consolidator=MagicMock(spec=Consolidator), session_manager=sessions)
|
||||
provider = MagicMock(spec=LLMProvider)
|
||||
@@ -410,7 +485,7 @@ async def test_abrupt_process_exit_preserves_terminal_records_and_interrupts_pen
|
||||
await manager.spawn("queued", session_key=parent.key, origin_turn_id="turn-1", runtime=runtime)
|
||||
statuses = manager.statuses_for_session(parent.key)
|
||||
ids = {status.task_description: task_id for task_id, status in statuses.items()}
|
||||
manager.send(ids["running"], parent.key, "Not yet delivered")
|
||||
await manager.send(ids["running"], parent.key, "Not yet delivered")
|
||||
Path(sys.argv[3]).write_text(json.dumps(ids))
|
||||
os._exit(0)
|
||||
asyncio.run(main())
|
||||
@@ -420,7 +495,7 @@ async def test_abrupt_process_exit_preserves_terminal_records_and_interrupts_pen
|
||||
manager, sessions, _ = manager_with_storage(workspace, sessions_root)
|
||||
manager.runner.run = AsyncMock()
|
||||
assert manager.check(ids["running"], "websocket:parent").state == "running"
|
||||
manager.recover_interrupted()
|
||||
await manager.recover_interrupted()
|
||||
gateway, connection, headers = gateway_for(manager, sessions, workspace)
|
||||
path = f"/api/sessions/{quote('websocket:parent', safe='')}/subagents"
|
||||
try:
|
||||
@@ -449,7 +524,7 @@ async def test_abrupt_process_exit_preserves_terminal_records_and_interrupts_pen
|
||||
assert {row["key"] for row in sessions.list_sessions()} == {
|
||||
"websocket:parent", *(SubagentSessions.key(task_id) for task_id in ids.values()),
|
||||
}
|
||||
assert [handle.session_key for handle in SessionHandleResolver(sessions).list_all()] == ["websocket:parent"]
|
||||
assert [handle.session_key for handle in await SessionHandleResolver(sessions).alist_all()] == ["websocket:parent"]
|
||||
assert not list(sessions.sessions_dir.glob("*.subagents.json"))
|
||||
with pytest.raises(SubagentControlError, match="task unavailable"):
|
||||
manager.check(ids["completed"], "websocket:other")
|
||||
@@ -514,7 +589,7 @@ async def test_child_is_unavailable_to_public_session_tools(tmp_path):
|
||||
await manager.run_inline("Private investigation", session_key="websocket:parent", runtime=runtime)
|
||||
task_id, = manager.statuses_for_session("websocket:parent")
|
||||
child_key = SubagentSessions.key(task_id)
|
||||
public_handle = SessionHandleResolver(sessions).handle_for_session("websocket:other")
|
||||
public_handle = await SessionHandleResolver(sessions).ahandle_for_session("websocket:other")
|
||||
sender = SendSessionMessageTool(sessions=sessions, bus=manager.bus)
|
||||
with request_context(RequestContext(channel="websocket", chat_id="other", session_key="websocket:other")):
|
||||
assert json.loads(await SearchSessionsTool(sessions).execute(query="Private investigation"))["results"] == []
|
||||
@@ -546,16 +621,16 @@ async def test_constructing_another_reader_does_not_interrupt_running_work(tmp_p
|
||||
await manager.spawn("inspect", session_key="websocket:parent", runtime=runtime)
|
||||
await entered.wait()
|
||||
task_id, = manager.statuses_for_session("websocket:parent")
|
||||
receipt = manager.send(task_id, "websocket:parent", "Follow-up")
|
||||
path = sessions._get_session_path(SubagentSessions.key(task_id))
|
||||
before = path.read_bytes()
|
||||
receipt = await manager.send(task_id, "websocket:parent", "Follow-up")
|
||||
child_key = SubagentSessions.key(task_id)
|
||||
before = sessions.read_session_file(child_key)
|
||||
reader, _, _ = manager_with_storage(workspace, root)
|
||||
observed = reader.check(task_id, "websocket:parent")
|
||||
assert observed.state == "running"
|
||||
assert observed.receipts[receipt["message_id"]] == "accepted"
|
||||
assert path.read_bytes() == before
|
||||
assert sessions.read_session_file(child_key) == before
|
||||
await reader.close()
|
||||
assert path.read_bytes() == before
|
||||
assert sessions.read_session_file(child_key) == before
|
||||
finally:
|
||||
release.set()
|
||||
await manager.close()
|
||||
@@ -611,19 +686,19 @@ async def test_history_outlives_the_runtime_cache_and_follows_parent_deletion(tm
|
||||
assert len(manager.statuses_for_session("websocket:parent", include_history=False)) == 1
|
||||
first = next(status for status in tasks.values() if status.task_description == "first")
|
||||
assert manager.check(first.task_id, "websocket:parent").result == "Verified"
|
||||
fork = sessions.fork_session_before_user_index("websocket:parent", "websocket:fork", 0)
|
||||
fork = await sessions.state.fork("websocket:parent", "websocket:fork", 0)
|
||||
assert TASK_METADATA_KEY not in fork.metadata
|
||||
assert sessions.child_session_keys(fork.key) == []
|
||||
child_paths = [sessions._get_session_path(SubagentSessions.key(task_id)) for task_id in tasks]
|
||||
assert all(path.exists() for path in child_paths)
|
||||
assert sessions.delete_session("websocket:parent")
|
||||
assert not any(path.exists() for path in child_paths)
|
||||
child_keys = [SubagentSessions.key(task_id) for task_id in tasks]
|
||||
assert all(sessions.read_session_file(key) is not None for key in child_keys)
|
||||
assert await sessions.state.delete("websocket:parent")
|
||||
assert all(sessions.read_session_file(key) is None for key in child_keys)
|
||||
assert manager.statuses_for_session("websocket:parent") == {}
|
||||
with pytest.raises(SubagentControlError):
|
||||
manager.check(first.task_id, "websocket:parent")
|
||||
manager.sessions.save(first)
|
||||
assert not await manager.sessions.save(first)
|
||||
assert sessions.read_session_file("websocket:parent") is None
|
||||
assert not any(path.exists() for path in child_paths)
|
||||
assert all(sessions.read_session_file(key) is None for key in child_keys)
|
||||
finally:
|
||||
await manager.close()
|
||||
|
||||
@@ -634,23 +709,17 @@ async def test_task_progress_does_not_rewrite_parent_history_or_invalidate_check
|
||||
parent = sessions.get_or_create("websocket:parent")
|
||||
parent.add_message("user", "Inspect config", webui_turn_id="turn-1")
|
||||
sessions.save(parent)
|
||||
path = sessions._get_session_path(parent.key)
|
||||
before, stamp = path.read_bytes(), path.stat()
|
||||
parent.metadata["runtime_checkpoint"] = {"phase": "tools_completed"}
|
||||
parent = await sessions.state.read(parent.key)
|
||||
parent.provider_state = ProviderConversationState(
|
||||
kind="openai_responses", provider="openai:test", model="test", version=1,
|
||||
payload={"response_id": "private-response"},
|
||||
)
|
||||
sessions.save_runtime_checkpoint(parent)
|
||||
checkpoint_path = sessions._get_runtime_checkpoint_path(parent.key)
|
||||
checkpoint = checkpoint_path.read_bytes()
|
||||
await sessions.state.checkpoint_view(parent, {"phase": "tools_completed"})
|
||||
before = sessions.read_session_file(parent.key)
|
||||
manager.runner.run = AsyncMock(return_value=AgentRunResult(messages=[], final_content="Verified"))
|
||||
try:
|
||||
await manager.run_inline("check", session_key=parent.key, runtime=runtime)
|
||||
assert path.read_bytes() == before
|
||||
assert path.stat().st_ino == stamp.st_ino
|
||||
assert path.stat().st_mtime_ns == stamp.st_mtime_ns
|
||||
assert checkpoint_path.read_bytes() == checkpoint
|
||||
assert sessions.read_session_file(parent.key) == before
|
||||
restored = SessionManager(tmp_path / "agent", sessions_root=tmp_path / "sessions").get_or_create(parent.key)
|
||||
assert restored.metadata["runtime_checkpoint"]["phase"] == "tools_completed"
|
||||
assert restored.provider_state.payload == {"response_id": "private-response"}
|
||||
@@ -660,9 +729,99 @@ async def test_task_progress_does_not_rewrite_parent_history_or_invalidate_check
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_temporary_parent_never_persists_task_content(tmp_path):
|
||||
async def test_task_control_and_panel_do_not_read_parent_or_child_history(tmp_path, monkeypatch):
|
||||
manager, sessions, runtime = manager_with_storage(tmp_path / "agent", tmp_path / "sessions")
|
||||
parent = sessions.get_or_create_transient("websocket:temporary")
|
||||
parent = sessions.get_or_create("websocket:parent")
|
||||
parent.add_message("user", "Inspect configuration.")
|
||||
sessions.save(parent)
|
||||
await sessions.state.read(parent.key)
|
||||
manager.runner.run = AsyncMock(return_value=AgentRunResult(messages=[], final_content="Verified"))
|
||||
gateway, connection, headers = gateway_for(manager, sessions, tmp_path / "agent")
|
||||
try:
|
||||
assert await manager.run_inline("check", session_key=parent.key, runtime=runtime) == "Verified"
|
||||
status, = manager.statuses_for_session(parent.key).values()
|
||||
|
||||
def history_unavailable(*_args, **_kwargs):
|
||||
pytest.fail("task ownership and status reads must not request conversation history")
|
||||
|
||||
def all_sessions_unavailable(*_args, **_kwargs):
|
||||
pytest.fail("task panels must query their own child metadata directly")
|
||||
|
||||
monkeypatch.setattr(sessions, "get_cached", history_unavailable)
|
||||
monkeypatch.setattr(sessions._store, "list_metadata", all_sessions_unavailable)
|
||||
assert manager.sessions.exists(parent.key)
|
||||
assert manager.sessions.contains(status.task_id, parent.key)
|
||||
assert not manager.sessions.contains(status.task_id, "websocket:other")
|
||||
metadata = sessions.get_cached_metadata(SubagentSessions.key(status.task_id))
|
||||
assert metadata[TASK_METADATA_KEY]["state"] == "done"
|
||||
assert metadata[TASK_METADATA_KEY]["revision"] == status.revision
|
||||
assert manager.check(status.task_id, parent.key).result == "Verified"
|
||||
response = await gateway.http.dispatch(
|
||||
connection, Request("/api/sessions/websocket%3Aparent/subagents", headers),
|
||||
)
|
||||
assert response.status_code == 200
|
||||
assert [task["task_id"] for task in json.loads(response.body)["tasks"]] == [status.task_id]
|
||||
finally:
|
||||
await manager.close()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_task_panel_reads_storage_off_loop_and_keeps_newer_completion(tmp_path, monkeypatch):
|
||||
manager, sessions, runtime = manager_with_storage(tmp_path / "agent", tmp_path / "sessions")
|
||||
gateway, connection, headers = gateway_for(manager, sessions, tmp_path / "agent")
|
||||
runner_entered, finish_task = asyncio.Event(), asyncio.Event()
|
||||
history_entered = asyncio.Event()
|
||||
release_history = threading.Event()
|
||||
loop = asyncio.get_running_loop()
|
||||
owner_thread = threading.get_ident()
|
||||
original_load = manager.sessions.load
|
||||
request_task = None
|
||||
|
||||
async def run(_spec):
|
||||
runner_entered.set()
|
||||
await finish_task.wait()
|
||||
return AgentRunResult(messages=[], final_content="Verified")
|
||||
|
||||
def paused_history(owner):
|
||||
assert threading.get_ident() != owner_thread, "task panel storage reads must leave the event loop"
|
||||
loop.call_soon_threadsafe(history_entered.set)
|
||||
assert release_history.wait(5), "task panel history read was not released"
|
||||
return original_load(owner)
|
||||
|
||||
manager.runner.run = run
|
||||
try:
|
||||
await manager.spawn("check", session_key="websocket:parent", runtime=runtime)
|
||||
await asyncio.wait_for(runner_entered.wait(), 5)
|
||||
task_id, = manager.statuses_for_session("websocket:parent")
|
||||
previous_revision = manager.check(task_id, "websocket:parent").revision
|
||||
execution = manager._running_tasks[task_id]
|
||||
monkeypatch.setattr(manager.sessions, "load", paused_history)
|
||||
request_task = asyncio.create_task(gateway.http.dispatch(
|
||||
connection, Request("/api/sessions/websocket%3Aparent/subagents", headers),
|
||||
))
|
||||
await asyncio.wait_for(history_entered.wait(), 5)
|
||||
finish_task.set()
|
||||
await asyncio.wait_for(execution, 5)
|
||||
release_history.set()
|
||||
|
||||
response = await asyncio.wait_for(request_task, 5)
|
||||
assert response.status_code == 200
|
||||
task, = json.loads(response.body)["tasks"]
|
||||
assert task["task_id"] == task_id and task["state"] == "done"
|
||||
assert task["revision"] > previous_revision
|
||||
finally:
|
||||
release_history.set()
|
||||
finish_task.set()
|
||||
if request_task is not None:
|
||||
request_task.cancel()
|
||||
await asyncio.gather(request_task, return_exceptions=True)
|
||||
await manager.close()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_temporary_parent_never_persists_task_content(tmp_path, monkeypatch):
|
||||
manager, sessions, runtime = manager_with_storage(tmp_path / "agent", tmp_path / "sessions")
|
||||
parent = await sessions.state.register_transient("websocket:temporary")
|
||||
async def run(_spec):
|
||||
assert current_request_context().log_content is False
|
||||
return AgentRunResult(messages=[], final_content="Private findings")
|
||||
@@ -676,6 +835,14 @@ async def test_temporary_parent_never_persists_task_content(tmp_path):
|
||||
child = sessions.get_cached(SubagentSessions.key(task_id))
|
||||
assert child is not None and not child.policy.persist
|
||||
assert sessions.read_session_file(child.key) is None
|
||||
|
||||
def history_unavailable(*_args, **_kwargs):
|
||||
pytest.fail("temporary task control must not request conversation history")
|
||||
|
||||
monkeypatch.setattr(sessions, "get_cached", history_unavailable)
|
||||
assert sessions.get_cached_metadata(child.key)[TASK_METADATA_KEY]["state"] == "done"
|
||||
assert manager.check(task_id, parent.key).result == "Private findings"
|
||||
assert len(manager.statuses_for_session(parent.key)) == 1
|
||||
reopened, _, _ = manager_with_storage(tmp_path / "agent", tmp_path / "sessions")
|
||||
assert reopened.statuses_for_session(parent.key) == {}
|
||||
await reopened.close()
|
||||
@@ -684,30 +851,60 @@ async def test_temporary_parent_never_persists_task_content(tmp_path):
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_child_sessions_use_common_restore_and_migration(tmp_path):
|
||||
async def test_child_sessions_migrate_from_legacy_jsonl_and_reopen(tmp_path):
|
||||
workspace, root = tmp_path / "agent", tmp_path / "sessions"
|
||||
manager, sessions, runtime = manager_with_storage(workspace, root)
|
||||
parent = sessions.get_or_create("websocket:parent")
|
||||
parent.add_message("user", "Inspect config")
|
||||
sessions.save(parent)
|
||||
manager.runner.run = AsyncMock(return_value=AgentRunResult(messages=[], final_content="Verified"))
|
||||
try:
|
||||
await manager.run_inline("inspect", session_key=parent.key, runtime=runtime)
|
||||
task_id, = manager.statuses_for_session(parent.key)
|
||||
child_key = SubagentSessions.key(task_id)
|
||||
paths = [sessions._get_session_path(key) for key in (parent.key, child_key)]
|
||||
result = sessions.restore_sessions_to_workspace()
|
||||
assert result.restored == 2 and result.conflicts == ()
|
||||
for path in paths:
|
||||
assert (workspace / "sessions" / path.name).read_bytes() == path.read_bytes()
|
||||
path.unlink()
|
||||
reopened, migrated, _ = manager_with_storage(workspace, root)
|
||||
assert migrated.child_session_keys(parent.key) == [child_key]
|
||||
assert reopened.check(task_id, parent.key).result == "Verified"
|
||||
assert not list((workspace / "sessions").glob("*.jsonl"))
|
||||
await reopened.close()
|
||||
finally:
|
||||
await manager.close()
|
||||
parent_key, task_id = "websocket:parent", "legacy-inspection"
|
||||
child_key = SubagentSessions.key(task_id)
|
||||
task_metadata = {
|
||||
"task_id": task_id, "owner": parent_key, "revision": 3,
|
||||
"label": "inspect", "task_description": "inspect", "state": "done", "phase": "done",
|
||||
"created_at": 1767225600.0, "completed_at": 1767225601.2, "elapsed_seconds": 1.2,
|
||||
"origin_turn_id": "turn-1", "iteration": 1, "result": "Verified", "stop_reason": "stop",
|
||||
}
|
||||
fixtures = {
|
||||
parent_key: [
|
||||
{"_type": "metadata", "key": parent_key, "metadata": {"webui": True},
|
||||
"created_at": "2026-01-01T00:00:00", "updated_at": "2026-01-01T00:00:00",
|
||||
"last_archived": 0},
|
||||
{"role": "user", "content": "Inspect config"},
|
||||
],
|
||||
child_key: [
|
||||
{"_type": "metadata", "key": child_key,
|
||||
"metadata": {SESSION_TYPE_KEY: SUBAGENT.name, PARENT_SESSION_KEY: parent_key,
|
||||
TASK_METADATA_KEY: task_metadata},
|
||||
"created_at": "2026-01-01T00:00:00", "updated_at": "2026-01-01T00:00:01.200000",
|
||||
"last_archived": 0},
|
||||
{"role": "user", "content": "inspect"},
|
||||
{"role": "assistant", "content": "Verified"},
|
||||
],
|
||||
}
|
||||
legacy = workspace / "sessions"
|
||||
legacy.mkdir(parents=True)
|
||||
for key, records in fixtures.items():
|
||||
(legacy / f"{SessionLocation.storage_key(key)}.jsonl").write_text(
|
||||
"\n".join(json.dumps(record) for record in records) + "\n", encoding="utf-8",
|
||||
)
|
||||
source_hashes = {path.name: hashlib.sha256(path.read_bytes()).hexdigest() for path in legacy.glob("*.jsonl")}
|
||||
|
||||
for _ in range(2):
|
||||
manager, sessions, _ = manager_with_storage(workspace, root)
|
||||
try:
|
||||
assert {row["key"] for row in sessions.list_sessions()} == set(fixtures)
|
||||
assert sessions.child_session_keys(parent_key) == [child_key]
|
||||
status = manager.check(task_id, parent_key)
|
||||
assert status.state == "done" and status.result == "Verified"
|
||||
assert status.origin_turn_id == "turn-1"
|
||||
assert manager.get_running_count() == 0
|
||||
for key, records in fixtures.items():
|
||||
restored = sessions.read_session_file(key)
|
||||
assert restored["metadata"] == records[0]["metadata"]
|
||||
assert restored["messages"] == records[1:]
|
||||
assert list(legacy.glob("*.jsonl")) == []
|
||||
backups = sessions.sessions_dir / WORKSPACE_BACKUP_DIR
|
||||
assert {path.name: hashlib.sha256(path.read_bytes()).hexdigest()
|
||||
for path in backups.glob("*.jsonl")} == source_hashes
|
||||
finally:
|
||||
await manager.close()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -720,7 +917,7 @@ async def test_unreadable_task_history_is_not_an_empty_list(tmp_path):
|
||||
task_id, = manager.statuses_for_session(parent.key)
|
||||
child = sessions.get_existing(SubagentSessions.key(task_id))
|
||||
child.metadata[TASK_METADATA_KEY] = "damaged"
|
||||
sessions.save(child)
|
||||
await sessions.state.update_metadata(child.key, {TASK_METADATA_KEY: "damaged"})
|
||||
gateway, connection, headers = gateway_for(manager, sessions, tmp_path / "agent")
|
||||
try:
|
||||
path = f"/api/sessions/{quote(parent.key, safe='')}/subagents"
|
||||
|
||||
Reference in new issue
Block a user