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
@@ -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
|
||||
Reference in new issue
Block a user