The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): run messages queued behind an exhausted context on the fresh session
Tekniumb5e2ca984ed5
diff --git a/gateway/run_turn_persistence.py b/gateway/run_turn_persistence.pyindex ffda879de4a..701f29300f6 100644--- a/gateway/run_turn_persistence.py+++ b/gateway/run_turn_persistence.py@@ -321,8 +321,9 @@ class GatewayTurnPersistenceMixin:)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)- new_entry = await self.async_session_store.reset_session(session_key)- from gateway.session_automation import move_route_wakes+ 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 = await reset_and_rehome_messages(self, session_key, session_entry.session_id)await move_route_wakes(self, session_key, session_entry.session_id)self._evict_cached_agent(session_key)# Conversation boundary: the funnel clears every conversation-scoped per-session dict.diff --git a/gateway/session_automation.py b/gateway/session_automation.pyindex 74ffd050c2d..731b56e4c3b 100644--- a/gateway/session_automation.py+++ b/gateway/session_automation.py@@ -296,6 +296,45 @@ async def move_route_wakes(runner, session_key, old_session_id):ordered=True, after=partial(authority._schedule_admitted, new))+async def reset_and_rehome_messages(runner, session_key, old_session_id):+ """The compression-exhaustion auto-reset: rotate the route to a fresh session, then move the old+ owner's still-queued native ``messaging:*`` rows onto it in one transaction, same order and+ request ids. Left behind they pause the old FIFO (``admission_conflict``) and never run, while a+ later message runs ahead of them. /new and /stop cancel these rows instead (the user asked for a+ clean break); the exhausted turn itself is started, so it is never moved. Both steps run under+ the old owner's ``mutation_lock``. Returns ``reset_session``'s entry."""+ from contextlib import nullcontext+ from gateway.session_authorities import active_authority+ authority = active_authority(runner)+ old = SessionRef(authority.profile_id, authority.logical_owner(old_session_id)) if authority else None+ live = authority.sessions.get(old.session_id) if old and old_session_id else None+ async with live.mutation_lock if live is not None else nullcontext():+ entry = await runner.async_session_store.reset_session(session_key)+ if live is None or entry is None:+ return entry+ import asyncio+ from functools import partial+ from gateway.session_authority import LiveSession+ from gateway.session_runtime_workers import tracked_write+ from hermes_state_runtime import rehome_queued_inputs+ new = SessionRef(authority.profile_id, authority.logical_owner(entry.session_id))+ if new == old:+ return entry+ if authority.db.get_session(new.session_id) is None:+ await asyncio.to_thread(authority.db.create_session, new.session_id, source=live.source.platform.value)+ # Ordered with native admissions: an admit already in flight to the old owner commits first+ # and is carried along.+ moved = await tracked_write(authority, partial(+ rehome_queued_inputs, authority.db, epoch=authority.epoch, old_session_id=old.session_id,+ new_session_id=new.session_id, principal_prefix='messaging:'), ordered=True)+ if moved:+ authority.sessions.setdefault(new.session_id, LiveSession(live.source, session_key))+ authority._publish_pending(old)+ authority._publish_pending(new)+ authority._schedule(new)+ return entry++async def admit_route_wake(runner, adapter, source, text, producer, metadata=None):"""Commit a producer wake (Kanban push wake, /loop tick) for ``source``'s route into theauthority FIFO, like heartbeats and process completions, instead of a classic turn thatdiff --git a/hermes_state_runtime.py b/hermes_state_runtime.pyindex 2d8d3b2a446..afde6c74996 100644--- a/hermes_state_runtime.py+++ b/hermes_state_runtime.py@@ -260,6 +260,37 @@ def cancel_session_input(db, *, epoch: int, admission_id: str) -> dict:return db._execute_write(write)+def rehome_queued_inputs(db, *, epoch: int, old_session_id: str, new_session_id: str,+ principal_prefix: str) -> list[str]:+ """Re-target the old owner's still-queued ``principal_prefix*`` admissions onto+ ``new_session_id`` in one transaction (the compression-exhaustion auto-reset). Each row keeps+ its admission id, request id and seq, so FIFO order and retry dedupe survive; the digest is+ re-keyed to the new target. Nothing moves while the old FIFO holds an ``unknown`` row (the+ operator's to resume). Returns the moved admission ids in FIFO order."""+ for value in (old_session_id, new_session_id, principal_prefix):+ _text(value)+ def write(conn):+ _epoch(conn, epoch)+ _session(conn, new_session_id)+ if conn.execute("SELECT 1 FROM session_admissions WHERE target_session_id=? AND status='unknown'",+ (old_session_id,)).fetchone():+ return []+ rows = conn.execute("SELECT * FROM session_admissions WHERE target_session_id=? AND status='queued' "+ "AND substr(principal_id,1,?)=? ORDER BY seq",+ (old_session_id, len(principal_prefix), principal_prefix)).fetchall()+ for row in rows:+ digest = admission_fingerprint(canonical_target=new_session_id, payload={+ 'input': json.loads(row['payload_json']), 'intent': row['intent']})+ conn.execute("UPDATE session_admissions SET target_session_id=?,lineage_json=?,payload_digest=? "+ "WHERE admission_id=? AND status='queued'",+ (new_session_id, json.dumps([new_session_id]), digest, row['admission_id']))+ if rows:+ for sid in (old_session_id, new_session_id):+ conn.execute('UPDATE sessions SET runtime_revision=runtime_revision+1 WHERE id=?', (sid,))+ return [row['admission_id'] for row in rows]+ return db._execute_write(write)++def recover_session_inputs(db, *, epoch: int) -> int:"""Never replay started work. Live worker adoption is a separate explicit operation."""def write(conn):diff --git a/tests/gateway/test_native_fifo_context_exhaustion.py b/tests/gateway/test_native_fifo_context_exhaustion.pynew file mode 100644index 00000000000..31b307d60bf--- /dev/null+++ b/tests/gateway/test_native_fifo_context_exhaustion.py@@ -0,0 +1,91 @@+"""Native messages queued behind a turn that exhausts its context run once, in order, on the fresh+session the auto-reset creates; the exhausted turn is not replayed and a transport retry of a+re-homed message still dedupes. Real GatewayRunner, DiscordAdapter, SessionAuthority and drain over+SQLite; the turn is a stand-in. Adapted from helix4u's #139673 headline test."""+import asyncio+from types import SimpleNamespace++import pytest+import pytest_asyncio++from gateway.config import GatewayConfig, Platform, PlatformConfig+from gateway.platforms.base import SendResult+from gateway.platforms.event import MessageEvent+from gateway.run import GatewayRunner+from gateway.session_authority import SessionAuthority, initialize_session_authority+from gateway.session_contract import SessionRef+from gateway.session_ingress_context import native_callback+from hermes_constants import get_hermes_home+from hermes_state_runtime import list_session_admissions+from plugins.platforms.discord.adapter import DiscordAdapter+++@pytest_asyncio.fixture+async def native(monkeypatch):+ monkeypatch.setenv("DISCORD_ALLOWED_USERS", "42")+ monkeypatch.setattr(SessionAuthority, "_schedule", lambda self, ref: None)+ runner = GatewayRunner(GatewayConfig())+ adapter = DiscordAdapter(PlatformConfig(enabled=True, token="fixture-token", typing_indicator=False))++ async def send(chat_id, content, reply_to=None, metadata=None):+ return SendResult(success=True, message_id="fixture-reply")++ monkeypatch.setattr(adapter, "send", send)+ runner.adapters = {Platform.DISCORD: adapter}+ authority = await initialize_session_authority(runner, profile_id="default", instance_id="fixture")+ runner._wire_adapter_handlers(adapter)+ source = adapter.build_source(chat_id="42", chat_type="dm", user_id="42")+ try:+ yield SimpleNamespace(runner=runner, adapter=adapter, authority=authority, source=source)+ finally:+ from gateway.session_runtime_workers import mutation_tasks+ await asyncio.gather(*mutation_tasks(authority))+ authority.db.close()+++async def _admit(native, text, event=None):+ event = event or MessageEvent(text=text, source=native.source, message_id=text)+ with native_callback(native.runner, event, get_hermes_home()):+ return event, await native.authority.admit_native(event)+++async def test_exhaustion_reset_runs_queued_native_messages_on_the_fresh_session(native, monkeypatch):+ from gateway.session_results import execution_result+ runner, authority, db = native.runner, native.authority, native.authority.db+ admitted = [await _admit(native, text) for text in ("A", "B", "C")]+ old = admitted[0][1].ref+ executed, fresh = [], {}++ async def turn(event, source, session_key, run_generation):+ entry = runner.session_store.lookup_by_session_key(session_key)+ executed.append((event.text, entry.session_id))+ captured = execution_result.get()+ if event.text == "A":+ result = {"failed": True, "compression_exhausted": True, "messages": []}+ captured["result"] = result+ _, new_entry = await runner._hmwa_compression_exhaustion_reset(+ result, "context exhausted", entry, session_key, source)+ fresh["sid"] = new_entry.session_id+ fresh["D"] = await _admit(native, "D") # admitted after the reset, behind B and C+ else:+ captured["result"] = {"final_response": "reply", "messages": []}+ return "reply"++ monkeypatch.setattr(runner, "_handle_message_with_agent", turn)+ await authority._drain(old)+ new = fresh["sid"]+ assert new != old.session_id+ if new in authority.sessions:+ await authority._drain(SessionRef(authority.profile_id, new))+ assert executed == [("A", old.session_id), ("B", new), ("C", new), ("D", new)]+ old_rows = list_session_admissions(db, session_id=old.session_id, pending_only=False)+ assert [(r["request_id"], r["status"]) for r in old_rows] == [("A", "terminal")]+ new_rows = list_session_admissions(db, session_id=new, pending_only=False)+ assert [(r["request_id"], r["status"], r["outcome"]) for r in new_rows] == [+ (t, "terminal", "completed") for t in ("B", "C", "D")]+ # The re-home keeps each message's admission identity; a transport retry of B dedupes onto it.+ assert [r["admission_id"] for r in new_rows[:2]] == [admitted[1][1].admission_id, admitted[2][1].admission_id]+ _, retry = await _admit(native, "B", admitted[1][0]) # the same delivery, redelivered+ assert retry.admission_id == admitted[1][1].admission_id+ assert [t for t, _ in executed].count("B") == 1