fix(session): serialize compaction with active turns

This commit is contained in:
chengyongru authored and chengyongru committed 2026-10-15 10:43:02 +08:00
1 parent 1d43b46e54
commit 2ad0da786d
6 files changed
+209 -29

No files matched your search

+3 -1
View File
@@ -592,11 +592,13 @@ Ingested messages must include `role` and `content`. Roles may be `user`, `assis
| `await compact_session(session_key)` | Run token-based consolidation for a session. |
| `await compact_idle_session(session_key, max_suffix=8)` | Run idle-session compaction and return its summary. |
Both compaction methods serialize with turns for the same session key. Call them after `bot.run()` returns, or from a separate task that can wait for the active turn to finish.
### Host integration context and persisted-turn callbacks
Host applications can attach external context without copying or modifying the nanobot agent loop. A context provider receives a `RequestContext` before each model turn and may return one or more `RuntimeContextBlock` values. Use `attributes` for caller-owned routing data; nanobot keeps it separate from trusted channel metadata and does not persist it in session messages.
`on_session_turn_persisted()` invokes its callback after a non-ephemeral turn has been saved. The callback receives `SessionTurnPersisted` and may read the completed transcript through `bot.sessions`. Callbacks run in registration order, and async callbacks are awaited before the run continues. They are observational: callback exceptions are logged and suppressed so the completed local turn remains successful. Durable external synchronization must catch failures and persist retry work before the callback returns. During SDK runs, callbacks execute while the session is still serialized and must not re-enter `bot.run()` for the same session.
`on_session_turn_persisted()` invokes its callback after a non-ephemeral turn has been saved. The callback receives `SessionTurnPersisted` and may read the completed transcript through `bot.sessions`. Callbacks run in registration order, and async callbacks are awaited before the run continues. They are observational: callback exceptions are logged and suppressed so the completed local turn remains successful. Durable external synchronization must catch failures and persist retry work before the callback returns. During SDK runs, callbacks execute while the session is still serialized and must not await `bot.run()`, `bot.runtime.compact_session()`, or `bot.runtime.compact_idle_session()` for the same session.
```python
import json
+17 -13
View File
@@ -2,6 +2,7 @@
from __future__ import annotations
import asyncio
from collections.abc import Collection
from datetime import datetime
from typing import TYPE_CHECKING, Any, Callable, Coroutine
@@ -27,13 +28,15 @@ SessionEventFactory = Callable[[str], EventSink]
class AutoCompact:
def __init__(self, sessions: SessionManager, consolidator: Consolidator,
session_ttl_minutes: int = 0,
bind_events: SessionEventFactory | None = None):
bind_events: SessionEventFactory | None = None,
*, session_lock: Callable[[str], asyncio.Lock]):
self.sessions = sessions
self.consolidator = consolidator
self._ttl = session_ttl_minutes
self._archiving: set[str] = set()
self._summaries: dict[str, SessionSummary] = {}
self._bind_events = bind_events
self._session_lock = session_lock
def _is_expired(self, ts: datetime | str | None,
now: datetime | None = None) -> bool:
@@ -91,19 +94,20 @@ class AutoCompact:
self._archiving.discard(key)
return
try:
summary = await self.consolidator.compact_idle_session(
key,
runtime=runtime,
events=self._bind_events(key) if self._bind_events else NO_EVENTS,
)
if summary:
session = self.sessions.get_or_create(key)
stored = session_summary_from_metadata(
session.metadata,
fallback_last_active=session.updated_at,
async with self._session_lock(key):
summary = await self.consolidator.compact_idle_session(
key,
runtime=runtime,
events=self._bind_events(key) if self._bind_events else NO_EVENTS,
)
if stored is not None:
self._summaries[key] = stored
if summary:
session = self.sessions.get_or_create(key)
stored = session_summary_from_metadata(
session.metadata,
fallback_last_active=session.updated_at,
)
if stored is not None:
self._summaries[key] = stored
except Exception:
logger.exception("Auto-compact: failed for {}", key)
finally:
+1
View File
@@ -437,6 +437,7 @@ class AgentLoop:
consolidator=self.consolidator,
session_ttl_minutes=session_ttl_minutes,
bind_events=self._idle_events,
session_lock=self._get_session_lock,
)
self._idle_compact_check_interval_s = idle_compact_check_interval_seconds
self._next_idle_compact_check_at = time.monotonic()
+16 -14
View File
@@ -210,20 +210,22 @@ class RuntimeClient:
async def compact_session(self, session_key: str) -> SessionSnapshot:
"""Summarize one session and exclude its archived messages from replay."""
session = self._loop.sessions.get_or_create(session_key)
runtime = self._loop.runtime_for_session(session)
await self._loop.consolidator.compact_idle_session(
session_key,
runtime=runtime,
)
return snapshot_from_session(self._loop.sessions.get_or_create(session_key))
async with self._loop._get_session_lock(session_key): # pyright: ignore[reportPrivateUsage]
session = self._loop.sessions.get_or_create(session_key)
runtime = self._loop.runtime_for_session(session)
await self._loop.consolidator.compact_idle_session(
session_key,
runtime=runtime,
)
return snapshot_from_session(self._loop.sessions.get_or_create(session_key))
async def compact_idle_session(self, session_key: str, *, max_suffix: int = 0) -> str | None:
"""Return a replacement summary; legacy ``max_suffix`` no longer retains history."""
session = self._loop.sessions.get_or_create(session_key)
runtime = self._loop.runtime_for_session(session)
return await self._loop.consolidator.compact_idle_session(
session_key,
runtime=runtime,
max_suffix=max_suffix,
)
async with self._loop._get_session_lock(session_key): # pyright: ignore[reportPrivateUsage]
session = self._loop.sessions.get_or_create(session_key)
runtime = self._loop.runtime_for_session(session)
return await self._loop.consolidator.compact_idle_session(
session_key,
runtime=runtime,
max_suffix=max_suffix,
)
+5 -1
View File
@@ -1,5 +1,6 @@
"""Direct unit tests for AutoCompact class methods in isolation."""
import asyncio
from datetime import datetime, timedelta
from unittest.mock import AsyncMock, MagicMock
@@ -48,6 +49,7 @@ def _make_autocompact(
sessions=sessions,
consolidator=consolidator,
session_ttl_minutes=ttl,
session_lock=lambda _key: asyncio.Lock(),
)
@@ -66,7 +68,8 @@ def test_default_ttl_disables_idle_compaction():
sessions.get_or_create.return_value = _make_session(
key="cli:idle", messages=[{"role": "user", "content": "pending"}],
)
ac = AutoCompact(sessions=sessions, consolidator=MagicMock())
ac = AutoCompact(sessions=sessions, consolidator=MagicMock(),
session_lock=lambda _key: asyncio.Lock())
schedule = MagicMock(side_effect=lambda pending: pending.close())
ac.check_expired(schedule, _runtime)
@@ -443,6 +446,7 @@ class TestArchiveDelegates:
consolidator=consolidator,
session_ttl_minutes=15,
bind_events=bind,
session_lock=lambda _key: asyncio.Lock(),
)
await ac._archive("cli:test", runtime=_runtime())
@@ -0,0 +1,167 @@
"""Compaction and SDK turns settle against the same persisted transcript."""
import asyncio
from datetime import datetime, timedelta
import pytest
from nanobot.nanobot import Nanobot
from nanobot.providers.base import LLMProvider, LLMResponse
class ControlledProvider(LLMProvider):
def __init__(self):
super().__init__(provider_name="test")
self.turn_started = asyncio.Event()
self.release_turn = asyncio.Event()
self.summary_started = asyncio.Event()
self.release_summary = asyncio.Event()
self.summary_messages = []
self.turn_messages = []
def get_default_model(self):
return "test-model"
async def chat(self, messages, **kwargs):
content = messages[-1]["content"]
if content.startswith("new question"):
self.turn_messages = messages
self.turn_started.set()
await self.release_turn.wait()
return LLMResponse(content="new reply")
if content.startswith("other question"):
return LLMResponse(content="other reply")
self.summary_messages = messages
self.summary_started.set()
await self.release_summary.wait()
return LLMResponse(content="Shared transcript summary.")
@pytest.fixture
async def bot(loop_factory):
provider = ControlledProvider()
bot = Nanobot(loop_factory(provider=provider, session_ttl_minutes=1))
try:
yield bot, provider
finally:
provider.release_turn.set()
provider.release_summary.set()
await bot.aclose()
async def seed_history(bot, key):
await bot.sessions.ingest(key, [
{"role": "user", "content": "old question"},
{"role": "assistant", "content": "old reply"},
])
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)
scheduled = []
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)
assert snapshot is not None
assert ("assistant", "new reply") in [
(message["role"], message["content"]) for message in snapshot.messages
]
assert snapshot.metadata["_last_summary"]["text"] == "Shared transcript summary."
@pytest.mark.parametrize("trigger", ["compact_session", "compact_idle_session", "scheduled_idle"])
async def test_compaction_waits_for_active_sdk_turn_and_preserves_reply(
bot, loop_factory, trigger,
):
bot, provider = bot
key = "sdk:shared"
await seed_history(bot, key)
idle_archive = schedule_idle_archive(bot, key) if trigger == "scheduled_idle" else None
compact_attempted = asyncio.Event()
async def compact():
compact_attempted.set()
if idle_archive is not None:
return await idle_archive
if trigger == "compact_session":
return await bot.runtime.compact_session(key)
return await bot.runtime.compact_idle_session(key, max_suffix=4)
turn = asyncio.create_task(bot.run("new question", session_key=key))
tasks = [turn]
try:
await asyncio.wait_for(provider.turn_started.wait(), timeout=5)
compaction = asyncio.create_task(compact())
tasks.append(compaction)
await asyncio.wait_for(compact_attempted.wait(), timeout=5)
other = await asyncio.wait_for(bot.run("other question", session_key="sdk:other"), timeout=5)
assert other.content == "other reply"
summary_started_during_turn = provider.summary_started.is_set()
provider.release_turn.set()
result = await asyncio.wait_for(turn, timeout=5)
assert result.content == "new reply"
await asyncio.wait_for(provider.summary_started.wait(), timeout=5)
provider.release_summary.set()
compacted = await asyncio.wait_for(compaction, timeout=5)
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":
assert compacted.metadata["_last_summary"]["text"] == "Shared transcript summary."
assert any(message["content"] == "new reply" for message in compacted.messages)
elif trigger == "compact_idle_session":
assert compacted == "Shared transcript summary."
await bot.aclose()
async with Nanobot(loop_factory(provider=ControlledProvider())) as restarted:
assert_reply_and_summary(restarted, key)
finally:
provider.release_turn.set()
provider.release_summary.set()
await asyncio.wait_for(asyncio.gather(*tasks, return_exceptions=True), timeout=5)
if idle_archive is not None:
idle_archive.close()
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))
turn_attempted = asyncio.Event()
async def run():
turn_attempted.set()
return await bot.run("new question", session_key=key)
tasks = [archive]
try:
await asyncio.wait_for(provider.summary_started.wait(), timeout=5)
turn = asyncio.create_task(run())
tasks.append(turn)
await asyncio.wait_for(turn_attempted.wait(), timeout=5)
other = await asyncio.wait_for(bot.run("other question", session_key="sdk:other"), timeout=5)
assert other.content == "other reply"
assert provider.turn_started.is_set() is False
provider.release_summary.set()
await asyncio.wait_for(archive, timeout=5)
await asyncio.wait_for(provider.turn_started.wait(), timeout=5)
assert "Shared transcript summary." in provider.turn_messages[0]["content"]
provider.release_turn.set()
result = await asyncio.wait_for(turn, timeout=5)
assert result.content == "new reply"
assert_reply_and_summary(bot, key)
finally:
provider.release_turn.set()
provider.release_summary.set()
await asyncio.wait_for(asyncio.gather(*tasks, return_exceptions=True), timeout=5)