The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): release paused admission observers without false settlement
David Dudok de Wit406e0b32ad9b
diff --git a/gateway/session_authority.py b/gateway/session_authority.pyindex 7660433c2d3..ad4f7b09432 100644--- a/gateway/session_authority.py+++ b/gateway/session_authority.py@@ -226,13 +226,11 @@ class SessionAuthority:def _pause(self, ref, reason):"""The FIFO stopped without claiming its head. Committed rows stay queued for a later- drain; only the process-local messaging delivery waiters on this session are released,+ drain; process-local delivery/HTTP/producer waiters on this session are released,with the reason instead of a reply, so an adapter loop is never parked on a turn thatwill not run. The ingress turns that refusal into one user-facing notice per episode."""for row in list_session_admissions(self.db, session_id=ref.session_id):admission_id = row['admission_id']- if admission_id not in self.native_waiters:- continueself.native_waiters.discard(admission_id)waiter = self.waiters.pop(admission_id, None)if waiter is not None and not waiter.done():@@ -528,6 +526,7 @@ class SessionAuthority:async def _drain(self, ref):from gateway.session_finite import execute_finite_admission+ from gateway.session_managed_worker import ManagedExecutionUnknownlive = self.sessions[ref.session_id]while True:try:@@ -558,6 +557,12 @@ class SessionAuthority:try:response = await execute_finite_admission(self, ref, row)outcome = 'completed'+ except ManagedExecutionUnknown:+ with live.event_stream.lock:+ live.event_stream.execution = {}+ self.pending_stops.pop(ref.session_id, None)+ self._pause(ref, 'unknown_execution')+ returnexcept Exception:import logginglogging.getLogger(__name__).exception('Admitted turn %s failed', admission_id)diff --git a/gateway/session_bot.py b/gateway/session_bot.pyindex 1e288e02f36..7c0a3cd7775 100644--- a/gateway/session_bot.py+++ b/gateway/session_bot.py@@ -316,11 +316,19 @@ async def _maybe_retry(authority, home, record):async def _record_reply(authority, home, key, future):- await asyncio.shield(future)+ try:+ await asyncio.shield(future)+ except RuntimeStoreError:+ # A paused FIFO is not a terminal Bot outcome; project the durable state below.+ passasync with _mailbox_order(authority):record = _read(_root(home) / f'{key}.json')record.update(_result(authority, record))_publish(home, record)+ admission_id, interim = peer_wait_admission(authority, record)+ if admission_id is not None and not interim:+ _watch_reply(authority, home, key, admission_id)+ returnawait _maybe_retry(authority, home, record)diff --git a/gateway/session_hosted_rpc.py b/gateway/session_hosted_rpc.pyindex bdcb7e92006..39da9e2996e 100644--- a/gateway/session_hosted_rpc.py+++ b/gateway/session_hosted_rpc.py@@ -167,6 +167,10 @@ class HostedRoomAuthorityRPC:def _completed(self, admission_id, future):if future.cancelled() or admission_id not in self.callbacks:return+ if future.exception() is not None:+ # A paused FIFO remains queued/unknown; polling or an explicit+ # resolution will publish its eventual durable terminal outcome.+ returnif self.authorizer('terminal', None, None) is not True:self.callbacks.pop(admission_id, None)returndiff --git a/gateway/session_managed_worker.py b/gateway/session_managed_worker.pyindex 28212061f5f..a9b8bf1684f 100644--- a/gateway/session_managed_worker.py+++ b/gateway/session_managed_worker.py@@ -22,6 +22,10 @@ HELLO_SECONDS = 60STOP_ACK_SECONDS = 30+class ManagedExecutionUnknown(RuntimeError):+ """The committed unknown verdict stops the FIFO without forging failed settlement."""++def managed_policy(authority, ref):"""Bypass (safe / config-only) sessions always execute out of process; other localsessions only under the explicit custom-provider opt-in.@@ -368,7 +372,7 @@ async def execute_managed(authority, ref, row, policy):waiter.set_result('Worker execution is unknown.')# Stop this drain without its ordinary Exception→failed settlement. The# committed unknown row deliberately pauses every accepted follower.- raise asyncio.CancelledError('managed_worker_unknown') from exc+ raise ManagedExecutionUnknown('managed_worker_unknown') from excfinally:workers.pop(ref.session_id, None)await asyncio.to_thread(worker.close)diff --git a/tests/gateway/test_authority_pause_recovery.py b/tests/gateway/test_authority_pause_recovery.pynew file mode 100644index 00000000000..9a8a7170d25--- /dev/null+++ b/tests/gateway/test_authority_pause_recovery.py@@ -0,0 +1,70 @@+"""Paused FIFO heads release observers and resume after their compute worker finishes."""+import asyncio+from types import SimpleNamespace++import pytest++from gateway.config import Platform+from gateway.session import SessionSource+from gateway.session_authority import LiveSession+from gateway.session_contract import Principal, SessionRef+from hermes_state_runtime import (RuntimeStoreError, admit_session_input, begin_runtime_epoch,+ get_session_admission, recover_session_inputs, register_worker_execution)+++def session(owner):+ owner.db.create_session('s', source='telegram')+ owner.sessions['s'] = LiveSession(SessionSource(Platform.TELEGRAM, 'chat'), 'route')+ return SessionRef(owner.profile_id, 's')+++async def test_worker_block_releases_waiter_and_finish_wakes_queued_input(owner, monkeypatch):+ from gateway.session_worker import worker_request+ ref = session(owner)+ register_worker_execution(owner.db, epoch=owner.epoch, execution_id='worker', session_id='s',+ generation=0, kind='compute', adoption_secret='private')+ row = admit_session_input(owner.db, epoch=owner.epoch, principal_id='human', session_id='s',+ request_id='queued', payload={'text': 'next'})+ waiter = owner.waiters[row['admission_id']] = asyncio.get_running_loop().create_future()+ await owner._drain(ref)+ assert waiter.done(), 'a blocked FIFO left its accepted input observer parked'+ with pytest.raises(RuntimeStoreError, match='session_busy'):+ await waiter+ assert get_session_admission(owner.db, admission_id=row['admission_id'])['status'] == 'queued'+ seen = []+ async def execute(authority, ref, row):+ seen.append(row['request_id'])+ return 'done'+ monkeypatch.setattr('gateway.session_finite.execute_finite_admission', execute)+ # Process identity is independent of this test's real receipt and scheduler path.+ monkeypatch.setattr('gateway.session_worker._claim', lambda *args: 'private')+ connection = SimpleNamespace(authority=owner, actor=Principal('human', owner.profile_id,+ frozenset({'worker:adopt'}), 'worker-transport'))+ await worker_request(connection, ref, dict(profile_id=owner.profile_id, session_id='s',+ execution_id='worker', generation=0, pid=1, birth=1, secret='private', epoch=owner.epoch,+ sequence=1, operation='execution.finish', payload={}), operation='persist')+ await owner.sessions['s'].task+ assert seen == ['queued']+++async def test_unknown_managed_execution_releases_all_observers_without_false_settlement(owner, monkeypatch):+ from gateway import session_managed_worker+ lost_execution = getattr(session_managed_worker, 'ManagedExecutionUnknown', asyncio.CancelledError)+ ref = session(owner)+ rows = [admit_session_input(owner.db, epoch=owner.epoch, principal_id='human', session_id='s',+ request_id=name, payload={'text': name}) for name in ('lost', 'follower')]+ waiters = [owner.waiters.setdefault(row['admission_id'], asyncio.get_running_loop().create_future()) for row in rows]+ async def execute(authority, ref, row):+ authority.epoch = begin_runtime_epoch(authority.db, instance_id='recovery')+ recover_session_inputs(authority.db, epoch=authority.epoch)+ raise lost_execution('worker lost')+ monkeypatch.setattr('gateway.session_finite.execute_finite_admission', execute)+ await owner._drain(ref)+ for waiter in waiters:+ assert waiter.done()+ with pytest.raises(RuntimeStoreError, match='unknown_execution'):+ await waiter+ assert owner.sessions['s'].event_stream.execution == {}+ assert [get_session_admission(owner.db, admission_id=row['admission_id'])['status'] for row in rows] == ['unknown', 'queued']diff --git a/tests/gateway/test_bot_paused_waiter.py b/tests/gateway/test_bot_paused_waiter.pynew file mode 100644index 00000000000..745daeab9f0--- /dev/null+++ b/tests/gateway/test_bot_paused_waiter.py@@ -0,0 +1,31 @@+"""The legacy Bot watcher survives a recoverable shared FIFO pause."""+import asyncio++import pytest++from tests.gateway.test_session_bot_retry import bot, KEY+++async def test_paused_bot_follower_rearms_until_its_durable_completion(bot, monkeypatch):+ from gateway.session_bot import deliver+ from gateway.session_contract import SessionRef+ from tools.bot_live_delivery import _read, _root++ authority = bot.authority+ schedule = authority._schedule+ monkeypatch.setattr(authority, '_schedule', lambda ref: None)+ accepted = await deliver(bot.connection, dict(id=KEY, profile='default', message='ping'))+ authority._pause(SessionRef(authority.profile_id, bot.chat), 'session_busy')+ async with asyncio.timeout(5):+ while _read(_root(bot.home) / f'{KEY}.json')['status'] != 'queued':+ await asyncio.sleep(.01)+ record = _read(_root(bot.home) / f'{KEY}.json')+ assert record['status'] == 'queued'+ schedule(SessionRef(authority.profile_id, bot.chat))+ await asyncio.wait_for(authority.sessions[bot.chat].task, 5)+ async with asyncio.timeout(5):+ while _read(_root(bot.home) / f'{KEY}.json')['status'] != 'settled':+ await asyncio.sleep(.01)+ record = _read(_root(bot.home) / f'{KEY}.json')+ assert record['status'] == 'settled' and record['reply'] == 'pong'