Skip to content

The agent that grows with you

fix(gateway): retire bot receipt tasks with authority

Brian Fernstromd50b2eda3d45
diff --git a/gateway/run_runtime.py b/gateway/run_runtime.py
index 3c7a7a3a843..55d59d7bd4e 100644
--- a/gateway/run_runtime.py
+++ b/gateway/run_runtime.py
@@ -157,6 +157,13 @@ def release_profile_home(runner, home):
process_ownership.release(home)
+def _authority_tasks(authority):
+ """Snapshot every async task family owned directly by one session authority."""
+ tasks = [live.task for live in authority.sessions.values() if live.task is not None]
+ tasks.extend(getattr(authority, '_bot_receipt_tasks', ()))
+ return list(dict.fromkeys(tasks))
+
+
async def _retire_profile_authority(authority):
"""Stop profile-local services/tasks before its ownership is released."""
from gateway.session_cron import unbind_owner
@@ -164,7 +171,7 @@ async def _retire_profile_authority(authority):
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]
+ tasks = _authority_tasks(authority)
for task in tasks:
task.cancel()
if tasks:
@@ -317,7 +324,6 @@ async def drain_gateway_runtime(runner):
async def settle_gateway_runtime(runner):
"""Keep authority tasks alive until their last durable settlement write."""
- tasks = [live.task for authority in _authorities(runner)
- for live in authority.sessions.values() if live.task is not None]
+ tasks = [task for authority in _authorities(runner) for task in _authority_tasks(authority)]
if tasks:
await asyncio.gather(*tasks, return_exceptions=True)
diff --git a/tests/gateway/test_run_runtime_hot_serve_cleanup.py b/tests/gateway/test_run_runtime_hot_serve_cleanup.py
index 7ebc102c5bf..1247ad03db0 100644
--- a/tests/gateway/test_run_runtime_hot_serve_cleanup.py
+++ b/tests/gateway/test_run_runtime_hot_serve_cleanup.py
@@ -1,4 +1,4 @@
-"""Failed hot-serve initialization must retire recovery work before ownership can be released."""
+"""Failed hot-serve initialization retires all authority task families before release."""
from __future__ import annotations
@@ -9,6 +9,9 @@ from types import SimpleNamespace
import pytest
from gateway import run_runtime
+from hermes_state import SessionDB
+from hermes_state_runtime import admit_session_input, begin_runtime_epoch
+from tools.bot_live_delivery import _locked, _write
class _Registry:
@@ -23,36 +26,67 @@ class _Registry:
@pytest.mark.asyncio
-async def test_failed_hot_serve_cancels_scheduled_authority_tasks(monkeypatch, tmp_path):
+async def test_failed_hot_serve_retires_session_and_bot_recovery_tasks(monkeypatch, tmp_path):
home = tmp_path.resolve()
registry = _Registry()
+ runner = SimpleNamespace(
+ session_authorities=registry,
+ session_control_server=object(),
+ )
+
+ db = SessionDB(home / "state.db")
+ db.create_session("s", source="gui")
+ epoch = begin_runtime_epoch(db, instance_id="hot-serve")
+ admission = admit_session_input(
+ db,
+ epoch=epoch,
+ principal_id="owner",
+ session_id="s",
+ request_id="bot:" + "a" * 32,
+ payload={"text": "queued bot delivery"},
+ )
+
live = SimpleNamespace(task=None)
authority = SimpleNamespace(
+ runner=runner,
+ db=db,
+ profile_id="default",
sessions={"s": live},
+ waiters={},
hosted_room_service=None,
)
- runner = SimpleNamespace(
- session_authorities=registry,
- session_control_server=object(),
- )
- started = asyncio.Event()
- released = asyncio.Event()
+
+ with _locked(home) as root:
+ _write(
+ root / f"{'a' * 32}.json",
+ {
+ "status": "canonical",
+ "admission_id": admission["admission_id"],
+ "delivery_id": "a" * 32,
+ "profile_home": str(home),
+ "session_id": "s",
+ "principal_id": "owner",
+ "message": "queued bot delivery",
+ },
+ )
+
+ pump_started = asyncio.Event()
+ pump_released = asyncio.Event()
+ watcher_seen = asyncio.Event()
+ watcher = None
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()
+ pump_started.set()
try:
await asyncio.Event().wait()
finally:
- released.set()
+ pump_released.set()
live.task = asyncio.create_task(background())
@@ -60,21 +94,63 @@ async def test_failed_hot_serve_cancels_scheduled_authority_tasks(monkeypatch, t
return None
async def fail_hosted(*args, **kwargs):
- await started.wait()
+ nonlocal watcher
+ await pump_started.wait()
+ tasks = getattr(authority, "_bot_receipt_tasks", set())
+ assert len(tasks) == 1
+ watcher = next(iter(tasks))
+ assert not watcher.done()
+ watcher_seen.set()
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]
+ 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))
+
+ try:
+ with pytest.raises(RuntimeError, match="late hot-serve failure"):
+ await run_runtime.serve_profile_runtime(runner, "cold", home)
+
+ assert watcher_seen.is_set()
+ assert registry.removed == [home]
+ assert live.task.done() and live.task.cancelled()
+ assert pump_released.is_set()
+ assert watcher is not None and watcher.done() and watcher.cancelled()
+ assert not getattr(authority, "_bot_receipt_tasks", set())
+ assert unbound == [authority]
+ finally:
+ db.close()
+
+async def test_settle_gateway_runtime_waits_for_bot_receipt_tasks():
+ release = asyncio.Event()
+ finished = asyncio.Event()
+
+ async def receipt_writer():
+ try:
+ await release.wait()
+ finally:
+ finished.set()
+
+ task = asyncio.create_task(receipt_writer())
+ authority = SimpleNamespace(sessions={}, _bot_receipt_tasks={task})
+ runner = SimpleNamespace(session_authority=authority)
+
+ settling = asyncio.create_task(run_runtime.settle_gateway_runtime(runner))
+ await asyncio.sleep(0)
+ assert not settling.done()
+
+ release.set()
+ await asyncio.wait_for(settling, 2)
+
+ assert task.done()
+ assert finished.is_set()