Skip to content

The agent that grows with you

fix(gateway): the FIFO head waits queued while a classic turn holds the route

Teknium2f18cd42f3ad
diff --git a/gateway/session_authority.py b/gateway/session_authority.py
index a8b24a4bc9f..61d2e2422af 100644
--- a/gateway/session_authority.py
+++ b/gateway/session_authority.py
@@ -101,6 +101,7 @@ class SessionAuthority:
# Set by profile retirement (unserve): the drain claims no successor after its running turn.
self.retiring = False
self.retired = False
+ self._classic_evict_at = {} # route -> last leaked/reaped-slot eviction check (monotonic)
def authorize(self, actor, ref, capability):
"""Every handler calls this first, so a later ``self.sessions[ref.session_id]`` is
@@ -646,6 +647,23 @@ class SessionAuthority:
interrupt_for_session(session_key=live.route, parent_session_id=parent, reason='user_stop')
return self._handle(ref)
+ def _classic_turn_holds(self, route):
+ """The route's running slot is held by a turn this FIFO did not claim (the drain is serial:
+ its own previous turn released the slot before this claim). Leaked and reaped slots are
+ evicted first, so they never block the FIFO; the reaped check reads state.db at most 1/s."""
+ runner = self.runner
+ running = getattr(runner, '_is_session_running', None)
+ if running is None or not running(route):
+ return False
+ import time
+ now = time.monotonic()
+ if now - self._classic_evict_at.get(route, 0.0) >= 1.0:
+ self._classic_evict_at[route] = now
+ runner._hm_evict_idle_stale_agent(route)
+ if running(route):
+ runner._hm_evict_reaped_agent(route)
+ return running(route)
+
def _runs_own_agent(self, ref):
"""The route's running slot holds a real agent (not the claim's pending sentinel), so the
Stop above reached the turn's own agent, not a cached one it may still replace."""
@@ -784,6 +802,11 @@ class SessionAuthority:
if first is not None and live.source.platform == Platform.API_SERVER:
from gateway.session_api_turn import check_api_turn
check_api_turn(self, ref, first['payload'])
+ if first is not None and self._classic_turn_holds(live.route):
+ # A classic turn (fallback wake, CLI handoff, legacy resume) holds the route's slot:
+ # a claim now would hand this row to its busy path and settle it unrun. The head
+ # waits queued, as main's pending slot did; /stop and /new still cancel it.
+ return 'classic_busy', first
self._require_admission_open()
from gateway.session_runtime_workers import tracked_write
live.rescan = False # a _schedule from here on may not be visible to this claim's read
@@ -809,6 +832,14 @@ class SessionAuthority:
self._publish_pending(ref)
return row
+ def _drain_stopping(self, ref, live):
+ """A drain about to wait (storage retry, classic slot) exits instead when the runtime drains,
+ the profile retires or the live entry was replaced; committed rows stay queued."""
+ if self.runner._draining or self.retiring or self.sessions.get(ref.session_id) is not live:
+ self._pause(ref, 'runtime_draining')
+ return True
+ return False
+
async def _drain(self, ref):
from gateway.session_finite import execute_finite_admission
from gateway.session_managed_worker import ManagedExecutionUnknown
@@ -827,8 +858,7 @@ class SessionAuthority:
# caller is event-driven: a dead drain would strand the committed head and hang its
# waiters until the next submit. Retry in place (like recover_failed_settlement),
# keeping waiters: releasing them fails requests that would run a moment later.
- if self.runner._draining or self.retiring or self.sessions.get(ref.session_id) is not live:
- self._pause(ref, 'runtime_draining')
+ if self._drain_stopping(ref, live):
return
backoff = min(max(backoff * 2, _CLAIM_RETRY_MIN_S), _CLAIM_RETRY_MAX_S)
import logging
@@ -837,6 +867,11 @@ class SessionAuthority:
await asyncio.sleep(backoff)
continue
backoff = 0.0
+ if row == 'classic_busy':
+ if self._drain_stopping(ref, live):
+ return
+ await asyncio.sleep(_CLAIM_RETRY_MIN_S)
+ continue
if row is False:
continue
if row is None and first is not None:
diff --git a/tests/gateway/test_classic_slot_holds_fifo_head.py b/tests/gateway/test_classic_slot_holds_fifo_head.py
new file mode 100644
index 00000000000..845bc2089ce
--- /dev/null
+++ b/tests/gateway/test_classic_slot_holds_fifo_head.py
@@ -0,0 +1,77 @@
+"""A user message admitted while a classic fallback wake holds the route's slot waits queued and runs
+as its own admitted turn; it is never handed to the wake's busy path and booked completed unrun (N82).
+Real GatewayRunner, DiscordAdapter, SessionAuthority and drain over SQLite; the turn is a stand-in."""
+import asyncio
+
+import pytest
+
+from tests.waiting import async_wait_until
+
+
[email protected]('stop', [False, True])
+async def test_message_during_classic_wake_runs_after_it_not_inside_it(monkeypatch, stop):
+ 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 initialize_session_authority
+ from gateway.session_ingress import executing_admission
+ from gateway.session_results import execution_result
+ from gateway.wake import deliver_wake
+ from hermes_state_runtime import list_session_admissions
+ from plugins.platforms.discord.adapter import DiscordAdapter
+
+ monkeypatch.setenv('DISCORD_ALLOWED_USERS', '42')
+ 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='sent')
+ monkeypatch.setattr(adapter, 'send', send)
+ adapter.gateway_runner = runner
+ runner.adapters = {Platform.DISCORD: adapter}
+ authority = await initialize_session_authority(runner, profile_id='default', instance_id='owner')
+ runner._wire_adapter_handlers(adapter)
+ source = adapter.build_source(chat_id='42', chat_type='dm', user_id='42')
+ key = runner.session_store._generate_session_key(source)
+ release = asyncio.Event()
+ started = []
+ wake = '[Kanban task completed] t_9'
+
+ class Agent:
+ def interrupt(self, *args, **kwargs):
+ pass
+
+ async def turn(event, source, quick_key, run_generation):
+ started.append((event.text, executing_admission.get()))
+ if event.text == wake:
+ runner._session_state(quick_key).turn.agent = Agent()
+ await release.wait()
+ captured = execution_result.get()
+ if captured is not None:
+ captured['result'] = {'final_response': 'ok', 'messages': []}
+ return 'ok'
+ monkeypatch.setattr(runner, '_handle_message_with_agent', turn)
+
+ await runner._handle_reset_command(MessageEvent(text='/new', source=source)) # fresh route: no native row
+ fallback = asyncio.create_task(deliver_wake(adapter, text=wake, source=source))
+ await async_wait_until(lambda: started, what='the classic fallback wake to hold the slot')
+ assert started == [(wake, False)]
+ await adapter.handle_message(MessageEvent(text='B', source=source, message_id='B'))
+ sid = runner.session_store.peek_session_id(key)
+
+ def rows():
+ return [(r['request_id'], r['status'], r['outcome'])
+ for r in list_session_admissions(authority.db, session_id=sid, pending_only=False)]
+ await async_wait_until(lambda: rows(), what='B to be admitted')
+ if stop:
+ await adapter.handle_message(MessageEvent(text='/stop', source=source, message_id='stop'))
+ release.set()
+ await fallback
+ if stop:
+ await async_wait_until(lambda: rows() == [('B', 'terminal', 'cancelled')], what='B to be cancelled')
+ assert ('B', True) not in started and ('B', False) not in started
+ return
+ await async_wait_until(lambda: ('B', True) in started, timeout=15, what='B to run as its own admitted turn')
+ await async_wait_until(lambda: rows() == [('B', 'terminal', 'completed')], what='B to settle')