fix(gateway): deliver kanban/delegate wake-ups to api_server sessions

Wake-ups for kanban notifications and background delegation completions were
injected via handle_message() using a build_session_key()-derived key, which
can never match the raw X-Hermes-Session-Id key that api_server sessions run
under — so the wake landed in a session nobody was reading. On top of that,
ApiServerAdapter.send() reports failure without raising, and that was treated
as a successful delivery, so the notify cursor advanced past events that were
permanently lost; and background delegation was forced synchronous on
api_server since there was no way to wake the session afterward.

Fix: route wake-ups for non-push adapters through a self-post to
/v1/chat/completions with the original session id, treat non-raising send
failures as failures (rewind instead of advancing the cursor), and re-enable
background delegation whenever a session id is available to wake.

The origin session id is captured from the request-scoped api_server chat_id
binding rather than HERMES_SESSION_ID: constructing a child agent calls
set_current_session_id() with the subagent's internal id, clobbering that
variable right before dispatch would read it and misrouting the wake into
the subagent's own session.

Related: #56580, #64609, #53027, #63169, #56531, #50319, #64113
This commit is contained in:
Ian Ker-Seymer 2026-07-15 09:25:08 -04:00 • committed by Teknium
parent 185b08a2eb
commit 246eacea7b
10 changed files with 979 additions and 7 deletions

View file

@ -621,3 +621,72 @@ def test_parse_session_key_too_short():
def test_parse_session_key_wrong_prefix():
assert _parse_session_key("cron:main:telegram:dm:123") is None
assert _parse_session_key("agent:cron:telegram:dm:123") is None
# ---------------------------------------------------------------------------
# api_server (stateless) wake routing — gateway/wake.py self-post path
# ---------------------------------------------------------------------------
@pytest.mark.asyncio
async def test_inject_watch_notification_raw_session_key_self_posts(monkeypatch, tmp_path):
"""An event whose session_key is a RAW api_server session id (not an
agent:main:... structured key) must wake the real session via the
/v1/chat/completions self-post instead of being dropped for missing
routing metadata."""
runner = _build_runner(monkeypatch, tmp_path, "all")
api_adapter = SimpleNamespace(
supports_async_delivery=False,
handle_message=AsyncMock(),
_host="127.0.0.1", _port=8642, _api_key="k", _model_name="m",
)
runner.adapters[Platform.API_SERVER] = api_adapter
posts = []
async def fake_self_post(adapter, *, text, session_id):
posts.append({"text": text, "session_id": session_id})
import gateway.wake as wake_mod
monkeypatch.setattr(wake_mod, "_self_post_chat_completion", fake_self_post)
evt = {
"session_id": "proc_watch",
"session_key": "raw-hq-session-id", # no agent:main:... structure
}
result = await runner._inject_watch_notification("[SYSTEM: subagent finished]", evt)
assert result is True
api_adapter.handle_message.assert_not_awaited()
assert posts == [
{"text": "[SYSTEM: subagent finished]", "session_id": "raw-hq-session-id"}
]
@pytest.mark.asyncio
async def test_inject_watch_notification_origin_session_id_wins(monkeypatch, tmp_path):
"""origin_session_id (stamped at dispatch time by async_delegation) takes
precedence as the wake target."""
runner = _build_runner(monkeypatch, tmp_path, "all")
api_adapter = SimpleNamespace(
supports_async_delivery=False,
handle_message=AsyncMock(),
_host="127.0.0.1", _port=8642, _api_key="k", _model_name="m",
)
runner.adapters[Platform.API_SERVER] = api_adapter
posts = []
async def fake_self_post(adapter, *, text, session_id):
posts.append(session_id)
import gateway.wake as wake_mod
monkeypatch.setattr(wake_mod, "_self_post_chat_completion", fake_self_post)
evt = {
"session_id": "proc_watch",
"session_key": "",
"origin_session_id": "raw-origin-sid",
}
result = await runner._inject_watch_notification("[SYSTEM: done]", evt)
assert result is True
assert posts == ["raw-origin-sid"]

View file

@ -0,0 +1,154 @@
"""Kanban notifier behavior on stateless (api_server) subscriptions.
Covers the wrong-session-wake / silent-loss fixes:
* a SendResult(success=False) return (the API server's send() stub) rewinds
the cursor instead of advancing past a never-delivered event;
* api_server subscriptions wake the creator's REAL session via the
/v1/chat/completions self-post (raw task.session_id), never via
handle_message (which would run under a build_session_key()-derived key
that never matches the raw X-Hermes-Session-Id session real turns use).
"""
import asyncio
from gateway.config import Platform
from gateway.platforms.base import SendResult
from gateway.run import GatewayRunner
from hermes_cli import kanban_db as kb
class SoftFailAdapter:
"""Push-capable adapter whose send() returns SendResult(success=False)
WITHOUT raising — previously treated as delivered (event lost)."""
def __init__(self):
self.attempts = 0
async def send(self, chat_id, text, metadata=None):
self.attempts += 1
return SendResult(success=False, error="soft failure")
class ApiServerLikeAdapter:
supports_async_delivery = False
def __init__(self):
self._host = "127.0.0.1"
self._port = 8642
self._api_key = "k"
self._model_name = "hermes"
self.handle_message_calls = []
self.send_calls = 0
async def send(self, chat_id, text, metadata=None):
self.send_calls += 1
return SendResult(
success=False,
error="API server uses HTTP request/response, not send()",
)
async def handle_message(self, event):
self.handle_message_calls.append(event)
async def _run_one_notifier_tick(monkeypatch, runner):
real_sleep = asyncio.sleep
async def fake_sleep(delay):
if delay == 5:
return None
runner._running = False
await real_sleep(0)
monkeypatch.setattr(asyncio, "sleep", fake_sleep)
await runner._kanban_notifier_watcher(interval=1)
def _make_runner(adapters):
runner = GatewayRunner.__new__(GatewayRunner)
runner._running = True
runner.adapters = adapters
runner._kanban_sub_fail_counts = {}
return runner
def _create_completed_subscription(platform, chat_id, session_id=None):
conn = kb.connect()
try:
tid = kb.create_task(
conn, title="notify once", assignee="worker", session_id=session_id,
)
kb.add_notify_sub(conn, task_id=tid, platform=platform, chat_id=chat_id)
kb.complete_task(conn, tid, summary="done once")
return tid
finally:
conn.close()
def _unseen_terminal_events(tid, platform, chat_id):
conn = kb.connect()
try:
_, events = kb.unseen_events_for_sub(
conn,
task_id=tid,
platform=platform,
chat_id=chat_id,
kinds=["completed", "blocked", "gave_up", "crashed", "timed_out"],
)
return events
finally:
conn.close()
def test_sendresult_failure_rewinds_cursor(tmp_path, monkeypatch):
"""SendResult(success=False) without an exception must count as a failed
delivery — cursor rewound, event retried on the next tick. Previously the
cursor advanced and the event was permanently lost."""
monkeypatch.setenv("HERMES_KANBAN_DB", str(tmp_path / "softfail.db"))
kb.init_db()
tid = _create_completed_subscription("telegram", "chat-1")
adapter = SoftFailAdapter()
runner = _make_runner({Platform.TELEGRAM: adapter})
asyncio.run(_run_one_notifier_tick(monkeypatch, runner))
assert adapter.attempts >= 1
assert [ev.kind for ev in _unseen_terminal_events(tid, "telegram", "chat-1")] == [
"completed"
]
def test_apiserver_sub_wakes_real_session_via_self_post(tmp_path, monkeypatch):
"""An api_server subscription wakes the creator's REAL session by
self-posting with the task's raw session_id — never handle_message (which
would run the wake under a build_session_key()-derived key that can't
match the raw X-Hermes-Session-Id session)."""
monkeypatch.setenv("HERMES_KANBAN_DB", str(tmp_path / "apiserver.db"))
kb.init_db()
tid = _create_completed_subscription(
"api_server", "raw-sid-123", session_id="raw-sid-123",
)
posts = []
async def fake_self_post(adapter, *, text, session_id):
posts.append({"text": text, "session_id": session_id})
import gateway.wake as wake_mod
monkeypatch.setattr(wake_mod, "_self_post_chat_completion", fake_self_post)
adapter = ApiServerLikeAdapter()
runner = _make_runner({Platform.API_SERVER: adapter})
asyncio.run(_run_one_notifier_tick(monkeypatch, runner))
assert adapter.handle_message_calls == [], (
"api_server wake must not go through handle_message (wrong-session bug)"
)
assert len(posts) == 1
assert posts[0]["session_id"] == "raw-sid-123"
assert tid in posts[0]["text"]
# The wake self-post IS the delivery on this path (no separate text-ping
# fallback is attempted for stateless api_server subs) — cursor advances
# once the wake succeeds.
assert _unseen_terminal_events(tid, "api_server", "raw-sid-123") == []

View file

@ -0,0 +1,188 @@
"""Tests for gateway/wake.py — background wake delivery.
Two strategies:
* push-capable adapters keep the synthetic MessageEvent / handle_message path;
* the stateless API server (supports_async_delivery=False) self-POSTs
/v1/chat/completions with the RAW session id in X-Hermes-Session-Id, so the
wake turn resumes the REAL session instead of a parallel invisible one
keyed by build_session_key().
"""
import asyncio
import pytest
from gateway.config import Platform
from gateway.session import SessionSource
from gateway.wake import deliver_wake, adapter_supports_push
class PushAdapter:
"""Default adapter shape — no supports_async_delivery attribute."""
def __init__(self):
self.handled = []
async def handle_message(self, event):
self.handled.append(event)
class ApiServerLikeAdapter:
supports_async_delivery = False
def __init__(self, host="0.0.0.0", port=0, key="test-key", model="hermes"):
self._host = host
self._port = port
self._api_key = key
self._model_name = model
async def handle_message(self, event): # pragma: no cover — must NOT be hit
raise AssertionError("non-push adapter must not receive handle_message wakes")
def _source():
return SessionSource(
platform=Platform.TELEGRAM,
chat_id="chat-1",
chat_type="group",
)
def test_adapter_supports_push_default_true():
assert adapter_supports_push(PushAdapter()) is True
assert adapter_supports_push(ApiServerLikeAdapter()) is False
def test_deliver_wake_push_adapter_uses_handle_message():
adapter = PushAdapter()
asyncio.run(deliver_wake(adapter, text="wake up", source=_source()))
assert len(adapter.handled) == 1
evt = adapter.handled[0]
assert evt.text == "wake up"
assert evt.internal is True
assert evt.source.chat_id == "chat-1"
def test_deliver_wake_push_adapter_requires_source():
with pytest.raises(ValueError):
asyncio.run(deliver_wake(PushAdapter(), text="x", session_id="sid"))
def test_deliver_wake_non_push_requires_session_id():
with pytest.raises(ValueError):
asyncio.run(deliver_wake(ApiServerLikeAdapter(), text="x", source=_source()))
def test_deliver_wake_non_push_requires_api_key():
"""Session continuation is 403-gated on API_SERVER_KEY — a missing key
must fail loudly instead of running the wake in a fresh session."""
adapter = ApiServerLikeAdapter(key="")
with pytest.raises(RuntimeError, match="API_SERVER_KEY"):
asyncio.run(deliver_wake(adapter, text="x", session_id="raw-sid"))
async def _serve(handler):
"""Spin an in-process aiohttp server on an ephemeral loopback port."""
from aiohttp import web
app = web.Application()
app.router.add_post("/v1/chat/completions", handler)
runner = web.AppRunner(app)
await runner.setup()
site = web.TCPSite(runner, "127.0.0.1", 0)
await site.start()
port = site._server.sockets[0].getsockname()[1]
return runner, port
def test_deliver_wake_non_push_self_posts_raw_session_id(monkeypatch):
"""The self-post carries the RAW session id header + bearer auth and a
single user message with stream=false — the exact entry point real
gateway turns use."""
from aiohttp import web
seen = {}
async def handler(request):
seen["session_id"] = request.headers.get("X-Hermes-Session-Id")
seen["auth"] = request.headers.get("Authorization")
seen["body"] = await request.json()
return web.json_response({"choices": [{"message": {"content": "ok"}}]})
async def run():
runner, port = await _serve(handler)
try:
adapter = ApiServerLikeAdapter(host="0.0.0.0", port=port, key="sekrit")
await deliver_wake(adapter, text="task done — wake", session_id="raw-sid-42")
finally:
await runner.cleanup()
asyncio.run(run())
assert seen["session_id"] == "raw-sid-42"
assert seen["auth"] == "Bearer sekrit"
assert seen["body"]["stream"] is False
assert seen["body"]["messages"] == [
{"role": "user", "content": "task done — wake"}
]
def test_deliver_wake_retries_429_then_succeeds(monkeypatch):
"""HTTP 429 (max_concurrent_runs cap) is transient — retried with backoff."""
from aiohttp import web
import gateway.wake as wake_mod
monkeypatch.setattr(wake_mod, "_RETRY_DELAYS_SECONDS", (0.01, 0.01, 0.01))
calls = {"n": 0}
async def handler(request):
calls["n"] += 1
if calls["n"] == 1:
return web.json_response({"error": "busy"}, status=429)
return web.json_response({"choices": []})
async def run():
runner, port = await _serve(handler)
try:
adapter = ApiServerLikeAdapter(port=port)
await deliver_wake(adapter, text="x", session_id="sid")
finally:
await runner.cleanup()
asyncio.run(run())
assert calls["n"] == 2
def test_deliver_wake_raises_on_permanent_http_error(monkeypatch):
"""Auth/validation errors (403/400) are permanent — raise immediately so
the caller can rewind instead of treating the event as delivered."""
from aiohttp import web
calls = {"n": 0}
async def handler(request):
calls["n"] += 1
return web.json_response({"error": "forbidden"}, status=403)
async def run():
runner, port = await _serve(handler)
try:
adapter = ApiServerLikeAdapter(port=port)
with pytest.raises(RuntimeError, match="HTTP 403"):
await deliver_wake(adapter, text="x", session_id="sid")
finally:
await runner.cleanup()
asyncio.run(run())
assert calls["n"] == 1
def test_deliver_wake_raises_after_exhausted_retries(monkeypatch):
"""Connection failures raise after bounded retries — never silent."""
import gateway.wake as wake_mod
monkeypatch.setattr(wake_mod, "_RETRY_DELAYS_SECONDS", (0.01,))
# Nothing is listening on this port.
adapter = ApiServerLikeAdapter(host="127.0.0.1", port=1, key="k")
with pytest.raises(RuntimeError, match="gave up"):
asyncio.run(deliver_wake(adapter, text="x", session_id="sid"))

View file

@ -0,0 +1,190 @@
"""delegate_task(background=true) on stateless API-server sessions.
Previously async_delivery_supported()=False forced SYNCHRONOUS execution for
every background dispatch on the API server, blocking the whole turn. Now
that background completions can wake the originating session via the
/v1/chat/completions self-post (gateway/wake.py), a session-continuable
turn (raw session id bound as the api_server chat_id) dispatches async; only
session-id-less one-shot requests keep the sync fallback.
The wake target must be captured from the request-scoped chat_id binding,
NOT from HERMES_SESSION_ID: constructing a child agent calls
set_current_session_id(child.session_id), clobbering the HERMES_SESSION_ID
ContextVar and os.environ with the subagent's internal id before the
dispatch code reads it — the fake child build below reproduces that clobber.
"""
import json
import time
from unittest.mock import MagicMock
import pytest
from gateway.session_context import set_session_vars
from tools.process_registry import process_registry
@pytest.fixture(autouse=True)
def _clean_queue_and_context(monkeypatch):
monkeypatch.delenv("HERMES_SESSION_ID", raising=False)
while not process_registry.completion_queue.empty():
try:
process_registry.completion_queue.get_nowait()
except Exception:
break
yield
# Restore ContextVars to the pristine "never set" sentinel rather than
# clear_session_vars()'s explicit-"" state, which would mask env vars for
# unrelated tests running later in the same worker.
import gateway.session_context as sc
for var in sc._VAR_MAP.values():
var.set(sc._UNSET)
sc._SESSION_ASYNC_DELIVERY.set(sc._UNSET)
# set_current_session_id (invoked by the clobber-reproducing fake child
# build) writes os.environ directly — scrub it so it can't leak into
# other test modules.
import os
os.environ.pop("HERMES_SESSION_ID", None)
while not process_registry.completion_queue.empty():
try:
process_registry.completion_queue.get_nowait()
except Exception:
break
def _drain_one(timeout=5.0):
deadline = time.time() + timeout
while time.time() < deadline:
if not process_registry.completion_queue.empty():
return process_registry.completion_queue.get_nowait()
time.sleep(0.02)
return None
def _fake_parent():
parent = MagicMock()
parent._delegate_depth = 0
parent.session_id = "sess"
parent._interrupt_requested = False
parent._active_children = []
parent._active_children_lock = None
return parent
def _patch_delegate(monkeypatch):
import tools.delegate_tool as dt
fake_child = MagicMock()
fake_child._delegate_role = "leaf"
fake_child._subagent_id = "s1"
def fast_child(task_index, goal, child=None, parent_agent=None, **kw):
return {
"task_index": 0, "status": "completed", "summary": f"done: {goal}",
"api_calls": 1, "duration_seconds": 0.1, "model": "m",
"exit_reason": "completed",
}
creds = {
"model": "m", "provider": None, "base_url": None, "api_key": None,
"api_mode": None, "command": None, "args": None,
}
def clobbering_build_child(**kw):
# Reproduce what the real _build_child_agent -> AIAgent -> agent_init
# path does: it synchronizes the child's internal session id into the
# HERMES_SESSION_ID ContextVar + os.environ, clobbering the spawner's
# id ~milliseconds before delegate_tool dispatches the batch.
from gateway.session_context import set_current_session_id
set_current_session_id("20260715_child1")
return fake_child
monkeypatch.setattr(dt, "_build_child_agent", clobbering_build_child)
monkeypatch.setattr(dt, "_run_single_child", fast_child)
monkeypatch.setattr(dt, "_resolve_delegation_credentials", lambda *a, **k: creds)
return dt
def test_apiserver_session_with_id_dispatches_background(monkeypatch):
"""async_delivery=False + a raw session id (HERMES_SESSION_ID) →
background dispatch (the completion wakes the session via the
api_server self-post), NOT the forced-sync fallback."""
dt = _patch_delegate(monkeypatch)
monkeypatch.setenv("HERMES_SESSION_ID", "raw-sid-7")
set_session_vars(
platform="api_server",
chat_id="raw-sid-7",
session_key="raw-sid-7",
session_id="raw-sid-7",
async_delivery=False,
)
out = dt.delegate_task(
goal="bg on api_server", context="ctx",
background=True, parent_agent=_fake_parent(),
)
parsed = json.loads(out)
assert parsed["status"] == "dispatched", parsed
assert parsed["mode"] == "background"
evt = _drain_one()
assert evt is not None
assert evt["type"] == "async_delegation"
# The raw session id is stamped so the gateway drain can self-post the
# wake to the REAL session (session_key alone is the raw id here, which
# carries no parseable routing metadata). Crucially this is the SPAWNER's
# id, not the subagent-internal id the child build clobbered
# HERMES_SESSION_ID with (see clobbering_build_child).
assert evt["origin_session_id"] == "raw-sid-7"
# ---------------------------------------------------------------------------
# _current_origin_session_id — the clobber-proof origin capture helper
# ---------------------------------------------------------------------------
def test_origin_helper_survives_child_session_clobber(monkeypatch):
"""set_current_session_id (child agent construction) rewrites the
HERMES_SESSION_ID ContextVar + env, but the request-scoped chat_id
binding is untouched — the helper must keep returning the spawner's id."""
from gateway.session_context import set_current_session_id
from tools.async_delegation import _current_origin_session_id
set_session_vars(platform="api_server", chat_id="raw-origin-1")
assert _current_origin_session_id() == "raw-origin-1"
set_current_session_id("20260715_child2") # the clobber
assert _current_origin_session_id() == "raw-origin-1"
def test_origin_helper_empty_on_push_platforms(monkeypatch):
"""On push platforms chat_id identifies a chat, not a session — the
helper must yield empty rather than misroute a wake there."""
from tools.async_delegation import _current_origin_session_id
set_session_vars(platform="telegram", chat_id="123456789")
assert _current_origin_session_id() == ""
def test_apiserver_session_without_id_stays_synchronous(monkeypatch):
"""No session id to wake → keep the sync fallback (a detached result
would never re-enter any conversation)."""
dt = _patch_delegate(monkeypatch)
set_session_vars(
platform="api_server",
chat_id="",
session_key="",
session_id="",
async_delivery=False,
)
out = dt.delegate_task(
goal="one-shot", context="ctx",
background=True, parent_agent=_fake_parent(),
)
parsed = json.loads(out)
assert parsed.get("status") != "dispatched", parsed
assert "SYNCHRONOUSLY" in parsed.get("note", "")
assert process_registry.completion_queue.empty()