Skip to content

The agent that grows with you

fix(gateway): run a LOCAL session's overflow auto-reset after its turn settles

Teknium2e20b4de6e53
diff --git a/gateway/run_turn_persistence.py b/gateway/run_turn_persistence.py
index 5d0fe75165f..a4f108979ab 100644
--- a/gateway/run_turn_persistence.py
+++ b/gateway/run_turn_persistence.py
@@ -344,42 +344,64 @@ class GatewayTurnPersistenceMixin:
logger.info("Keeping API 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:
- logger.info("Auto-resetting session %s after compression exhaustion.", session_entry.session_id)
- from gateway.session_automation import move_route_wakes, reset_and_rehome_messages
- # Messages queued behind the exhausted turn still run, on the fresh session (unlike /new).
- new_entry, release_fresh = await reset_and_rehome_messages(self, session_key, session_entry.session_id)
- try:
- await move_route_wakes(self, session_key, session_entry.session_id)
- self._evict_cached_agent(session_key)
- # The /queue overflow behind the deferred head slot is queued user input, like the
- # re-homed native rows: it survives the boundary the funnel below otherwise clears.
- queued = list(self._overflow_queue(session_key) or ())
- # Conversation boundary: the funnel clears every conversation-scoped per-session dict.
- self._clear_conversation_scope(session_key, reason="compression_exhausted_reset")
- if queued:
- self._session_state(session_key).conversation.queued_events.extend(queued)
- if new_entry is not None:
- # Re-point the Telegram topic binding at the fresh session, or the binding-heal walk
- # switches the next message back onto the bloated child and re-triggers exhaustion
- # forever. No-op on non-topic lanes.
- # Compression rotated session_entry.session_id to the oversized compressed child earlier
- # this turn (the agent-result sync above), and that _sync also rewrote the (chat_id,
- # thread_id) -> bloated-child binding. reset_session swaps in a clean, parentless session,
- # but without re-syncing the binding the next inbound message in this topic gets
- # switch_session'd back onto the bloated child by the binding-heal walk, reloads the
- # oversized transcript, and re-triggers compression exhaustion forever (#35809 — regression
- # of the #9893/#10063 auto-reset).
- session_entry = new_entry
- await asyncio.to_thread(
- self._sync_telegram_topic_binding, source, session_entry, reason="compression-exhausted-reset",
- )
- finally:
- # Only now may the fresh session's FIFO claim (it is fenced until here, against every
- # scheduler): after eviction, scope clear and binding sync.
- release_fresh()
+ if not self._hmwa_defer_exhaustion_reset(session_entry, session_key, source):
+ session_entry = await self._hmwa_rotate_exhausted_session(session_entry, session_key, source)
response = (response or "") + t("gateway.session.auto_reset_context_exhausted")
return response, session_entry
+ def _hmwa_defer_exhaustion_reset(self, session_entry, session_key, source):
+ """True when the reset was handed to the authority drain. A LOCAL session (the Bot Chat a
+ ``hermes peer dm`` lands in) resets its target in the store, which refuses while an admission
+ on it is started (``session_busy``): this turn's own. The drain runs the reset right after it
+ settles this admission, before it claims any successor (the Bot Chat's retry included)."""
+ from gateway.session_ingress import executing_admission
+ if getattr(source, "platform", None) != Platform.LOCAL or not executing_admission.get():
+ return False
+ from gateway.session_authorities import active_authority
+ authority = active_authority(self)
+ if authority is None:
+ return False
+ authority.deferred_resets[session_key] = lambda: self._hmwa_rotate_exhausted_session(
+ session_entry, session_key, source)
+ return True
+
+ async def _hmwa_rotate_exhausted_session(self, session_entry, session_key, source):
+ """The compression-exhaustion auto-reset itself; returns the route's (fresh) entry."""
+ logger.info("Auto-resetting session %s after compression exhaustion.", session_entry.session_id)
+ from gateway.session_automation import move_route_wakes, reset_and_rehome_messages
+ # Messages queued behind the exhausted turn still run, on the fresh session (unlike /new).
+ new_entry, release_fresh = await reset_and_rehome_messages(self, session_key, session_entry.session_id)
+ try:
+ await move_route_wakes(self, session_key, session_entry.session_id)
+ self._evict_cached_agent(session_key)
+ # The /queue overflow behind the deferred head slot is queued user input, like the
+ # re-homed native rows: it survives the boundary the funnel below otherwise clears.
+ queued = list(self._overflow_queue(session_key) or ())
+ # Conversation boundary: the funnel clears every conversation-scoped per-session dict.
+ self._clear_conversation_scope(session_key, reason="compression_exhausted_reset")
+ if queued:
+ self._session_state(session_key).conversation.queued_events.extend(queued)
+ if new_entry is not None:
+ # Re-point the Telegram topic binding at the fresh session, or the binding-heal walk
+ # switches the next message back onto the bloated child and re-triggers exhaustion
+ # forever. No-op on non-topic lanes.
+ # Compression rotated session_entry.session_id to the oversized compressed child earlier
+ # this turn (the agent-result sync above), and that _sync also rewrote the (chat_id,
+ # thread_id) -> bloated-child binding. reset_session swaps in a clean, parentless session,
+ # but without re-syncing the binding the next inbound message in this topic gets
+ # switch_session'd back onto the bloated child by the binding-heal walk, reloads the
+ # oversized transcript, and re-triggers compression exhaustion forever (#35809 — regression
+ # of the #9893/#10063 auto-reset).
+ session_entry = new_entry
+ await asyncio.to_thread(
+ self._sync_telegram_topic_binding, source, session_entry, reason="compression-exhausted-reset",
+ )
+ finally:
+ # Only now may the fresh session's FIFO claim (it is fenced until here, against every
+ # scheduler): after eviction, scope clear and binding sync.
+ release_fresh()
+ return session_entry
+
@staticmethod
def _hmwa_user_transcript_entry(event, prepared, ts):
"""Transcript row for the inbound user turn (clean text + event time when captured)."""
diff --git a/gateway/session_authority.py b/gateway/session_authority.py
index d85b652650b..a18d2931247 100644
--- a/gateway/session_authority.py
+++ b/gateway/session_authority.py
@@ -130,6 +130,9 @@ class SessionAuthority:
# Logical owner rotated away by the exhaustion auto-reset -> its session key: an admission
# that reserved it before the rotation commits on that key's current route instead.
self.rotated_owners = {}
+ # route -> the compression-exhaustion auto-reset its LOCAL turn deferred: the store refuses a
+ # reset while that turn's admission is started, so the drain runs it once the turn settles.
+ self.deferred_resets = {}
def authorize(self, actor, ref, capability):
"""Every handler calls this first, so a later ``self.sessions[ref.session_id]`` is
@@ -1133,10 +1136,24 @@ class SessionAuthority:
self.pending_deliveries.pop(admission_id, None)
from gateway.session_ingress import waiter_replies
waiter_replies(self).pop(admission_id, None)
+ # Taken on every exit, so a turn that never settled leaves no reset for a later one.
+ reset = self.deferred_resets.pop(live.route, None)
+ await self._run_deferred_reset(live.route, reset)
from gateway.session_ingress import deliver_settled
await deliver_settled(self, admission_id)
await self._resolve_settled_waiter(admission_id, response)
+ @staticmethod
+ async def _run_deferred_reset(route, reset):
+ """The auto-reset the settled turn deferred (``_hmwa_defer_exhaustion_reset``), before its
+ waiter wakes: a delivery retry or the next DM then reads the fresh target."""
+ if reset is not None:
+ try:
+ await reset()
+ except Exception:
+ import logging
+ logging.getLogger(__name__).exception('Deferred auto-reset of %s failed', route)
+
async def _resolve_settled_waiter(self, admission_id, response):
"""Hand the settled reply to its waiter. The adapter sending it adopted the turn's crash marker
and releases it once the reply is ledgered (seconds with auto-TTS); a follower claimed before
diff --git a/tests/gateway/test_peer_dm_bot_chat_context_overflow.py b/tests/gateway/test_peer_dm_bot_chat_context_overflow.py
new file mode 100644
index 00000000000..b7ea6ddf584
--- /dev/null
+++ b/tests/gateway/test_peer_dm_bot_chat_context_overflow.py
@@ -0,0 +1,157 @@
+"""A peer DM that overflows the LOCAL Bot Chat's context auto-resets it, and the follow-up is answered.
+
+``hermes peer dm`` lands in the peer's Bot Chat, a ``source='local'`` session the authority FIFO owns
+(not an API conversation, so the API_SERVER exemption from the compression-exhaustion reset never
+applies). The reset ran INSIDE the overflowing turn, while that turn's own admission was still
+``started``: ``reset_local_target`` refused it (``session_busy``), the exception became a failed turn
+that persisted the DM a second time, and the Bot Chat kept its oversized transcript, so every later
+DM overflowed too (HTTP 502 forever). Real daemon (``python -m gateway.run``), real api_server door,
+real SessionDB and authority; only the model is a loopback window-capped stub.
+"""
+from contextlib import closing
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+import json
+from pathlib import Path
+import socket
+import sqlite3
+import threading
+from types import SimpleNamespace
+import urllib.error
+import urllib.request
+
+import pytest
+
+from tests.gateway.fixtures.local_recovery_probe import child_env, daemon
+
+KEY = 'lc23-peer-dm-overflow-key-0123456789'
+CAP = 30000 # request bytes the stub's "model" accepts
+
+
+class WindowCappedModel(BaseHTTPRequestHandler):
+ """Main (tool-bearing or not) requests over CAP bytes get a numberless 400 context overflow."""
+
+ def log_message(self, *args):
+ pass
+
+ def do_POST(self):
+ raw = self.rfile.read(int(self.headers['Content-Length']))
+ body = json.loads(raw)
+ if len(raw) > CAP:
+ self.server.rejected += 1
+ payload = json.dumps({'error': {'message': "This model's maximum context length was exceeded. "
+ 'Please reduce the length of the messages.',
+ 'type': 'invalid_request_error',
+ 'code': 'context_length_exceeded'}}).encode()
+ return self._send(400, payload, 'application/json')
+ text = next((m.get('content', '') for m in reversed(body.get('messages', [])) if m['role'] == 'user'), '')
+ message = {'role': 'assistant', 'content': 'ACK ' + str(text)[:40]}
+ payload = json.dumps({'id': 'local', 'model': body.get('model'), 'choices': [
+ {'index': 0, 'message': message, 'finish_reason': 'stop'}],
+ 'usage': {'prompt_tokens': 10, 'completion_tokens': 5, 'total_tokens': 15}}).encode()
+ kind = 'application/json'
+ if body.get('stream'):
+ payload = ('data: ' + json.dumps({'id': 'local', 'choices': [
+ {'index': 0, 'delta': message, 'finish_reason': 'stop'}]}) + '\n\ndata: [DONE]\n\n').encode()
+ kind = 'text/event-stream'
+ self._send(200, payload, kind)
+
+ def _send(self, status, payload, kind):
+ try:
+ self.send_response(status)
+ self.send_header('Content-Type', kind)
+ self.send_header('Content-Length', str(len(payload)))
+ self.end_headers()
+ self.wfile.write(payload)
+ except (BrokenPipeError, ConnectionResetError):
+ pass
+
+
+def _free_port():
+ with closing(socket.socket()) as s:
+ s.bind(('127.0.0.1', 0))
+ return s.getsockname()[1]
+
+
+def _post(port, path, body, timeout=180):
+ req = urllib.request.Request(f'http://127.0.0.1:{port}{path}', data=json.dumps(body).encode(), method='POST',
+ headers={'Authorization': f'Bearer {KEY}', 'Content-Type': 'application/json'})
+ try:
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
+ return resp.status, json.loads(resp.read())
+ except urllib.error.HTTPError as exc:
+ return exc.code, json.loads(exc.read() or b'{}')
+
+
[email protected](scope='module')
+def overflow_run(tmp_path_factory):
+ """Two DMs into a fresh headless Bot Chat: an oversized one, then a short follow-up."""
+ tmp_path = tmp_path_factory.mktemp('lc23')
+ root = Path(__file__).resolve().parents[2]
+ home, user = tmp_path / 'state', tmp_path / 'user'
+ home.mkdir(mode=0o700)
+ user.mkdir()
+ model = ThreadingHTTPServer(('127.0.0.1', 0), WindowCappedModel)
+ model.rejected = 0
+ threading.Thread(target=model.serve_forever, daemon=True).start()
+ url = f'http://127.0.0.1:{model.server_port}/v1'
+ api_port = _free_port()
+ (home / 'config.yaml').write_text(json.dumps({
+ 'gateway': {'multiplex_profiles': False},
+ 'model': {'provider': 'custom', 'default': 'fake-model', 'base_url': url, 'context_length': 65536},
+ 'agent': {'api_max_retries': 1},
+ 'approvals': {'mode': 'off'},
+ 'compression': {'protect_last_n': 2},
+ 'memory': {'memory_enabled': False, 'user_profile_enabled': False},
+ 'auxiliary': {'title_generation': {'enabled': False},
+ 'compression': {'provider': 'custom', 'model': 'fake-model', 'base_url': url}},
+ 'platforms': {'api_server': {'enabled': True, 'extra': {'host': '127.0.0.1', 'port': api_port, 'key': KEY}}},
+ 'platform_toolsets': {'cli': [], 'api_server': []}}))
+ env = child_env() | dict(HOME=str(user), USERPROFILE=str(user), HERMES_HOME=str(home), PYTHONPATH=str(root),
+ OPENAI_API_KEY='loopback-only', PYTHONUNBUFFERED='1')
+ big = 'MKBIG ' + 'lorem ipsum dolor sit amet ' * 12000 # the live repro's DM (capped to 64 KB at the door)
+ try:
+ with daemon(root, home, env, barrier=False):
+ status, created = _post(api_port, '/api/sessions', {'title': 'Bot Chat', 'source': 'bot_peer_dm'})
+ assert status == 201, created
+ sid = created['session']['id']
+ first = _post(api_port, f'/api/sessions/{sid}/chat', {'message': big})
+ follow = _post(api_port, f'/api/sessions/{sid}/chat', {'message': 'short follow-up MKFOLLOW'})
+ finally:
+ model.shutdown()
+ log = (home / 'restart.log').read_text(errors='replace')
+ for name in ('gateway.log', 'errors.log'):
+ if (home / 'logs' / name).exists():
+ log += (home / 'logs' / name).read_text(errors='replace')
+ with closing(sqlite3.connect(f'file:{home / "state.db"}?mode=ro', uri=True)) as db:
+ rows = db.execute("SELECT session_id, role, substr(coalesce(content,''),1,24) FROM messages ORDER BY id").fetchall()
+ bot_chat = db.execute('SELECT end_reason FROM sessions WHERE id=?', (sid,)).fetchone()
+ return SimpleNamespace(first=first, follow=follow, log=log, rows=rows, rejected=model.rejected,
+ bot_chat_end=bot_chat[0])
+
+
+def _stored(run, marker):
+ return sum(1 for _, role, text in run.rows if role == 'user' and text.startswith(marker))
+
+
+def test_peer_dm_overflow_resets_the_local_bot_chat_and_answers_the_follow_up(overflow_run):
+ run = overflow_run
+ assert run.rejected >= 1, 'the first DM never overflowed'
+ assert 'session_busy' not in run.log, [line for line in run.log.splitlines() if 'session_busy' in line][:5]
+ # The overflow is answered with its typed reason, and the Bot Chat was reset after that turn settled.
+ assert run.first[0] == 502 and run.first[1]['error']['code'] == 'context_overflow', run.first
+ assert run.bot_chat_end == 'session_reset', run.rows
+ # The follow-up runs on the fresh transcript, is answered, and is stored once.
+ assert run.follow[0] == 200, (run.follow, run.rows)
+ assert run.follow[1]['message']['content'].startswith('ACK short follow-up'), run.follow
+ assert _stored(run, 'short follow-up') == 1, run.rows
+
+
[email protected](strict=True, reason=(
+ "The overflowing DM's first attempt fails transiently, is closed with the durable failed-turn "
+ "boundary (#107070), and the owner's one Bot Chat retry (session_bot._maybe_retry) runs a fresh "
+ "turn after that boundary, so it appends the DM a second time. Adopting the closed row needs an "
+ "owner-side adoption seam that the retry declines by design."))
+def test_overflowing_peer_dm_is_stored_once(overflow_run):
+ assert _stored(overflow_run, 'MKBIG') == 1, overflow_run.rows