The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(webhook): recover finalization of settled admissions
unsupportedpastels87763c4bc485
diff --git a/gateway/platforms/webhook_ingress.py b/gateway/platforms/webhook_ingress.pyindex 4a42e8244e6..5f62466ef38 100644--- a/gateway/platforms/webhook_ingress.py+++ b/gateway/platforms/webhook_ingress.py@@ -69,7 +69,9 @@ async def _webhook_retry(authority, event):if len(rows) != 1 or row['payload'] != payload:raise RuntimeStoreError('admission_conflict')event._webhook_duplicate = True- return authority._receipt(row)+ receipt = authority._receipt(row)+ finalize_webhook(authority, receipt)+ return receiptdef finalize_webhook(authority, receipt):@@ -87,6 +89,40 @@ def finalize_webhook(authority, receipt):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,+ authority.epoch, receipt.admission_id, sid, receipt.execution_generation,receipt.authority_epoch, sid), sid, 'webhook_complete')return bool(authority.db._execute_write(write))+++async def recover_webhook_finalizations(authority):+ """Close settled original webhooks only after current route authorization succeeds."""+ from gateway.session_envelope import check_native_route+ from hermes_state_runtime import RuntimeStoreError, get_session_admission++ rows = authority.db._read_all("""+ SELECT a.admission_id FROM sessions AS s INDEXED BY idx_sessions_source+ JOIN session_admissions AS a INDEXED BY session_admissions_pending+ ON a.target_session_id=s.id+ WHERE s.source='webhook' AND s.ended_at IS NULL+ AND a.status='terminal' AND a.generation IS NOT NULL+ AND json_extract(a.payload_json, '$.native_text_v1.source.platform')='webhook'+ AND json_extract(a.payload_json, '$.native_text_v1.automation') IS NULL+ """)+ results = {}+ for candidate in rows:+ row = get_session_admission(authority.db, admission_id=candidate['admission_id'])+ if row is None:+ continue+ sid = row['target_session_id']+ try:+ envelope = row['payload']['native_text_v1']+ entry = authority.runner.session_store.lookup_by_session_key(envelope['route'])+ if entry is None or authority.logical_owner(entry.session_id) != sid:+ raise RuntimeStoreError('admission_conflict')+ adapter = authority.runner._adapter_for_source(entry.origin) if entry.origin is not None else None+ await check_native_route(authority.runner, row['payload'], sid, entry.origin, adapter)+ results[sid] = 'finalized' if finalize_webhook(+ authority, authority._receipt(row)) else 'unchanged'+ except (KeyError, RuntimeStoreError):+ results[sid] = 'unavailable'+ return resultsdiff --git a/gateway/run_runtime.py b/gateway/run_runtime.pyindex e08114fd562..1c01ad15946 100644--- a/gateway/run_runtime.py+++ b/gateway/run_runtime.py@@ -98,6 +98,8 @@ async def recover_gateway_native_sessions(runner):for authority in authorities:with owner_scope(authority):recover_local_sessions(authority, schedule=True)+ from gateway.platforms.webhook_ingress import recover_webhook_finalizations+ await recover_webhook_finalizations(authority)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 = [(owner, entry.origin, runner._adapter_for_source(entry.origin))diff --git a/tests/gateway/test_hosted_mux_runtime.py b/tests/gateway/test_hosted_mux_runtime.pyindex c7389b59f5a..bc118a324b5 100644--- a/tests/gateway/test_hosted_mux_runtime.py+++ b/tests/gateway/test_hosted_mux_runtime.py@@ -77,6 +77,29 @@ def test_hosted_lifecycle_serves_and_stops_every_authority(mux):assert all(not s.runtime.status()['running'] for s in services.values())+def test_native_recovery_checks_webhook_finalization_in_each_owner_scope(mux, monkeypatch):+ from gateway.run_runtime import recover_gateway_native_sessions+ from hermes_constants import get_hermes_home++ runner, homes, _, call = mux+ observed = []++ async def record_scope(authority):+ observed.append((authority.profile_id, get_hermes_home().resolve()))+ return {}++ monkeypatch.setattr(+ "gateway.platforms.webhook_ingress.recover_webhook_finalizations", record_scope+ )+ call(recover_gateway_native_sessions(runner))++ assert observed == [+ (authority.profile_id, Path(authority.profile_id).resolve())+ for authority in runner.session_authorities+ ]+ assert {home for _profile, home in observed} == {home.resolve() for home in homes.values()}++def test_secondary_owner_transport_routes_both_directions_through_mux(mux):from gateway import hosted_roomsfrom gateway.session_authorities import owner_scopediff --git a/tests/gateway/test_webhook_finalization_recovery.py b/tests/gateway/test_webhook_finalization_recovery.pynew file mode 100644index 00000000000..39ab48a8956--- /dev/null+++ b/tests/gateway/test_webhook_finalization_recovery.py@@ -0,0 +1,122 @@+"""Settled webhook admissions remain closeable without repeating their turn."""+import asyncio+import hashlib+import hmac+import json+from contextlib import asynccontextmanager, suppress++import pytest+from aiohttp import web+from aiohttp.test_utils import TestClient, TestServer++from gateway.config import PlatformConfig+from gateway.platforms.webhook import WebhookAdapter+from hermes_state_runtime import claim_session_input, settle_session_input+from tests.gateway.fixtures.webhook_route_authority import mount_authority+++@asynccontextmanager+async def settled_before_finalizer():+ config = PlatformConfig(enabled=True, extra={+ "secret": "owned-secret",+ "routes": {"fixture": {"prompt": "{text}", "deliver": "log"}},+ })+ adapter = WebhookAdapter(config)+ app = web.Application()+ mount_authority(app, adapter)+ app.router.add_post("/webhooks/{route_name}", adapter._handle_webhook)+ async with TestClient(TestServer(app)) as client:+ body = json.dumps({"text": "one turn only"}).encode()+ headers = {+ "X-GitHub-Delivery": "settled-before-finalizer",+ "X-Hub-Signature-256": "sha256=" + hmac.new(+ b"owned-secret", body, hashlib.sha256+ ).hexdigest(),+ }+ response = await client.post("/webhooks/fixture", data=body, headers=headers)+ assert response.status == 202, await response.text()+ runner = adapter._message_handler.__self__+ authority = runner.session_authority+ row = authority.db._read_one("SELECT * FROM session_admissions")+ claimed = claim_session_input(+ authority.db, epoch=authority.epoch, session_id=row["target_session_id"]+ )+ settle_session_input(+ authority.db,+ epoch=authority.epoch,+ admission_id=row["admission_id"],+ generation=claimed["generation"],+ outcome="completed",+ )+ # Crash after the durable settlement but before the process-local finalizer.+ for task in list(adapter._background_tasks):+ task.cancel()+ with suppress(asyncio.CancelledError):+ await task+ assert authority.db.get_session(row["target_session_id"])["ended_at"] is None+ yield client, body, headers, runner, authority, row+++async def test_restart_finalizes_settled_webhook_without_provider_retry(monkeypatch):+ async with settled_before_finalizer() as (_client, _body, _headers, runner, authority, row):+ from gateway import run_runtime+ from gateway.session_authority import initialize_session_authority++ async def skip_unrelated_hosted_service(_runner):+ return None++ monkeypatch.setattr(+ "gateway.session_hosted_service.ensure_hosted_service",+ skip_unrelated_hosted_service,+ )+ restarted = await initialize_session_authority(+ runner,+ profile_id=authority.profile_id,+ instance_id="replacement-owner",+ db=authority.db,+ )+ scheduled = []+ restarted._schedule = scheduled.append++ await run_runtime.recover_gateway_native_sessions(runner)++ saved = authority.db.get_session(row["target_session_id"])+ assert saved["end_reason"] == "webhook_complete"+ assert scheduled == []+ assert len(authority.db._read_all("SELECT * FROM session_admissions")) == 1+++async def test_duplicate_request_finalizes_settled_webhook_without_reexecution():+ async with settled_before_finalizer() as (client, body, headers, _runner, authority, row):+ scheduled = []+ authority._schedule = scheduled.append+ response = await client.post("/webhooks/fixture", data=body, headers=headers)++ assert response.status == 200, await response.text()+ assert (await response.json())["status"] == "duplicate"+ assert authority.db.get_session(row["target_session_id"])["end_reason"] == "webhook_complete"+ assert scheduled == []+ assert len(authority.db._read_all("SELECT * FROM session_admissions")) == 1++[email protected]("route", [None, {"prompt": "changed {text}", "deliver": "log"}])+async def test_startup_leaves_settled_webhook_open_when_route_is_missing_or_changed(route):+ async with settled_before_finalizer() as (_client, _body, _headers, _runner, authority, row):+ from gateway.platforms.webhook_ingress import recover_webhook_finalizations++ entry = authority.runner.session_store.lookup_by_session_id(row["target_session_id"])+ adapter = authority.runner._adapter_for_source(entry.origin)+ if route is None:+ adapter._routes.pop("fixture")+ else:+ adapter._routes["fixture"] = route++ await recover_webhook_finalizations(authority)++ saved = authority.db.get_session(row["target_session_id"])+ assert saved["ended_at"] is None+ assert saved["end_reason"] is None+ assert len(authority.db._read_all("SELECT * FROM session_admissions")) == 1diff --git a/tests/gateway/test_webhook_session_close.py b/tests/gateway/test_webhook_session_close.pyindex a8692faed50..3830cd919fb 100644--- a/tests/gateway/test_webhook_session_close.py+++ b/tests/gateway/test_webhook_session_close.py@@ -46,3 +46,52 @@ async def test_webhook_finalization_is_exact_session_and_generation(tmp_path):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'+++async def test_old_authority_callback_cannot_mutate_after_replacement(tmp_path):+ runner = GatewayRunner()+ old = await initialize_session_authority(runner, profile_id='default', instance_id='old-owner')+ runner._session_db = old.db+ adapter = WebhookAdapter(PlatformConfig(enabled=True, extra={'secret': 'owned-close-secret'}))+ adapter.gateway_runner = runner+ runner.adapters[Platform.WEBHOOK] = adapter+ runner._wire_adapter_handlers(adapter)+ source = adapter.build_source(chat_id='webhook:close:replacement', user_id='webhook:close', chat_type='webhook')+ ref = old.register(source)+ row = admit_session_input(old.db, epoch=old.epoch, principal_id='fixture',+ session_id=ref.session_id, request_id='settled', payload={'text': 'fixture'})+ claimed = claim_session_input(old.db, epoch=old.epoch, session_id=ref.session_id)+ receipt = old._receipt(settle_session_input(old.db, epoch=old.epoch,+ admission_id=row['admission_id'], generation=claimed['generation'], outcome='completed'))+ replacement = await initialize_session_authority(runner, profile_id='default',+ instance_id='replacement-owner', db=old.db)+ event = MessageEvent(text='fixture', source=source, message_id='settled')++ event._webhook_receipt = (old, receipt)+ await adapter._end_webhook_session(event, source.chat_id)+ assert old.db.get_session(ref.session_id)['ended_at'] is None++ event._webhook_receipt = (replacement, receipt)+ await adapter._end_webhook_session(event, source.chat_id)+ assert old.db.get_session(ref.session_id)['end_reason'] == 'webhook_complete'+++async def test_webhook_finalization_is_blocked_by_nonterminal_sibling(tmp_path):+ runner = GatewayRunner()+ authority = await initialize_session_authority(runner, profile_id='default', instance_id='sibling-test')+ source = WebhookAdapter(PlatformConfig(enabled=True, extra={'secret': 'secret'})).build_source(+ chat_id='webhook:close:sibling', user_id='webhook:close', chat_type='webhook')+ ref = authority.register(source)+ first = admit_session_input(authority.db, epoch=authority.epoch, principal_id='fixture',+ session_id=ref.session_id, request_id='first', payload={'text': 'first'})+ claimed = claim_session_input(authority.db, epoch=authority.epoch, session_id=ref.session_id)+ receipt = authority._receipt(settle_session_input(authority.db, epoch=authority.epoch,+ admission_id=first['admission_id'], generation=claimed['generation'], outcome='completed'))+ admit_session_input(authority.db, epoch=authority.epoch, principal_id='fixture',+ session_id=ref.session_id, request_id='second', payload={'text': 'second'})++ from gateway.platforms.webhook_ingress import finalize_webhook+ assert finalize_webhook(authority, receipt) is False+ assert authority.db.get_session(ref.session_id)['ended_at'] is None