The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: fence webhook finalization by admitted session and generation
Tekniumca2211f0d845
diff --git a/gateway/platforms/webhook.py b/gateway/platforms/webhook.pyindex acf14632963..0c31e1be8d7 100644--- a/gateway/platforms/webhook.py+++ b/gateway/platforms/webhook.py@@ -105,17 +105,6 @@ def _json_error(message: str, status: int) -> "web.Response":return web.json_response({"error": message}, status=status)-def _peek_session_id(store, session_key: str):- """Prefer the store's lock-held accessor; the private-path fallback is for older stores / test doubles."""- if callable(peek := getattr(store, "peek_session_id", None)):- return peek(session_key)- if hasattr(store, "_ensure_loaded"):- with suppress(Exception):- store._ensure_loaded()- entry = (getattr(store, "_entries", {}) or {}).get(session_key)- return getattr(entry, "session_id", None) if entry else None--def check_webhook_requirements() -> bool:"""Check if webhook adapter dependencies are available."""return AIOHTTP_AVAILABLE@@ -588,40 +577,37 @@ class WebhookAdapter(BasePlatformAdapter):len(prompt), delivery_id)from gateway.platforms.webhook_ingress import admit_producertry:- await admit_producer(self, event)+ receipt = await admit_producer(self, event)except Exception:logger.exception("[webhook] Durable admission failed for %s", delivery_id)return _json_error("Admission unavailable; retry this delivery", 503)+ authority = self._message_handler.__self__.session_authority+ task = asyncio.create_task(self._finalize_delivery(event, authority, receipt))+ self._background_tasks.add(task)+ task.add_done_callback(self._background_tasks.discard)return web.json_response({"status": "accepted", "route": route_name, "event": event_type,"delivery_id": delivery_id}, status=202)- async def on_processing_complete(self, event: "MessageEvent", outcome: Any) -> None:- """Close the one-shot per-delivery session: ``prune_sessions`` only reaps rows with ``ended_at`` set, so- unclosed webhook sessions leak unbounded. Fires at the true end of the run; ``end_session()`` is- first-reason-wins."""- await self._end_webhook_session(event, event.source.chat_id)+ async def _finalize_delivery(self, event, authority, receipt):+ from hermes_state_runtime import get_session_admission+ try:+ row = get_session_admission(authority.db, admission_id=receipt.admission_id)+ if row['status'] in {'queued', 'started'}:+ waiter = authority.waiters.setdefault(receipt.admission_id,+ asyncio.get_running_loop().create_future())+ await asyncio.shield(waiter)+ row = get_session_admission(authority.db, admission_id=receipt.admission_id)+ event._webhook_receipt = (authority, authority._receipt(row))+ await self._end_webhook_session(event, event.source.chat_id)+ except Exception:+ logger.exception("[webhook] Could not finalize admitted delivery %s", receipt.admission_id)async def _end_webhook_session(self, event: "MessageEvent", session_chat_id: str) -> None:- """Mark the per-delivery session ended via ``SessionDB.end_session`` (never a hand-written UPDATE),- resolving session_id from the SAME source the run was keyed on."""- runner = self.gateway_runner- session_db, store = getattr(runner, "_session_db", None), getattr(runner, "session_store", None)- key_fn = getattr(runner, "_session_key_for_source", None)- if runner is None or session_db is None or store is None or key_fn is None:- return- try:- session_key = key_fn(event.source)- session_id = _peek_session_id(store, session_key)- if not session_id:- logger.debug("[webhook] No session_id to close for %s (key=%s)", session_chat_id, session_key)- return- # AsyncSessionDB forwards end_session via to_thread; plain SessionDB is sync.- result = session_db.end_session(session_id, "webhook_complete")- if asyncio.iscoroutine(result):- await result- logger.debug("[webhook] Closed session %s for delivery %s", session_id, session_chat_id)- except Exception as e:- logger.debug("[webhook] Failed to close session for %s: %s", session_chat_id, e)+ from gateway.platforms.webhook_ingress import finalize_webhook+ binding = getattr(event, '_webhook_receipt', None)+ if binding is not None:+ authority, receipt = binding+ finalize_webhook(authority, receipt)# --- Signature validation ---diff --git a/gateway/platforms/webhook_ingress.py b/gateway/platforms/webhook_ingress.pyindex 3b70925df0e..9e98b8fa1ac 100644--- a/gateway/platforms/webhook_ingress.py+++ b/gateway/platforms/webhook_ingress.py@@ -31,4 +31,49 @@ async def producer_scope(adapter, event):async def admit_producer(adapter, event):async with producer_scope(adapter, event) as authority:+ from gateway.config import Platform+ if adapter.platform == Platform.WEBHOOK:+ prior = await _webhook_retry(authority, event)+ if prior is not None:+ return priorreturn await authority.admit_native(event)+++async def _webhook_retry(authority, event):+ # One-shot finalization ends the route. Resolve an existing provider receipt+ # before SessionStore would rotate it into a new physical session.+ import json+ from gateway.session_envelope import prepare_native, restore_native+ from hermes_state_runtime import get_session_admission+ payload = await prepare_native(authority.runner, event)+ source = restore_native(payload).source+ identity = json.dumps([source.profile, source.platform.value, source.chat_id,+ source.thread_id, source.user_id], separators=(',', ':'))+ rows = authority.db._read_all('SELECT admission_id FROM session_admissions '+ 'WHERE principal_id=? AND request_id=?', ('messaging:' + identity, event.message_id))+ if not rows:+ return None+ row = get_session_admission(authority.db, admission_id=rows[0]['admission_id'])+ if len(rows) != 1 or row['payload'] != payload:+ raise RuntimeStoreError('admission_conflict')+ return authority._receipt(row)+++def finalize_webhook(authority, receipt):+ """End only the settled admitted generation, atomically with the epoch fence."""+ import time+ if receipt.status != 'terminal' or receipt.execution_generation is None:+ return False+ sid = receipt.ref.session_id+ def write(conn):+ return authority.db._end_and_bump(conn, """+ UPDATE sessions SET ended_at=?, end_reason=?+ WHERE id=? AND ended_at IS NULL AND runtime_generation=?+ AND EXISTS (SELECT 1 FROM runtime_epoch WHERE singleton=1 AND epoch=?)+ AND EXISTS (SELECT 1 FROM session_admissions WHERE admission_id=?+ AND target_session_id=? AND status='terminal' AND generation=? AND owner_epoch=?)+ AND NOT EXISTS (SELECT 1 FROM session_admissions WHERE target_session_id=? AND status!='terminal')+ """, (time.time(), 'webhook_complete', sid, receipt.execution_generation,+ receipt.authority_epoch, receipt.admission_id, sid, receipt.execution_generation,+ receipt.authority_epoch, sid), sid, 'webhook_complete')+ return bool(authority.db._execute_write(write))diff --git a/tests/gateway/test_webhook_authority.py b/tests/gateway/test_webhook_authority.pyindex 31d34762a7e..a135b1dee28 100644--- a/tests/gateway/test_webhook_authority.py+++ b/tests/gateway/test_webhook_authority.py@@ -66,6 +66,10 @@ async def probe(peer):duplicate = await client.post(url, data=body, headers=headers)assert duplicate.status in (200, 202), await duplicate.text()assert len(rows()) == 1 and len(peer.requests) == 1+ async with asyncio.timeout(5):+ while adapter._background_tasks:+ await asyncio.sleep(.01)+ assert authority.db.get_session(rows()[0]['target_session_id'])['ended_at'] is not NonePath(os.environ['HERMES_HOME'], 'webhook-receipt.json').write_text(json.dumps({'failed_status': failed.status, 'retry_status': accepted.status,'admissions': len(rows()), 'inferences': len(peer.requests), 'signature_denied': denied.status}))diff --git a/tests/gateway/test_webhook_session_close.py b/tests/gateway/test_webhook_session_close.pyindex 9901a1bb749..a8692faed50 100644--- a/tests/gateway/test_webhook_session_close.py+++ b/tests/gateway/test_webhook_session_close.py@@ -1,153 +1,48 @@-"""Invariant test: a completed webhook delivery closes its session.--Regression guard for the ghost-session leak. Webhook deliveries create a-unique one-shot session (``delivery_id`` baked into the session key), but the-adapter historically fired ``handle_message`` without ever ending the session.-``SessionDB.prune_sessions`` only reaps rows where ``ended_at IS NOT NULL``, so-every webhook session stayed unprunable and state.db grew without bound (this-was the primary driver of the SQLite lock-contention gateway outage).--The invariant asserted here is a *behavior contract*, not a snapshot: once a-webhook delivery's agent run completes, the session row for that delivery must-have ``ended_at`` set — mirroring how a cron run closes its session with-``end_session(..., "cron_complete")``.--CRITICAL: these tests go through the REAL ``handle_message`` →-``_process_message_background`` → ``on_processing_complete`` pipeline (only the-runner-side ``_message_handler`` is stubbed, exactly the seam the live gateway-injects). ``handle_message`` is fire-and-forget — it spawns the background-task and returns before the run starts — so any close bolted around-``handle_message`` itself runs BEFORE the session row exists and silently-no-ops. A test that fakes ``handle_message`` to create the row synchronously-masks exactly that bug (the first version of this fix shipped that way).-"""--import asyncio-+"""A late webhook finalizer cannot end a replacement route or generation."""import pytest-from gateway.config import GatewayConfig, Platform, PlatformConfig-from gateway.platforms.event import MessageEvent, MessageType-from gateway.platforms.webhook import WebhookAdapter, _INSECURE_NO_AUTH-from gateway.session import SessionSource, SessionStore---def _make_adapter(routes, **extra_kw) -> WebhookAdapter:- extra = {"host": "127.0.0.1", "port": 0, "routes": routes}- extra.update(extra_kw)- config = PlatformConfig(enabled=True, extra=extra)- return WebhookAdapter(config)---class _FakeRunner:- """Minimal gateway runner surface the webhook close path depends on.-- Wires a real ``SessionStore`` (which owns a real ``SessionDB``) and reuses- that same ``SessionDB`` as ``_session_db`` so the row created at routing- time is the row the close path ends — exactly the wiring the live gateway- has (``self.session_store`` + ``self._session_db``).- """-- def __init__(self, store: SessionStore):- self.session_store = store- self._session_db = store._db-- def _session_key_for_source(self, source: SessionSource) -> str:- return self.session_store._generate_session_key(source)---def _make_store(tmp_path) -> SessionStore:- sessions_dir = tmp_path / "sessions"- sessions_dir.mkdir()- config = GatewayConfig(- platforms={Platform.WEBHOOK: PlatformConfig(enabled=True)}- )- store = SessionStore(sessions_dir=sessions_dir, config=config)- assert store._db is not None, "test requires a real SessionDB"- return store---def _make_event(adapter: WebhookAdapter, delivery_id: str, text: str) -> MessageEvent:- session_chat_id = f"webhook:alerts:{delivery_id}"- source = adapter.build_source(- chat_id=session_chat_id,- chat_name="webhook/alerts",- chat_type="webhook",- user_id="webhook:alerts",- user_name="alerts",- )- return MessageEvent(- text=text,- message_type=MessageType.TEXT,- source=source,- raw_message={"message": text},- message_id=delivery_id,- )---async def _drain_background_tasks(adapter: WebhookAdapter, timeout: float = 5.0) -> None:- """Wait for the adapter's spawned processing task(s) to finish."""- deadline = asyncio.get_event_loop().time() + timeout- while adapter._background_tasks and asyncio.get_event_loop().time() < deadline:- await asyncio.sleep(0.02)- # One extra tick for done-callbacks to run.- await asyncio.sleep(0.05)+from gateway.config import Platform, PlatformConfig+from gateway.platforms.event import MessageEvent+from gateway.platforms.webhook import WebhookAdapter+from gateway.run import GatewayRunner+from gateway.session_authority import initialize_session_authority+from hermes_state_runtime import admit_session_input, claim_session_input, settle_session_input@pytest.mark.asyncio-async def test_completed_webhook_delivery_closes_its_session(tmp_path):- """After a webhook run finishes (REAL dispatch path), ended_at is set."""- store = _make_store(tmp_path)- runner = _FakeRunner(store)-- adapter = _make_adapter(- {- "alerts": {- "secret": _INSECURE_NO_AUTH,- "prompt": "Alert: {message}",- "deliver": "log",- }- }- )+async def test_webhook_finalization_is_exact_session_and_generation(tmp_path):+ runner = GatewayRunner()+ authority = await initialize_session_authority(runner, profile_id='default', instance_id='close-test')+ runner._session_db = authority.db+ adapter = WebhookAdapter(PlatformConfig(enabled=True, extra={'secret': 'owned-close-secret'}))adapter.gateway_runner = runner-- # Stub the RUNNER-side handler (the seam the live gateway injects) — the- # adapter's own handle_message / _process_message_background pipeline runs- # for real, including the fire-and-forget task spawn and the- # on_processing_complete hook. The handler creates the session row, just- # like GatewayRunner._handle_message does at routing time.- created = {}-- async def _message_handler(event: MessageEvent):- entry = store.get_or_create_session(event.source)- created["session_id"] = entry.session_id- return "" # webhook deliver=log — nothing to send back-- adapter._message_handler = _message_handler-- event = _make_event(adapter, "alert-close-001", "Alert: server on fire")-- # Exactly what _handle_webhook schedules.- await adapter.handle_message(event)- # handle_message is fire-and-forget: the session must NOT be expected to- # exist yet. (Guards against reintroducing a close wrapped around- # handle_message itself, which ran before the row existed and no-op'd.)- await _drain_background_tasks(adapter)-- session_id = created["session_id"]- row = store._db.get_session(session_id)- assert row is not None-- # INVARIANT: a completed webhook session must be closed so prune can reap it.- assert row["ended_at"] is not None, (- "webhook session was never closed — ended_at is NULL, so "- "prune_sessions can never reap it (the ghost-session leak)"- )- assert row["end_reason"] == "webhook_complete"-- # And the closed row is actually prunable, unlike the pre-fix leak.- pruned = store._db.prune_sessions(older_than_days=0, source="webhook")- assert pruned >= 1- store._db.close()--+ runner.adapters[Platform.WEBHOOK] = adapter+ runner._wire_adapter_handlers(adapter)+ source = adapter.build_source(chat_id='webhook:close:one', user_id='webhook:close', chat_type='webhook')+ ref = authority.register(source)++ def settled(identity):+ row = admit_session_input(authority.db, epoch=authority.epoch, principal_id='fixture',+ session_id=ref.session_id, request_id=identity, payload={'text': 'fixture'})+ claimed = claim_session_input(authority.db, epoch=authority.epoch, session_id=ref.session_id)+ return authority._receipt(settle_session_input(authority.db, epoch=authority.epoch,+ admission_id=row['admission_id'], generation=claimed['generation'], outcome='completed'))++ receipt = settled('first')+ event = MessageEvent(text='fixture', source=source, message_id='first')+ event._webhook_receipt = (authority, receipt)+ successor = runner.session_store.get_or_create_session(source, force_new=True)+ assert successor.session_id != ref.session_id+ # Simulate a delayed callback after route publication. The old authority+ # receipt, not the current route, is the only admissible finalization target.+ await adapter._end_webhook_session(event, source.chat_id)+ assert authority.db.get_session(successor.session_id)['ended_at'] is None++ authority.db.reopen_session(ref.session_id)+ newer = settled('second')+ assert newer.execution_generation > receipt.execution_generation+ await adapter._end_webhook_session(event, source.chat_id)+ assert authority.db.get_session(ref.session_id)['ended_at'] is None+ event._webhook_receipt = (authority, newer)+ await adapter._end_webhook_session(event, source.chat_id)+ assert authority.db.get_session(ref.session_id)['end_reason'] == 'webhook_complete'