feat: make context compaction visible in channels (#5656)

* feat: surface context compaction lifecycle

* fix: complete and simplify context compaction notifications
This commit is contained in:
chengyongru authored and GitHub committed 2026-09-05 20:21:54 +08:00
1 parent 455533169d
commit 5229989f28
52 files changed
+1849 -140

No files matched your search

+10 -3
View File
@@ -83,7 +83,14 @@ def _make_fake_compact(
):
state = {"count": 0}
async def _fake_compact(key: str, *, runtime, max_suffix: int = 8) -> str:
async def _fake_compact(
key: str,
*,
runtime,
max_suffix: int = 8,
trigger: str = "policy",
on_compaction=None,
) -> str:
state["count"] += 1
session = loop.sessions.get_or_create(key)
@@ -884,7 +891,7 @@ class TestProactiveAutoCompact:
started = asyncio.Event()
block_forever = asyncio.Event()
async def _slow_compact(key, *, runtime, max_suffix=8):
async def _slow_compact(key, *, runtime, max_suffix=8, **_kwargs):
nonlocal archive_count
archive_count += 1
started.set()
@@ -916,7 +923,7 @@ class TestProactiveAutoCompact:
session.updated_at = datetime.now() - timedelta(minutes=20)
loop.sessions.save(session)
async def _failing_compact(key, *, runtime, max_suffix=8):
async def _failing_compact(key, *, runtime, max_suffix=8, **_kwargs):
raise RuntimeError("LLM down")
loop.consolidator.compact_idle_session = _failing_compact
+33
View File
@@ -6,6 +6,7 @@ from unittest.mock import AsyncMock, MagicMock
import pytest
from nanobot.agent.autocompact import AutoCompact
from nanobot.bus.outbound_events import ContextCompactionEvent
from nanobot.session.manager import Session, SessionManager
@@ -268,6 +269,7 @@ class TestCheckExpired:
"cli:old",
runtime=admitted,
max_suffix=ac._RECENT_SUFFIX_MESSAGES,
on_compaction=None,
)
@pytest.mark.parametrize("resolution_error", [KeyError, ValueError])
@@ -443,8 +445,39 @@ class TestArchiveDelegates:
"cli:test",
runtime=runtime,
max_suffix=ac._RECENT_SUFFIX_MESSAGES,
on_compaction=None,
)
@pytest.mark.asyncio
async def test_forwards_timeout_compaction_events_with_session_key(self):
sessions = MagicMock(spec=SessionManager)
consolidator = MagicMock()
observed: list[tuple[str, ContextCompactionEvent]] = []
def bind(key: str):
async def publish(event: ContextCompactionEvent) -> None:
observed.append((key, event))
return publish
async def compact(key: str, **kwargs):
event = ContextCompactionEvent(compaction_id="compact-1", phase="started")
await kwargs["on_compaction"](event)
return "Summary."
consolidator.compact_idle_session = AsyncMock(side_effect=compact)
ac = AutoCompact(
sessions=sessions,
consolidator=consolidator,
session_ttl_minutes=15,
bind_compaction=bind,
)
await ac._archive("cli:test", runtime=_runtime())
assert len(observed) == 1
assert observed[0][0] == "cli:test"
assert observed[0][1].phase == "started"
@pytest.mark.asyncio
async def test_dream_session_is_ignored(self):
ac = _make_autocompact()
+63 -9
View File
@@ -10,6 +10,7 @@ from nanobot.agent.memory import (
Consolidator,
MemoryStore,
)
from nanobot.bus.outbound_events import ContextCompactionEvent
from nanobot.providers.base import (
GenerationSettings,
LLMResponse,
@@ -141,7 +142,7 @@ class TestTurnTranscriptSummary:
content="replacement checkpoint",
)
summary = await consolidator.summarize_transcript(
result = await consolidator.summarize_transcript(
accepted,
"previous checkpoint",
runtime=runtime,
@@ -149,7 +150,7 @@ class TestTurnTranscriptSummary:
tools=tools,
)
assert summary == "replacement checkpoint"
assert result == "replacement checkpoint"
call = mock_provider.chat_with_retry.await_args.kwargs
assert call["messages"][:-1] == accepted
assert call["messages"][-1]["role"] == "user"
@@ -172,7 +173,7 @@ class TestTurnTranscriptSummary:
content="replacement checkpoint",
)
summary = await consolidator.summarize_provider_compaction(
result = await consolidator.summarize_provider_compaction(
state,
accepted,
"previous checkpoint",
@@ -181,7 +182,7 @@ class TestTurnTranscriptSummary:
tools=[{"type": "function", "function": {"name": "inspect"}}],
)
assert summary == "replacement checkpoint"
assert result == "replacement checkpoint"
call = mock_provider.chat_with_retry.await_args.kwargs
assert call["messages"][0] == accepted[0]
assert call["messages"][-1]["content"] == _ARCHIVE_PROMPT
@@ -242,7 +243,7 @@ class TestConsolidatorSummarize:
async def test_summarize_appends_to_history(
self, consolidator, mock_provider, store, runtime
):
"""Consolidator should call LLM to summarize, then append to HISTORY.md."""
"""Consolidator should persist the LLM summary in history.jsonl."""
mock_provider.chat_with_retry.return_value = MagicMock(
content="User fixed a bug in the auth module."
)
@@ -555,6 +556,56 @@ class TestCompactIdleSession:
assert "last_active" in meta
assert reloaded.updated_at == old_ts
@pytest.mark.asyncio
async def test_emits_manual_compaction_lifecycle(
self, real_consolidator, mock_provider, runtime
):
mock_provider.chat_with_retry.return_value = MagicMock(
content="Summary.", finish_reason="stop"
)
session = real_consolidator.sessions.get_or_create("cli:events")
session.add_message("user", "question")
session.add_message("assistant", "answer")
real_consolidator.sessions.save(session)
events: list[ContextCompactionEvent] = []
async def observe(event: ContextCompactionEvent) -> None:
events.append(event)
result = await real_consolidator.compact_idle_session(
"cli:events",
runtime=runtime,
on_compaction=observe,
)
assert result == "Summary."
assert [event.phase for event in events] == ["started", "succeeded"]
assert events[0].compaction_id == events[1].compaction_id
@pytest.mark.asyncio
async def test_event_callback_failure_does_not_abort_compaction(
self, real_consolidator, mock_provider, runtime
):
mock_provider.chat_with_retry.return_value = MagicMock(
content="Summary.", finish_reason="stop"
)
session = real_consolidator.sessions.get_or_create("cli:event-callback-failure")
session.add_message("user", "question")
real_consolidator.sessions.save(session)
async def fail_observer(_event: ContextCompactionEvent) -> None:
raise RuntimeError("channel unavailable")
result = await real_consolidator.compact_idle_session(
"cli:event-callback-failure",
runtime=runtime,
on_compaction=fail_observer,
)
assert result == "Summary."
reloaded = real_consolidator.sessions.get_or_create("cli:event-callback-failure")
assert reloaded.last_archived == 1
@pytest.mark.asyncio
async def test_short_idle_session_archives_once(
self, real_consolidator, mock_provider, store, runtime
@@ -894,6 +945,8 @@ class TestCompactIdleSession:
mock_provider.chat_with_retry.side_effect = RuntimeError("LLM unavailable")
sessions = real_consolidator.sessions
session = sessions.get_or_create("cli:fail")
session.add_message("user", "/compact", _command=True)
session.add_message("assistant", "Nothing to compact.", _command=True)
for i in range(10):
session.add_message("user", f"u{i}")
session.add_message("assistant", f"a{i}")
@@ -907,12 +960,11 @@ class TestCompactIdleSession:
# raw_archive should have been called (history.jsonl gets an entry)
entries = store.read_unprocessed_history(since_cursor=0)
assert any("[RAW]" in e["content"] for e in entries)
assert entries[0]["content"].startswith("[RAW] 20 messages")
reloaded = sessions.get_or_create("cli:fail")
assert len(reloaded.messages) == 20
assert reloaded.messages[0]["content"] == "u0"
assert reloaded.last_archived == 20
assert reloaded.messages == session.messages
assert reloaded.last_archived == 22
assert reloaded.metadata["_last_summary"]["text"] == result
assert [m["content"] for m in reloaded.get_history(max_messages=20)] == [
"u6",
@@ -1356,6 +1408,7 @@ class TestArchivePersistence:
)
persisted = store.read_unprocessed_history(since_cursor=0)[0]["content"]
assert summary is not None
assert summary == persisted == "safe summary"
async def test_oversized_summary_uses_history_emergency_cap(
@@ -1376,4 +1429,5 @@ class TestArchivePersistence:
entry = store.read_unprocessed_history(since_cursor=0)[0]
assert len(entry["content"]) <= _HISTORY_ENTRY_HARD_CAP + 50
assert summary is not None
assert summary == entry["content"]
+7 -1
View File
@@ -1197,6 +1197,9 @@ async def test_process_message_persists_unified_session_delivery_route(tmp_path:
loop.sessions.invalidate(UNIFIED_SESSION_KEY)
persisted = loop.sessions.get_or_create(UNIFIED_SESSION_KEY)
assert persisted.metadata[LAST_CHANNEL_METADATA_KEY] == "feishu:oc_123"
assert persisted.metadata["_compaction_route"] == {
"channel": "feishu", "chat_id": "oc_123", "metadata": {},
}
@pytest.mark.parametrize(
@@ -1251,7 +1254,10 @@ def test_unified_session_route_ignores_non_user_destinations(
session = loop.sessions.get_or_create(UNIFIED_SESSION_KEY)
session.metadata[LAST_CHANNEL_METADATA_KEY] = "telegram:existing"
loop._remember_unified_session_route(session, msg, is_user_turn=is_user_turn)
loop._remember_session_route(
session, msg, is_user_turn=is_user_turn,
delivery=loop.turn_delivery_factory.unrouted(msg, session.key),
)
assert session.metadata[LAST_CHANNEL_METADATA_KEY] == "telegram:existing"
+57 -14
View File
@@ -13,8 +13,10 @@ from nanobot.agent.context_governance import (
ContextGovernanceConfig,
ContextGovernor,
ContextWindowExceededError,
ModelRequestState,
)
from nanobot.agent.runner import AgentRunner, AgentRunSpec
from nanobot.bus.outbound_events import ContextCompactionEvent
from nanobot.config.schema import AgentDefaults
from nanobot.providers.base import (
LLMProvider,
@@ -23,6 +25,7 @@ from nanobot.providers.base import (
ProviderConversationState,
ToolCallRequest,
)
from nanobot.providers.conversation_state import ProviderConversationStateController
from nanobot.session.summary import SUMMARY_CONTINUATION_TEXT
_MAX_TOOL_RESULT_CHARS = AgentDefaults().max_tool_result_chars
@@ -369,7 +372,13 @@ async def test_native_compaction_uses_provider_request_boundary(
lambda *_args: (100, "test-counter"),
)
consolidate = AsyncMock(return_value="portable checkpoint")
consolidate_native = AsyncMock(return_value="portable checkpoint")
consolidate_native = AsyncMock(
return_value="portable checkpoint"
)
compaction_events: list[ContextCompactionEvent] = []
async def observe_compaction(event: ContextCompactionEvent) -> None:
compaction_events.append(event)
result = await AgentRunner().run(make_run_spec(
provider,
@@ -391,6 +400,7 @@ async def test_native_compaction_uses_provider_request_boundary(
max_tokens=100,
max_iterations=2,
max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,
compaction_callback=observe_compaction,
))
consolidate.assert_not_awaited()
@@ -405,6 +415,10 @@ async def test_native_compaction_uses_provider_request_boundary(
assert result.provider_compaction_applied is True
assert any(message.get("content") == "inspect the project" for message in result.messages)
assert any(message.get("content") == "complete tool result" for message in result.messages)
assert [event.phase for event in compaction_events] == ["started", "succeeded"]
assert {event.compaction_id for event in compaction_events} == {
compaction_events[0].compaction_id
}
async def test_runner_keeps_current_tool_exchange_outside_summary(monkeypatch):
@@ -506,7 +520,14 @@ async def test_repeated_pressure_advances_summary_boundary(monkeypatch):
"nanobot.agent.context_governance.estimate_prompt_tokens_chain",
estimate,
)
consolidate = AsyncMock(side_effect=["checkpoint-1", "checkpoint-2"])
consolidate = AsyncMock(side_effect=[
"checkpoint-1",
"checkpoint-2",
])
compaction_events: list[ContextCompactionEvent] = []
async def observe_compaction(event: ContextCompactionEvent) -> None:
compaction_events.append(event)
result = await AgentRunner().run(make_run_spec(
provider,
@@ -521,6 +542,7 @@ async def test_repeated_pressure_advances_summary_boundary(monkeypatch):
max_tokens=100,
max_iterations=3,
max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,
compaction_callback=observe_compaction,
))
assert consolidate.await_count == 2
@@ -533,6 +555,13 @@ async def test_repeated_pressure_advances_summary_boundary(monkeypatch):
assert result.summary_checkpoint is not None
assert result.summary_checkpoint.summary == "checkpoint-2"
assert result.summary_checkpoint.transcript_boundary == 4
assert [event.phase for event in compaction_events] == [
"started", "succeeded", "started", "succeeded",
]
first_id, second_id = compaction_events[0].compaction_id, compaction_events[2].compaction_id
assert first_id == compaction_events[1].compaction_id
assert second_id == compaction_events[3].compaction_id
assert first_id != second_id
async def test_runner_refuses_checkpoint_that_cannot_fit_with_delta(monkeypatch):
@@ -874,7 +903,7 @@ async def test_runner_fits_max_iteration_finalization_before_dispatch(monkeypatc
("input_tokens", "expected_fitted"),
[(500, True), (100, False)],
)
def test_matching_reported_provider_usage_avoids_local_estimate(
async def test_matching_reported_provider_usage_avoids_local_estimate(
monkeypatch,
input_tokens,
expected_fitted,
@@ -901,18 +930,25 @@ def test_matching_reported_provider_usage_avoids_local_estimate(
governor = ContextGovernor()
monkeypatch.setattr(governor, "fit_to_budget", lambda *_args, **_kwargs: [])
_messages, fitted = governor.fit_request(
_governance_config(provider, tools, spec),
state = ModelRequestState(
config=_governance_config(provider, tools, spec),
conversation=ProviderConversationStateController(
provider=provider, model=spec.runtime.model, messages=spec.initial_messages,
),
usage=LLMUsage.reported(input_tokens=input_tokens, output_tokens=10),
messages=spec.initial_messages,
tool_definitions=[],
)
messages, _context = await governor.prepare_request(
state,
spec.initial_messages,
LLMUsage.reported(input_tokens=input_tokens, output_tokens=10),
usage_matches_messages=True,
tool_definitions=tools.get_definitions(),
)
assert fitted is expected_fitted
assert messages == ([] if expected_fitted else spec.initial_messages)
def test_changed_messages_use_local_estimate_after_reported_usage(monkeypatch):
async def test_changed_messages_use_local_estimate_after_reported_usage(monkeypatch):
provider = MagicMock(spec=LLMProvider)
tools = MagicMock()
tools.get_definitions.return_value = []
@@ -934,15 +970,22 @@ def test_changed_messages_use_local_estimate_after_reported_usage(monkeypatch):
governor = ContextGovernor()
monkeypatch.setattr(governor, "fit_to_budget", lambda *_args, **_kwargs: [])
_messages, fitted = governor.fit_request(
_governance_config(provider, tools, spec),
state = ModelRequestState(
config=_governance_config(provider, tools, spec),
conversation=ProviderConversationStateController(
provider=provider, model=spec.runtime.model, messages=spec.initial_messages,
),
usage=LLMUsage.reported(input_tokens=900, output_tokens=10),
messages=[{"role": "user", "content": "previous request"}],
tool_definitions=[],
)
messages, _context = await governor.prepare_request(
state,
spec.initial_messages,
LLMUsage.reported(input_tokens=900, output_tokens=10),
usage_matches_messages=False,
tool_definitions=tools.get_definitions(),
)
assert fitted is True
assert messages == []
estimate.assert_called_once()
+75
View File
@@ -4,6 +4,7 @@ import pytest
from nanobot.agent.turn_delivery import TurnDeliveryFactory
from nanobot.bus.events import InboundMessage
from nanobot.bus.outbound_events import ContextCompactionEvent
from nanobot.bus.queue import MessageBus
from nanobot.bus.runtime_events import RuntimeEventBus
from nanobot.session.manager import SessionManager
@@ -14,6 +15,80 @@ from nanobot.webui.metadata import (
)
@pytest.mark.parametrize("unified", [False, True])
@pytest.mark.parametrize(("key", "channel", "chat_id", "metadata"), [
("slack:C123:1700000000.000100", "slack", "C123",
{"slack": {"thread_ts": "1700000000.000100"}}),
("telegram:-100123:topic:42", "telegram", "-100123", {"message_thread_id": 42}),
("discord:456:thread:777", "discord", "777", {}),
("mattermost:channel:root", "mattermost", "channel", {"mattermost": {"root_id": "root"}}),
("matrix:!room:example.org:thread:$root", "matrix", "!room:example.org",
{"thread_root_event_id": "$root", "thread_reply_to_event_id": "$reply"}),
("feishu:chat:thread:root", "feishu", "chat",
{"message_id": "reply", "thread_id": "root", "chat_type": "group"}),
("dingtalk:group:conversation:user", "dingtalk", "group:conversation", {}),
])
async def test_idle_compaction_uses_the_session_delivery_route(
key, channel, chat_id, metadata, unified,
) -> None:
factory = TurnDeliveryFactory(MessageBus(), RuntimeEventBus())
event = ContextCompactionEvent(compaction_id="compact-1", phase="started")
key = "unified:default" if unified else key
msg = InboundMessage(
channel=channel, sender_id="user", chat_id=chat_id, content="hello",
metadata={
"webui_turn_id": "turn-1", "sender_name": "User",
"message_id": "received-1", "thread_id": "received-thread", **metadata,
},
)
delivery = factory.create(msg, key)
session_metadata = {}
delivery.remember_session_route(session_metadata)
callback = factory.session_compaction_callback(key, session_metadata)
assert callback is not None
await callback(event)
outbound = factory.bus.outbound.get_nowait()
assert (outbound.channel, outbound.chat_id, outbound.metadata) == (channel, chat_id, metadata)
assert outbound.event is event
async def test_idle_compaction_keeps_its_route_when_a_unified_session_moves() -> None:
factory = TurnDeliveryFactory(MessageBus(), RuntimeEventBus())
key = "unified:default"
session_metadata = {}
original = InboundMessage(
channel="slack", sender_id="user", chat_id="C123", content="hello",
metadata={"slack": {"thread_ts": "1700000000.000100"}},
)
factory.create(original, key).remember_session_route(session_metadata)
callback = factory.session_compaction_callback(key, session_metadata)
assert callback is not None
await callback(ContextCompactionEvent("compact-1", "started"))
latest = InboundMessage(
channel="telegram", sender_id="user", chat_id="42", content="next question",
)
factory.create(latest, key).remember_session_route(session_metadata)
await callback(ContextCompactionEvent("compact-1", "succeeded"))
events = [factory.bus.outbound.get_nowait() for _ in range(2)]
assert [(msg.channel, msg.chat_id, msg.metadata) for msg in events] == [
("slack", "C123", {"slack": {"thread_ts": "1700000000.000100"}}),
] * 2
async def test_idle_compaction_can_deliver_to_a_legacy_websocket_session() -> None:
factory = TurnDeliveryFactory(MessageBus(), RuntimeEventBus())
event = ContextCompactionEvent(compaction_id="compact-1", phase="succeeded")
callback = factory.session_compaction_callback("websocket:chat", {})
assert callback is not None
await callback(event)
outbound = factory.bus.outbound.get_nowait()
assert (outbound.channel, outbound.chat_id, outbound.event) == ("websocket", "chat", event)
def test_websocket_lifecycles_get_distinct_internal_owners(tmp_path: Path) -> None:
factory = TurnDeliveryFactory(
MessageBus(),