Skip to content

The agent that grows with you

fix(gateway): messages queued behind a running worker are acknowledged and run when it ends

Teknium58d8b41ee3b0
diff --git a/gateway/session_authority.py b/gateway/session_authority.py
index 980683e7de0..174e1c0b6f5 100644
--- a/gateway/session_authority.py
+++ b/gateway/session_authority.py
@@ -216,6 +216,13 @@ class SessionAuthority:
live.task = asyncio.create_task(self._drain(ref))
live.task.add_done_callback(_log_drain_failure)
+ def wake_after_worker(self, session_id):
+ """A worker execution on ``session_id`` (a logical owner or its compression continuation)
+ ended: a drain that parked behind it re-runs. A no-op while a drain is running."""
+ for sid in dict.fromkeys((session_id, self.logical_owner(session_id))):
+ if sid in self.sessions:
+ self._schedule(SessionRef(self.profile_id, sid))
+
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,
@@ -514,6 +521,12 @@ class SessionAuthority:
logging.getLogger(__name__).warning('Session %s paused: %s', ref.session_id, exc.reason)
self._pause(ref, exc.reason)
return
+ if row is None and first is not None:
+ # Not empty: a live worker (or a claim this drain does not own) blocks the head.
+ # Release the delivery waiters like any pause; the worker's finish wakes the FIFO
+ # (``wake_after_worker``) and the drain then answers through the adapter.
+ self._pause(ref, 'session_busy')
+ return
# The FIFO is moving again (or empty): the next pause is a new episode.
live.pause_notified = False
if row is None:
diff --git a/gateway/session_ingress.py b/gateway/session_ingress.py
index 7e60b81b95a..981ee7bb255 100644
--- a/gateway/session_ingress.py
+++ b/gateway/session_ingress.py
@@ -45,6 +45,9 @@ def pause_notice(authority, ref, reason):
if reason == 'runtime_draining':
# Transient: the row runs when the restarted owner drains it, so /reset would be wrong advice.
return '⏳ Hermes is restarting — your message is saved and will be answered when it is back.'
+ if reason == 'session_busy':
+ # Transient: queued behind work already running on this conversation (a worker execution).
+ return '⏳ Your message is saved and will be answered when the work running in this conversation finishes.'
if reason == 'unknown_execution':
cause = 'a previous turn did not finish when Hermes restarted, so nothing queued after it will run'
else:
diff --git a/gateway/session_worker.py b/gateway/session_worker.py
index f3d5ebf7a96..2a7887417d0 100644
--- a/gateway/session_worker.py
+++ b/gateway/session_worker.py
@@ -84,5 +84,9 @@ async def worker_request(connection, ref, params, *, operation):
if operation == 'adopt':
return await asyncio.to_thread(adopt_worker_execution, authority.db, epoch=authority.epoch,
**scope, adoption_secret=claim)
- return await asyncio.to_thread(mutate_worker_execution, authority.db, epoch=params['epoch'],
+ result = await asyncio.to_thread(mutate_worker_execution, authority.db, epoch=params['epoch'],
**scope, sequence=params['sequence'], operation=params['operation'], payload=params['payload'])
+ if params['operation'] == 'execution.finish':
+ # Queued input parked behind this worker; nothing else would restart its FIFO.
+ authority.wake_after_worker(params['session_id'])
+ return result
diff --git a/tests/gateway/test_worker_admission_reservation.py b/tests/gateway/test_worker_admission_reservation.py
index 34261a3fbd5..847b70d61c7 100644
--- a/tests/gateway/test_worker_admission_reservation.py
+++ b/tests/gateway/test_worker_admission_reservation.py
@@ -62,7 +62,8 @@ async def test_reserved_process_uses_existing_authenticated_adoption_and_persist
try:
db.create_session('owned', 'cli')
epoch = begin_runtime_epoch(db, instance_id='owner')
- authority = SimpleNamespace(db=db, epoch=epoch, profile_id=str(tmp_path), _require_admission_open=lambda: None)
+ authority = SimpleNamespace(db=db, epoch=epoch, profile_id=str(tmp_path), _require_admission_open=lambda: None,
+ wake_after_worker=lambda session_id: None)
admitted = admit_session_input(db, epoch=epoch, principal_id='human', session_id='owned', request_id='input', payload={})
claim_session_input(db, epoch=epoch, session_id='owned')
scope = reserve_admission_worker(authority, admission_id=admitted['admission_id'], process=process, principal_id='human', hello=hello(process))
@@ -82,3 +83,59 @@ async def test_reserved_process_uses_existing_authenticated_adoption_and_persist
process.stdin.close()
process.wait(timeout=5)
db.close()
+
+
+async def test_input_queued_behind_a_live_worker_is_released_then_runs_when_it_finishes(tmp_path, monkeypatch):
+ """A FIFO blocked by a live worker is not an empty FIFO: the messaging waiter is released
+ with a pause (never parked on a turn that cannot run yet), and the worker's durable finish
+ restarts the drain so the queued input runs without an unrelated submit."""
+ import asyncio
+ from gateway.config import Platform
+ from gateway.session_authority import LiveSession, SessionAuthority
+ from gateway.session_contract import Principal, SessionRef, Submission
+ from gateway.session_ingress import admit_message
+ from gateway.session_worker import worker_request
+ from gateway import session_finite
+ from hermes_state_runtime import get_session_admission
+
+ monkeypatch.setenv('HERMES_HOME', str(tmp_path))
+ db = SessionDB(tmp_path / 'state.db')
+ db.create_session('owned', 'telegram')
+ runner = SimpleNamespace(_draining=False, config=SimpleNamespace(multiplex_profiles=False),
+ _adapter_for_source=lambda source: None)
+ authority = SessionAuthority(runner, profile_id='p', instance_id='owner', db=db,
+ epoch=begin_runtime_epoch(db, instance_id='owner'))
+ authority.sessions['owned'] = LiveSession(SimpleNamespace(platform=Platform.TELEGRAM, user_id='human'), 'route')
+ ran = []
+
+ async def execute(authority, ref, row):
+ ran.append(row['admission_id'])
+ return 'answered'
+ monkeypatch.setattr(session_finite, 'execute_finite_admission', execute)
+ process = subprocess.Popen([sys.executable, '-c', 'import sys; sys.stdin.read()'], stdin=subprocess.PIPE,
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
+ actor = Principal('human', 'p', frozenset({'session:submit', 'session:control', 'worker:adopt'}), 't')
+ connection = SimpleNamespace(authority=authority, actor=actor)
+ ref = SessionRef('p', 'owned')
+ scope = {'profile_id': 'p', 'session_id': 'owned', 'execution_id': 'compute', 'generation': 0,
+ 'pid': process.pid, 'birth': psutil.Process(process.pid).create_time(), 'secret': 'w' * 32}
+ try:
+ registered = await worker_request(connection, ref, scope | {'kind': 'compute'}, operation='register')
+ # Native ingress waits on the admission it committed; a blocked FIFO must answer it.
+ event = SimpleNamespace()
+ async def admit_native(_event):
+ return await authority.submit(actor, Submission('behind', ref, {'text': 'hi'}, 'queue'))
+ authority.admit_native = admit_native
+ reply = await asyncio.wait_for(admit_message(authority, event), 5)
+ assert reply is not None and reply.startswith('⏳'), reply
+ assert ran == []
+ await worker_request(connection, ref, scope | {'epoch': registered['owner_epoch'], 'sequence': 1,
+ 'operation': 'execution.finish', 'payload': {}}, operation='persist')
+ await asyncio.wait_for(authority.sessions['owned'].task, 5)
+ assert len(ran) == 1
+ assert get_session_admission(db, admission_id=ran[0])['outcome'] == 'completed'
+ finally:
+ process.stdin.close()
+ process.wait(timeout=5)
+ db.close()