The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): order the exhaustion re-home with redeliveries and cleanup
Teknium18d043df5f36
diff --git a/gateway/run_turn_persistence.py b/gateway/run_turn_persistence.pyindex 701f29300f6..0b963894794 100644--- a/gateway/run_turn_persistence.py+++ b/gateway/run_turn_persistence.py@@ -323,7 +323,7 @@ class GatewayTurnPersistenceMixin: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 = await reset_and_rehome_messages(self, session_key, session_entry.session_id)+ new_entry, run_moved = 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.@@ -343,6 +343,8 @@ class GatewayTurnPersistenceMixin:await asyncio.to_thread(self._sync_telegram_topic_binding, source, session_entry, reason="compression-exhausted-reset",)+ # Only now may the moved messages start: after eviction, scope clear and binding sync.+ run_moved()response = (response or "") + t("gateway.session.auto_reset_context_exhausted")return response, session_entrydiff --git a/gateway/session_automation.py b/gateway/session_automation.pyindex 731b56e4c3b..ae928939869 100644--- a/gateway/session_automation.py+++ b/gateway/session_automation.py@@ -297,42 +297,49 @@ async def move_route_wakes(runner, session_key, old_session_id):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+ """The compression-exhaustion auto-reset: rotate the route to a fresh session and move the oldowner's still-queued native ``messaging:*`` rows onto it in one transaction, same order andrequest ids. Left behind they pause the old FIFO (``admission_conflict``) and never run, while alater 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+ clean break); the exhausted turn itself is started, so it is never moved.++ The rotation and the move are one write ordered with native admissions: a redelivery that+ resolves the route to the fresh session commits after the move and dedupes onto the moved row+ (committed first, it would collide with it and roll the whole move back). Returns+ ``(entry, schedule)``: the caller runs ``schedule()`` once its conversation cleanup and topic+ binding sync are done, so a moved message never starts a turn against stale state."""from gateway.session_authorities import active_authorityauthority = active_authority(runner)old = SessionRef(authority.profile_id, authority.logical_owner(old_session_id)) if authority else Nonelive = 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+ if live is None:+ return await runner.async_session_store.reset_session(session_key), lambda: None+ 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++ def rotate_and_move():+ entry = runner.session_store.reset_session(session_key)+ if entry is None:+ return None, None, []new = SessionRef(authority.profile_id, authority.logical_owner(entry.session_id))if new == old:- return entry+ return entry, None, []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+ authority.db.create_session(new.session_id, source=live.source.platform.value)+ return entry, new, rehome_queued_inputs(+ authority.db, epoch=authority.epoch, old_session_id=old.session_id,+ new_session_id=new.session_id, principal_prefix='messaging:')++ async with live.mutation_lock:+ entry, new, moved = await tracked_write(authority, rotate_and_move, ordered=True)+ if not moved:+ return entry, lambda: None+ authority.sessions.setdefault(new.session_id, LiveSession(live.source, session_key))+ authority._publish_pending(old)+ authority._publish_pending(new)+ return entry, partial(authority._schedule, new)async def admit_route_wake(runner, adapter, source, text, producer, metadata=None):diff --git a/tests/gateway/test_native_fifo_context_exhaustion.py b/tests/gateway/test_native_fifo_context_exhaustion.pyindex 31b307d60bf..664e799d949 100644--- a/tests/gateway/test_native_fifo_context_exhaustion.py+++ b/tests/gateway/test_native_fifo_context_exhaustion.py@@ -89,3 +89,63 @@ async def test_exhaustion_reset_runs_queued_native_messages_on_the_fresh_session_, retry = await _admit(native, "B", admitted[1][0]) # the same delivery, redeliveredassert retry.admission_id == admitted[1][1].admission_idassert [t for t, _ in executed].count("B") == 1+++[email protected]("redeliver", [True, False])+async def test_exhaustion_reset_is_ordered_with_redelivery_and_cleanup(native, monkeypatch, redeliver):+ """A redelivery of queued B that resolves the route to the fresh session mid-reset dedupes onto+ the moved row (no UNIQUE collision rolling the whole move back); and the reset schedules the+ moved rows only after the conversation cleanup and topic binding sync."""+ from gateway.session_results import execution_result+ runner, authority, db = native.runner, native.authority, native.authority.db+ loop = asyncio.get_running_loop()+ admitted = [await _admit(native, text) for text in ("A", "B", "C")]+ old = admitted[0][1].ref+ events, redelivery = [], {}+ real_reset = runner.session_store.reset_session++ def reset_then_redeliver(session_key, *args, **kwargs):+ entry = real_reset(session_key, *args, **kwargs)+ if redeliver: # the transport redelivers B right after the route rotated+ redelivery["B"] = future = asyncio.run_coroutine_threadsafe(_admit(native, "B", admitted[1][0]), loop)+ try:+ future.result(timeout=1) # times out when (correctly) ordered behind the move+ except TimeoutError:+ pass+ return entry++ monkeypatch.setattr(runner.session_store, "reset_session", reset_then_redeliver)+ monkeypatch.setattr(runner, "_clear_conversation_scope", lambda *a, **k: events.append("clear"))+ monkeypatch.setattr(runner, "_sync_telegram_topic_binding", lambda *a, **k: events.append("sync"))+ monkeypatch.setattr(SessionAuthority, "_schedule", lambda self, ref: events.append("schedule"))+ 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)+ 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+ else:+ captured["result"] = {"final_response": "reply", "messages": []}+ return "reply"++ monkeypatch.setattr(runner, "_handle_message_with_agent", turn)+ await authority._drain(old)+ new = fresh["sid"]+ if redeliver:+ _, retry = await asyncio.wrap_future(redelivery["B"])+ assert retry.admission_id == admitted[1][1].admission_id+ else:+ assert events == ["clear", "sync", "schedule"]+ await authority._drain(SessionRef(authority.profile_id, new))+ assert executed == ["A", "B", "C"]+ new_rows = list_session_admissions(db, session_id=new, pending_only=False)+ assert [(r["request_id"], r["admission_id"], r["status"]) for r in new_rows] == [+ ("B", admitted[1][1].admission_id, "terminal"), ("C", admitted[2][1].admission_id, "terminal")]