Skip to content

The agent that grows with you

fix: recover committed API queue when its adapter reconnects

Teknium8ef9fbe8ef06
diff --git a/gateway/run_adapters.py b/gateway/run_adapters.py
index 95b27759d0a..a9a7c2a3230 100644
--- a/gateway/run_adapters.py
+++ b/gateway/run_adapters.py
@@ -760,6 +760,9 @@ class GatewayAdapterLifecycleMixin:
def _publish_primary_adapter(self, platform, adapter) -> None:
"""Register a connected primary adapter and wire voice mode/input (transcription without /voice join)."""
self.adapters[platform] = adapter
+ if platform == Platform.API_SERVER:
+ from gateway.session_api_turn import recover_api_turns
+ recover_api_turns(adapter)
self._sync_voice_mode_state_to_adapter(adapter)
self._bind_voice_input_callback(adapter)
diff --git a/gateway/session_api_turn.py b/gateway/session_api_turn.py
index 33838ab93a4..b7ec4eba6a2 100644
--- a/gateway/session_api_turn.py
+++ b/gateway/session_api_turn.py
@@ -94,6 +94,30 @@ def admit_api_turn(adapter, **kwargs):
return authority, ref, row
+def recover_api_turns(adapter):
+ """Recover committed work only after the real API adapter is published."""
+ authority = getattr(adapter.gateway_runner, 'session_authority', None)
+ if authority is None:
+ return
+ from hermes_state_runtime import list_session_admissions
+ import logging
+ with authority.db._read_ctx() as conn:
+ targets = [row[0] for row in conn.execute(
+ "SELECT DISTINCT target_session_id FROM session_admissions WHERE principal_id='api' AND status='queued'")]
+ for sid in targets:
+ try:
+ ref = restore_api_session(authority, sid)
+ pending = list_session_admissions(authority.db, session_id=sid)
+ if any(row['status'] == 'unknown' for row in pending):
+ continue
+ for row in pending:
+ if row['status'] == 'queued':
+ check_api_turn(authority, ref, row['payload'])
+ authority._schedule(ref)
+ except RuntimeStoreError as exc:
+ logging.getLogger(__name__).warning('API session %s paused: %s', sid, exc.reason)
+
+
async def run_api_turn(adapter, **kwargs):
admitted = admit_api_turn(adapter, **kwargs)
return await observe_api_turn(admitted, **kwargs)
diff --git a/tests/gateway/fixtures/api_recovery_daemon.py b/tests/gateway/fixtures/api_recovery_daemon.py
new file mode 100644
index 00000000000..4707dfd0641
--- /dev/null
+++ b/tests/gateway/fixtures/api_recovery_daemon.py
@@ -0,0 +1,17 @@
+"""Hold only execution scheduling after a real API commit and HTTP ACK."""
+import runpy
+from gateway.session_authority import SessionAuthority
+from hermes_state_runtime import list_session_admissions
+
+schedule = SessionAuthority._schedule
+
+
+def hold_safe(self, ref):
+ pending = list_session_admissions(self.db, session_id=ref.session_id)
+ if any(row['payload'].get('text') == 'SAFE_QUEUE' for row in pending):
+ return
+ return schedule(self, ref)
+
+
+SessionAuthority._schedule = hold_safe
+runpy.run_module('gateway.run', run_name='__main__')
diff --git a/tests/gateway/test_api_crash_recovery.py b/tests/gateway/test_api_crash_recovery.py
new file mode 100644
index 00000000000..6cd3aa01e21
--- /dev/null
+++ b/tests/gateway/test_api_crash_recovery.py
@@ -0,0 +1,106 @@
+"""SIGKILL recovery exercises authenticated HTTP on ordinary fresh daemons."""
+import asyncio
+from http.server import ThreadingHTTPServer
+import json
+import os
+from pathlib import Path
+import socket
+import sqlite3
+import threading
+
+import aiohttp
+
+from tests.gateway.fixtures.local_recovery_probe import daemon, Model
+
+
+def test_api_crash_queue_and_identified_result_retry(tmp_path):
+ root = Path(__file__).resolve().parents[2]
+ home, user = tmp_path / 'state', tmp_path / 'user'
+ home.mkdir(mode=0o700); user.mkdir()
+ peer = ThreadingHTTPServer(('127.0.0.1', 0), Model)
+ peer.requests = []
+ peer.blocked, peer.release = threading.Event(), threading.Event()
+ threading.Thread(target=peer.serve_forever, daemon=True).start()
+ with socket.socket() as sock:
+ sock.bind(('127.0.0.1', 0)); port = sock.getsockname()[1]
+ base = f'http://127.0.0.1:{peer.server_port}/v1'
+ cfg = {'model': {'provider': 'custom', 'default': 'local-wire-stub', 'base_url': base},
+ 'gateway': {'platforms': {'api_server': {'enabled': True, 'port': port, 'host': '127.0.0.1'}}, 'multiplex_profiles': False},
+ 'auxiliary': {'title_generation': {'enabled': False}}, 'terminal': {'cwd': str(home)}}
+ (home / 'config.yaml').write_text(json.dumps(cfg))
+ env = {k: os.environ[k] for k in ('PATH', 'LANG', 'TZ') if k in os.environ}
+ env.update(HOME=str(user), USERPROFILE=str(user), HERMES_HOME=str(home), PYTHONPATH=str(root),
+ OPENAI_API_KEY='loopback-only', OPENAI_BASE_URL=base, API_SERVER_KEY='ordinary-daemon-owned-secret',
+ API_SERVER_ENABLED='true', API_SERVER_PORT=str(port), PYTHONUNBUFFERED='1')
+ url = f'http://127.0.0.1:{port}/v1'
+ headers = {'Authorization': 'Bearer ordinary-daemon-owned-secret'}
+ runs = {}
+ pids, epochs = [], []
+
+ def rows():
+ with sqlite3.connect(f'file:{home / "state.db"}?mode=ro', uri=True) as db:
+ return dict(db.execute('SELECT request_id,status FROM session_admissions'))
+
+ async def run(client, name, text, session):
+ async with client.post(url + '/runs', json={'input': text, 'session_id': session},
+ headers={'Idempotency-Key': name}) as response:
+ data = await response.json()
+ assert response.status == 202, data
+ if name in runs:
+ assert runs[name] == data['run_id'] and data['replayed'], data
+ runs[name] = data['run_id']
+ return data
+
+ async def first():
+ async with aiohttp.ClientSession(headers=headers) as client:
+ # Warm before the exact model barrier (onboarding may decorate first input).
+ async with client.post(url + '/chat/completions', json={'messages': [{'role': 'user', 'content': 'WARM'}]},
+ headers={'X-Hermes-Session-Id': 'unknown'}) as response:
+ assert response.status == 200, await response.text()
+ await run(client, 'started', 'BLOCK_STARTED', 'unknown')
+ assert await asyncio.to_thread(peer.blocked.wait, 15)
+ await run(client, 'follower', 'NEVER_REPLAY', 'unknown')
+ await run(client, 'safe', 'SAFE_QUEUE', 'safe')
+ assert rows()[runs['safe']] == 'queued'
+ assert rows()[runs['follower']] == 'queued'
+
+ async def restarted():
+ async with aiohttp.ClientSession(headers=headers, timeout=aiohttp.ClientTimeout(total=8)) as client:
+ async with asyncio.timeout(20):
+ while rows()[runs['safe']] != 'terminal':
+ await asyncio.sleep(.05)
+ assert rows()[runs['started']] == 'unknown' and rows()[runs['follower']] == 'queued', rows()
+ before = len(peer.requests)
+ await run(client, 'safe', 'SAFE_QUEUE', 'safe')
+ async with client.get(url + '/runs/' + runs['safe']) as response:
+ result = await response.json()
+ assert result['status'] == 'completed' and 'SAFE_QUEUE' in result['output'], result
+ assert len(peer.requests) == before
+ # A new identified chat submission executes once; retry after another SIGKILL
+ # must use retained results, independent of delivery format.
+ body = {'messages': [{'role': 'user', 'content': 'RESULT_ONCE'}]}
+ hs = {'X-Hermes-Session-Id': 'result', 'Idempotency-Key': 'result-once'}
+ async with client.post(url + '/chat/completions', json=body, headers=hs) as response:
+ reply = await response.json()
+ assert response.status == 200 and 'RESULT_ONCE' in reply['choices'][0]['message']['content'], reply
+ assert rows()['chat:result-once'] == 'terminal'
+
+ try:
+ with daemon(root, home, env, barrier=True, fixture='api_recovery_daemon.py') as (proc, desc):
+ pids.append(proc.pid); epochs.append(desc['authority_epoch'])
+ asyncio.run(first())
+ proc.kill(); proc.wait(timeout=10)
+ peer.release.set()
+ for _ in range(2):
+ with daemon(root, home, env, barrier=False) as (proc, desc):
+ pids.append(proc.pid); epochs.append(desc['authority_epoch'])
+ asyncio.run(restarted())
+ proc.kill(); proc.wait(timeout=10)
+ texts = [next((m.get('content', '') for m in reversed(req['messages']) if m['role'] == 'user'), '') for req in peer.requests]
+ assert sum('SAFE_QUEUE' in str(t) for t in texts) == 1, texts
+ assert sum('RESULT_ONCE' in str(t) for t in texts) == 1, texts
+ assert texts.count('BLOCK_STARTED') == 1 and not any('NEVER_REPLAY' in str(t) for t in texts), texts
+ assert epochs == sorted(set(epochs)) and len(set(pids)) == 3
+ print(json.dumps({'pids': pids, 'epochs': epochs, 'rows': rows(), 'inference_texts': texts}))
+ finally:
+ peer.release.set(); peer.shutdown(); peer.server_close()