From d149232621367c4f7f9b634d9ef590eaf696f30d Mon Sep 17 00:00:00 2001 From: chengyongru <61816729+chengyongru@users.noreply.github.com> Date: Wed, 23 Sep 2026 14:05:54 +0800 Subject: [PATCH] fix: isolate maintenance-session compaction notifications (#5874) * fix: keep heartbeat compaction notices off user channels * refactor: centralize maintenance session identity --- nanobot/agent/autocompact.py | 14 +++++--------- nanobot/agent/memory.py | 3 ++- nanobot/agent/turn_delivery.py | 28 +++++++++++++++++++++++----- nanobot/cli/gateway_runtime.py | 8 ++++++-- nanobot/session/keys.py | 11 +++++++++++ tests/agent/test_auto_compact.py | 20 ++++++++++++++++++++ tests/agent/test_turn_delivery.py | 29 +++++++++++++++++++++++++++++ 7 files changed, 96 insertions(+), 17 deletions(-) diff --git a/nanobot/agent/autocompact.py b/nanobot/agent/autocompact.py index 4c77f1028..8dfe8a093 100644 --- a/nanobot/agent/autocompact.py +++ b/nanobot/agent/autocompact.py @@ -9,6 +9,7 @@ from typing import TYPE_CHECKING, Any, Callable, Coroutine from loguru import logger from nanobot.events import NO_EVENTS, EventSink +from nanobot.session.keys import is_dream_session from nanobot.session.manager import Session, SessionManager from nanobot.session.summary import ( SessionSummary, @@ -24,8 +25,6 @@ SessionEventFactory = Callable[[str], EventSink] class AutoCompact: - _INTERNAL_SESSION_PREFIXES = ("dream:",) - def __init__(self, sessions: SessionManager, consolidator: Consolidator, session_ttl_minutes: int = 0, bind_events: SessionEventFactory | None = None): @@ -61,10 +60,6 @@ class AutoCompact: for message in session.messages[session.last_archived:] ) - @classmethod - def _is_internal_session(cls, key: str) -> bool: - return key.startswith(cls._INTERNAL_SESSION_PREFIXES) - def check_expired( self, schedule_background: Callable[[Coroutine[Any, Any, None]], None], @@ -75,7 +70,8 @@ class AutoCompact: now = datetime.now() for info in self.sessions.list_sessions(): key = info.get("key", "") - if not key or self._is_internal_session(key) or key in self._archiving: + # Dream sessions are per-run; persistent maintenance sessions still compact. + if not key or is_dream_session(key) or key in self._archiving: continue if key in active_session_keys: continue @@ -91,7 +87,7 @@ class AutoCompact: schedule_background(self._archive(key, runtime=runtime)) async def _archive(self, key: str, *, runtime: LLMRuntime) -> None: - if self._is_internal_session(key): + if is_dream_session(key): self._archiving.discard(key) return try: @@ -114,7 +110,7 @@ class AutoCompact: self._archiving.discard(key) def prepare_session(self, session: Session, key: str) -> tuple[Session, SessionSummary | None]: - if self._is_internal_session(key): + if is_dream_session(key): self._archiving.discard(key) self._summaries.pop(key, None) return session, None diff --git a/nanobot/agent/memory.py b/nanobot/agent/memory.py index 1464fbb09..2ab35de5e 100644 --- a/nanobot/agent/memory.py +++ b/nanobot/agent/memory.py @@ -26,6 +26,7 @@ from nanobot.llm_usage.context import llm_usage_source from nanobot.providers.base import LLMResponse, ProviderConversationState from nanobot.providers.conversation_state import ProviderConversationStateController from nanobot.runtime_context import public_history_messages +from nanobot.session.keys import is_dream_session from nanobot.session.manager import Session, SessionManager from nanobot.session.summary import is_summary_checkpoint, session_summary_from_metadata from nanobot.utils.gitstore import GitStore @@ -751,7 +752,7 @@ class MemoryStore: dream_files: list[tuple[Path, str]] = [] for path in sessions_dir.glob("*.jsonl"): decoded_key = SessionManager.decode_storage_key(path.stem) - if decoded_key is not None and decoded_key.startswith("dream:"): + if decoded_key is not None and is_dream_session(decoded_key): dream_files.append((path, decoded_key)) dream_files.sort(key=lambda item: item[0].stat().st_mtime) diff --git a/nanobot/agent/turn_delivery.py b/nanobot/agent/turn_delivery.py index 672e2ef5c..328e98d97 100644 --- a/nanobot/agent/turn_delivery.py +++ b/nanobot/agent/turn_delivery.py @@ -20,9 +20,19 @@ from nanobot.bus.outbound_events import ( from nanobot.bus.queue import MessageBus from nanobot.bus.runtime_events import RuntimeEventPublisher from nanobot.channels.notification_routes import notification_metadata -from nanobot.events import AgentEvent, EventSink, ResponseSource, ResponseSourceEvent +from nanobot.events import ( + AgentEvent, + ContextCompactionEvent, + EventSink, + ResponseSource, + ResponseSourceEvent, +) from nanobot.providers.base import LLMUsage -from nanobot.session.keys import UNIFIED_SESSION_KEY, last_channel_from_metadata +from nanobot.session.keys import ( + UNIFIED_SESSION_KEY, + is_internal_session, + last_channel_from_metadata, +) from nanobot.utils.helpers import strip_think if TYPE_CHECKING: @@ -43,12 +53,15 @@ TurnRoutePolicy = Callable[[InboundMessage, str, TurnRoute], TurnRoute] def _bind_events( - bus: MessageBus, route: TurnRoute, + bus: MessageBus, route: TurnRoute, session_key: str, ) -> EventSink: channel, chat_id = route.channel, route.chat_id metadata = deepcopy(route.metadata) def accepts(event_type: type[AgentEvent]) -> bool: + # A maintenance result destination does not own the internal context. + if is_internal_session(session_key) and issubclass(event_type, ContextCompactionEvent): + return False return notification_is_deliverable( event_type, channel=channel, publish_lifecycle=route.publish_lifecycle, ) @@ -124,6 +137,8 @@ class TurnDeliveryFactory: session_metadata: dict[str, Any], ) -> EventSink: """Bind idle notifications to one route without acquiring a turn owner.""" + if is_internal_session(session_key): + return EventSink() saved_route = session_metadata.get("_compaction_route") if isinstance(saved_route, dict): saved_route = cast(dict[str, Any], saved_route) @@ -148,7 +163,7 @@ class TurnDeliveryFactory: metadata = {} metadata = deepcopy(metadata) - return _bind_events(self.bus, TurnRoute(channel, chat_id, metadata)) + return _bind_events(self.bus, TurnRoute(channel, chat_id, metadata), session_key) @staticmethod def _default_route(msg: InboundMessage, session_key: str) -> TurnRoute: @@ -202,7 +217,7 @@ class TurnDelivery: _stream_source_unknown: bool = field(init=False, default=False) def __post_init__(self) -> None: - self._routed_events = _bind_events(self.bus, self.route) + self._routed_events = _bind_events(self.bus, self.route, self.session_key) self.events = EventSink(self._publish_event, self._routed_events.accepts) self.delivery_message = dataclasses.replace( self.input_message, @@ -222,6 +237,9 @@ class TurnDelivery: def remember_session_route(self, session_metadata: dict[str, Any]) -> None: """Keep only routing fields needed to deliver a later idle notification.""" + if is_internal_session(self.session_key): + session_metadata.pop("_compaction_route", None) + return # Keep the storage key readable by older gateways. session_metadata["_compaction_route"] = { "channel": self.route.channel, diff --git a/nanobot/cli/gateway_runtime.py b/nanobot/cli/gateway_runtime.py index dff86e244..581a45e56 100644 --- a/nanobot/cli/gateway_runtime.py +++ b/nanobot/cli/gateway_runtime.py @@ -36,7 +36,11 @@ from nanobot.config.paths import is_default_workspace from nanobot.config.schema import Config from nanobot.gateway.runtime import GatewayInstance from nanobot.security.network import is_loopback_host -from nanobot.session.keys import UNIFIED_SESSION_KEY, last_channel_from_metadata +from nanobot.session.keys import ( + HEARTBEAT_SESSION_KEY, + UNIFIED_SESSION_KEY, + last_channel_from_metadata, +) from nanobot.utils.evaluator import evaluate_response, resolve_evaluator_prompt from nanobot.utils.helpers import sync_workspace_templates from nanobot.webui.build import BuildMode @@ -648,7 +652,7 @@ def _run_gateway( await mcp_provider.connect() resp = await agent.process_direct( prompt, - session_key="heartbeat", + session_key=HEARTBEAT_SESSION_KEY, channel=channel, chat_id=chat_id, on_progress=_silent, diff --git a/nanobot/session/keys.py b/nanobot/session/keys.py index 45f6d1cf7..27be56858 100644 --- a/nanobot/session/keys.py +++ b/nanobot/session/keys.py @@ -6,9 +6,20 @@ from collections.abc import Mapping, MutableMapping from typing import Any UNIFIED_SESSION_KEY = "unified:default" +HEARTBEAT_SESSION_KEY = "heartbeat" LAST_CHANNEL_METADATA_KEY = "last_channel" +def is_dream_session(key: str) -> bool: + """Identify the per-run session namespace owned by Dream.""" + return key.startswith("dream:") + + +def is_internal_session(key: str) -> bool: + """Identify maintenance sessions whose context is not a user conversation.""" + return key == HEARTBEAT_SESSION_KEY or is_dream_session(key) + + def session_key_for_channel(channel: str, chat_id: str, *, unified_session: bool = False) -> str: """Return the session key for a channel/chat pair.""" if unified_session: diff --git a/tests/agent/test_auto_compact.py b/tests/agent/test_auto_compact.py index 861a044f4..6bd5282ea 100644 --- a/tests/agent/test_auto_compact.py +++ b/tests/agent/test_auto_compact.py @@ -15,6 +15,7 @@ from nanobot.command import CommandContext from nanobot.config.schema import AgentDefaults, Config from nanobot.events import NO_EVENTS from nanobot.providers.base import LLMResponse +from nanobot.session.keys import HEARTBEAT_SESSION_KEY def _make_loop( @@ -132,6 +133,25 @@ async def _drain_background_tasks(loop: AgentLoop) -> None: await asyncio.sleep(0) +async def test_heartbeat_idle_compaction_persists_summary_without_channel_notices(tmp_path): + loop = _make_loop(tmp_path) + session = loop.sessions.get_or_create(HEARTBEAT_SESSION_KEY) + _add_turns(session, 2) + session.metadata["_compaction_route"] = {"channel": "telegram", "chat_id": "chat"} + session.updated_at = datetime.now() - timedelta(minutes=20) + 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 _drain_background_tasks(loop) + + loop.consolidator.archive_session.assert_awaited_once() + loop.sessions.invalidate(HEARTBEAT_SESSION_KEY) + refreshed = loop.sessions.get_or_create(HEARTBEAT_SESSION_KEY) + assert refreshed.metadata["_last_summary"]["text"] == "Heartbeat summary." + assert loop.bus.outbound.empty() + + class TestSessionTTLConfig: """Test session TTL configuration.""" diff --git a/tests/agent/test_turn_delivery.py b/tests/agent/test_turn_delivery.py index d2ae67433..22c2deaf3 100644 --- a/tests/agent/test_turn_delivery.py +++ b/tests/agent/test_turn_delivery.py @@ -9,6 +9,7 @@ from nanobot.bus.queue import MessageBus from nanobot.bus.runtime_events import TurnCompleted from nanobot.events import RetryStatusEvent from nanobot.providers.base import LLMProvider, ProviderCallContext +from nanobot.session.keys import HEARTBEAT_SESSION_KEY from nanobot.session.manager import SessionManager from nanobot.session.webui_turns import WebuiTurnRoutePolicy from nanobot.webui.metadata import ( @@ -17,6 +18,34 @@ from nanobot.webui.metadata import ( ) +@pytest.mark.parametrize("channel", ["telegram", "discord", "websocket", "cli", "custom"]) +@pytest.mark.parametrize("legacy_route", [False, True]) +@pytest.mark.parametrize("key", [HEARTBEAT_SESSION_KEY, "dream:20260602-155256"]) +async def test_internal_compaction_never_reaches_its_result_destination(channel, legacy_route, key): + factory = TurnDeliveryFactory(MessageBus()) + msg = InboundMessage(channel=channel, sender_id="user", chat_id="chat", content="check") + delivery = factory.create(msg, key) + metadata = {"_compaction_route": {"channel": channel, "chat_id": "chat"}} if legacy_route else {} + idle_events = factory.session_events(key, metadata) + for sink in (delivery.events, idle_events): + assert not sink.accepts(ContextCompactionEvent) + for phase in ("started", "succeeded", "failed", "cancelled"): + await sink.emit(ContextCompactionEvent("internal-compact", phase)) + assert factory.bus.outbound.empty() + + delivery.remember_session_route(metadata) + assert "_compaction_route" not in metadata + + # The same destination still receives the user's own compaction lifecycle. + user_delivery = factory.create(msg, f"{channel}:chat") + user_delivery.remember_session_route(metadata) + for sink in (user_delivery.events, factory.session_events(f"{channel}:chat", metadata)): + await sink.emit(ContextCompactionEvent("user-compact", "succeeded")) + assert factory.bus.outbound.get_nowait().event == ContextCompactionEvent( + "user-compact", "succeeded", + ) + + @pytest.mark.parametrize("unified", [False, True]) @pytest.mark.parametrize(("key", "channel", "chat_id", "metadata"), [ ("slack:C123:1700000000.000100", "slack", "C123",