The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway,relay): stop frozen-preview finals and dropped idle-session delegation callbacks (#82592)
victor-kyriazakos6a7cf19302eb
diff --git a/gateway/relay/adapter.py b/gateway/relay/adapter.pyindex 9e071864294..5c9507031f7 100644--- a/gateway/relay/adapter.py+++ b/gateway/relay/adapter.py@@ -20,6 +20,7 @@ from __future__ import annotationsimport asyncioimport logging+import timefrom typing import Any, Callable, Dict, Optional, Tuple, castfrom gateway.config import Platform, PlatformConfig@@ -487,6 +488,24 @@ class RelayAdapter(BasePlatformAdapter):except Exception: # noqa: BLE001 - media localization must never break inboundlogger.debug("relay inbound media localization failed", exc_info=True)+ def prime_routing_cache(self, event) -> None:+ """Warm the per-chat egress routing caches from a SYNTHETIC event.++ The caches (_scope_by_chat/_dm_user_by_chat/...) are normally warmed+ only by the inbound path (_on_inbound -> _capture_scope). A synthetic+ completion turn injected right after a restart (durable+ async-delegation replay) reaches handle_message with the caches COLD,+ so every reply it produces egresses without metadata.scope_id /+ metadata.user_id and is declined by the connector's fail-closed+ tenant guard ("target not routed to an onboarded tenant" — staging+ 2026-08-09, defect #4). The synthetic event's session-store origin+ already carries the discriminators; feed it through the same capture+ used for real inbound. Never raises.+ """+ if event is None or getattr(event, "source", None) is None:+ return+ self._capture_scope(event)+def _capture_scope(self, event) -> None:"""Remember a chat_id's egress discriminator from an inbound event so ouroutbound (the agent's reply) can re-assert it for the connector's egress@@ -823,6 +842,17 @@ class RelayAdapter(BasePlatformAdapter):return partsasync def disconnect(self) -> None:+ # Budget accounting: the runner wraps this whole call in+ # asyncio.wait_for(_adapter_disconnect_timeout_secs()). Everything we+ # spend on monitor teardown and go_idle below eats into what the+ # transport can spend on its outbound drain, so measure from the top+ # and thread the REMAINDER down — otherwise worst-case+ # monitor(1s) + go_idle(2s) + drain + 3×teardown(1s) can blow the 5s+ # budget, cancelling teardown mid-drain and skipping the transport's+ # fail-pending loop (callers then block on _OUTBOUND_TIMEOUT_S).+ from gateway.relay.ws_transport import _env_disconnect_budget_s+ _started = time.monotonic()+ _budget = _env_disconnect_budget_s()# Phase 7 Unit 7d-B: stop the revocation monitor first so it can't fire a# spurious fatal during/after a deliberate teardown.if self._revocation_monitor is not None:@@ -866,7 +896,16 @@ class RelayAdapter(BasePlatformAdapter):)finally:try:- await asyncio.shield(self._transport.disconnect())+ _remaining = max(0.0, _budget - (time.monotonic() - _started))+ try:+ _td = cast(Any, self._transport).disconnect(+ budget_s=_remaining+ )+ except TypeError:+ # Transports without the budget_s keyword (stubs,+ # older implementations) keep the legacy signature.+ _td = self._transport.disconnect()+ await asyncio.shield(_td)except Exception: # noqa: BLE001 - teardown must not block outer cancel propagationlogger.debug("relay transport disconnect failed during drain",diff --git a/gateway/relay/ws_transport.py b/gateway/relay/ws_transport.pyindex 07981a327e7..b0e067fc162 100644--- a/gateway/relay/ws_transport.py+++ b/gateway/relay/ws_transport.py@@ -32,6 +32,7 @@ from __future__ import annotationsimport asyncioimport jsonimport logging+import osimport uuidfrom dataclasses import dataclassfrom typing import Any, Dict, List, Optional@@ -57,6 +58,45 @@ _OUTBOUND_TIMEOUT_S = 30.0# adapter.disconnect. Three sequential awaits at 1.0s stay under the runner's# default 5s adapter disconnect budget (plus the 2s go_idle ACK budget)._TEARDOWN_AWAIT_TIMEOUT_S = 1.0+# Bounded drain for in-flight outbound frames at disconnect: long enough for a+# platform edit round-trip through the connector, short enough that shutdown+# stays snappy when the connector is gone. The EFFECTIVE grace is clamped at+# disconnect time so drain + the three sequential teardown awaits stay inside+# the runner's adapter-disconnect budget (gateway/run.py wraps disconnect() in+# asyncio.wait_for; blowing that budget cancels teardown mid-drain, skips the+# fail-pending loop, and leaves callers blocked on _OUTBOUND_TIMEOUT_S).+_DISCONNECT_DRAIN_GRACE_S = 5.0+++def _disconnect_drain_grace_s(budget_s: Optional[float] = None) -> float:+ """Effective drain grace: clamped to the caller's disconnect budget.++ ``budget_s`` is the REMAINING budget threaded down by the caller+ (RelayAdapter.disconnect measures what go_idle and monitor teardown+ already consumed). When None, mirrors+ gateway/run.py:_adapter_disconnect_timeout_secs (env override with+ the same variable, same default) rather than importing it — the+ transport must stay importable without the gateway runner. Reserves+ the three sequential teardown awaits plus a small margin.+ """+ budget = _env_disconnect_budget_s() if budget_s is None else max(0.0, budget_s)+ reserved = 3 * _TEARDOWN_AWAIT_TIMEOUT_S + 0.5+ return max(0.0, min(_DISCONNECT_DRAIN_GRACE_S, budget - reserved))+++def _env_disconnect_budget_s() -> float:+ """The runner's adapter-disconnect budget, read the same way+ gateway/run.py:_adapter_disconnect_timeout_secs reads it (same env+ variable, same default). Callers above the transport use this to+ apportion the budget across go_idle / monitor teardown / drain."""+ budget = 5.0 # _ADAPTER_DISCONNECT_TIMEOUT_SECS_DEFAULT in gateway/run.py+ raw = os.getenv("HERMES_GATEWAY_ADAPTER_DISCONNECT_TIMEOUT", "").strip()+ if raw:+ try:+ budget = max(0.0, float(raw))+ except ValueError:+ pass+ return budget# Phase 7 Unit 7d-B: the application close code the connector sends when it# rejects/revokes a gateway's WS upgrade auth (mirrors the connector's@@ -500,38 +540,69 @@ class WebSocketRelayTransport:token = make_upgrade_token(self._gateway_id, self._upgrade_secret)return {"Authorization": f"Bearer {token}"}- async def disconnect(self) -> None:+ async def disconnect(self, *, budget_s: Optional[float] = None) -> None:+ """Tear down the socket, draining in-flight outbound frames first.++ ``budget_s`` is the REMAINING wall-clock budget the caller can spend+ here (RelayAdapter.disconnect threads it down after go_idle / monitor+ teardown). When None, the env-mirrored runner default applies.+ """self._closing = True- if self._supervisor is not None:- self._supervisor.cancel()- try:- await asyncio.wait_for(- self._supervisor, timeout=_TEARDOWN_AWAIT_TIMEOUT_S- )- except (asyncio.TimeoutError, asyncio.CancelledError, Exception): # noqa: BLE001 - best-effort teardown- pass- self._supervisor = None- if self._reader is not None:- self._reader.cancel()- try:- await asyncio.wait_for(self._reader, timeout=_TEARDOWN_AWAIT_TIMEOUT_S)- except (asyncio.TimeoutError, asyncio.CancelledError, Exception): # noqa: BLE001 - best-effort teardown- pass- self._reader = None- if self._ws is not None:- try:- await asyncio.wait_for(self._ws.close(), timeout=_TEARDOWN_AWAIT_TIMEOUT_S)- except (asyncio.TimeoutError, asyncio.CancelledError, Exception): # noqa: BLE001- pass- finally:- self._ws = None- # Fail any in-flight outbound waiters so callers don't hang.- for fut in self._pending.values():- if not fut.done():- fut.set_exception(RuntimeError("relay transport closed"))- self._pending.clear()- if self._going_idle_ack is not None and not self._going_idle_ack.done():- self._going_idle_ack.set_exception(RuntimeError("relay transport closed"))+ try:+ # Drain grace: a trailing outbound frame (typically the turn's+ # finalize edit) may still be awaiting its outbound_result. Failing+ # it immediately loses a message the connector was about to ack —+ # staging incident 2026-08-09 froze a Slack reply at its preview+ # snapshot exactly this way. Give in-flight requests a short bounded+ # window to resolve before tearing the socket down.+ pending = [f for f in self._pending.values() if not f.done()]+ if pending:+ _grace = _disconnect_drain_grace_s(budget_s)+ if _grace > 0:+ try:+ # asyncio.wait (not wait_for+gather): on timeout it must NOT+ # cancel the futures — the fail-any-remaining loop below owns+ # their terminal state.+ await asyncio.wait(pending, timeout=_grace)+ except Exception: # noqa: BLE001 - grace is best-effort+ pass+ if self._supervisor is not None:+ self._supervisor.cancel()+ try:+ await asyncio.wait_for(+ self._supervisor, timeout=_TEARDOWN_AWAIT_TIMEOUT_S+ )+ except (asyncio.TimeoutError, asyncio.CancelledError, Exception): # noqa: BLE001 - best-effort teardown+ pass+ self._supervisor = None+ if self._reader is not None:+ self._reader.cancel()+ try:+ await asyncio.wait_for(self._reader, timeout=_TEARDOWN_AWAIT_TIMEOUT_S)+ except (asyncio.TimeoutError, asyncio.CancelledError, Exception): # noqa: BLE001 - best-effort teardown+ pass+ self._reader = None+ if self._ws is not None:+ try:+ await asyncio.wait_for(self._ws.close(), timeout=_TEARDOWN_AWAIT_TIMEOUT_S)+ except (asyncio.TimeoutError, asyncio.CancelledError, Exception): # noqa: BLE001+ pass+ finally:+ self._ws = None+ finally:+ # Fail any in-flight outbound waiters so callers don't hang.+ # Runs in a finally so a cancellation landing anywhere in the+ # drain/teardown above (the runner's wait_for budget, an outer+ # cleanup deadline) can NEVER leave a registered future+ # unresolved — a stranded waiter would otherwise block until+ # _OUTBOUND_TIMEOUT_S (30s). Idempotent: done futures are+ # skipped, so a second disconnect() pass is safe.+ for fut in self._pending.values():+ if not fut.done():+ fut.set_exception(RuntimeError("relay transport closed"))+ self._pending.clear()+ if self._going_idle_ack is not None and not self._going_idle_ack.done():+ self._going_idle_ack.set_exception(RuntimeError("relay transport closed"))async def handshake(self) -> CapabilityDescriptor:if self._descriptor is not None:@@ -696,6 +767,12 @@ class WebSocketRelayTransport:*,platform: Optional[str] = None,) -> Dict[str, Any]:+ if self._closing:+ # Teardown in progress: the disconnect() fail-pending loop may+ # already have run, so a future registered now would never be+ # resolved or failed — the caller would block the full+ # _OUTBOUND_TIMEOUT_S for a socket that is going away. Fail fast.+ return {"success": False, "error": "relay transport closed"}if self._ws is None:return {"success": False, "error": "relay transport not connected"}request_id = uuid.uuid4().hexdiff --git a/gateway/run.py b/gateway/run.pyindex a38a81bd981..6b54cf163af 100644--- a/gateway/run.py+++ b/gateway/run.py@@ -85,6 +85,20 @@ _PLATFORM_CONNECT_TIMEOUT_SECS_DEFAULT = 30.0# wall deadlines plus readiness; other platforms retain the 30s isolation bound._TELEGRAM_CONNECT_TIMEOUT_SECS_DEFAULT = 180.0_ADAPTER_DISCONNECT_TIMEOUT_SECS_DEFAULT = 5.0+# End reasons that mean the USER deliberately closed this thread of work+# (/new -> session_reset / new_session, an explicit exit, or a /switch).+# Shared by _classify_completion_target (pre-flight verdict) and+# _resolve_async_delegation_session (in-pipeline routing) so the two can+# never disagree: every reason the classifier calls "deliver" must be one+# the resolver actually delivers, otherwise the durable row is acked at+# adapter acceptance and then silently dropped inside the pipeline —+# a falsely-acknowledged permanent loss.+_USER_BOUNDARY_END_REASONS = (+ "session_reset",+ "user_exit",+ "session_switch",+ "new_session",+)# Round-2 #2: upper bound on a single stall-notify adapter.send so a wedged# transport cannot block the session-stall watcher pass (notify-only path;# on timeout the latch stays clear and the next tick retries).@@ -14258,15 +14272,35 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatewtarget_session_id = pinned_session_idfollows_compression = Falseif pinned_row.get("ended_at"):- if pinned_row.get("end_reason") != "compression":+ _end_reason = str(pinned_row.get("end_reason") or "")+ if _end_reason in _USER_BOUNDARY_END_REASONS:logger.warning(- "Async-delegation completion pinned to ended session %s "+ "Async-delegation completion pinned to user-closed session %s ""(end_reason=%r); dropping injection instead of resurrecting it ""(#55578 fail-closed).",pinned_session_id,- pinned_row.get("end_reason"),+ _end_reason,)return None+ if _end_reason != "compression":+ # Idle/timeout/lifecycle end (scale-to-zero norm): the chat+ # route remains valid and ``session_entry`` IS the routing+ # key's current session for this same chat, so deliver the+ # finished work there instead of dropping it. This is the+ # delivery leg _classify_completion_target promises when it+ # returns "deliver" for non-boundary ends — without it the+ # pre-flight verdict and this resolver disagree, and the+ # durable row is acked at adapter acceptance then silently+ # dropped here (falsely-acknowledged permanent loss;+ # staging incident 2026-08-09 defect #2).+ logger.info(+ "Async-delegation completion pinned to %s-ended session %s; "+ "retargeting to the chat's current session %s.",+ _end_reason or "idle",+ pinned_session_id,+ session_entry.session_id,+ )+ return session_entryfollows_compression = Truetry:@@ -21962,6 +21996,7 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatewthread_id=str(context.source.thread_id) if context.source.thread_id else "",user_id=str(context.source.user_id) if context.source.user_id else "",user_name=str(context.source.user_name) if context.source.user_name else "",+ scope_id=str(getattr(context.source, "scope_id", "") or ""),session_key=context.session_key,message_id=str(context.source.message_id) if context.source.message_id else "",profile=getattr(context.source, "profile", "") or "",@@ -22501,6 +22536,21 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatew)return None+ scope_id = str(evt.get("scope_id") or "").strip() or None+ if scope_id is None and chat_type not in ("dm", "thread"):+ # Reconstructed (non-persisted) source for a scoped chat with no+ # scope discriminator: on a relay-fronted deployment the+ # connector's fail-closed tenant guard may decline the reply+ # unless user_id resolves it (resolveByUser). Don't fail here —+ # DMs and author-bound scoped chats still route, and native+ # adapters don't need scope_id — but say so, so a post-restart+ # egress decline isn't silent.+ logger.warning(+ "Synthetic event source for %s chat=%s (%s) reconstructed "+ "without scope_id; scoped relay egress may be declined by "+ "the connector's tenant guard (user_id fallback only).",+ platform_name, chat_id, chat_type,+ )return SessionSource(platform=platform,chat_id=chat_id,@@ -22508,6 +22558,7 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatewthread_id=str(evt.get("thread_id") or "").strip() or None,user_id=str(evt.get("user_id") or "").strip() or None,user_name=str(evt.get("user_name") or "").strip() or None,+ scope_id=scope_id,)async def _inject_watch_notification(@@ -22567,11 +22618,35 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatew)return Noneplatform_name = source.platform.value if hasattr(source.platform, "value") else str(source.platform)+ # Alias-aware resolution (relay-plane): a relay-fronted gateway+ # registers ONE adapter under Platform.RELAY fronting N logical+ # platforms, so a literal ``p.value == platform_name`` scan misses+ # "slack" and silently drops the completion as "no gateway route"+ # (staging incident 2026-08-09, second occurrence). Resolve through+ # the shared transport resolver — native adapter wins; relay is+ # eligible only when it advertises fronting the logical platform.adapter = None- for p, a in self.adapters.items():- if p.value == platform_name:- adapter = a- break+ try:+ _platform_enum = Platform(platform_name)+ except (ValueError, KeyError):+ _platform_enum = None+ if _platform_enum is not None:+ try:+ _transport = resolve_delivery_transport(+ _platform_enum, self.config, self.adapters,+ )+ except Exception:+ _transport = None+ if _transport is not None:+ adapter = _transport.adapter+ if adapter is None:+ # Legacy literal scan — still correct for native adapters, and+ # keeps minimal runner stubs (tests) and exotic platform strings+ # working when the resolver can't run.+ for p, a in self.adapters.items():+ if p.value == platform_name:+ adapter = a+ breakif not adapter:return Nonefrom gateway.wake import adapter_supports_push as _wake_push_ok@@ -22617,6 +22692,15 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatewsource.chat_id,source.thread_id,)+ # Relay-plane egress priming (defect #4, staging 2026-08-09): a+ # synthetic turn injected right after a restart reaches a relay+ # adapter whose per-chat routing caches are cold (they warm only+ # on inbound), so its replies egress without tenant+ # discriminators and the connector's fail-closed guard declines+ # them. Prime the caches from this event's session-store origin.+ _prime = getattr(adapter, "prime_routing_cache", None)+ if callable(_prime):+ _prime(synth_event)await adapter.handle_message(synth_event)return Trueexcept Exception as e:@@ -22678,8 +22762,22 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatewreturn "terminal"if not parent.get("ended_at"):return "deliver"- if parent.get("end_reason") != "compression":- return "terminal"+ end_reason = str(parent.get("end_reason") or "")+ if end_reason != "compression":+ # An ended parent is only unreachable when the USER closed the+ # thread of work (explicit boundary: /new -> session_reset /+ # new_session, user_exit, session_switch). Idle/timeout ends are+ # the norm on scale-to-zero relay deployments — the platform chat+ # remains routable, and the #55578 resolver retargets the+ # completion to the chat's current session. Dropping those loses+ # finished work (staging incident 2026-08-09: completed+ # delegation batch never delivered because the parent had+ # idle-ended). The boundary set is shared with the resolver+ # (_USER_BOUNDARY_END_REASONS) so this verdict and the pipeline's+ # routing decision cannot drift apart.+ if end_reason in _USER_BOUNDARY_END_REASONS:+ return "terminal"+ return "deliver"try:tip_session_id = await session_db.get_compression_tip(parent_session_id)if not tip_session_id or tip_session_id == parent_session_id:diff --git a/gateway/session_context.py b/gateway/session_context.pyindex 0cf35ef229d..ccdd0287551 100644--- a/gateway/session_context.py+++ b/gateway/session_context.py@@ -79,6 +79,13 @@ _SESSION_CHAT_NAME: ContextVar = ContextVar("HERMES_SESSION_CHAT_NAME", default=_SESSION_THREAD_ID: ContextVar = ContextVar("HERMES_SESSION_THREAD_ID", default=_UNSET)_SESSION_USER_ID: ContextVar = ContextVar("HERMES_SESSION_USER_ID", default=_UNSET)_SESSION_USER_NAME: ContextVar = ContextVar("HERMES_SESSION_USER_NAME", default=_UNSET)+# Platform-neutral scope discriminator (Discord guild / Slack workspace /+# Matrix server) of the originating chat. Captured at session-bind time so+# async producers (delegate_task background=True, terminal watchers) can+# persist a completion's full routing origin — on a relay-fronted deployment+# the connector's fail-closed egress guard needs scope_id (or a user binding)+# to resolve the tenant for a scoped reply after a restart.+_SESSION_SCOPE_ID: ContextVar = ContextVar("HERMES_SESSION_SCOPE_ID", default=_UNSET)_SESSION_KEY: ContextVar = ContextVar("HERMES_SESSION_KEY", default=_UNSET)_SESSION_ID: ContextVar = ContextVar("HERMES_SESSION_ID", default=_UNSET)# In-process UI session/window id for multi-session desktop/TUI hosts. This is@@ -136,6 +143,7 @@ _VAR_MAP = {"HERMES_SESSION_THREAD_ID": _SESSION_THREAD_ID,"HERMES_SESSION_USER_ID": _SESSION_USER_ID,"HERMES_SESSION_USER_NAME": _SESSION_USER_NAME,+ "HERMES_SESSION_SCOPE_ID": _SESSION_SCOPE_ID,"HERMES_SESSION_KEY": _SESSION_KEY,"HERMES_SESSION_ID": _SESSION_ID,"HERMES_UI_SESSION_ID": _SESSION_UI_SESSION_ID,@@ -212,6 +220,7 @@ def set_session_vars(thread_id: str = "",user_id: str = "",user_name: str = "",+ scope_id: str = "",session_key: str = "",session_id: str = "",message_id: str = "",@@ -254,6 +263,7 @@ def set_session_vars(_SESSION_THREAD_ID.set(thread_id),_SESSION_USER_ID.set(user_id),_SESSION_USER_NAME.set(user_name),+ _SESSION_SCOPE_ID.set(scope_id),_SESSION_KEY.set(session_key),_SESSION_ID.set(session_id),_SESSION_UI_SESSION_ID.set(ui_session_id),@@ -291,6 +301,7 @@ def clear_session_vars(tokens: list) -> None:_SESSION_THREAD_ID,_SESSION_USER_ID,_SESSION_USER_NAME,+ _SESSION_SCOPE_ID,_SESSION_KEY,_SESSION_ID,_SESSION_UI_SESSION_ID,diff --git a/gateway/stream_consumer.py b/gateway/stream_consumer.pyindex c7f8d5b6ecf..836ba980a77 100644--- a/gateway/stream_consumer.py+++ b/gateway/stream_consumer.py@@ -418,6 +418,27 @@ class GatewayStreamConsumer:self._accumulated += textself._stream_ledger += text+ def _mark_skip_redundant_finalize(self) -> None:+ """Mark the turn final as delivered by a prior mid-stream edit.++ Used by the run loop when the final accumulated content was already+ delivered by the last visible edit and the explicit finalize edit is+ skipped. Records what was actually ACKED on the wire, not what was+ accumulated: a throttled edit-transport stream can reach this state+ with the last acked edit still holding an earlier preview snapshot+ (cursor-suffixed). Recording ``_accumulated`` would let a frozen+ preview reconcile as the delivered final and suppress the corrective+ send, leaving the user a cut-off message. The multi-message split+ path keeps its ledger substitution inside+ ``_record_turn_final_payload``.+ """+ self._final_response_sent = True+ self._final_content_delivered = True+ acked = self._last_sent_text or self._accumulated+ if self.cfg.cursor and acked.endswith(self.cfg.cursor):+ acked = acked[: -len(self.cfg.cursor)]+ self._record_turn_final_payload(acked)+def _record_turn_final_payload(self, text: str) -> None:"""Record what the user has actually seen as this turn's final answer.@@ -1089,9 +1110,12 @@ class GatewayStreamConsumer:# the full text would overflow-split again into# the adopted continuation, duplicating chunks# on screen.- self._final_response_sent = True- self._final_content_delivered = True- self._record_turn_final_payload(self._accumulated)+ #+ # Delivery is recorded via the shared helper so+ # the recorded payload is the last ACKED edit,+ # not the accumulated text (frozen-preview+ # incident class; see _mark_skip_redundant_finalize).+ self._mark_skip_redundant_finalize()elif self._message_id:# Either the mid-stream edit didn't run (no# visible update this tick) OR the adapter needsdiff --git a/tests/gateway/test_relay_completion_injection_routing.py b/tests/gateway/test_relay_completion_injection_routing.pynew file mode 100644index 00000000000..226d0b48a4a--- /dev/null+++ b/tests/gateway/test_relay_completion_injection_routing.py@@ -0,0 +1,96 @@+"""Regression: completion injection must resolve the RELAY adapter for+fronted platforms.++Staging incident 2026-08-09 (second occurrence): async delegation batch+completed, watcher drained the event, and delivery silently vanished — no+injection log, no terminal-drop warning, no retry. Root cause:+``_inject_watch_notification`` resolves its adapter with a literal+``p.value == platform_name`` scan of ``self.adapters``. A relay-fronted+gateway registers ONE adapter under ``Platform.RELAY`` fronting N logical+platforms, so the literal scan misses "slack" and the injection returns+``None`` ("no gateway route") — the completion is dropped without a trace.++run.py already documents the trap and ships the alias-aware resolver+(``resolve_delivery_transport``); the handoff path uses it. Contract under+test: the injection path (and by extension every completion delivered on a+relay-plane deployment) must resolve through the shared resolver.+"""++from types import SimpleNamespace+from unittest.mock import AsyncMock++import pytest++from gateway.config import Platform+from gateway.run import GatewayRunner+++class _RelayAdapter:+ """Stub relay adapter fronting slack."""++ name = "relay"++ def __init__(self):+ self.handled = []+ self.handle_message = AsyncMock(side_effect=self.handled.append)++ def fronts_platform(self, platform):+ return platform == Platform.SLACK+++def _runner_with_relay(adapter):+ runner = object.__new__(GatewayRunner)+ runner._running = True+ runner.adapters = {Platform.RELAY: adapter}+ runner.config = SimpleNamespace(platforms={})+ return runner+++def _slack_async_event():+ return {+ "type": "async_delegation",+ "delegation_id": "deleg_relay_route",+ "session_key": "agent:main:slack:dm:D0BJTDCSR7C:1786298425.877239",+ "platform": "slack",+ "chat_type": "dm",+ "chat_id": "D0BJTDCSR7C",+ "status": "completed",+ "is_batch": True,+ "results": [{"goal": "g1", "status": "completed", "summary": "done"}],+ }+++async def test_injection_resolves_relay_adapter_for_fronted_platform():+ """A gateway whose only adapter is the relay (fronting slack) must+ deliver a slack-routed completion through it — not drop it as+ 'no gateway route'."""+ adapter = _RelayAdapter()+ runner = _runner_with_relay(adapter)++ result = await runner._inject_watch_notification(+ "[delegation completed]", _slack_async_event()+ )++ assert result is True, (+ f"injection returned {result!r} on a relay-fronted gateway — the "+ "completion was dropped exactly as in the 2026-08-09 staging "+ "incident (literal adapter scan misses Platform.RELAY)"+ )+ assert adapter.handle_message.await_count == 1+++async def test_injection_still_none_when_platform_not_fronted():+ """Control: a platform the relay does NOT front stays undeliverable+ (returns None) — the resolver must not let relay hijack unrelated+ targets."""+ adapter = _RelayAdapter() # fronts slack only+ runner = _runner_with_relay(adapter)+ evt = _slack_async_event()+ evt["session_key"] = "agent:main:discord:dm:123:456"+ evt["platform"] = "discord"++ result = await runner._inject_watch_notification("[x]", evt)+ assert result is None+ assert adapter.handle_message.await_count == 0diff --git a/tests/gateway/test_relay_delivery_followups.py b/tests/gateway/test_relay_delivery_followups.pynew file mode 100644index 00000000000..6982361a46a--- /dev/null+++ b/tests/gateway/test_relay_delivery_followups.py@@ -0,0 +1,475 @@+"""Follow-up regressions for the 2026-08-09 relay delivery fixes (#82592).++Four review findings on the original branch:++1. HIGH — classifier/resolver mismatch: ``_classify_completion_target``+ returned "deliver" for idle-ended parents, but+ ``_resolve_async_delegation_session`` (untouched) still dropped every+ non-compression-ended pin. The durable row was acked at adapter+ acceptance, then the injection silently died inside the pipeline — a+ falsely-acknowledged permanent loss, strictly worse than the honest+ terminal drop on main. Fix: the resolver retargets non-user-boundary+ ends to the chat's current session; both sides share+ ``_USER_BOUNDARY_END_REASONS`` so they cannot drift again.++2. HIGH — the drain-grace clamp only budgeted drain + 3×teardown, but+ ``RelayAdapter.disconnect`` spends monitor-teardown + go_idle time+ BEFORE the transport drain inside the same runner wait_for. Fix: the+ adapter measures its own elapsed time and threads the REMAINING budget+ into ``transport.disconnect(budget_s=...)``.++3. P1 — a ``_request_response`` racing disconnect could register a future+ after the fail-pending loop and strand its caller for the full+ 30s outbound timeout. Fix: fast-fail when ``_closing`` is set.++4. P1 — ``_build_process_event_source``'s last-resort reconstruction+ omitted ``scope_id``, so a scoped relay completion whose session-store+ origin was unavailable primed no scope discriminator and could still+ bounce off the connector's tenant guard. Fix: thread ``scope_id``+ through the reconstruction (and warn when it's absent for scoped chats).+"""++import asyncio+import os+from datetime import datetime+from types import SimpleNamespace+from unittest.mock import AsyncMock, MagicMock++import pytest++from gateway.config import Platform+from gateway.relay.ws_transport import (+ _DISCONNECT_DRAIN_GRACE_S,+ _TEARDOWN_AWAIT_TIMEOUT_S,+ _disconnect_drain_grace_s,+ WebSocketRelayTransport,+)+from gateway.run import GatewayRunner, _USER_BOUNDARY_END_REASONS+from gateway.session import AsyncSessionStore, SessionEntry+++# ---------------------------------------------------------------------------+# 1. Classifier/resolver coherence (the falsely-acked-loss class)+# ---------------------------------------------------------------------------++def _entry(session_id, session_key="agent:main:slack:dm:U1"):+ return SessionEntry(+ session_key=session_key,+ session_id=session_id,+ created_at=datetime.now(),+ updated_at=datetime.now(),+ platform=Platform.SLACK,+ chat_type="dm",+ )+++def _runner_with_rows(rows, *, switched_entry=None):+ runner = object.__new__(GatewayRunner)+ db = MagicMock()+ db.get_session = AsyncMock(side_effect=lambda session_id: rows.get(session_id))+ db.get_compression_tip = AsyncMock(return_value=None)+ runner._session_db = db+ runner.session_store = MagicMock()+ runner.session_store.switch_session = MagicMock(return_value=switched_entry)+ runner.session_store.advance_compression_session = MagicMock(+ return_value=switched_entry+ )+ runner._async_session_store = AsyncSessionStore(runner.session_store)+ return runner++[email protected]("end_reason", ["idle", "idle_timeout", "timeout", None, ""])+async def test_resolver_retargets_idle_ended_pin_to_current_session(end_reason):+ """The delivery leg the classifier's "deliver" verdict promises: an+ idle-ended pin must resolve to the chat's CURRENT session, not drop."""+ current = _entry("sess_current")+ runner = _runner_with_rows(+ {+ "sess_idle": {+ "id": "sess_idle",+ "ended_at": "2026-08-09T00:00:00",+ "end_reason": end_reason,+ }+ }+ )++ resolved = await runner._resolve_async_delegation_session(+ current, "sess_idle"+ )++ assert resolved is current, (+ f"end_reason={end_reason!r}: idle-ended pin must retarget to the "+ f"chat's current session (got {resolved!r}); dropping here after "+ "the classifier said 'deliver' acks the durable row for a message "+ "that never went out"+ )++[email protected]("end_reason", sorted(_USER_BOUNDARY_END_REASONS))+async def test_resolver_still_drops_user_boundary_ends(end_reason):+ current = _entry("sess_current")+ runner = _runner_with_rows(+ {+ "sess_closed": {+ "id": "sess_closed",+ "ended_at": "2026-08-09T00:00:00",+ "end_reason": end_reason,+ }+ }+ )+ resolved = await runner._resolve_async_delegation_session(+ current, "sess_closed"+ )+ assert resolved is None+++ "end_reason",+ ["idle", "idle_timeout", "timeout", "", None, "agent_close", "cron_complete"],+)+async def test_classifier_and_resolver_agree_on_ended_parents(end_reason):+ """Coherence invariant: whenever the pre-flight classifier says+ "deliver" for an ended parent, the in-pipeline resolver must actually+ deliver (return a session), and when it says "terminal" the resolver+ must drop. Divergence in the deliver->drop direction acks the durable+ row for an injection the pipeline then discards."""+ row = {+ "id": "sess_x",+ "ended_at": "2026-08-09T00:00:00",+ "end_reason": end_reason,+ }+ current = _entry("sess_current")+ runner = _runner_with_rows({"sess_x": row})++ verdict = await runner._classify_completion_target("sess_x")+ resolved = await runner._resolve_async_delegation_session(current, "sess_x")++ if verdict == "deliver":+ assert resolved is not None, (+ f"classifier said deliver for end_reason={end_reason!r} but the "+ "resolver dropped — durable row would be falsely acknowledged"+ )+ elif verdict == "terminal":+ assert resolved is None+++# ---------------------------------------------------------------------------+# 2. Disconnect budget threading (adapter -> transport drain)+# ---------------------------------------------------------------------------++def test_drain_grace_uses_threaded_remaining_budget(monkeypatch):+ """An explicit remaining budget must override the env-mirrored default:+ the adapter has already spent monitor/go_idle time out of the runner's+ wait_for, so the transport can only drain what is actually left."""+ monkeypatch.delenv("HERMES_GATEWAY_ADAPTER_DISCONNECT_TIMEOUT", raising=False)+ reserved = 3 * _TEARDOWN_AWAIT_TIMEOUT_S + 0.5+ # Plenty of remaining budget: grace caps at the constant.+ assert _disconnect_drain_grace_s(100.0) == _DISCONNECT_DRAIN_GRACE_S+ # Exactly reserved left: no drain.+ assert _disconnect_drain_grace_s(reserved) == 0.0+ # Less than reserved / nothing left: clamped to zero, never negative.+ assert _disconnect_drain_grace_s(0.0) == 0.0+ # Partial remainder: drain gets exactly the surplus.+ assert _disconnect_drain_grace_s(reserved + 1.0) == pytest.approx(1.0)+++def test_drain_grace_env_fallback_unchanged(monkeypatch):+ """No threaded budget -> the env-mirrored runner default still applies+ (the original #82592 clamp semantics are preserved)."""+ monkeypatch.setenv("HERMES_GATEWAY_ADAPTER_DISCONNECT_TIMEOUT", "10")+ reserved = 3 * _TEARDOWN_AWAIT_TIMEOUT_S + 0.5+ assert _disconnect_drain_grace_s() == pytest.approx(+ min(_DISCONNECT_DRAIN_GRACE_S, 10.0 - reserved)+ )+++async def test_adapter_disconnect_threads_remaining_budget():+ """RelayAdapter.disconnect must pass budget_s to the transport, and the+ value must be <= the full budget (its own spend subtracted)."""+ from gateway.relay.adapter import RelayAdapter++ adapter = object.__new__(RelayAdapter)+ adapter._revocation_monitor = None++ seen = {}++ class _Transport:+ async def go_idle(self, timeout_s=10.0):+ await asyncio.sleep(0.05)+ return True++ def disconnect(self, budget_s=None):+ seen["budget_s"] = budget_s++ async def _noop():+ return None++ return _noop()++ adapter._transport = _Transport()+ await adapter.disconnect()++ assert "budget_s" in seen, "transport.disconnect never received budget_s"+ from gateway.relay.ws_transport import _env_disconnect_budget_s++ full = _env_disconnect_budget_s()+ assert seen["budget_s"] is not None+ assert seen["budget_s"] <= full+ # go_idle slept 0.05s, so some budget must have been consumed.+ assert seen["budget_s"] < full+++async def test_adapter_disconnect_tolerates_legacy_transport_signature():+ """A transport without the budget_s keyword (stubs) must still be torn+ down through the legacy no-arg call, not crash."""+ from gateway.relay.adapter import RelayAdapter++ adapter = object.__new__(RelayAdapter)+ adapter._revocation_monitor = None+ called = {}++ class _LegacyTransport:+ def disconnect(self): # no budget_s+ called["legacy"] = True++ async def _noop():+ return None++ return _noop()++ adapter._transport = _LegacyTransport()+ await adapter.disconnect()+ assert called.get("legacy") is True+++# ---------------------------------------------------------------------------+# 3. _request_response vs disconnect race+# ---------------------------------------------------------------------------++async def test_request_response_fails_fast_when_closing():+ """A request racing teardown must fail immediately instead of+ registering a future the fail-pending loop may already have missed+ (which would strand the caller for _OUTBOUND_TIMEOUT_S)."""+ transport = object.__new__(WebSocketRelayTransport)+ transport._closing = True+ transport._ws = object() # socket still nominally open+ transport._pending = {}++ result = await transport._request_response({"a": 1})++ assert result == {"success": False, "error": "relay transport closed"}+ assert not transport._pending, (+ "no future may be registered once _closing is set"+ )+++# ---------------------------------------------------------------------------+# 4. scope_id in fallback source reconstruction+# ---------------------------------------------------------------------------++def _fallback_runner():+ runner = object.__new__(GatewayRunner)+ store = MagicMock()+ store._ensure_loaded = MagicMock(side_effect=RuntimeError("store down"))+ store._entries = {}+ runner.session_store = store+ runner._session_sources = None+ return runner+++def test_fallback_source_reconstruction_carries_scope_id():+ """When the session-store origin is unavailable, the reconstructed+ SessionSource must carry the event's scope_id so relay egress priming+ still captures the tenant discriminator."""+ runner = _fallback_runner()+ evt = {+ "session_key": "agent:main:discord:group:C123:U9",+ "platform": "discord",+ "chat_type": "group",+ "chat_id": "C123",+ "user_id": "U9",+ "scope_id": "G777",+ "type": "async_delegation",+ }+ source = runner._build_process_event_source(evt)+ assert source is not None+ assert source.scope_id == "G777"+ assert source.user_id == "U9"+++def test_fallback_source_reconstruction_without_scope_still_routes():+ """Absent scope_id must not fail the reconstruction (DMs and+ author-bound scoped chats still route via user_id)."""+ runner = _fallback_runner()+ evt = {+ "session_key": "agent:main:slack:dm:D42",+ "platform": "slack",+ "chat_type": "dm",+ "chat_id": "D42",+ "user_id": "U1",+ "type": "async_delegation",+ }+ source = runner._build_process_event_source(evt)+ assert source is not None+ assert source.scope_id is None+ assert source.user_id == "U1"+++# ---------------------------------------------------------------------------+# 5. Cancellation-safe pending-future failure (round-3 finding 1)+# ---------------------------------------------------------------------------++def _bare_transport():+ t = object.__new__(WebSocketRelayTransport)+ t._closing = False+ t._supervisor = None+ t._reader = None+ t._ws = None+ t._pending = {}+ t._going_idle_ack = None+ return t+++async def test_disconnect_cancellation_still_fails_pending_futures():+ """A cancellation landing during the drain (outer cleanup deadline,+ runner wait_for) must NOT leave registered futures unresolved — a+ stranded waiter would block until _OUTBOUND_TIMEOUT_S (30s). The+ fail-pending loop runs in a finally, so cancellation cannot skip it."""+ t = _bare_transport()+ loop = asyncio.get_running_loop()+ fut = loop.create_future()+ t._pending["req-1"] = fut++ task = asyncio.create_task(t.disconnect(budget_s=60.0))+ # Let the drain start waiting on the pending future...+ await asyncio.sleep(0.05)+ assert not task.done(), "disconnect should be inside the drain wait"+ # ...then cancel it mid-drain, as the runner's wait_for would.+ task.cancel()+ with pytest.raises(asyncio.CancelledError):+ await task++ assert fut.done(), (+ "pending outbound future left unresolved after cancelled disconnect"+ )+ with pytest.raises(RuntimeError, match="relay transport closed"):+ fut.result()+ assert not t._pending+++async def test_disconnect_idempotent_second_pass():+ """A second disconnect() (adapter and outer cleanup can both run one)+ must be safe: done futures are skipped, cleared map stays cleared."""+ t = _bare_transport()+ await t.disconnect()+ await t.disconnect() # must not raise+ assert not t._pending+++# ---------------------------------------------------------------------------+# 6. Durable routing origin: scope_id survives dispatch -> restart -> replay+# ---------------------------------------------------------------------------++def test_durable_dispatch_persists_and_recovers_scope_id(tmp_path, monkeypatch):+ """End-to-end restart shape: dispatch with a scoped session context bound,+ simulate owner death, recover — the recovered completion event must carry+ scope_id/user_id, and the reconstructed SessionSource must prime them."""+ import tools.async_delegation as ad+ from gateway.session_context import clear_session_vars, set_session_vars++ ad._reset_for_tests()+ monkeypatch.setattr(ad, "_db_path", lambda: tmp_path / "state.db")++ tokens = set_session_vars(+ platform="discord",+ chat_id="C123",+ chat_type="group",+ user_id="U9",+ scope_id="G777",+ session_key="agent:main:discord:group:C123:U9",+ )+ try:+ record = {+ "delegation_id": "d-scope-1",+ "session_key": "agent:main:discord:group:C123:U9",+ "origin_ui_session_id": "",+ "origin_session_id": "",+ "parent_session_id": "sess-p",+ "goal": "scoped goal",+ "dispatched_at": 100.0,+ **ad._capture_routing_origin(),+ }+ assert record.get("scope_id") == "G777", (+ "dispatch-time capture must snapshot HERMES_SESSION_SCOPE_ID"+ )+ ad._persist_dispatch(record)+ finally:+ clear_session_vars(tokens)++ # Simulate the owner process being gone: recovery marks the row unknown+ # and rebuilds the completion event from the durable task_json.+ monkeypatch.setattr("gateway.status._pid_exists", lambda pid: False)+ ad.recover_abandoned_delegations()++ with ad._transaction() as conn:+ row = conn.execute(+ "SELECT event_json FROM async_delegations WHERE delegation_id='d-scope-1'"+ ).fetchone()+ assert row and row[0], "recovered row must have an event_json"+ import json as _json++ evt = _json.loads(row[0])+ assert evt.get("scope_id") == "G777", (+ "recovered completion event lost scope_id — post-restart scoped "+ "relay egress would be declined by the connector's tenant guard"+ )+ assert evt.get("user_id") == "U9"++ # The gateway-side fallback reconstruction must carry it into the source.+ runner = _fallback_runner()+ source = runner._build_process_event_source(evt)+ assert source is not None+ assert source.scope_id == "G777"+ assert source.user_id == "U9"+++def test_live_completion_event_carries_scope_id(tmp_path, monkeypatch):+ """The live (non-restart) completion event must carry the dispatch-time+ routing origin too, so priming works even when the in-memory source+ cache was evicted."""+ import tools.async_delegation as ad++ record = {+ "delegation_id": "d-live-1",+ "session_key": "agent:main:discord:group:C123:U9",+ "scope_id": "G777",+ "user_id": "U9",+ "goal": "g",+ "dispatched_at": 100.0,+ "completed_at": 101.0,+ }++ captured = {}++ class _Q:+ def put(self, evt):+ captured.update(evt)++ class _PR:+ completion_queue = _Q()++ monkeypatch.setattr(ad, "_db_path", lambda: tmp_path / "state.db")+ monkeypatch.setattr(+ "tools.process_registry.process_registry", _PR(), raising=False+ )+ ad._push_completion_event(record, {"summary": "ok"}, "completed")+ assert captured.get("scope_id") == "G777"+ assert captured.get("user_id") == "U9"diff --git a/tests/gateway/test_relay_final_delivery_incident.py b/tests/gateway/test_relay_final_delivery_incident.pynew file mode 100644index 00000000000..906794a3f45--- /dev/null+++ b/tests/gateway/test_relay_final_delivery_incident.py@@ -0,0 +1,152 @@+"""Regression: relay-plane delivery defects (staging incident 2026-08-09).++Defect A — the "skip redundant final edit" branch records ``self._accumulated``+as the delivered turn-final payload even when the last edit that actually+reached the platform was an earlier throttled preview snapshot. The recorded+payload then satisfies ``delivered_final_matches`` and the gateway suppresses+the corrective final send, leaving the user staring at a frozen preview ending+in the streaming cursor.++Contract under test (end-to-end): the payload recorded as *delivered* must be+what was last acknowledged on the wire, so a preview/final mismatch yields+``delivered_final_matches(final) is False`` and the normal final send fires.++Defect B — ``_classify_completion_target`` treats every ended parent session+as terminal unless it ended by compression. Relay-plane sessions end on idle+by design (scale-to-zero); the chat route remains valid, so async delegation+completions must classify "deliver", not be terminally dropped. Explicit user+boundaries (/new -> session_reset / user_exit) stay terminal.+"""++import asyncio+from types import SimpleNamespace++import pytest++from gateway.run import GatewayRunner+from gateway.stream_consumer import GatewayStreamConsumer, StreamConsumerConfig+++# ---------------------------------------------------------------------------+# Defect A: stale preview recorded as delivered final+# ---------------------------------------------------------------------------++class _EditAdapter:+ """Adapter stub: every send/edit succeeds and remembers the last payload."""++ name = "stub"++ def __init__(self):+ self.sent = []++ async def send_message(self, chat_id, content, **kw):+ self.sent.append(content)+ return SimpleNamespace(success=True, message_id="m1")++ async def edit_message(self, chat_id, message_id, content, **kw):+ self.sent.append(content)+ return SimpleNamespace(success=True, message_id=message_id)+++def _consumer(adapter):+ cfg = StreamConsumerConfig(edit_interval=0.01)+ return GatewayStreamConsumer(adapter, "C1", config=cfg)+++async def test_skip_redundant_finalize_records_acked_payload_not_accumulated():+ """The delivered record must reflect the last ACKED edit, so a stale+ preview cannot masquerade as the delivered final (incident class:+ 'It launched but ▉')."""+ adapter = _EditAdapter()+ sc = _consumer(adapter)++ preview = "It launched but"+ final = (+ "It launched but the worker had no credentials, so the check did "+ "not run. The delegates completed; results follow."+ )++ # Simulate: a mid-stream edit delivered the throttled preview snapshot,+ # then the turn finished with more content accumulated and the consumer+ # took the skip-redundant-finalize branch (no further edit issued).+ sc._message_id = "m1"+ sc._last_sent_text = preview + sc.cfg.cursor+ sc._accumulated = final+ sc._mark_skip_redundant_finalize()++ verdict = sc.delivered_final_matches(final)+ assert verdict is False, (+ "stale preview snapshot must NOT be reconciled as the delivered "+ f"final (got verdict={verdict!r}); the normal final send would be "+ "suppressed and the user left with a frozen preview"+ )+++async def test_finalize_edit_success_still_reconciles_true():+ """Control: when the finalize edit actually delivered the full final+ text, reconciliation must remain True (no dup sends regression)."""+ adapter = _EditAdapter()+ sc = _consumer(adapter)+ final = "Complete final answer."+ sc._message_id = "m1"+ sc._last_sent_text = final+ sc._accumulated = final+ sc._mark_skip_redundant_finalize()+ assert sc.delivered_final_matches(final) is True+++# ---------------------------------------------------------------------------+# Defect B: idle-ended relay session terminally drops completions+# ---------------------------------------------------------------------------++class _SessionDB:+ def __init__(self, row):+ self._row = row++ async def get_session(self, session_id):+ return self._row++ async def get_compression_tip(self, session_id):+ return None+++def _classify_runner(row):+ runner = object.__new__(GatewayRunner)+ runner._session_db = _SessionDB(row)+ return runner++[email protected]("end_reason", ["idle_timeout", "timeout", None, ""])+async def test_idle_ended_parent_classifies_deliver(end_reason):+ """Relay-plane norm: session ended on idle, chat still routable ->+ the completion must be deliverable, not terminally dropped."""+ runner = _classify_runner(+ {"ended_at": 1786288000.0, "end_reason": end_reason}+ )+ verdict = await runner._classify_completion_target("sess-idle")+ assert verdict == "deliver", (+ f"end_reason={end_reason!r} must classify 'deliver' "+ f"(got {verdict!r}); completed delegation work was dropped in "+ "staging because idle-ended sessions classified terminal"+ )++[email protected]("end_reason", ["session_reset", "user_exit", "session_switch"])+async def test_user_boundary_still_terminal(end_reason):+ """Explicit user boundaries remain terminal — /new means the user+ closed the thread of work on purpose."""+ runner = _classify_runner(+ {"ended_at": 1786288000.0, "end_reason": end_reason}+ )+ verdict = await runner._classify_completion_target("sess-reset")+ assert verdict == "terminal"+++async def test_unknown_session_still_terminal():+ runner = _classify_runner(None)+ assert await runner._classify_completion_target("gone") == "terminal"diff --git a/tests/gateway/test_relay_injection_egress_priming.py b/tests/gateway/test_relay_injection_egress_priming.pynew file mode 100644index 00000000000..3200c0b3b51--- /dev/null+++ b/tests/gateway/test_relay_injection_egress_priming.py@@ -0,0 +1,189 @@+"""Regression: synthetic injections must prime relay egress routing metadata.++Staging incident 2026-08-09 (defect #4, post-restart replay): restored+async-delegation completions injected fine after the routing fix, but their+egress bounced at the connector — "slack egress declined: target not routed+to an onboarded tenant". The relay adapter re-attaches the tenant+discriminators (metadata.scope_id / metadata.user_id) from per-chat caches+warmed ONLY by the inbound path (_on_inbound -> _capture_scope). Synthetic+completion turns call handle_message directly, so right after a restart the+caches are cold and every reply the injected turn produces is declined by+the fail-closed egress guard until real inbound traffic arrives.++The session-store origin carried on the synthetic event already holds+scope_id/user_id — the fix is priming the adapter's routing caches from the+synthetic event before dispatching it.++Also pins the replay staleness cap: restored completions older than the cap+must be terminally dropped, not replayed as full-context turns (one July+session replayed in August burned a 102K-token context).+"""++import json+import time+from types import SimpleNamespace++import pytest++from gateway.config import Platform+from gateway.relay.adapter import RelayAdapter+from gateway.session import SessionSource+++def _bare_relay_adapter():+ a = object.__new__(RelayAdapter)+ a._scope_by_chat = {}+ a._dm_user_by_chat = {}+ a._platform_by_chat = {}+ a._chat_type_by_chat = {}+ a._last_inbound_ts_by_chat = {}+ return a+++def _synth_event_with_origin():+ source = SessionSource(+ platform=Platform.SLACK,+ chat_id="D0BJTDCSR7C",+ chat_type="dm",+ user_id="U0B5F8EEYAD",+ scope_id="T0AAAA111",+ )+ return SimpleNamespace(source=source, message_id="1786298425.877239")+++def test_prime_routing_cache_warms_egress_discriminators():+ """Priming from a synthetic event must give _with_scope everything the+ connector's egress guard needs — scope_id AND user_id."""+ adapter = _bare_relay_adapter()+ adapter.prime_routing_cache(_synth_event_with_origin())++ meta = adapter._with_scope("D0BJTDCSR7C", None)+ assert meta.get("user_id") == "U0B5F8EEYAD", (+ "DM tenant discriminator missing after priming — egress would be "+ "declined 'not routed to an onboarded tenant' (defect #4)"+ )+ assert meta.get("scope_id") == "T0AAAA111"+++async def test_injection_path_primes_before_handle_message():+ """End-to-end wiring: _inject_watch_notification must call+ prime_routing_cache on the resolved adapter BEFORE handle_message —+ a helper nobody calls fixes nothing."""+ from unittest.mock import AsyncMock+ from gateway.run import GatewayRunner++ calls = []++ class _Adapter:+ name = "relay"++ def fronts_platform(self, platform):+ return platform == Platform.SLACK++ def prime_routing_cache(self, event):+ calls.append(("prime", getattr(event.source, "chat_id", None)))++ async def handle_message(self, event):+ calls.append(("handle", getattr(event.source, "chat_id", None)))++ runner = object.__new__(GatewayRunner)+ runner._running = True+ adapter = _Adapter()+ runner.adapters = {Platform.RELAY: adapter}+ runner.config = SimpleNamespace(platforms={})++ evt = {+ "type": "async_delegation",+ "delegation_id": "deleg_prime_wiring",+ "session_key": "agent:main:slack:dm:D0BJTDCSR7C:1786298425.877239",+ "platform": "slack",+ "chat_type": "dm",+ "chat_id": "D0BJTDCSR7C",+ "status": "completed",+ }+ result = await runner._inject_watch_notification("[done]", evt)+ assert result is True+ assert calls and calls[0][0] == "prime", (+ f"injection path never primed the adapter (calls={calls}) — cold "+ "caches would bounce every post-restart reply at the egress guard"+ )+ assert calls == [("prime", "D0BJTDCSR7C"), ("handle", "D0BJTDCSR7C")]+++def test_prime_routing_cache_never_raises_on_malformed_event():+ adapter = _bare_relay_adapter()+ adapter.prime_routing_cache(SimpleNamespace(source=None))+ adapter.prime_routing_cache(None)+ assert adapter._with_scope("X", {"k": "v"}).get("k") == "v"+++# ---------------------------------------------------------------------------+# Staleness cap on restored completions+# ---------------------------------------------------------------------------++def _isolated_delegation_db(tmp_path, monkeypatch):+ import tools.async_delegation as ad++ monkeypatch.setattr(ad, "_db_path", lambda: tmp_path / "state.db")+ return ad+++def _insert_pending(ad, delegation_id, completed_at):+ evt = {+ "type": "async_delegation",+ "delegation_id": delegation_id,+ "session_key": "agent:main:slack:dm:D1:2",+ "status": "completed",+ }+ with ad._DB_LOCK, ad._transaction() as conn:+ conn.execute(+ """INSERT INTO async_delegations+ (delegation_id, origin_session, origin_ui_session_id,+ parent_session_id, state, dispatched_at, completed_at,+ delivery_state, event_json, updated_at)+ VALUES (?, ?, '', ?, 'completed', ?, ?, 'pending', ?, ?)""",+ (+ delegation_id, "agent:main:slack:dm:D1:2", "parent-1",+ completed_at, completed_at, json.dumps(evt), completed_at,+ ),+ )+++class _Queue:+ def __init__(self):+ self.items = []++ def put(self, item):+ self.items.append(item)+++def test_restore_drops_completions_older_than_replay_cap(_isolated_delegation_db):+ ad = _isolated_delegation_db+ now = time.time()+ _insert_pending(ad, "deleg_fresh", now - 3600)+ # ABSOLUTE age, deliberately NOT derived from the cap constant: a 30-day+ # old completion must never replay, whatever the cap is tuned to.+ _insert_pending(ad, "deleg_stale", now - 30 * 24 * 3600)+ assert ad._MAX_COMPLETION_REPLAY_AGE_S <= 7 * 24 * 3600, (+ "replay cap drifted past a week — the 102K-token stale-replay class "+ "would return"+ )++ q = _Queue()+ restored = ad.restore_undelivered_completions(q)++ ids = [e.get("delegation_id") for e in q.items]+ assert "deleg_fresh" in ids+ assert "deleg_stale" not in ids, (+ "a weeks-old completion was replayed as a fresh full-context turn "+ "(102K-token replay incident class)"+ )+ assert restored == 1+ # The stale row must converge to a terminal state, not replay forever.+ with ad._DB_LOCK, ad._transaction() as conn:+ state = conn.execute(+ "SELECT delivery_state FROM async_delegations WHERE delegation_id='deleg_stale'"+ ).fetchone()[0]+ assert state == "dropped"diff --git a/tests/gateway/test_relay_teardown_drain.py b/tests/gateway/test_relay_teardown_drain.pynew file mode 100644index 00000000000..7731a37eca9--- /dev/null+++ b/tests/gateway/test_relay_teardown_drain.py@@ -0,0 +1,101 @@+"""Regression: relay transport teardown must drain in-flight outbound frames.++Staging incident 2026-08-09 (frozen preview "It launched but ▉"): a trailing+finalize edit was in flight — awaiting its ``outbound_result`` — when the+gateway tore down the relay transport. ``disconnect()`` failed the pending+future immediately with "relay transport closed", so the finalize edit never+reached the platform even though the connector socket was still perfectly+able to serve it.++Contract under test: ``disconnect()`` gives in-flight outbound requests a+bounded grace window to resolve before failing them; requests that resolve+inside the window succeed, and the teardown still completes promptly when+the connector never answers.+"""++import asyncio++import pytest++from gateway.relay.ws_transport import WebSocketRelayTransport+++def _transport():+ t = object.__new__(WebSocketRelayTransport)+ t._closing = False+ t._supervisor = None+ t._reader = None+ t._ws = None+ t._pending = {}+ t._going_idle_ack = None+ return t+++async def test_disconnect_waits_for_inflight_outbound():+ """An outbound frame whose result arrives during teardown must resolve+ successfully, not be failed with 'relay transport closed'."""+ t = _transport()+ fut = asyncio.get_running_loop().create_future()+ t._pending["req-1"] = fut++ async def _connector_answers_soon():+ await asyncio.sleep(0.05)+ if not fut.done():+ fut.set_result({"success": True, "message_id": "m9"})++ answer_task = asyncio.create_task(_connector_answers_soon())+ await t.disconnect()+ await answer_task++ assert fut.done()+ assert fut.exception() is None, (+ "in-flight finalize edit was failed at teardown instead of being "+ "allowed to complete within the drain grace window"+ )+ assert fut.result()["success"] is True+++async def test_disconnect_still_bounded_when_connector_silent():+ """No answer ever arrives: the drain must give up within the grace+ bound and fail the future so callers don't hang."""+ t = _transport()+ fut = asyncio.get_running_loop().create_future()+ t._pending["req-2"] = fut++ started = asyncio.get_running_loop().time()+ await t.disconnect()+ elapsed = asyncio.get_running_loop().time() - started++ assert fut.done() and fut.exception() is not None+ assert elapsed < 10.0, f"teardown took {elapsed:.1f}s — grace must be bounded"+++def test_drain_grace_clamps_to_disconnect_budget(monkeypatch):+ """Drain + the three sequential teardown awaits must fit the runner's+ adapter-disconnect budget (default 5s): grace = budget - 3*1.0s - margin."""+ from gateway.relay import ws_transport as wt++ monkeypatch.delenv("HERMES_GATEWAY_ADAPTER_DISCONNECT_TIMEOUT", raising=False)+ grace = wt._disconnect_drain_grace_s()+ budget = 5.0+ reserved = 3 * wt._TEARDOWN_AWAIT_TIMEOUT_S+ assert grace + reserved < budget, (+ f"grace {grace}s + teardown awaits {reserved}s exceeds the runner's "+ f"{budget}s disconnect budget — wait_for would cancel teardown "+ "mid-drain and skip the fail-pending loop"+ )+ assert grace > 0, "budget default must still leave usable drain time"+++def test_drain_grace_honors_env_budget(monkeypatch):+ from gateway.relay import ws_transport as wt++ monkeypatch.setenv("HERMES_GATEWAY_ADAPTER_DISCONNECT_TIMEOUT", "12")+ assert wt._disconnect_drain_grace_s() == wt._DISCONNECT_DRAIN_GRACE_S+ monkeypatch.setenv("HERMES_GATEWAY_ADAPTER_DISCONNECT_TIMEOUT", "3.5")+ grace = wt._disconnect_drain_grace_s()+ assert 0 <= grace <= 3.5 - 3 * wt._TEARDOWN_AWAIT_TIMEOUT_S+ monkeypatch.setenv("HERMES_GATEWAY_ADAPTER_DISCONNECT_TIMEOUT", "1")+ assert wt._disconnect_drain_grace_s() == 0.0diff --git a/tests/gateway/test_suppression_contract_matrix.py b/tests/gateway/test_suppression_contract_matrix.pynew file mode 100644index 00000000000..e49612c0f1b--- /dev/null+++ b/tests/gateway/test_suppression_contract_matrix.py@@ -0,0 +1,272 @@+"""Contract matrix for the gateway's final-send suppression (#82656).++The gateway skips its own final send when the stream consumer claims the turn+final already reached the user (``gateway/run.py``: ``final_response_sent`` /+``final_content_delivered``, reconciled through ``delivered_final_matches``).+Every incident in this family — #71643 (stale finalize snapshot), #78541+(payload-less multi-message split), #82656 (frozen preview left with a visible+cursor) — is the same failure: the consumer claimed delivery for text the+platform never rendered, so the corrective send was suppressed and the answer+was lost with no retry.++Each of those was fixed with a scenario test pinned to one branch of+``GatewayStreamConsumer.run()``. ``run()``'s ``got_done`` handler now has five+sibling branches that each set the suppression flags and record a turn-final+payload, and nothing checks them as a group — a new branch (or a new early+return in ``_send_or_edit``) can reintroduce the class without failing a test.++This module pins the invariant instead of the branch:++ If the consumer offers the gateway any signal it would trust, the COMPLETE+ final text must have reached the wire.++It drives the real consumer against a matrix of adapter behaviours and asserts+the invariant for every combination, so the guarantee holds no matter which+branch a given scenario happens to take.+"""++import asyncio++import pytest++from gateway.config import Platform, PlatformConfig+from gateway.platforms.base import BasePlatformAdapter, SendResult+from gateway.stream_consumer import GatewayStreamConsumer, StreamConsumerConfig++CURSOR = " ▉"+PREFIX = "Ack received. Starting the deploy now,"+TAIL = " and here is the rest of the answer, generated after the last preview edit."+FULL = PREFIX + TAIL+++# ---------------------------------------------------------------------------+# Adapter behaviours+# ---------------------------------------------------------------------------+#+# A behaviour maps "how many frames have rendered so far" to one of:+# True — the call succeeds and the frame renders+# False — the call fails (flood control, transport error)+# "lie" — the call is ACKed but the frame never renders+#+# The "lie" mode is the transport failure the #82656 report describes: an edit+# the platform accepts and then drops. The consumer advances its bookkeeping+# from the ACK, so it has no way to know.++ALWAYS = lambda rendered: True # noqa: E731+NEVER = lambda rendered: False # noqa: E731+DIES_AFTER_2 = lambda rendered: rendered < 2 # noqa: E731+LIES_AFTER_2 = lambda rendered: True if rendered < 2 else "lie" # noqa: E731+LIES_ALWAYS = lambda rendered: "lie" # noqa: E731++EDIT_BEHAVIOURS = {+ "edit_always": ALWAYS,+ "edit_dies_after_2": DIES_AFTER_2,+ "edit_never": NEVER,+ "edit_lies_after_2": LIES_AFTER_2,+ "edit_lies_always": LIES_ALWAYS,+}+SEND_BEHAVIOURS = {+ "send_always": ALWAYS,+ "send_never": NEVER,+}++# Only a lying edit transport can put a claim on the wire that the consumer+# cannot audit. Those combinations are tracked separately (see+# ``test_lying_edit_transport_is_the_open_gap``) so the honest-transport matrix+# stays a hard guarantee.+LYING_EDITS = {"edit_lies_after_2", "edit_lies_always"}+++class WireAdapter(BasePlatformAdapter):+ """Adapter that records only the frames a user could actually see."""++ def __init__(self, *, edit_behaviour, send_behaviour, prefers_fresh_final):+ super().__init__(PlatformConfig(enabled=True, token="***"), Platform.TELEGRAM)+ self._edit_behaviour = edit_behaviour+ self._send_behaviour = send_behaviour+ self._prefers_fresh_final = prefers_fresh_final+ self.wire = [] # (kind, payload) for every frame that rendered+ self._next_id = 0++ def prefers_fresh_final_streaming(self, text=None) -> bool:+ return self._prefers_fresh_final++ async def connect(self, *, is_reconnect: bool = False) -> bool:+ return True++ async def disconnect(self) -> None:+ return None++ async def get_chat_info(self, chat_id):+ return {}++ async def send_typing(self, chat_id, metadata=None) -> None:+ return None++ async def send(self, chat_id, content, reply_to=None, metadata=None) -> SendResult:+ if self._send_behaviour(len(self.wire)) is not True:+ return SendResult(success=False, error="send rejected")+ self._next_id += 1+ self.wire.append(("send", content))+ return SendResult(success=True, message_id=f"m-{self._next_id}")++ async def edit_message(+ self, chat_id, message_id, content, *, finalize: bool = False, metadata=None+ ) -> SendResult:+ verdict = self._edit_behaviour(len(self.wire))+ if verdict is True:+ self.wire.append(("edit", content))+ return SendResult(success=True, message_id=message_id)+ if verdict == "lie":+ return SendResult(success=True, message_id=message_id)+ return SendResult(success=False, error="flood control")++ async def delete_message(self, chat_id, message_id) -> bool:+ self.wire.append(("delete", message_id))+ return True++ def rendered_complete_answer(self, final_text: str) -> bool:+ """True when some frame the platform rendered carried *final_text*."""+ return any(+ kind in ("send", "edit") and final_text.strip() in payload+ for kind, payload in self.wire+ )+++# ---------------------------------------------------------------------------+# Helpers+# ---------------------------------------------------------------------------+++async def _drive(adapter, *, interrupt: bool):+ """Stream PREFIX then TAIL, then either finish or cancel the consumer."""+ consumer = GatewayStreamConsumer(+ adapter, "chat-1", StreamConsumerConfig(cursor=CURSOR, edit_interval=0.0)+ )+ task = asyncio.create_task(consumer.run())+ for delta in (PREFIX, TAIL):+ consumer.on_delta(delta)+ await asyncio.sleep(0.01)+ if interrupt:+ task.cancel()+ try:+ await task+ except asyncio.CancelledError:+ pass+ else:+ consumer.finish()+ try:+ await asyncio.wait_for(task, timeout=2.0)+ except (asyncio.TimeoutError, asyncio.CancelledError):+ task.cancel()+ return consumer+++def _consumer_claims_final_delivery(consumer, final_text: str) -> bool:+ """Whether the gateway would suppress its normal final send.++ Mirrors the decision in ``gateway/run.py`` (``_stream_confirmed_final_delivery``+ plus the ``_stale_finalized`` reconciliation), which lives inside+ ``_run_agent`` and cannot be imported. Kept deliberately small: a+ ``False`` verdict from ``delivered_final_matches`` vetoes both flags,+ anything else lets them through.+ """+ verdict = consumer.delivered_final_matches(final_text)+ if verdict is False:+ return False+ return bool(consumer.final_response_sent or consumer.final_content_delivered)+++def _scenarios(*, lying_edits: bool):+ for edit_name, edit_behaviour in EDIT_BEHAVIOURS.items():+ if (edit_name in LYING_EDITS) is not lying_edits:+ continue+ for send_name, send_behaviour in SEND_BEHAVIOURS.items():+ for prefers_fresh_final in (False, True):+ for interrupt in (False, True):+ yield pytest.param(+ edit_behaviour,+ send_behaviour,+ prefers_fresh_final,+ interrupt,+ id=f"{edit_name}-{send_name}"+ f"-fresh{int(prefers_fresh_final)}"+ f"-{'interrupted' if interrupt else 'clean'}",+ )+++# ---------------------------------------------------------------------------+# The contract+# ---------------------------------------------------------------------------+++ "edit_behaviour,send_behaviour,prefers_fresh_final,interrupt",+ list(_scenarios(lying_edits=False)),+)+async def test_suppression_requires_the_complete_answer_on_the_wire(+ edit_behaviour, send_behaviour, prefers_fresh_final, interrupt+):+ """No honest-transport scenario may claim delivery it cannot back up.++ This is the guarantee the #71643 / #78541 / #82656 fixes each established+ for one branch. Asserting it across the matrix means a new ``got_done``+ branch, or a new early ``return True`` in ``_send_or_edit``, cannot+ reintroduce the class unnoticed.+ """+ adapter = WireAdapter(+ edit_behaviour=edit_behaviour,+ send_behaviour=send_behaviour,+ prefers_fresh_final=prefers_fresh_final,+ )+ consumer = await _drive(adapter, interrupt=interrupt)++ if _consumer_claims_final_delivery(consumer, FULL):+ assert adapter.rendered_complete_answer(FULL), (+ "consumer claims the turn final was delivered, but no rendered frame "+ "carried the complete answer — the gateway would suppress its final "+ f"send and lose it. flags=(response_sent={consumer.final_response_sent}, "+ f"content_delivered={consumer.final_content_delivered}) "+ f"verdict={consumer.delivered_final_matches(FULL)!r} wire={adapter.wire!r}"+ )+++ "edit_behaviour,send_behaviour,prefers_fresh_final,interrupt",+ list(_scenarios(lying_edits=True)),+)+async def test_lying_edit_transport_is_the_open_gap(+ edit_behaviour, send_behaviour, prefers_fresh_final, interrupt+):+ """An edit ACKed but never rendered can still suppress the final send.++ ``_send_or_edit`` advances ``_last_sent_text`` from the call's return value,+ and every ``got_done`` branch records its turn-final payload from that same+ (or an even more optimistic) source. When the transport ACKs a frame it+ drops, both the recorded payload and the acked text hold the complete+ answer while the screen still shows the cursor-suffixed preview — exactly+ the #82656 report.++ This test documents the remaining exposure rather than asserting it away:+ the invariant is checked, and the scenarios that still violate it are+ reported as expected failures. Closing the gap turns them into passes,+ at which point this test's ``xfail`` branch stops being reached and the+ marker can be dropped along with the fix.+ """+ adapter = WireAdapter(+ edit_behaviour=edit_behaviour,+ send_behaviour=send_behaviour,+ prefers_fresh_final=prefers_fresh_final,+ )+ consumer = await _drive(adapter, interrupt=interrupt)++ claims = _consumer_claims_final_delivery(consumer, FULL)+ rendered = adapter.rendered_complete_answer(FULL)+ if claims and not rendered:+ pytest.xfail(+ "known gap (#82656): claim rests on an ACK the platform dropped; "+ f"wire={adapter.wire!r}"+ )+ assert not claims or rendereddiff --git a/tests/tools/test_restored_delegation_ownership.py b/tests/tools/test_restored_delegation_ownership.pyindex 250650284d9..7c764b4b42a 100644--- a/tests/tools/test_restored_delegation_ownership.py+++ b/tests/tools/test_restored_delegation_ownership.py@@ -1,6 +1,11 @@"""Regression coverage for #64484 — durable-restored delegation completionsmust never be adopted by a session that cannot positively prove ownership.+Fixture timestamps are recent (now-based): restore_undelivered_completions+terminally drops pending completions older than _MAX_COMPLETION_REPLAY_AGE_S,+so epoch-era toy timestamps would exercise the staleness cap instead of the+restored-flag contract under test here.+Layers under test:1. ``restore_undelivered_completions`` stamps every restored event with``restored=True`` (in-memory only).@@ -13,6 +18,7 @@ Layers under test:import jsonimport queue+import timefrom tools.process_registry import ProcessRegistry@@ -41,8 +47,8 @@ def _delegation_event(session_key="", restored=False, delegation_id="d1"):"summary": "SECRET RESULT","api_calls": 3,"duration_seconds": 1.5,- "dispatched_at": 1.0,- "completed_at": 2.0,+ "dispatched_at": time.time() - 2.0,+ "completed_at": time.time() - 1.0,}if restored:evt["restored"] = True@@ -65,7 +71,7 @@ def test_restore_stamps_restored_flag(tmp_path, monkeypatch):"origin_ui_session_id": "","parent_session_id": "OLD_SESSION_A","status": "running",- "dispatched_at": 1.0,+ "dispatched_at": time.time() - 2.0,"completed_at": None,"interrupt_fn": None,}diff --git a/tools/async_delegation.py b/tools/async_delegation.pyindex 3fd08531e0f..4965363a07e 100644--- a/tools/async_delegation.py+++ b/tools/async_delegation.py@@ -83,6 +83,11 @@ _MAX_DURABLE_PENDING = 1000# attempts so an unroutable row converges to a terminal 'dropped' state# instead of replaying on every restart forever._MAX_DELIVERY_ATTEMPTS = 8+# Staleness cap for restart replay: a pending completion older than this is+# terminally dropped instead of re-run as a fresh full-context turn (see+# restore_undelivered_completions). 48h keeps overnight/weekend results+# deliverable while stopping weeks-old sessions from replaying after upgrades.+_MAX_COMPLETION_REPLAY_AGE_S = 48 * 3600.0_DB_LOCK = threading.Lock()# ---------------------------------------------------------------------------@@ -197,6 +202,37 @@ def _transaction() -> Iterator[sqlite3.Connection]:conn.close()+def _capture_routing_origin() -> Dict[str, Any]:+ """Snapshot the dispatching turn's routing origin for the completion event.++ Captured on the PARENT thread at dispatch time (the daemon worker doesn't+ carry the contextvars) and persisted with the durable record, so a+ completion replayed after a restart can reconstruct a full SessionSource+ even when the session-store origin and in-memory source cache are gone.+ scope_id matters most: on a relay-fronted deployment the connector's+ fail-closed egress guard needs the tenant discriminator (or a user+ binding) to route a scoped reply; without it, post-restart scoped+ completions bounce with "target not routed to an onboarded tenant"+ (staging 2026-08-09 defect #4). Best-effort — empty values are simply+ omitted so CLI/contextvar-unaware paths persist nothing new.+ """+ origin: Dict[str, Any] = {}+ try:+ from gateway.session_context import get_session_env++ for evt_key, env_name in (+ ("scope_id", "HERMES_SESSION_SCOPE_ID"),+ ("user_id", "HERMES_SESSION_USER_ID"),+ ("user_name", "HERMES_SESSION_USER_NAME"),+ ):+ value = get_session_env(env_name, "")+ if value:+ origin[evt_key] = value+ except Exception: # noqa: BLE001 - routing origin is additive, never fatal+ pass+ return origin++def _persist_dispatch(record: Dict[str, Any]) -> None:now = time.time()try:@@ -206,7 +242,13 @@ def _persist_dispatch(record: Dict[str, Any]) -> None:owner_started_at = Nonetask_payload = {key: record.get(key)- for key in ("goal", "goals", "context", "toolsets", "role", "model", "is_batch")+ for key in (+ "goal", "goals", "context", "toolsets", "role", "model", "is_batch",+ # Routing origin (scope_id/user_id/user_name): persisted so a+ # restart-recovered completion can reconstruct a full+ # SessionSource — see _capture_routing_origin.+ "scope_id", "user_id", "user_name",+ )if key in record}with _DB_LOCK, _transaction() as conn:@@ -330,6 +372,12 @@ def recover_abandoned_delegations() -> int:"error": "Delegation owner exited before recording a terminal result; outcome unknown.","dispatched_at": dispatched_at, "completed_at": now,}+ # Routing origin persisted at dispatch (see _capture_routing_origin):+ # restores scope_id/user_id for the reconstructed SessionSource so+ # relay egress priming works after a restart.+ for _k in ("scope_id", "user_id", "user_name"):+ if task.get(_k):+ event[_k] = task[_k]result = {"status": "unknown", "summary": None, "error": event["error"]}conn.execute("""UPDATE async_delegations SET state='unknown', completed_at=?,@@ -352,20 +400,48 @@ def restore_undelivered_completions(target_queue) -> int:leave them queued for a consumer that can positively prove ownership,otherwise a brand-new session adopts a dead session's delegationresults seconds after boot (#64484).++ Staleness cap: a pending completion older than+ ``_MAX_COMPLETION_REPLAY_AGE_S`` is terminally dropped instead of+ replayed. Replaying a weeks-old completion re-runs its parent session as+ a full-context turn (a July session replayed in August burned a+ 102K-token context on the staging fleet) for a result nobody is waiting+ on anymore; the payload stays queryable on the dropped row."""recover_abandoned_delegations()+ now = time.time()+ restored = 0with _DB_LOCK, _transaction() as conn:rows = conn.execute(- """SELECT delegation_id, event_json FROM async_delegations+ """SELECT delegation_id, event_json, completed_at, dispatched_at+ FROM async_delegationsWHERE state != 'running' AND delivery_state='pending' AND event_json IS NOT NULLORDER BY completed_at, delegation_id""").fetchall()- for _delegation_id, payload in rows:+ for delegation_id, payload, completed_at, dispatched_at in rows:+ age_basis = completed_at or dispatched_at+ if age_basis and (now - age_basis) > _MAX_COMPLETION_REPLAY_AGE_S:+ conn.execute(+ """UPDATE async_delegations SET delivery_state='dropped',+ delivery_claim=NULL, delivery_claimed_at=NULL,+ updated_at=?+ WHERE delegation_id=? AND delivery_state='pending'""",+ (now, delegation_id),+ )+ logger.warning(+ "Async delegation %s: pending completion is %.1fh old "+ "(cap %.1fh); terminally dropping the replay (result "+ "remains queryable).",+ delegation_id, (now - age_basis) / 3600.0,+ _MAX_COMPLETION_REPLAY_AGE_S / 3600.0,+ )+ continueevt = json.loads(payload)if isinstance(evt, dict):evt["restored"] = Truetarget_queue.put(evt)- return len(rows)+ restored += 1+ return restoreddef mark_completion_delivered(delegation_id: str) -> bool:@@ -745,6 +821,7 @@ def dispatch_async_delegation("origin_ui_session_id": origin_ui_session_id,"origin_session_id": origin_session_id,"parent_session_id": parent_session_id,+ **_capture_routing_origin(),"status": "running","dispatched_at": dispatched_at,"completed_at": None,@@ -908,6 +985,12 @@ def _push_completion_event("completed_at": completed_at,"exit_reason": result.get("exit_reason"),}+ # Routing origin captured at dispatch (see _capture_routing_origin):+ # additive, lets the gateway reconstruct a full SessionSource (incl.+ # scope_id for relay tenant egress) when its own caches are cold.+ for _k in ("scope_id", "user_id", "user_name"):+ if record.get(_k):+ evt[_k] = record[_k]# Structured stall metadata (#51690) — additive, present only on# stall-monitor finalizations.for _k in (@@ -985,6 +1068,7 @@ def dispatch_async_delegation_batch("origin_ui_session_id": origin_ui_session_id,"origin_session_id": origin_session_id,"parent_session_id": parent_session_id,+ **_capture_routing_origin(),"status": "running","dispatched_at": dispatched_at,"completed_at": None,@@ -1117,6 +1201,10 @@ def _push_batch_completion_event("dispatched_at": dispatched_at,"completed_at": completed_at,}+ # Routing origin captured at dispatch (see _capture_routing_origin).+ for _k in ("scope_id", "user_id", "user_name"):+ if event_record.get(_k):+ evt[_k] = event_record[_k]# Structured stall metadata (#51690) — additive, present only on# stall-monitor finalizations.for _k in (