Skip to content

The agent that grows with you

fix: recover native admissions after ordinary adapter startup

Teknium706596765107
diff --git a/gateway/run_runtime.py b/gateway/run_runtime.py
index 6030e28ec77..41d407d1209 100644
--- a/gateway/run_runtime.py
+++ b/gateway/run_runtime.py
@@ -44,6 +44,28 @@ async def start_gateway_runtime_api(runner):
await recover_bot_deliveries(runner.session_authority)
+async def recover_gateway_native_sessions(runner):
+ """Recover against the published routing index and currently connected adapters.
+
+ Stored envelopes are input, not authority to create a route or reconnect a
+ transport. The authority preflights every queued sender before any claim.
+ """
+ authority = getattr(runner, 'session_authority', None)
+ if authority is None:
+ return {}
+ pending = {row['target_session_id'] for row in authority.db._read_all(
+ "SELECT DISTINCT target_session_id FROM session_admissions WHERE status IN ('queued','unknown')")}
+ bindings = [(entry.session_id, entry.origin, runner._adapter_for_source(entry.origin))
+ for entry in runner.session_store.list_sessions()
+ if entry.session_id in pending and entry.origin is not None]
+ results = await authority.recover_native_sessions(bindings)
+ import logging
+ logger = logging.getLogger(__name__)
+ for sid, outcome in results.items():
+ logger.info('Native session startup recovery %s: %s', sid, outcome)
+ return results
+
+
def publish_gateway_runtime_ready(runner):
descriptor = runner.session_runtime_descriptor
if runner.session_api.task.done() or not runner._running or runner._draining:
diff --git a/gateway/run_startup.py b/gateway/run_startup.py
index c80b40616e6..fd08091a03d 100644
--- a/gateway/run_startup.py
+++ b/gateway/run_startup.py
@@ -517,6 +517,15 @@ class GatewayStartupMixin:
now = datetime.now()
scheduled = 0
for entry in candidates:
+ # Canonical admissions own restart decisions, including unknown pauses.
+ # Legacy synthetic resume must not race their restored FIFO.
+ authority = getattr(self, 'session_authority', None)
+ if authority is not None:
+ if authority.db._read_one(
+ 'SELECT 1 FROM session_admissions WHERE target_session_id=? LIMIT 1',
+ (entry.session_id,),
+ ):
+ continue
marker = entry.last_resume_marked_at or entry.updated_at
if marker is not None and (now - marker).total_seconds() > window:
continue
@@ -1255,6 +1264,8 @@ class GatewayStartupMixin:
# auto-resume stays visible on the next user message.
self._schedule_resume_pending_sessions()
await self._finish_startup_restore()
+ from gateway.run_runtime import recover_gateway_native_sessions
+ await recover_gateway_native_sessions(self)
# Surface state.db init failures to messaging platforms before the user loses data.
# See #88235.
await self._send_session_db_warning_notifications()
diff --git a/tests/gateway/fixtures/native_telegram_recovery_daemon.py b/tests/gateway/fixtures/native_telegram_recovery_daemon.py
new file mode 100644
index 00000000000..74a0903f7d9
--- /dev/null
+++ b/tests/gateway/fixtures/native_telegram_recovery_daemon.py
@@ -0,0 +1,18 @@
+"""First-owner-only scheduler barrier; every recovery boot is ordinary."""
+import runpy
+
+from gateway.session_authority import SessionAuthority
+from hermes_state_runtime import list_session_admissions
+
+schedule = SessionAuthority._schedule
+
+
+def hold_queued(self, ref):
+ pending = list_session_admissions(self.db, session_id=ref.session_id)
+ if any(row['payload'].get('text', '').startswith(('SAFE_', 'REVOKED_')) for row in pending):
+ return
+ return schedule(self, ref)
+
+
+SessionAuthority._schedule = hold_queued
+runpy.run_module('gateway.run', run_name='__main__')
diff --git a/tests/gateway/test_native_startup_recovery.py b/tests/gateway/test_native_startup_recovery.py
new file mode 100644
index 00000000000..b1f91b09117
--- /dev/null
+++ b/tests/gateway/test_native_startup_recovery.py
@@ -0,0 +1,93 @@
+"""Ordinary startup recovers native admissions without a recovery fixture call."""
+import asyncio
+from contextlib import closing
+from http.server import ThreadingHTTPServer
+import hashlib
+import hmac
+import json
+from pathlib import Path
+import socket
+import sqlite3
+import threading
+
+import aiohttp
+
+from tests.gateway.fixtures.local_recovery_probe import Model, child_env, daemon
+
+
+def test_native_queue_recovers_only_after_current_adapter_publication(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': {'multiplex_profiles': False},
+ 'platforms': {'webhook': {'enabled': True, 'extra': {'host': '127.0.0.1', 'port': port,
+ 'secret': 'owned-secret', 'routes': {'fixture': {'prompt': '{text}', 'deliver': 'log'}}}}},
+ 'auxiliary': {'title_generation': {'enabled': False}}, 'terminal': {'cwd': str(home)}}
+ config = home / 'config.yaml'
+ config.write_text(json.dumps(cfg))
+ env = child_env()
+ env.update(HOME=str(user), USERPROFILE=str(user), HERMES_HOME=str(home), PYTHONPATH=str(root),
+ OPENAI_API_KEY='loopback-only', OPENAI_BASE_URL=base, PYTHONUNBUFFERED='1')
+ def rows():
+ with closing(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 submit():
+ body = json.dumps({'text': 'SAFE_QUEUE'}).encode()
+ headers = {'X-GitHub-Delivery': 'safe', 'X-GitHub-Event': 'push',
+ 'X-Hub-Signature-256': 'sha256=' + hmac.new(b'owned-secret', body, hashlib.sha256).hexdigest()}
+ async with aiohttp.ClientSession() as client:
+ async with client.post(f'http://127.0.0.1:{port}/webhooks/fixture', data=body, headers=headers) as response:
+ assert response.status == 202, await response.text()
+ assert rows() == {'safe': 'queued'}
+ async def settled():
+ async with asyncio.timeout(25):
+ while rows()['safe'] != 'terminal':
+ await asyncio.sleep(.05)
+ evidence = []
+ try:
+ with daemon(root, home, env, barrier=True, fixture='api_recovery_daemon.py') as (proc, desc):
+ asyncio.run(submit())
+ evidence.append({'pid': proc.pid, 'epoch': desc['authority_epoch'], 'rows': rows()})
+ proc.kill()
+ proc.wait(timeout=10)
+ # No current transport: keep the durable row, do not spend its claim.
+ cfg['platforms']['webhook']['enabled'] = False
+ config.write_text(json.dumps(cfg))
+ with daemon(root, home, env, barrier=False) as (proc, desc):
+ assert rows() == {'safe': 'queued'} and not peer.requests
+ evidence.append({'pid': proc.pid, 'epoch': desc['authority_epoch'], 'rows': rows()})
+ cfg['platforms']['webhook']['enabled'] = True
+ config.write_text(json.dumps(cfg))
+ # Changed connector authority and an absent configured route both fail closed.
+ extra = cfg['platforms']['webhook']['extra']
+ for secret, routes in [('changed-secret', {'fixture': {'prompt': '{text}', 'deliver': 'log'}}),
+ ('owned-secret', {})]:
+ extra['secret'], extra['routes'] = secret, routes
+ config.write_text(json.dumps(cfg))
+ with daemon(root, home, env, barrier=False) as (proc, desc):
+ assert rows() == {'safe': 'queued'} and not peer.requests
+ evidence.append({'pid': proc.pid, 'epoch': desc['authority_epoch'], 'rows': rows()})
+ extra['routes'] = {'fixture': {'prompt': '{text}', 'deliver': 'log'}}
+ config.write_text(json.dumps(cfg))
+ for _ in range(2):
+ with daemon(root, home, env, barrier=False) as (proc, desc):
+ asyncio.run(settled())
+ assert peer.requests, '\n'.join(p.read_text() for p in (home / 'logs').glob('*.log')) + (home / 'restart.log').read_text()
+ evidence.append({'pid': proc.pid, 'epoch': desc['authority_epoch'], 'rows': rows()})
+ assert len(peer.requests) == 1, peer.requests
+ assert 'SAFE_QUEUE' in json.dumps(peer.requests)
+ print(json.dumps({'boots': evidence, 'inferences': len(peer.requests)}))
+ finally:
+ peer.release.set()
+ peer.shutdown()
+ peer.server_close()
diff --git a/tests/gateway/test_native_telegram_startup_recovery.py b/tests/gateway/test_native_telegram_startup_recovery.py
new file mode 100644
index 00000000000..80b81b833e9
--- /dev/null
+++ b/tests/gateway/test_native_telegram_startup_recovery.py
@@ -0,0 +1,161 @@
+"""Actual Telegram polling ingress, SIGKILL, and uninstrumented owner recovery."""
+from contextlib import closing
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+import json
+from pathlib import Path
+import queue
+import sqlite3
+import threading
+import time
+from urllib.parse import parse_qs
+
+import pytest
+
+from tests.gateway.fixtures.local_recovery_probe import Model, child_env, daemon
+
+
+class BotAPI(BaseHTTPRequestHandler):
+ def log_message(self, *args):
+ pass
+
+ def do_POST(self):
+ raw = self.rfile.read(int(self.headers.get('Content-Length', 0)))
+ body = json.loads(raw) if 'application/json' in self.headers.get('Content-Type', '') else {
+ k: values[0] for k, values in parse_qs(raw.decode()).items()
+ }
+ method = self.path.rsplit('/', 1)[-1]
+ self.server.calls.append(method)
+ if method == 'getUpdates':
+ try:
+ result = [self.server.updates.get(timeout=.2)]
+ except queue.Empty:
+ result = []
+ elif method == 'getMe':
+ result = {'id': 987654321, 'is_bot': True, 'first_name': 'Fixture', 'username': 'recovery_fixture_bot'}
+ elif method == 'getWebhookInfo':
+ result = {'url': '', 'pending_update_count': 0}
+ elif method in ('sendMessage', 'editMessageText'):
+ self.server.sent.append(body)
+ result = {'message_id': len(self.server.sent) + 1000, 'date': int(time.time()),
+ 'chat': {'id': int(body['chat_id']), 'type': 'private'}, 'text': body.get('text', '')}
+ else:
+ result = True
+ payload = json.dumps({'ok': True, 'result': result}).encode()
+ try:
+ self.send_response(200)
+ self.send_header('Content-Type', 'application/json')
+ self.send_header('Content-Length', str(len(payload)))
+ self.end_headers()
+ self.wfile.write(payload)
+ except (BrokenPipeError, ConnectionResetError):
+ pass
+
+
+def wait_for(predicate, detail, timeout=30):
+ deadline = time.monotonic() + timeout
+ while time.monotonic() < deadline:
+ if predicate():
+ return
+ time.sleep(.05)
+ pytest.fail(detail())
+
+
+def test_telegram_fifo_unknown_and_current_authorization_survive_sigkill(tmp_path):
+ root = Path(__file__).resolve().parents[2]
+ home, user = tmp_path / 'state', tmp_path / 'user'
+ home.mkdir(mode=0o700)
+ user.mkdir()
+ model = ThreadingHTTPServer(('127.0.0.1', 0), Model)
+ model.requests = []
+ model.blocked, model.release = threading.Event(), threading.Event()
+ bot = ThreadingHTTPServer(('127.0.0.1', 0), BotAPI)
+ bot.calls, bot.sent, bot.updates = [], [], queue.Queue()
+ for peer in (model, bot):
+ threading.Thread(target=peer.serve_forever, daemon=True).start()
+ base = f'http://127.0.0.1:{model.server_port}/v1'
+ cfg = {'model': {'provider': 'custom', 'default': 'local-wire-stub', 'base_url': base},
+ 'gateway': {'multiplex_profiles': False},
+ 'platforms': {'telegram': {'enabled': True, 'extra': {
+ 'base_url': f'http://127.0.0.1:{bot.server_port}/bot', 'dm_policy': 'allowlist'}}},
+ 'auxiliary': {'title_generation': {'enabled': False}},
+ 'platform_toolsets': {'telegram': []}, 'terminal': {'cwd': str(home)}}
+ (home / 'config.yaml').write_text(json.dumps(cfg))
+ env = child_env()
+ env.update(HOME=str(user), USERPROFILE=str(user), HERMES_HOME=str(home), PYTHONPATH=str(root),
+ OPENAI_API_KEY='loopback-only', OPENAI_BASE_URL=base, PYTHONUNBUFFERED='1',
+ TELEGRAM_BOT_TOKEN='987654321:owned-loopback-fixture', TELEGRAM_ALLOWED_USERS='101,202,303')
+
+ def rows():
+ with closing(sqlite3.connect(f'file:{home / "state.db"}?mode=ro', uri=True)) as db:
+ return {json.loads(payload)['text']: {'id': aid, 'request_id': rid, 'session': sid, 'status': status}
+ for aid, rid, sid, status, payload in db.execute(
+ 'SELECT admission_id,request_id,target_session_id,status,payload_json FROM session_admissions')}
+
+ def diagnostic():
+ return repr(rows()) + '\n' + '\n'.join(p.read_text() for p in (home / 'logs').glob('*.log'))
+
+ update_id = 0
+
+ def send(uid, text, status):
+ nonlocal update_id
+ update_id += 1
+ bot.updates.put({'update_id': update_id, 'message': {
+ 'message_id': update_id, 'date': int(time.time()),
+ 'chat': {'id': uid, 'type': 'private', 'first_name': 'Owned'},
+ 'from': {'id': uid, 'is_bot': False, 'first_name': 'Owned'}, 'text': text}})
+ wait_for(lambda: rows().get(text, {}).get('status') == status, diagnostic)
+
+ boots = []
+ try:
+ with daemon(root, home, env, barrier=True, fixture='native_telegram_recovery_daemon.py') as (proc, desc):
+ # Warm the started route so first-message onboarding cannot obscure the model barrier.
+ send(202, 'WARM_HISTORY', 'terminal')
+ send(202, 'BLOCK_STARTED', 'started')
+ assert model.blocked.wait(20), diagnostic()
+ send(202, 'NEVER_REPLAY', 'queued')
+ send(101, 'SAFE_FIRST', 'queued')
+ send(101, 'SAFE_SECOND', 'queued')
+ send(303, 'REVOKED_FIRST', 'queued')
+ send(303, 'REVOKED_SECOND', 'queued')
+ before = rows()
+ assert before['SAFE_FIRST']['session'] == before['SAFE_SECOND']['session']
+ assert before['BLOCK_STARTED']['session'] == before['NEVER_REPLAY']['session']
+ boots.append({'pid': proc.pid, 'epoch': desc['authority_epoch']})
+ proc.kill()
+ assert proc.wait(timeout=10) == -9
+ model.release.set()
+ env['TELEGRAM_ALLOWED_USERS'] = '101,202'
+ for _ in range(2):
+ with daemon(root, home, env, barrier=False) as (proc, desc):
+ wait_for(lambda: rows()['SAFE_SECOND']['status'] == 'terminal', diagnostic)
+ after = rows()
+ assert after['SAFE_FIRST']['status'] == 'terminal'
+ assert after['BLOCK_STARTED']['status'] == 'unknown'
+ assert after['NEVER_REPLAY']['status'] == 'queued'
+ assert after['REVOKED_FIRST'] == before['REVOKED_FIRST']
+ assert after['REVOKED_SECOND'] == before['REVOKED_SECOND']
+ for text in before:
+ assert after[text]['id'] == before[text]['id']
+ assert after[text]['session'] == before[text]['session']
+ boots.append({'pid': proc.pid, 'epoch': desc['authority_epoch']})
+ # Re-authorizing later proves refusal retained executable rows, not just tombstones.
+ env['TELEGRAM_ALLOWED_USERS'] = '101,202,303'
+ with daemon(root, home, env, barrier=False) as (proc, desc):
+ wait_for(lambda: rows()['REVOKED_SECOND']['status'] == 'terminal', diagnostic)
+ assert rows()['REVOKED_FIRST']['status'] == 'terminal'
+ assert rows()['NEVER_REPLAY']['status'] == 'queued'
+ boots.append({'pid': proc.pid, 'epoch': desc['authority_epoch']})
+ texts = [next(m['content'] for m in reversed(r['messages']) if m['role'] == 'user') for r in model.requests]
+ markers = ['WARM_HISTORY', 'BLOCK_STARTED', 'SAFE_FIRST', 'SAFE_SECOND', 'REVOKED_FIRST', 'REVOKED_SECOND']
+ observed = [next((marker for marker in markers if marker in text), text) for text in texts]
+ assert observed == markers, observed
+ assert len(set(b['pid'] for b in boots)) == len(boots)
+ assert all(b['epoch'] > a['epoch'] for a, b in zip(boots, boots[1:]))
+ assert 'getUpdates' in bot.calls and bot.sent
+ print(json.dumps({'boots': boots, 'model_inputs': observed, 'final_rows': rows()}))
+ finally:
+ model.release.set()
+ for peer in (model, bot):
+ peer.shutdown()
+ peer.server_close()
diff --git a/website/docs/developer-guide/gateway-internals.md b/website/docs/developer-guide/gateway-internals.md
index b1ceb035af4..a6e83728c8f 100644
--- a/website/docs/developer-guide/gateway-internals.md
+++ b/website/docs/developer-guide/gateway-internals.md
@@ -95,6 +95,22 @@ Text-only submissions keep the `{text}` payload and fingerprint. The ACP transpo
agent uses this for image, image resource-link and embedded-image prompt blocks;
Ink and Desktop still attach through the legacy `image.attach`/`file.attach` RPCs.
+## Native admission startup recovery
+
+Ordinary gateway startup recovers accepted native inputs after adapter connection,
+route publication, and the startup restore gate. Only never-started queued work is
+eligible. Recovery uses the current routing index and connected adapter, rechecks
+sender authorization and the retained connector/profile binding, and leaves rows
+queued when a route, transport, or authorization is unavailable. Restoring that
+configuration permits recovery on a later startup.
+
+An interrupted started admission becomes `unknown` and pauses its session's FIFO;
+its followers do not automatically run. Legacy synthetic restart turns are excluded
+from sessions with canonical admission history, so they cannot race the durable
+queue or bypass an unknown pause. Completed inputs are not reinferred on restart.
+This recovery does not enable multiplex profile authorities, which remain refused
+by the ordinary bootstrap.
+
## Shared authority local slash commands
Authenticated local sessions accept `slash.exec({session_id, command})` and