fix(agent): recheck idle expiry after acquiring session lock

Reload settled activity inside the existing session lock before an idle
archive delegates to the consolidator. A fresh turn restarts the idle
interval; manual compaction keeps its existing behavior.

Cover both scheduling orderings and later genuine idleness, and give
existing direct idle-archive fixtures explicit idle preconditions.
This commit is contained in:
lenin authored and Xubin Ren committed 2026-10-25 13:18:39 +08:00
1 parent 6b930432cb
commit 9650f4fd5b
5 files changed
+157 -10

No files matched your search

+4
View File
@@ -96,6 +96,10 @@ class AutoCompact:
return
try:
async with self._session_lock(key):
# A turn may have refreshed activity while this archive waited.
session = await self.sessions.state.get_header(key)
if not self._is_expired(session.updated_at):
return
# Idle compaction and turns share one transcript boundary.
summary = await self.consolidator.compact_idle_session(
key,
+105 -4
View File
@@ -462,6 +462,7 @@ class TestAutoCompact:
loop = _make_loop(tmp_path, session_ttl_minutes=15)
session = loop.sessions.get_or_create("cli:test")
_add_turns(session, 6)
session.updated_at = datetime.now() - timedelta(minutes=20)
loop.sessions.save(session)
archived_messages = []
@@ -488,6 +489,7 @@ class TestAutoCompact:
for i in range(8):
_add_tool_turn(session, "recent", i)
session.add_message("assistant", "done")
session.updated_at = datetime.now() - timedelta(minutes=20)
loop.sessions.save(session)
await loop.auto_compact._archive("cli:test", runtime=loop.llm_runtime())
@@ -548,6 +550,7 @@ class TestAutoCompact:
session = loop.sessions.get_or_create("cli:test")
_add_turns(session, 14)
session.last_archived = 18
session.updated_at = datetime.now() - timedelta(minutes=20)
loop.sessions.save(session)
archived_messages = []
@@ -1248,7 +1251,7 @@ class TestProactiveAutoCompact:
await loop.aclose()
@pytest.mark.asyncio
async def test_session_can_be_compacted_again_after_new_messages(self, tmp_path):
async def test_session_can_be_compacted_again_after_new_messages(self, tmp_path, monkeypatch):
"""After successful compact + user sends new messages + idle again, should compact again."""
loop = _make_loop(tmp_path, session_ttl_minutes=15)
session = loop.sessions.get_or_create("cli:test")
@@ -1267,8 +1270,11 @@ class TestProactiveAutoCompact:
msg = InboundMessage(channel="cli", sender_id="user", chat_id="test", content="second topic")
await loop._process_message(msg)
# Explicit archival does not require another TTL scan.
# Second compact cycle should succeed
# New messages have now been idle for a fresh TTL interval.
monkeypatch.setattr("nanobot.agent.autocompact.datetime", SimpleNamespace(
now=lambda: datetime.now() + timedelta(minutes=20),
fromisoformat=datetime.fromisoformat,
))
await loop.auto_compact._archive("cli:test", runtime=loop.llm_runtime())
assert _fake_compact.state["count"] == 2
await loop.aclose()
@@ -1365,7 +1371,7 @@ class TestSummaryPersistence:
await loop.aclose()
@pytest.mark.asyncio
async def test_new_summary_overrides_old(self, tmp_path):
async def test_new_summary_overrides_old(self, tmp_path, monkeypatch):
"""A fresh archive writes a new summary that replaces the old one."""
loop = _make_loop(tmp_path, session_ttl_minutes=15)
session = loop.sessions.get_or_create("cli:test")
@@ -1394,6 +1400,11 @@ class TestSummaryPersistence:
loop.consolidator.compact_idle_session = _make_fake_compact(
loop, summary="Second summary.",
)
# New messages have now been idle for a fresh TTL interval.
monkeypatch.setattr("nanobot.agent.autocompact.datetime", SimpleNamespace(
now=lambda: datetime.now() + timedelta(minutes=20),
fromisoformat=datetime.fromisoformat,
))
await loop.auto_compact._archive("cli:test", runtime=loop.llm_runtime())
# The second archive writes a new summary
@@ -1431,3 +1442,93 @@ class TestSummaryPersistence:
fresh = loop.sessions.get_or_create("cli:test")
assert "_last_summary" not in fresh.metadata
await loop.aclose()
@pytest.mark.parametrize("ordering", ["scan_during_turn", "archive_queued_before_turn"])
async def test_idle_compaction_rechecks_settled_activity(tmp_path, monkeypatch, ordering):
monkeypatch.setattr("nanobot.config.home._home_path", tmp_path / "home")
monkeypatch.setattr("nanobot.config.loader._current_config_path", tmp_path / "config.json")
now = [datetime.now()]
class Clock(datetime):
@classmethod
def now(cls, tz=None):
return now[0] if tz is None else now[0].replace(tzinfo=tz)
# The scanner and settled-turn/summary writers must share the same clock.
for module in ("nanobot.agent.autocompact", "nanobot.agent.loop", "nanobot.session.manager"):
monkeypatch.setattr(f"{module}.datetime", Clock)
loop = _make_loop(tmp_path / "workspace")
key = HEARTBEAT_SESSION_KEY
session = loop.sessions.get_or_create(key)
_add_turns(session, 2)
session.updated_at = now[0] - timedelta(minutes=20)
loop.sessions.save(session)
entered, release = asyncio.Event(), asyncio.Event()
archived = []
other_responses = []
async def respond(**_kwargs):
request = current_request_context()
if request is not None and request.session_key == key:
entered.set()
await release.wait()
return LLMResponse(content="completed reply", tool_calls=[])
async def archive(captured, **_kwargs):
if captured.key == key:
archived.append([message.get("content") for message in captured.messages])
return "Idle summary."
async def finish_turn():
try:
await asyncio.wait_for(entered.wait(), 5)
now[0] += timedelta(minutes=20)
if ordering == "scan_during_turn":
loop._next_idle_compact_check_at = 0
await loop._check_expired_sessions_if_due()
other_responses.append(await asyncio.wait_for(
loop.process_direct("other input", session_key="cli:other"), 5,
))
assert archived == [] # The real turn still holds its session lock.
finally:
release.set()
loop.provider.chat_stream_with_retry.side_effect = respond
loop.consolidator.archive_session = archive
finishing = None
try:
if ordering == "archive_queued_before_turn":
loop._next_idle_compact_check_at = 0
await loop._check_expired_sessions_if_due()
assert key in loop.auto_compact._archiving
finishing = asyncio.create_task(finish_turn())
# Await inline: the direct call takes the free lock before the already
# scheduled archive task runs. No scheduler or lock is replaced.
async with asyncio.timeout(5):
response = await loop.process_direct("new input", session_key=key)
await asyncio.wait_for(finishing, 5)
await asyncio.wait_for(_drain_background_tasks(loop), 5)
assert len(archived) == 0
saved = await loop.sessions.state.get(key)
assert response is not None and response.content == "completed reply"
assert saved.messages[-1]["content"] == "completed reply"
assert saved.updated_at == now[0]
assert "_last_summary" not in saved.metadata
assert key not in loop.auto_compact._archiving
assert other_responses[0].content == "completed reply"
now[0] += timedelta(minutes=20)
loop._next_idle_compact_check_at = 0
await loop._check_expired_sessions_if_due()
await asyncio.wait_for(_drain_background_tasks(loop), 5)
assert len(archived) == 1
assert "completed reply" in archived[0]
saved = await loop.sessions.state.get(key)
assert saved.metadata["_last_summary"]["text"] == "Idle summary."
assert key not in loop.auto_compact._archiving
finally:
release.set()
if finishing is not None:
await asyncio.wait_for(asyncio.gather(finishing, return_exceptions=True), 5)
await asyncio.wait_for(loop.aclose(), 10)
+11 -3
View File
@@ -15,6 +15,7 @@ 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.get_header = 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
@@ -247,6 +248,7 @@ class TestCheckExpired:
old_dt = datetime.now() - timedelta(minutes=20)
session = _make_session("cli:old", updated_at=old_dt)
_add_turns(session, 5)
session.updated_at = old_dt
ac.sessions.list_sessions.return_value = [
{"key": "cli:old", "updated_at": old_dt.isoformat()}
]
@@ -413,7 +415,7 @@ class TestArchiveDelegates:
async def test_calls_compact_idle_session(self):
ac = _make_autocompact()
mock_sm = _mock_sessions()
mock_sm.get_or_create.return_value = Session(key="cli:test")
mock_sm.get_or_create.return_value = _make_session(updated_at=datetime.now() - timedelta(minutes=20))
ac.sessions = mock_sm
ac.consolidator.compact_idle_session = AsyncMock(return_value="Summary.")
@@ -430,7 +432,7 @@ class TestArchiveDelegates:
@pytest.mark.asyncio
async def test_forwards_timeout_compaction_events_with_session_key(self):
sessions = _mock_sessions()
sessions.get_or_create.return_value = Session(key="cli:test")
sessions.get_or_create.return_value = _make_session(updated_at=datetime.now() - timedelta(minutes=20))
consolidator = MagicMock()
observed: list[tuple[str, ContextCompactionEvent]] = []
@@ -475,6 +477,7 @@ class TestArchiveDelegates:
ac = _make_autocompact()
mock_sm = _mock_sessions()
session = _make_session(
updated_at=datetime.now() - timedelta(minutes=20),
metadata={"_last_summary": {"text": "Hello.", "last_active": "2026-05-13T10:00:00"}}
)
mock_sm.get_or_create.return_value = session
@@ -490,7 +493,7 @@ class TestArchiveDelegates:
@pytest.mark.asyncio
async def test_no_summary_when_compact_returns_empty(self):
mock_sm = _mock_sessions()
mock_sm.get_or_create.return_value = _make_session(metadata={
mock_sm.get_or_create.return_value = _make_session(updated_at=datetime.now() - timedelta(minutes=20), metadata={
"_last_summary": {"text": "Previous checkpoint.", "last_active": "2026-05-13T10:00:00"},
})
ac = _make_autocompact(sessions=mock_sm)
@@ -498,18 +501,23 @@ class TestArchiveDelegates:
await ac._archive("cli:test", runtime=_runtime())
ac.consolidator.compact_idle_session.assert_awaited_once()
assert "cli:test" not in ac._summaries
@pytest.mark.asyncio
async def test_exception_still_removes_from_archiving(self):
ac = _make_autocompact()
mock_sm = _mock_sessions()
mock_sm.get_or_create.return_value = _make_session(
updated_at=datetime.now() - timedelta(minutes=20),
)
ac.sessions = mock_sm
ac.consolidator.compact_idle_session = AsyncMock(side_effect=RuntimeError("fail"))
ac._archiving.add("cli:test")
await ac._archive("cli:test", runtime=_runtime())
ac.consolidator.compact_idle_session.assert_awaited_once()
assert "cli:test" not in ac._archiving
+34 -3
View File
@@ -109,6 +109,33 @@ async def test_compaction_waits_for_active_sdk_turn_and_preserves_reply(
provider.release_turn.set()
result = await asyncio.wait_for(turn, timeout=5)
assert result.content == "new reply"
if trigger == "scheduled_idle":
provider.release_summary.set()
await asyncio.wait_for(compaction, timeout=5)
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
]
assert "_last_summary" not in snapshot.metadata
assert provider.summary_messages == []
assert provider.summary_started.is_set() is False
assert key not in bot._loop.auto_compact._archiving
# Only the later, genuinely idle scan may summarize the fresh reply.
# sdk:other is idle by then too; this expectation concerns sdk:shared.
scheduled = []
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,
active_session_keys={"sdk:other"},
)
assert len(scheduled) == 1
compaction = asyncio.create_task(scheduled[0])
tasks.append(compaction)
await asyncio.wait_for(provider.summary_started.wait(), timeout=5)
await asyncio.wait_for(provider.summary_started.wait(), timeout=5)
provider.release_summary.set()
compacted = await asyncio.wait_for(compaction, timeout=5)
@@ -137,16 +164,20 @@ 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(await schedule_idle_archive(bot))
turn_attempted = asyncio.Event()
async def run():
turn_attempted.set()
return await bot.run("new question", session_key=key)
tasks = [archive]
tasks = []
try:
await asyncio.wait_for(provider.summary_started.wait(), timeout=5)
with patch("nanobot.agent.autocompact.datetime") as clock:
clock.now.return_value = datetime.now() + timedelta(minutes=30)
clock.fromisoformat.side_effect = datetime.fromisoformat
archive = asyncio.create_task(await schedule_idle_archive(bot))
tasks.append(archive)
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)
+3
View File
@@ -165,6 +165,9 @@ async def test_compacted_session_waits_for_new_input_without_continuation(
session = loop.sessions.get_or_create(key)
session.add_message("user", "Inspect the checkpoint")
session.add_message("assistant", "Inspection complete.")
if trigger == "idle":
loop.auto_compact._ttl = 15
session.updated_at = datetime.now() - timedelta(minutes=20)
loop.sessions.save(session)
loop.provider.estimate_prompt_tokens.return_value = (100, "test")
loop.provider.chat_stream_with_retry.return_value = LLMResponse(content=summary)