Skip to content

The agent that grows with you

fix(gateway): recover mixed local queues and retire failed hot serves

Brian Fernstromf4fd982b5692
diff --git a/gateway/run_runtime.py b/gateway/run_runtime.py
index 0d931d14d33..3c7a7a3a843 100644
--- a/gateway/run_runtime.py
+++ b/gateway/run_runtime.py
@@ -157,6 +157,21 @@ def release_profile_home(runner, home):
process_ownership.release(home)
+async def _retire_profile_authority(authority):
+ """Stop profile-local services/tasks before its ownership is released."""
+ from gateway.session_cron import unbind_owner
+
+ service = getattr(authority, 'hosted_room_service', None)
+ if service is not None:
+ await asyncio.to_thread(service.stop, timeout=5)
+ tasks = [live.task for live in authority.sessions.values() if live.task is not None]
+ for task in tasks:
+ task.cancel()
+ if tasks:
+ await asyncio.gather(*tasks, return_exceptions=True)
+ unbind_owner(authority)
+
+
async def serve_profile_runtime(runner, name, home):
"""Hot-serve one reserved profile's runtime: build its authority, recover its durable state and
publish it in the descriptor/ticket store — the steps boot performs per secondary. Raises when
@@ -180,6 +195,7 @@ async def serve_profile_runtime(runner, name, home):
await _ensure_hosted_service(runner, authority)
except BaseException:
registry.remove(home)
+ await _retire_profile_authority(authority)
raise
_publish_served_set(runner)
start_ready_hosted_services(runner)
@@ -189,21 +205,12 @@ async def serve_profile_runtime(runner, name, home):
async def unserve_profile_runtime(runner, home):
"""Retire one profile's authority (deleted while running) and shrink the published set.
No-op for a profile this process never served."""
- from gateway.session_cron import unbind_owner
home = Path(home).resolve()
registry = runner.session_authorities
authority = registry.remove(home) if home in registry else None
if authority is None:
return
- service = getattr(authority, 'hosted_room_service', None)
- if service is not None:
- await asyncio.to_thread(service.stop, timeout=5)
- tasks = [live.task for live in authority.sessions.values() if live.task is not None]
- for task in tasks:
- task.cancel()
- if tasks:
- await asyncio.gather(*tasks, return_exceptions=True)
- unbind_owner(authority)
+ await _retire_profile_authority(authority)
_publish_served_set(runner)
diff --git a/gateway/session_authority.py b/gateway/session_authority.py
index 37ef8938e1c..f66d55e1581 100644
--- a/gateway/session_authority.py
+++ b/gateway/session_authority.py
@@ -268,10 +268,18 @@ class SessionAuthority:
source, route = await check_native_route(self.runner, native[-1]['payload'], target,
available_source, adapter)
for row in rows:
- if row['status'] == 'queued':
- if 'native_text_v1' not in row['payload']:
- raise RuntimeStoreError('invalid_params')
+ if row['status'] != 'queued':
+ continue
+ if 'native_text_v1' in row['payload']:
await check_native_route(self.runner, row['payload'], target, available_source, adapter)
+ elif 'local_automation_v1' in row['payload']:
+ from gateway.session_automation import check_local_automation
+ check_local_automation(
+ self, SessionRef(self.profile_id, sid), row, route=route)
+ else:
+ from gateway.session_operator import check_local_input
+ check_local_input(
+ self, SessionRef(self.profile_id, sid), row, source=source)
self._require_admission_open()
self.sessions.setdefault(sid, LiveSession(source, route))
if any(row['status'] == 'unknown' for row in rows):
diff --git a/gateway/session_automation.py b/gateway/session_automation.py
index f13a32c87e8..536ada2e5ea 100644
--- a/gateway/session_automation.py
+++ b/gateway/session_automation.py
@@ -139,16 +139,17 @@ def snapshot_local_automation(authority, adapter, event, identity, entry):
return {'text': event.text, 'local_automation_v1': descriptor}, entry
-def check_local_automation(authority, ref, row):
- live = authority.sessions[ref.session_id]
+def check_local_automation(authority, ref, row, *, route=None):
+ live = authority.sessions.get(ref.session_id)
+ route = route or (live.route if live is not None else None)
payload = row['payload']
descriptor = payload['local_automation_v1']
- if (set(payload) != {'text', 'local_automation_v1'}
- or row['principal_id'] != 'automation:' + live.route
- or descriptor['owner'] != ref.session_id or descriptor['route'] != live.route
+ if (not route or set(payload) != {'text', 'local_automation_v1'}
+ or row['principal_id'] != 'automation:' + route
+ or descriptor['owner'] != ref.session_id or descriptor['route'] != route
or descriptor['identity'] != row['request_id']):
raise RuntimeStoreError('permission_denied')
- entry = authority.runner.session_store.lookup_by_session_key(live.route)
+ entry = authority.runner.session_store.lookup_by_session_key(route)
if (entry is None or entry.suspended or (entry.session_id != descriptor['target']
and authority.db.get_compression_tip(descriptor['target']) != entry.session_id)):
raise RuntimeStoreError('admission_conflict')
diff --git a/gateway/session_operator.py b/gateway/session_operator.py
index 890773008c7..b643e3be9ee 100644
--- a/gateway/session_operator.py
+++ b/gateway/session_operator.py
@@ -8,7 +8,7 @@ public submission parameters cannot supply it.
from hermes_state_runtime import RuntimeStoreError
-def check_local_input(authority, ref, row):
+def check_local_input(authority, ref, row, *, source=None):
payload = row['payload']
allowed = {'text', 'attachments_v1', 'finite', 'unattended', 'surface_v1'}
if 'local_operator_v1' in payload:
@@ -17,7 +17,9 @@ def check_local_input(authority, ref, row):
'profile_id': authority.profile_id, 'session_id': ref.session_id,
'principal_id': row['principal_id']}:
raise RuntimeStoreError('permission_denied')
- elif row['principal_id'] != authority.sessions[ref.session_id].source.user_id:
- raise RuntimeStoreError('permission_denied')
+ else:
+ source = source or authority.sessions[ref.session_id].source
+ if row['principal_id'] != source.user_id:
+ raise RuntimeStoreError('permission_denied')
if not {'text'} <= set(payload) <= allowed:
raise RuntimeStoreError('permission_denied')
diff --git a/tests/gateway/test_native_recovery_viewer_queue.py b/tests/gateway/test_native_recovery_viewer_queue.py
new file mode 100644
index 00000000000..1372bfc02ab
--- /dev/null
+++ b/tests/gateway/test_native_recovery_viewer_queue.py
@@ -0,0 +1,68 @@
+"""Native restart recovery accepts already-authorized local viewer work in the same FIFO."""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+import pytest
+
+from gateway.session_authority import SessionAuthority
+
+
+async def test_recovery_validates_queued_viewer_payload_instead_of_rejecting_it(monkeypatch):
+ from gateway.config import Platform
+ from gateway.platforms.event import SessionSource
+
+ sid = "native-session"
+ source = SessionSource(
+ platform=Platform.TELEGRAM, chat_id="chat", user_id="native-user", profile="default")
+ route = "telegram:default:chat"
+ native = {
+ "status": "terminal",
+ "payload": {"native_text_v1": {"source": {}, "route": route}},
+ "principal_id": "messaging:native",
+ "request_id": "native",
+ }
+ viewer = {
+ "status": "queued",
+ "payload": {
+ "text": "viewer follow-up",
+ "local_operator_v1": {
+ "profile_id": "default",
+ "session_id": sid,
+ "principal_id": "authenticated-viewer",
+ },
+ },
+ "principal_id": "authenticated-viewer",
+ "request_id": "viewer",
+ }
+
+ monkeypatch.setattr(
+ "gateway.session_authority.list_session_admissions",
+ lambda db, session_id, pending_only=False: [native, viewer],
+ )
+
+ async def check_native_route(runner, payload, target, available_source, adapter):
+ return source, route
+
+ monkeypatch.setattr("gateway.session_envelope.check_native_route", check_native_route)
+
+ scheduled = []
+ fake = SimpleNamespace(
+ db=object(),
+ profile_id="default",
+ runner=SimpleNamespace(session_store=SimpleNamespace()),
+ sessions={},
+ physical_target=lambda ref: "physical",
+ _require_admission_open=lambda: None,
+ _schedule=lambda ref: scheduled.append(ref.session_id),
+ )
+
+ result = await SessionAuthority.recover_native_sessions(
+ fake, [(sid, source, object())])
+
+ assert result == {sid: "ready"}
+ assert fake.sessions[sid].source is source
+ assert fake.sessions[sid].route == route
+ assert scheduled == [sid]
diff --git a/tests/gateway/test_run_runtime_hot_serve_cleanup.py b/tests/gateway/test_run_runtime_hot_serve_cleanup.py
new file mode 100644
index 00000000000..7ebc102c5bf
--- /dev/null
+++ b/tests/gateway/test_run_runtime_hot_serve_cleanup.py
@@ -0,0 +1,80 @@
+"""Failed hot-serve initialization must retire recovery work before ownership can be released."""
+
+from __future__ import annotations
+
+import asyncio
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+
+from gateway import run_runtime
+
+
+class _Registry:
+ def __init__(self):
+ self.removed = []
+
+ def for_home(self, home):
+ return None
+
+ def remove(self, home):
+ self.removed.append(Path(home).resolve())
+
+
+async def test_failed_hot_serve_cancels_scheduled_authority_tasks(monkeypatch, tmp_path):
+ home = tmp_path.resolve()
+ registry = _Registry()
+ live = SimpleNamespace(task=None)
+ authority = SimpleNamespace(
+ sessions={"s": live},
+ hosted_room_service=None,
+ )
+ runner = SimpleNamespace(
+ session_authorities=registry,
+ session_control_server=object(),
+ )
+ started = asyncio.Event()
+ released = asyncio.Event()
+
+ async def build(*args, **kwargs):
+ return authority
+
+ async def recover_bot(_authority):
+ return None
+
+ def recover_local(_authority, schedule):
+ assert schedule is True
+
+ async def background():
+ started.set()
+ try:
+ await asyncio.Event().wait()
+ finally:
+ released.set()
+
+ live.task = asyncio.create_task(background())
+
+ async def recover_webhook(_authority):
+ return None
+
+ async def fail_hosted(*args, **kwargs):
+ await started.wait()
+ raise RuntimeError("late hot-serve failure")
+
+ unbound = []
+ monkeypatch.setattr(run_runtime, "_build_profile_authority", build)
+ monkeypatch.setattr("gateway.session_bot.recover_bot_deliveries", recover_bot)
+ monkeypatch.setattr("gateway.session_local_recovery.recover_local_sessions", recover_local)
+ monkeypatch.setattr("gateway.platforms.webhook_ingress.recover_webhook_finalizations", recover_webhook)
+ monkeypatch.setattr("gateway.session_hosted_service._ensure_hosted_service", fail_hosted)
+ monkeypatch.setattr("gateway.session_cron.unbind_owner", lambda value: unbound.append(value))
+
+ with pytest.raises(RuntimeError, match="late hot-serve failure"):
+ await run_runtime.serve_profile_runtime(runner, "cold", home)
+
+ assert registry.removed == [home]
+ assert live.task.done() and live.task.cancelled()
+ assert released.is_set()
+ assert unbound == [authority]