fix(slack): wait for Retry-After before retrying a reply (#8266)

* fix(slack): wait for Retry-After before retrying a reply

chat.postMessage retries at 1s/2s and then drops the reply when Slack
returns HTTP 429. The WebClient default handlers do not retry rate
limits, and the error's Retry-After header was ignored. Wait the longer
of the shared backoff and that hint, capped at 60s per attempt.

* docs(slack): address retry review notes

* docs(slack): drop the changelog hunk

The review of 383a2ec asks to remove the Unreleased entry.
Maintainers add changelog lines at merge time.

* fix(slack): abandon a rate-limited reply when Retry-After exceeds the inline budget

Slack sends run inline on the shared inbound workers, so waiting out a
long Retry-After held a worker other providers need. Cap the inline wait
at 15s; a longer hint re-raises the 429 with a warning instead of
sleeping or retrying early.
This commit is contained in:
alexcastgonz 2026-11-23 07:59:20 -05:00 committed by GitHub
parent b669144246
commit 7287c7945f
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
4 changed files with 237 additions and 0 deletions

View File

@ -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

View File

@ -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:

View File

@ -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())

View File

@ -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.