Skip to content

The agent that grows with you

fix(gateway): a detached conversation leaves the chat's topic alone, never fakes a reset, and runs its queued prompt after a restart

Teknium226c9bffd8aa
diff --git a/gateway/run_runtime.py b/gateway/run_runtime.py
index 329fd974efe..b741c0769b5 100644
--- a/gateway/run_runtime.py
+++ b/gateway/run_runtime.py
@@ -652,6 +652,8 @@ async def recover_profile_native_sessions(runner, authority):
for entry in runner.session_store.list_sessions() if entry.origin is not None
for owner in [authority.logical_owner(entry.session_id)] if owner in pending]
outcome = await authority.recover_native_sessions(bindings)
+ from gateway.session_detached import recover_detached_sessions
+ outcome.update(dict.fromkeys(recover_detached_sessions(authority, pending - set(outcome)), 'detached'))
for sid, verdict in outcome.items():
logger.info('Native session startup recovery %s (%s): %s', sid, authority.profile_id, verdict)
return outcome
diff --git a/gateway/run_topics.py b/gateway/run_topics.py
index 3a5e40152cd..f76d4063850 100644
--- a/gateway/run_topics.py
+++ b/gateway/run_topics.py
@@ -85,10 +85,14 @@ class GatewayTopicThreadsMixin:
)
def _is_telegram_topic_lane(self, source: SessionSource) -> bool:
- """True for a user-created Telegram private-chat topic lane."""
+ """True for a user-created Telegram private-chat topic lane. Never a conversation its chat
+ moved past (gateway/session_detached.py): its turns neither heal nor rewrite the topic's
+ binding, nor rename the topic, which belong to the chat's current conversation."""
+ from gateway.session_detached import detached_route_of
tid = str(source.thread_id or "")
return (
- self._is_telegram_dm(source) and self._telegram_topic_mode_enabled(source)
+ detached_route_of(source) is None
+ and self._is_telegram_dm(source) and self._telegram_topic_mode_enabled(source)
and bool(tid) and tid not in self._TELEGRAM_GENERAL_TOPIC_IDS
)
diff --git a/gateway/run_turn_persistence.py b/gateway/run_turn_persistence.py
index 962e31e1b8c..dc87bb75d54 100644
--- a/gateway/run_turn_persistence.py
+++ b/gateway/run_turn_persistence.py
@@ -26,6 +26,7 @@ from gateway.session import (
SessionSource, _session_key_namespace, build_channel_continuity_note,
build_session_context,
)
+from gateway.session_detached import detached_route_of
from gateway.session_transcript import TranscriptReadError
from gateway.turn_context import TurnContext
from gateway.warning_notifications import diagnostic_wake_muted
@@ -340,11 +341,14 @@ class GatewayTurnPersistenceMixin:
"session intact; the next message retries normally.",
session_entry.session_id if session_entry else "?",
)
- elif agent_result.get("compression_exhausted") and getattr(source, "platform", None) == Platform.API_SERVER:
+ elif agent_result.get("compression_exhausted") and (
+ getattr(source, "platform", None) == Platform.API_SERVER or detached_route_of(source)):
# The caller addresses an API conversation by its id and every API door re-validates that
# binding (``restore_api_session``): a rotated entry would refuse each later request to it
- # (``admission_conflict``). The caller gets the typed ``compression_exhausted`` result instead.
- logger.info("Keeping API session %s after compression exhaustion.",
+ # (``admission_conflict``). A conversation its chat moved past has no route of its own to
+ # reset (gateway/session_detached.py). Either caller gets the typed ``compression_exhausted``
+ # result instead, never a reset that did not happen.
+ logger.info("Keeping session %s after compression exhaustion.",
session_entry.session_id if session_entry else "?")
elif agent_result.get("compression_exhausted") and session_entry and session_key:
if not self._hmwa_defer_exhaustion_reset(session_entry, session_key, source):
diff --git a/gateway/session_detached.py b/gateway/session_detached.py
index 674cafb0a64..c422bb8dc63 100644
--- a/gateway/session_detached.py
+++ b/gateway/session_detached.py
@@ -57,6 +57,26 @@ def detach(authority, live, session_id) -> None:
live.source = replace_source(live.source, detached_route=live.route)
+def recover_detached_sessions(authority, pending):
+ """Boot: schedule the queued input of conversations their chats moved past (an app prompt
+ accepted during a restart's after-turn wait). The routing index names only each chat's current
+ conversation, so native recovery never binds these, and no chat message will wake them."""
+ from gateway.session_contract import SessionRef
+ from gateway.session_route_recovery import restore_routed_session
+ scheduled = []
+ from hermes_state_runtime import list_session_admissions
+ for session_id in sorted(pending):
+ if session_id in authority.sessions or not any( # a lost (unknown) turn waits for /discard
+ row['status'] == 'queued' for row in list_session_admissions(authority.db, session_id=session_id)):
+ continue
+ if restore_routed_session(authority, session_id) is None:
+ continue
+ if authority.sessions[session_id].detached:
+ authority._schedule(SessionRef(authority.profile_id, session_id))
+ scheduled.append(session_id)
+ return scheduled
+
+
def detached_entry(store, source):
"""The routing entry a detached *source* resolves to: its own conversation, at the compression
tip a turn writes to. Never stored: the chat's route stays the only one this conversation has."""
diff --git a/tests/gateway/test_authority_lane_moves_on.py b/tests/gateway/test_authority_lane_moves_on.py
index 9fd7f9bce36..c08ca781e3d 100644
--- a/tests/gateway/test_authority_lane_moves_on.py
+++ b/tests/gateway/test_authority_lane_moves_on.py
@@ -131,3 +131,58 @@ async def test_the_old_conversation_runs_beside_the_chats_turn_and_resume_brings
assert await _app_turn(authority, ref_a, 'after resume') == ('terminal', 'completed')
assert ran[-1] == ('after resume', a, lane) # back on the chat's route
assert sent[chat_replies:] == [f"reply to 'after resume' from {a}"]
+
+
+async def test_the_old_conversation_never_drives_the_chats_topic_or_claims_a_reset(monkeypatch):
+ """Review on #144840: a detached turn's compression must not rewrite the chat's Telegram topic
+ binding (the chat would fall back into A), and its context exhaustion has no route to reset."""
+ from gateway.session_detached import detach
+ from gateway.session_identity import replace_source
+ runner, adapter, authority, source, sent, _ran, _gates = await _gateway(monkeypatch)
+ await _chat(adapter, source, sent, 'hello')
+ ref_a = authority.register(source)
+ await _chat(adapter, source, sent, '/new')
+ detached = authority.sessions[ref_a.session_id].source
+ assert detached.detached_route # /new detached A
+ monkeypatch.setattr(runner, '_is_telegram_dm', lambda source: True)
+ monkeypatch.setattr(runner, '_telegram_topic_mode_enabled', lambda source: True)
+ topic = replace_source(source, thread_id='9')
+ assert runner._is_telegram_topic_lane(topic)
+ live = authority.sessions[ref_a.session_id]
+ live.source = replace_source(topic, detached_route=None)
+ live.route = runner.session_store._generate_session_key(topic)
+ detach(authority, live, ref_a.session_id)
+ assert not runner._is_telegram_topic_lane(live.source)
+
+ entry = runner.session_store.get_or_create_session(detached)
+ response, kept = await runner._hmwa_compression_exhaustion_reset(
+ {'compression_exhausted': True}, 'too long', entry, entry.session_key, detached)
+ assert (response, kept.session_id) == ('too long', ref_a.session_id)
+
+
+async def test_an_app_prompt_queued_for_the_old_conversation_runs_after_a_restart(monkeypatch):
+ """Review on #144840: the routing index names only the chat's current conversation, so boot
+ recovery of queued input never reached a detached one; its queued app prompt now runs."""
+ from gateway.config import GatewayConfig
+ from gateway.run import GatewayRunner
+ from gateway.run_runtime import recover_profile_native_sessions
+ from gateway.session_authority import initialize_session_authority
+ from gateway.session_contract import Submission
+ runner, adapter, authority, source, sent, _ran, _gates = await _gateway(monkeypatch)
+ await _chat(adapter, source, sent, 'hello')
+ ref_a = authority.register(source)
+ await _chat(adapter, source, sent, '/new')
+ await _chat(adapter, source, sent, 'hello again')
+ authority._schedule = lambda ref: None # accepted, then the gateway stops before running it
+ await authority.submit(_app(), Submission('queued', ref_a, {'text': 'queued over the restart'}, 'queue'))
+
+ restarted = GatewayRunner(GatewayConfig())
+ restarted.adapters = dict(runner.adapters)
+ cold = await initialize_session_authority(restarted, profile_id='default', instance_id='restarted')
+ scheduled = []
+ cold._schedule = scheduled.append
+ outcome = await recover_profile_native_sessions(restarted, cold)
+ assert outcome.get(ref_a.session_id) == 'detached' and scheduled == [ref_a]
+ assert cold.sessions[ref_a.session_id].detached