diff --git a/backend/app/channels/AGENTS.md b/backend/app/channels/AGENTS.md index a4e2fbb26d..b3f99b04f0 100644 --- a/backend/app/channels/AGENTS.md +++ b/backend/app/channels/AGENTS.md @@ -40,6 +40,13 @@ make test-blocking-io # channels share the Gate - **Goal handoff pins the saved thread.** Recheck the conversation binding after confirmation delivery and run preparation. Use run-admission evidence when reporting a rejected start or a response lost after submission. +- **Slack does not retry HTTP 429 inside the SDK.** `WebClient` is created with + the default handlers, which cover connection failures only. `SlackChannel.send` + waits for `Retry-After` in the shared channel retry up to 15 seconds; a longer + hint abandons the reply with a log line so it cannot hold a shared inbound + worker. A missing or shorter hint keeps + the 1s/2s backoff. File uploads, connection replies, and the Working-on-it acknowledgment + (`_send_running_reply`) still try once. - **Telegram photo fallback is narrow.** Only a photo `BadRequest` with `PHOTO_INVALID_DIMENSIONS` or `IMAGE_PROCESS_FAILED` is retried, once, as a document with the same bytes, file name and reply target. Other errors and diff --git a/backend/app/channels/slack.py b/backend/app/channels/slack.py index 9274be0b15..72d784c6d6 100644 --- a/backend/app/channels/slack.py +++ b/backend/app/channels/slack.py @@ -5,6 +5,7 @@ from __future__ import annotations import asyncio import html import logging +import math import re from typing import Any from urllib.parse import urlsplit @@ -29,6 +30,11 @@ from deerflow.uploads.manager import is_upload_staging_file, normalize_filename logger = logging.getLogger(__name__) SLACK_STOP_TIMEOUT_SECONDS = 5.0 +# Outbound sends run inline on the shared inbound workers, so a long wait would +# hold a worker that other providers also need. A 429 Retry-After up to this +# budget is waited out; a longer one abandons the reply (logged) instead of +# sleeping, and never retries before Slack allows it. +SLACK_MAX_OUTBOUND_RETRY_DELAY_SECONDS = 15.0 # Match the manager's URL download ceiling. Slack workspace limits may be higher; # this keeps a single upload from exhausting Gateway memory. SLACK_MAX_INBOUND_FILE_BYTES = 50 * 1024 * 1024 @@ -275,6 +281,56 @@ class SlackChannel(Channel): pass raise + def _outbound_retry_delay(self, attempt: int, exc: Exception) -> float: + """Wait out a Slack HTTP 429 before the next ``chat.postMessage``. + + ``WebClient`` keeps the SDK's default handlers, which retry connection + errors only, so a 429 reaches this shared loop. The header is seconds. + A missing or unusable hint keeps ``2**attempt``, and a shorter hint + does not shrink it. A hint above ``SLACK_MAX_OUTBOUND_RETRY_DELAY_SECONDS`` + re-raises the 429 so the shared loop stops retrying: sleeping that long + would occupy a shared inbound worker, and retrying sooner would be + rejected again. + """ + delay = super()._outbound_retry_delay(attempt, exc) + hint = self._slack_retry_after_seconds(exc) + if hint is None: + return delay + if hint > SLACK_MAX_OUTBOUND_RETRY_DELAY_SECONDS: + logger.warning( + "[Slack] Retry-After %ss exceeds the inline wait budget of %ss; abandoning the send", + hint, + SLACK_MAX_OUTBOUND_RETRY_DELAY_SECONDS, + ) + raise exc + return max(delay, hint) + + @staticmethod + def _slack_retry_after_seconds(exc: Exception) -> float | None: + response = getattr(exc, "response", None) + if getattr(response, "status_code", None) != 429: + return None + headers = getattr(response, "headers", None) + items = getattr(headers, "items", None) + if not callable(items): + return None + raw = None + for key, value in items(): + if str(key).lower() == "retry-after": + raw = value + break + if isinstance(raw, (list, tuple)): + raw = raw[0] if raw else None + if raw is None or isinstance(raw, bool): + return None + try: + hint = float(raw) + except (TypeError, ValueError, OverflowError): + return None + if not math.isfinite(hint): + return None + return hint + async def send_file(self, msg: OutboundMessage, attachment: ResolvedAttachment) -> bool: web_client = await self._get_web_client_for_message(msg) if not web_client: diff --git a/backend/tests/test_slack_send_retry_after.py b/backend/tests/test_slack_send_retry_after.py new file mode 100644 index 0000000000..db333bc2d2 --- /dev/null +++ b/backend/tests/test_slack_send_retry_after.py @@ -0,0 +1,173 @@ +"""Slack replies wait for a 429 Retry-After instead of the 1s/2s backoff.""" + +from __future__ import annotations + +import asyncio +from types import SimpleNamespace + +import pytest +from slack_sdk.errors import SlackApiError + +from app.channels.message_bus import MessageBus, OutboundMessage +from app.channels.slack import SLACK_MAX_OUTBOUND_RETRY_DELAY_SECONDS, SlackChannel + + +def _run(coro): + loop = asyncio.new_event_loop() + try: + return loop.run_until_complete(coro) + finally: + loop.close() + + +def _api_error(status_code: int, headers: dict | None): + response = SimpleNamespace(status_code=status_code, headers={} if headers is None else headers) + return SlackApiError("ratelimited", response) + + +def _channel(): + channel = SlackChannel(bus=MessageBus(), config={"bot_token": "xoxb-test", "app_token": "xapp-test"}) + client = SimpleNamespace(posts=[]) + + def chat_postMessage(**kwargs): + client.posts.append(kwargs) + return {"ok": True, "ts": "1.0"} + + client.chat_postMessage = chat_postMessage + channel._web_client = client + return channel, client + + +def _patch_retry_sleep(monkeypatch): + sleeps: list[float] = [] + + async def fake_sleep(delay): + sleeps.append(delay) + + monkeypatch.setattr("app.channels.base.asyncio.sleep", fake_sleep) + return sleeps + + +def _reply(text: str = "hello") -> OutboundMessage: + return OutboundMessage(channel_name="slack", chat_id="C123", thread_id="t1", text=text) + + +def _install(client, failures: list[BaseException]): + real = client.chat_postMessage + pending = list(failures) + + def flaky(**kwargs): + if pending: + raise pending.pop(0) + return real(**kwargs) + + client.chat_postMessage = flaky + + +class TestSlackSendRetryAfter: + def test_rate_limited_reply_waits_for_retry_after(self, monkeypatch): + async def go(): + channel, client = _channel() + sleeps = _patch_retry_sleep(monkeypatch) + _install(client, [_api_error(429, {"Retry-After": "12"})]) + + await channel.send(_reply()) + + assert sleeps == [12.0] + assert [post["text"] for post in client.posts] == ["hello"] + + _run(go()) + + def test_lowercase_header_and_second_hint(self, monkeypatch): + async def go(): + channel, client = _channel() + sleeps = _patch_retry_sleep(monkeypatch) + _install( + client, + [ + _api_error(429, {"retry-after": "5"}), + _api_error(429, {"Retry-After": "8"}), + ], + ) + + await channel.send(_reply("again")) + + assert sleeps == [5.0, 8.0] + assert len(client.posts) == 1 + + _run(go()) + + def test_hint_above_the_budget_abandons_without_sleeping(self, monkeypatch): + async def go(): + channel, client = _channel() + sleeps = _patch_retry_sleep(monkeypatch) + _install(client, [_api_error(429, {"Retry-After": "120"})]) + + with pytest.raises(SlackApiError): + await channel.send(_reply()) + + assert sleeps == [] + assert client.posts == [] + assert SLACK_MAX_OUTBOUND_RETRY_DELAY_SECONDS == 15.0 + + _run(go()) + + def test_hint_at_the_budget_is_still_waited_out(self, monkeypatch): + async def go(): + channel, client = _channel() + sleeps = _patch_retry_sleep(monkeypatch) + _install(client, [_api_error(429, {"Retry-After": "15"})]) + + await channel.send(_reply()) + + assert sleeps == [15.0] + + _run(go()) + + def test_short_hint_does_not_shrink_the_backoff(self, monkeypatch): + async def go(): + channel, client = _channel() + sleeps = _patch_retry_sleep(monkeypatch) + _install(client, [_api_error(429, {"Retry-After": "0.25"})]) + + await channel.send(_reply()) + + assert sleeps == [1.0] + + _run(go()) + + @pytest.mark.parametrize( + "error", + [ + ConnectionError("reset"), + _api_error(429, {}), + _api_error(429, {"Retry-After": "soon"}), + _api_error(429, {"Retry-After": "nan"}), + _api_error(500, {"Retry-After": "40"}), + ], + ) + def test_unusable_hint_keeps_exponential_backoff(self, monkeypatch, error): + async def go(): + channel, client = _channel() + sleeps = _patch_retry_sleep(monkeypatch) + _install(client, [error, error]) + + await channel.send(_reply()) + + assert sleeps == [1, 2] + + _run(go()) + + def test_three_attempts_still_drop_the_reply(self, monkeypatch): + async def go(): + channel, client = _channel() + sleeps = _patch_retry_sleep(monkeypatch) + _install(client, [_api_error(429, {"Retry-After": "15"})] * 3) + + with pytest.raises(SlackApiError): + await channel.send(_reply()) + + assert sleeps == [15.0, 15.0] + assert client.posts == [] + + _run(go()) diff --git a/docs/guide/im-channels.md b/docs/guide/im-channels.md index 9c1f11b255..36fad1f4be 100644 --- a/docs/guide/im-channels.md +++ b/docs/guide/im-channels.md @@ -181,6 +181,7 @@ Notes: - In Telegram private chats, text, attachment and streaming replies (including "Working on it...") can still be delivered if their referenced user or bot message was deleted, such as after clearing chat history during a run. Group reply-target requirements remain unchanged to preserve forum routing. - In Telegram groups, replying to a delivered bot response or attachment continues its DeerFlow conversation. Reply mappings survive restarts and stay scoped to the user's connection when one is bound. New, unrelated group messages still start separate conversations; private-chat routing is unchanged. - New Telegram final-reply sends use the bot API's rate-limit wait up to 60 seconds per retry. Missing, invalid, or shorter hints use the usual backoff. The "Working on it..." acknowledgment is best effort. +- Slack replies that the Web API rejects with HTTP 429 wait for the `Retry-After` header, up to 15 seconds per retry; a longer hint abandons the reply with a log line instead of holding a shared worker. Missing, invalid, or shorter hints use the usual backoff. File uploads, connection replies, and the Working-on-it acknowledgment (`_send_running_reply`) still try once. - Feishu/Lark now queues rapid follow-up messages per mapped DeerFlow `thread_id` instead of immediately surfacing the generic busy reply, and topic replies keep a per-message card with a compact source-message preview across queued/running/final patches. - Streaming IM channels treat backend `error` events like transport failures and follow the same reply and retry path. The channel logs the error type and message for diagnosis.