Skip to content

The agent that grows with you

fix(gateway): fence the fresh FIFO for the whole exhaustion reset

Teknium3b1c70e5c584
diff --git a/gateway/run_turn_persistence.py b/gateway/run_turn_persistence.py
index 0b963894794..9811520e385 100644
--- a/gateway/run_turn_persistence.py
+++ b/gateway/run_turn_persistence.py
@@ -323,28 +323,31 @@ 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, 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.
- self._clear_conversation_scope(session_key, reason="compression_exhausted_reset")
- 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",
- )
- # Only now may the moved messages start: after eviction, scope clear and binding sync.
- run_moved()
+ 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)
+ # Conversation boundary: the funnel clears every conversation-scoped per-session dict.
+ self._clear_conversation_scope(session_key, reason="compression_exhausted_reset")
+ 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()
response = (response or "") + t("gateway.session.auto_reset_context_exhausted")
return response, session_entry
diff --git a/gateway/session_automation.py b/gateway/session_automation.py
index ae928939869..f3c6a395697 100644
--- a/gateway/session_automation.py
+++ b/gateway/session_automation.py
@@ -298,23 +298,25 @@ 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 and 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.
-
- 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."""
+ owner's still-queued native ``messaging:*`` rows onto it, 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.
+
+ The rotation (sessions.json) and the move (one SQLite transaction) run in one worker step
+ ordered with native admissions, not atomically across the two stores: a redelivery that
+ resolves the route to the fresh session commits after the move and dedupes onto the moved row.
+ Returns ``(entry, release)``. Until the caller runs ``release()``
+ (once, after its conversation cleanup and topic binding sync, also on failure) the fresh
+ session's ``claim_gate`` is held, so no scheduler (a redelivery, a moved route wake, this
+ move) starts a turn there against stale state; ``release()`` then schedules its FIFO."""
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
if live is None:
return await runner.async_session_store.reset_session(session_key), lambda: None
- from functools import partial
+ import asyncio
from gateway.session_authority import LiveSession
from gateway.session_runtime_workers import tracked_write
from hermes_state_runtime import rehome_queued_inputs
@@ -332,14 +334,43 @@ async def reset_and_rehome_messages(runner, session_key, old_session_id):
authority.db, epoch=authority.epoch, old_session_id=old.session_id,
new_session_id=new.session_id, principal_prefix='messaging:')
+ async def fence(result):
+ # In the write's own task step, before any later ordered admission schedules the fresh FIFO.
+ new = result[1]
+ if new is None:
+ return result, None
+ fresh = authority.sessions.setdefault(new.session_id, LiveSession(live.source, session_key))
+ await fresh.claim_gate.acquire()
+ return result, fresh
+
async with live.mutation_lock:
- entry, new, moved = await tracked_write(authority, rotate_and_move, ordered=True)
- if not moved:
+ write = asyncio.ensure_future(tracked_write(authority, rotate_and_move, fence, ordered=True))
+ try:
+ (entry, new, moved), fresh = await asyncio.shield(write)
+ except asyncio.CancelledError:
+ # The rotation still commits and takes the fence: lift it, or the fresh FIFO never runs.
+ def lift(done):
+ gate = None if done.cancelled() or done.exception() else done.result()[1]
+ if gate is not None:
+ gate.claim_gate.release()
+ authority._schedule(done.result()[0][1])
+ write.add_done_callback(lift)
+ raise
+ if fresh is None:
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)
+ if moved:
+ authority._publish_pending(old)
+ authority._publish_pending(new)
+
+ released = []
+
+ def release(): # once: a second call must not lift a claim the drain took meanwhile
+ if not released:
+ released.append(True)
+ fresh.claim_gate.release()
+ if authority.sessions.get(new.session_id) is fresh:
+ authority._schedule(new)
+ return entry, release
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.py
index 664e799d949..a4a1233354e 100644
--- a/tests/gateway/test_native_fifo_context_exhaustion.py
+++ b/tests/gateway/test_native_fifo_context_exhaustion.py
@@ -19,6 +19,8 @@ from hermes_constants import get_hermes_home
from hermes_state_runtime import list_session_admissions
from plugins.platforms.discord.adapter import DiscordAdapter
+_REAL_SCHEDULE = SessionAuthority._schedule # the fixture parks scheduling; races restore it
+
@pytest_asyncio.fixture
async def native(monkeypatch):
@@ -149,3 +151,58 @@ async def test_exhaustion_reset_is_ordered_with_redelivery_and_cleanup(native, m
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")]
+
+
+async def test_no_scheduler_starts_the_fresh_fifo_before_reset_cleanup_finishes(native, monkeypatch):
+ """With the real scheduler, a redelivery of B while the topic binding sync is still running
+ (it schedules the fresh FIFO itself) must not start B there before the reset finishes."""
+ import threading
+ from gateway.session_results import execution_result
+ runner, authority = native.runner, native.authority
+ loop = asyncio.get_running_loop()
+ admitted = [await _admit(native, text) for text in ("A", "B", "C")]
+ old = admitted[0][1].ref
+ events, executed, entered, release = [], [], asyncio.Event(), threading.Event()
+
+ def held_sync(*args, **kwargs):
+ events.append("sync:entered")
+ loop.call_soon_threadsafe(entered.set)
+ assert release.wait(10)
+ events.append("sync:done")
+
+ monkeypatch.setattr(runner, "_sync_telegram_topic_binding", held_sync)
+
+ 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))
+ events.append("turn:" + event.text)
+ captured = execution_result.get()
+ if event.text == "A":
+ result = {"failed": True, "compression_exhausted": True, "messages": []}
+ captured["result"] = result
+ # Production's turn cleanup releases the running slot before the reset runs.
+ runner._release_running_agent_state(session_key, run_generation=run_generation)
+ await runner._hmwa_compression_exhaustion_reset(result, "context exhausted", entry, session_key, source)
+ else:
+ captured["result"] = {"final_response": "reply", "messages": []}
+ return "reply"
+
+ monkeypatch.setattr(runner, "_handle_message_with_agent", turn)
+ monkeypatch.setattr(SessionAuthority, "_schedule", _REAL_SCHEDULE)
+ authority._schedule(old)
+ await asyncio.wait_for(entered.wait(), 10)
+ _, retry = await _admit(native, "B", admitted[1][0]) # dedupes, then schedules its FIFO
+ assert retry.admission_id == admitted[1][1].admission_id
+ for _ in range(25):
+ await asyncio.sleep(0.02)
+ assert [t for t, _ in executed] == ["A"] # nothing ran on the fresh session during the sync
+ release.set()
+ for _ in range(300):
+ if len(executed) == 3:
+ break
+ await asyncio.sleep(0.02)
+ new = runner.session_store.lookup_by_session_key(authority.sessions[old.session_id].route).session_id
+ assert executed == [("A", old.session_id), ("B", new), ("C", new)]
+ assert events.index("sync:done") < events.index("turn:B")
+