Skip to content

The agent that grows with you

fix(google-chat): answer a parked-profile HTTP event retryably

unsupportedpastels5ec9bb6b108d
diff --git a/gateway/AGENTS.md b/gateway/AGENTS.md
index 2ffdec619bd..d57799eb29a 100644
--- a/gateway/AGENTS.md
+++ b/gateway/AGENTS.md
@@ -101,7 +101,9 @@ gateway under the backend, and do NOT "fix" update locks by widening the tree-ki
before it; an unresolved identity under multiplexing (route to an unserved profile) is dropped
with one WARNING at the first seam it reaches, never keyed into `agent:main`
(`parked_route_refusal.drop_rejected_route`; a route to a *parked* profile also tells the sender
- in-channel to resend, since a direct bot's update is already confirmed and never redelivered).
+ in-channel to resend, since a direct bot's update is already confirmed and never redelivered; a
+ dispatch its transport has not acknowledged yet, e.g. Google Chat HTTP events, runs in
+ `retryable_ingress()` and answers `ParkedRouteRefused` (503) instead, releasing its dedup claim).
`_transport_owner`, `_authorization_home_for_source`, `_resolve_profile_home_for_source`, `_session_key_profile` and
`_resolve_profile_for_key` read the identity when present and fall back to their old chain only
for sources nothing resolved (restored rows, hand-built sources). Never derive a second answer
diff --git a/gateway/parked_route_refusal.py b/gateway/parked_route_refusal.py
index 76197899e51..988e37b9044 100644
--- a/gateway/parked_route_refusal.py
+++ b/gateway/parked_route_refusal.py
@@ -7,12 +7,48 @@ confirmed the update to its platform before the gateway sees it, so the platform
(Discord's own missed-message backfill, when enabled, can still pick it up after recovery). Holding it
here would be a second inbound queue outside the one durable queue, kept for a profile whose store is
the one that cannot be trusted. So the sender is told, in-channel, to resend, and nothing is admitted.
+
+A transport that answers only after an awaited dispatch (Google Chat HTTP events) has not acknowledged
+the delivery yet: it runs that dispatch in :func:`retryable_ingress` and answers the named, retryable
+:class:`ParkedRouteRefused` instead, so the platform redelivers it.
"""
import asyncio
+import contextvars
import logging
+from contextlib import contextmanager
logger = logging.getLogger(__name__)
+
+class ParkedRouteRefused(Exception):
+ """An unacknowledged delivery routed to a parked profile: nothing was admitted, answer ``status``."""
+ code, status, headers = 'profile_parked', 503, {'Retry-After': '30'}
+
+ def __init__(self):
+ super().__init__('The routed profile is not being served right now; retry this delivery')
+
+
+class _RetryableIngress:
+ def __init__(self):
+ self.open, self.refused = True, False
+
+
+_retryable_ingress = contextvars.ContextVar('parked_route_retryable_ingress', default=None)
+
+
+@contextmanager
+def retryable_ingress():
+ """Scope an awaited dispatch its transport has not acknowledged. A parked route inside it is only
+ recorded (``scope.refused``) for the caller to raise :class:`ParkedRouteRefused`; no in-chat notice.
+ Closed on exit, so a task that outlives the dispatch still refuses in-channel."""
+ scope = _RetryableIngress()
+ token = _retryable_ingress.set(scope)
+ try:
+ yield scope
+ finally:
+ scope.open = False
+ _retryable_ingress.reset(token)
+
# Generic on purpose: the chat is not told which profile the route targets or why it is parked.
# Worded as an outage notice Discord's backfill recognises (``_is_down_notice_content``): the reply
# must not mark the never-admitted message answered, so backfill picks it up once it is served again.
@@ -31,6 +67,13 @@ def drop_rejected_route(adapter, source):
'[%s] Dropping inbound event for %s: explicit profile route targets an unserved profile', name, chat_id)
return
platform = getattr(getattr(source, 'platform', None), 'value', None) or '?'
+ scope = _retryable_ingress.get()
+ if scope is not None and scope.open:
+ scope.refused = True
+ logger.warning(
+ '[%s] Refusing inbound event for %s: routed profile %r on %s is parked (reason=profile_parked); '
+ 'nothing was admitted, the delivery is answered retryably', name, chat_id, profile, platform)
+ return
logger.warning(
'[%s] Refusing inbound event for %s: routed profile %r on %s is parked (reason=profile_parked); '
'nothing was admitted, the sender was asked to resend', name, chat_id, profile, platform)
diff --git a/gateway/platforms/api_server.py b/gateway/platforms/api_server.py
index e400ad2b9c0..b5a4a6387f9 100644
--- a/gateway/platforms/api_server.py
+++ b/gateway/platforms/api_server.py
@@ -158,8 +158,8 @@ from gateway.browser_control_broker import (
ControllerScope, ControllerTicketInvalid, browser_control_developer_mode,
browser_control_protocol_supported, filter_browser_control_capabilities, get_browser_control_broker)
-from gateway.platforms._shared import coerce_port as _coerce_port
-from gateway.platforms._shared import get_scoped_secret as _get_scoped_secret
+from gateway.parked_route_refusal import ParkedRouteRefused
+from gateway.platforms._shared import coerce_port as _coerce_port, get_scoped_secret as _get_scoped_secret
from gateway.platforms.tcp_site import start_tcp_site
from hermes_state_errors import SessionActiveWriteGuardError
@@ -1562,11 +1562,11 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):
return _error_response("Platform event must be a JSON object", 400, code="invalid_request")
try:
result = await dispatcher(payload)
+ except ParkedRouteRefused as exc: # nothing admitted, nothing acknowledged: the platform retries it
+ return _error_response(str(exc), exc.status, err_type="server_error", code=exc.code, headers=exc.headers)
except Exception:
logger.exception("Platform HTTP event dispatch failed for %s", platform_name)
- return _error_response(
- "Platform event dispatch failed", 500, err_type="server_error",
- code="platform_event_dispatch_failed")
+ return _error_response("Platform event dispatch failed", 500, err_type="server_error", code="platform_event_dispatch_failed")
return web.json_response(result if isinstance(result, dict) else {})
# -- Multi-profile multiplexing (/p/<profile>/...) --------------------------------
diff --git a/plugins/platforms/google_chat/adapter.py b/plugins/platforms/google_chat/adapter.py
index 9e4fed8dcdf..0cecf5b3c70 100644
--- a/plugins/platforms/google_chat/adapter.py
+++ b/plugins/platforms/google_chat/adapter.py
@@ -329,6 +329,13 @@ class _ThreadCountStore:
self._save()
return prev
+ def decr(self, chat_id: str, thread_name: str) -> None:
+ """Undo one :meth:`incr` for an inbound that was not admitted; never below zero."""
+ chat_counts = self._counts.get(chat_id, {})
+ if chat_counts.get(thread_name, 0) > 0:
+ chat_counts[thread_name] -= 1
+ self._save()
+
def _save(self) -> None:
"""Atomic write; failure is non-fatal (in-memory counts stay consistent)."""
try:
@@ -858,11 +865,28 @@ class GoogleChatAdapter(BasePlatformAdapter):
message.ack()
async def dispatch_http_event(self, envelope: dict[str, Any]) -> dict[str, Any]:
+ from gateway.parked_route_refusal import ParkedRouteRefused, retryable_ingress
prepared = self._prepare_inbound(envelope)
- if prepared is not None:
+ if prepared is None:
+ return {}
+ # The callback answers after this dispatch, so the delivery is not acknowledged yet: a route
+ # to a parked profile is answered retryably (Google redelivers a non-2xx), not refused in chat.
+ with retryable_ingress() as scope:
await self._dispatch_message(*prepared)
+ if scope.refused:
+ self._release_unadmitted(*prepared)
+ raise ParkedRouteRefused()
return {}
+ def _release_unadmitted(self, msg: dict[str, Any], envelope: dict[str, Any]) -> None:
+ """Undo what ingress recorded for a delivery that was not admitted (its dedup claim and DM
+ thread count), so the platform's redelivery is admitted and read as the first delivery."""
+ self._dedup.discard(msg.get("name") or "")
+ space_name = (envelope.get("space") or msg.get("space") or {}).get("name") or ""
+ thread_name = (msg.get("thread") or {}).get("name") or ""
+ if space_name and thread_name:
+ self._thread_count_store.decr(space_name, thread_name)
+
def verify_http_event_request(self, auth_header: str) -> tuple[bool, str]:
if not self._http_events_audience or not self._http_events_service_account_email:
return False, "google_chat_http_events_not_configured"
diff --git a/tests/gateway/test_parked_route_refusal_google_chat.py b/tests/gateway/test_parked_route_refusal_google_chat.py
new file mode 100644
index 00000000000..e218cc2fe00
--- /dev/null
+++ b/tests/gateway/test_parked_route_refusal_google_chat.py
@@ -0,0 +1,90 @@
+"""A Google Chat HTTP event routed to a parked profile is answered retryably; Pub/Sub is refused in chat.
+
+The HTTP callback awaits the dispatch before it answers, so unlike Pub/Sub (acked on hand-off) the
+delivery is not yet acknowledged: Google retries a failed or non-2xx interaction event. So the
+parked-profile refusal answers 503 and releases the adapter's dedup claim, and the redelivery after
+the rescan is admitted exactly once.
+"""
+import asyncio
+import json
+from types import SimpleNamespace
+from unittest.mock import AsyncMock
+
+import pytest
+
+from gateway.config import Platform, PlatformConfig
+from gateway.platforms.api_server import APIServerAdapter
+from gateway.platforms.base import SendResult
+from gateway.profile_routing import ProfileRoute
+from tests.gateway.test_google_chat import GoogleChatAdapter, _make_chat_envelope
+from tests.gateway.test_parked_profile_ingress import (
+ _admissions, _close, _homes, _runner_with_beta_parked, _serve_beta_again,
+)
+from tests.waiting import async_wait_until
+
+MESSAGE, SPACE, THREAD = 'spaces/S/messages/M.M', 'spaces/S', 'spaces/S/threads/T'
+
+
+async def _shared_chat_bot_with_beta_parked(tmp_path, monkeypatch):
+ homes = _homes(tmp_path, monkeypatch)
+ runner = await _runner_with_beta_parked(
+ tmp_path, monkeypatch, homes,
+ profile_routes=[ProfileRoute(name='to-beta', platform='google_chat', profile='beta', chat_id=SPACE)])
+ monkeypatch.setattr(runner, '_is_user_authorized', lambda *_a, **_k: True) # allowlists are not under test
+ bot = GoogleChatAdapter(PlatformConfig(enabled=True))
+ bot._thread_count_store._path = tmp_path / 'google_chat_thread_counts.json'
+ bot.gateway_runner = runner
+ runner.adapters[Platform('google_chat')] = bot
+ runner._wire_adapter_handlers(bot)
+ bot.send = AsyncMock(return_value=SendResult(success=True, message_id='notice'))
+ bot.verify_http_event_request = lambda header: (True, '')
+ return homes, runner, bot
+
+
+async def _post(bot, envelope):
+ """The real platform-event callback, as Google's HTTP delivery reaches it."""
+ request = SimpleNamespace(match_info={'platform': 'google_chat'}, app={'google_chat_adapter': bot},
+ headers={}, json=AsyncMock(return_value=envelope))
+ response = await object.__new__(APIServerAdapter)._handle_platform_event_callback(request)
+ await asyncio.gather(*list(bot._background_tasks), return_exceptions=True)
+ return response
+
+
+async def test_an_http_event_for_a_parked_profile_is_retried_and_admitted_once(tmp_path, monkeypatch):
+ homes, runner, bot = await _shared_chat_bot_with_beta_parked(tmp_path, monkeypatch)
+ beta = homes[1][1]
+ try:
+ refused = await _post(bot, _make_chat_envelope())
+ assert refused.status == 503, (
+ f'not admitted but acknowledged with {refused.status}: Google will not retry it '
+ f'(dedup holds it: {bot._dedup.contains(MESSAGE)})')
+ assert json.loads(refused.text)['error']['code'] == 'profile_parked', refused.text
+ assert refused.headers.get('Retry-After')
+ assert not bot._dedup.contains(MESSAGE), 'the unadmitted delivery keeps its dedup claim'
+ assert bot.send.await_count == 0, 'Google retries it: no in-chat notice as well'
+ assert _admissions(beta) == 0
+ await _serve_beta_again(runner, beta.resolve())
+ retried = await _post(bot, _make_chat_envelope())
+ assert retried.status == 200, retried.text
+ await async_wait_until(lambda: _admissions(beta) == 1, what='the redelivery admitted')
+ assert (await _post(bot, _make_chat_envelope())).status == 200
+ assert _admissions(beta) == 1, 'the event was admitted more than once'
+ # The redelivery reads the DM thread as the first delivery did (top-level, not a side thread).
+ assert bot._thread_count_store.get(SPACE, THREAD) == 1
+ finally:
+ _close(runner, homes)
+
+
+async def test_a_pubsub_event_for_a_parked_profile_is_still_refused_in_chat(tmp_path, monkeypatch):
+ """Pub/Sub acks on hand-off, so ``_dispatch_message`` (what it submits) tells the sender instead."""
+ homes, runner, bot = await _shared_chat_bot_with_beta_parked(tmp_path, monkeypatch)
+ try:
+ await bot._dispatch_message(*bot._prepare_inbound(_make_chat_envelope(), 'google.workspace.chat.message.v1.created'))
+ await asyncio.gather(*list(bot._background_tasks), return_exceptions=True)
+ assert bot.send.await_count == 1
+ assert bot._dedup.contains(MESSAGE)
+ assert all(_admissions(home) == 0 for _, home in homes)
+ finally:
+ _close(runner, homes)