The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(platforms): photon rides the base send-retry loop; slack/discord parse Retry-After with the shared parser
teknium181d77c280a27
diff --git a/gateway/platforms/base.py b/gateway/platforms/base.pyindex 4206a81cdbf..0f96e8916aa 100644--- a/gateway/platforms/base.py+++ b/gateway/platforms/base.py@@ -3256,7 +3256,7 @@ class BasePlatformAdapter(ABC):async def _send(text: str) -> "SendResult":return await self.send(chat_id=chat_id, content=text, reply_to=reply_to, metadata=metadata)result = await _send(content)- if result.success:+ if result.success or self._send_retry_is_final(result):return resulterror_str = result.error or ""# A rate-limited / flood-capped send is transient: it should back off@@ -3302,6 +3302,8 @@ class BasePlatformAdapter(ABC):logger.info("[%s] Send succeeded on retry %d", self.name, attempt)return resulterror_str = result.error or ""+ if self._send_retry_is_final(result):+ return resultif result.retry_after is not None:server_retry_after = result.retry_after# The failure kind can change between attempts (a transient error may@@ -3345,11 +3347,24 @@ class BasePlatformAdapter(ABC):# rate-limited error never reaches here: it classifies as network above and the# loop only breaks on a non-transient, non-rate-limited error.logger.warning("[%s] Send failed: %s — trying plain-text fallback", self.name, error_str)- fallback_result = await _send(f"(Response formatting failed, plain text:)\n\n{content[:3500]}")+ fallback_result = await self._send_plain_fallback(chat_id, content, reply_to=reply_to, metadata=metadata)if not fallback_result.success:logger.error("[%s] Fallback send also failed: %s", self.name, fallback_result.error)return fallback_result+ def _send_retry_is_final(self, result: "SendResult") -> bool:+ """True when a failed send must be returned as-is: neither a retry nor the plain-text+ fallback can fix it (a structured auth/target refusal). Default: never."""+ return False++ async def _send_plain_fallback(+ self, chat_id: str, content: str, *, reply_to: Optional[str], metadata: Any) -> "SendResult":+ """Last-resort send after a non-transient failure; platforms whose markup is not the+ likely culprit override it (Photon drops rich links instead of adding the banner)."""+ return await self.send(+ chat_id=chat_id, content=f"(Response formatting failed, plain text:)\n\n{content[:3500]}",+ reply_to=reply_to, metadata=metadata)+@staticmethoddef _merge_caption(existing_text: Optional[str], new_text: str) -> str:"""Merge a new caption into existing text unless an identical (stripped) caption alreadydiff --git a/plugins/platforms/discord/adapter.py b/plugins/platforms/discord/adapter.pyindex c6605db0228..a1238237fee 100644--- a/plugins/platforms/discord/adapter.py+++ b/plugins/platforms/discord/adapter.py@@ -31,6 +31,7 @@ from urllib.parse import quote, urljoinfrom agent.async_utils import (consume_detached_task_result as _consume_background_task_result)from agent.display import ToolPreview+from agent.retry_utils import parse_retry_after_secondslogger = logging.getLogger(__name__)@@ -1908,27 +1909,23 @@ class DiscordAdapter(DiscordMediaMixin, BasePlatformAdapter):@staticmethoddef _extract_discord_retry_after(exc: BaseException) -> Optional[float]:+ """Seconds to wait after a 429: discord.py's ``retry_after`` attribute, else the response's+ ``Retry-After`` (numeric or HTTP-date) or Discord-specific ``X-RateLimit-Reset-After``+ header; floored at 1s so a sub-second hint does not hot-loop."""value = getattr(exc, "retry_after", None)if value is not None:+ parsed = parse_retry_after_seconds(value)+ return None if parsed is None else max(1.0, parsed)+ headers = getattr(getattr(exc, "response", None), "headers", None)+ if not headers:+ return None+ parsed = parse_retry_after_seconds(headers)+ if parsed is None:try:- return max(1.0, float(value))- except (TypeError, ValueError):- return None- response = getattr(exc, "response", None)- headers = getattr(response, "headers", None)- if headers:- for key in ("Retry-After", "X-RateLimit-Reset-After"):- try:- raw = headers.get(key)- except Exception:- raw = None- if raw is None:- continue- try:- return max(1.0, float(raw))- except (TypeError, ValueError):- continue- return None+ parsed = parse_retry_after_seconds(headers.get("X-RateLimit-Reset-After"))+ except Exception:+ parsed = None+ return None if parsed is None else max(1.0, parsed)@staticmethoddef _is_discord_rate_limit(exc: BaseException) -> bool:diff --git a/plugins/platforms/photon/adapter.py b/plugins/platforms/photon/adapter.pyindex f509df80a2c..f24b27754e5 100644--- a/plugins/platforms/photon/adapter.py+++ b/plugins/platforms/photon/adapter.py@@ -1315,48 +1315,14 @@ class PhotonAdapter(BasePlatformAdapter):return (isinstance(raw, dict) and raw.get("retryable") is Falseand raw.get("error_class") in ("auth_or_config", "target_not_allowed"))- async def _send_with_retry(self, chat_id: str, content: str, reply_to: Optional[str] = None,- metadata: Any = None, max_retries: int = 1, base_delay: float = 2.0) -> SendResult:- """Retry sends without the generic Markdown banner (replies are markdown or- already-stripped plain text, so it never applies)."""- text = self.format_message(content)-- async def _send() -> SendResult:- return await self.send(chat_id=chat_id, content=text, reply_to=reply_to, metadata=metadata)-- result = await _send()- if result.success:- return result- if self._is_permanent_sidecar_failure(result):- return result # structured failure already carries the user-facing explanation- error_str = result.error or ""- is_network = result.retryable or self._is_retryable_error(error_str)- if not is_network and self._is_timeout_error(error_str):- return result- if is_network:- for attempt in range(1, max_retries + 1):- delay = base_delay * (2 ** (attempt - 1))- logger.warning("[photon] Send failed (attempt %d/%d, retrying in %.1fs): %s",- attempt, max_retries, delay, error_str)- await asyncio.sleep(delay)- result = await _send()- if result.success:- return result- error_str = result.error or ""- if self._is_permanent_sidecar_failure(result):- return result- if not (result.retryable or self._is_retryable_error(error_str)):- break- else:- logger.error("[photon] Failed to deliver response after %d retries: %s", max_retries, error_str)- # Fall through to plain text; for URL-only responses this bypasses richlink()- # so a rich-link outage doesn't strand a sendable URL.- logger.warning("[photon] Send failed: %s - retrying plain-text message", error_str)- fallback_result = await self._sidecar_send(- chat_id, text[: self.MAX_MESSAGE_LENGTH], richlink=False, markdown=False)- if not fallback_result.success:- logger.error("[photon] Plain-text retry also failed: %s", fallback_result.error)- return fallback_result+ def _send_retry_is_final(self, result: SendResult) -> bool:+ return self._is_permanent_sidecar_failure(result) # already carries the user-facing explanation++ async def _send_plain_fallback(self, chat_id: str, content: str, *, reply_to: Optional[str], metadata: Any) -> SendResult:+ """No Markdown banner (replies are markdown or already-stripped plain text); bypass+ richlink() so a rich-link outage doesn't strand a sendable URL."""+ return await self._sidecar_send(+ chat_id, self.format_message(content)[: self.MAX_MESSAGE_LENGTH], richlink=False, markdown=False)async def _post_send(self, path: str, body: Dict[str, Any], *, structured: bool = False) -> SendResult:"""POST a send-like body and wrap the outcome as a SendResult. ``structured`` carriesdiff --git a/plugins/platforms/slack/adapter.py b/plugins/platforms/slack/adapter.pyindex 8c1fe11072e..16da69ef73c 100644--- a/plugins/platforms/slack/adapter.py+++ b/plugins/platforms/slack/adapter.py@@ -32,6 +32,7 @@ from pathlib import Path as _Pathsys.path.insert(0, str(_Path(__file__).resolve().parents[3]))+from agent.retry_utils import parse_retry_after_secondsfrom agent.secret_scope import UnscopedSecretError, get_secretfrom gateway.config import Platform, PlatformConfigfrom gateway.platforms.helpers import MessageDeduplicator@@ -2143,15 +2144,8 @@ class SlackAdapter(BasePlatformAdapter):@staticmethoddef _retry_after_from_exc(e: BaseException) -> Optional[float]:- """``Retry-After`` header (seconds) from an SDK error response, else None."""- _resp = getattr(e, "response", None)- if _resp is None:- return None- try:- _ra = getattr(_resp, "headers", {}).get("Retry-After")- return float(_ra) if _ra is not None else None- except (TypeError, ValueError, AttributeError):- return None+ """``Retry-After`` (seconds or HTTP-date) from an SDK error response, else None."""+ return parse_retry_after_seconds(getattr(getattr(e, "response", None), "headers", None))async def _send_slash_reply(self, chat_id: str, slash_ctx: Dict[str, Any], content: str,diff --git a/tests/gateway/test_send_retry_hooks.py b/tests/gateway/test_send_retry_hooks.pynew file mode 100644index 00000000000..c42e48f77ef--- /dev/null+++ b/tests/gateway/test_send_retry_hooks.py@@ -0,0 +1,100 @@+"""Invariants for the shared send-retry path.++Photon used to fork ``BasePlatformAdapter._send_with_retry`` and so missed three landed fixes+(server ``retry_after`` honoured, the inline wait cap, no failure notice inside a flood penalty).+It now overrides two hooks. Slack and Discord parsed ``Retry-After`` by hand and only understood+the numeric form; both now go through ``agent.retry_utils.parse_retry_after_seconds``.+"""++from email.utils import format_datetime+from datetime import datetime, timedelta, timezone+from types import SimpleNamespace+from typing import Any, Dict++import pytest++from gateway.config import Platform, PlatformConfig+from gateway.platforms.base import BasePlatformAdapter, SendResult+++class _Adapter(BasePlatformAdapter):+ """Sends fail with a scripted list of results; records every call."""++ def __init__(self, results):+ super().__init__(PlatformConfig(enabled=True), Platform.TELEGRAM)+ self._results = list(results)+ self.sent: list = []++ async def connect(self, *, is_reconnect: bool = False) -> bool:+ return True++ async def disconnect(self) -> None:+ pass++ async def get_chat_info(self, chat_id: str) -> Dict[str, Any]:+ return {}++ async def send(self, chat_id, content, reply_to=None, metadata=None) -> SendResult:+ self.sent.append(content)+ return self._results.pop(0) if self._results else SendResult(success=True, message_id="ok")+++class _FinalOnRefusal(_Adapter):+ def _send_retry_is_final(self, result: SendResult) -> bool:+ return isinstance(result.raw_response, dict) and result.raw_response.get("error_class") == "target_not_allowed"+++async def test_final_failure_skips_retry_and_plain_text_fallback(monkeypatch):+ """A structured refusal must come back untouched: no backoff sleep, no second send."""+ slept = []++ async def _sleep(d):+ slept.append(d)+ monkeypatch.setattr("gateway.platforms.base.asyncio.sleep", _sleep)+ refusal = SendResult(success=False, error="Target not allowed", retryable=True,+ raw_response={"error_class": "target_not_allowed", "retryable": False})+ adapter = _FinalOnRefusal([refusal])+ result = await adapter._send_with_retry("c", "hello")+ assert result is refusal+ assert adapter.sent == ["hello"] and slept == []+++async def test_server_retry_after_is_honoured_by_every_adapter(monkeypatch):+ """Photon's fork slept base_delay*2**n regardless of the server hint; via the base every+ adapter waits what the server asked (plus jitter) — the fix that landed once now reaches all."""+ slept = []++ async def _sleep(d):+ slept.append(d)+ monkeypatch.setattr("gateway.platforms.base.asyncio.sleep", _sleep)+ monkeypatch.setattr("gateway.platforms.base.random.uniform", lambda a, b: 0.0)+ adapter = _FinalOnRefusal([SendResult(success=False, error="429 rate limited", retryable=True, retry_after=7.0)])+ result = await adapter._send_with_retry("c", "hello", base_delay=2.0)+ assert result.success and adapter.sent == ["hello", "hello"]+ assert slept == [7.0]+++def _http_date_in(seconds: int) -> str:+ return format_datetime(datetime.now(timezone.utc) + timedelta(seconds=seconds), usegmt=True)+++def test_slack_retry_after_understands_http_date():+ from plugins.platforms.slack.adapter import SlackAdapter+ exc = SimpleNamespace(response=SimpleNamespace(headers={"Retry-After": _http_date_in(90)}))+ seconds = SlackAdapter._retry_after_from_exc(exc)+ assert seconds is not None and 80 <= seconds <= 90+ assert SlackAdapter._retry_after_from_exc(SimpleNamespace(response=None)) is None+++def test_discord_retry_after_understands_http_date_and_reset_after():+ from plugins.platforms.discord.adapter import DiscordAdapter+ extract = DiscordAdapter._extract_discord_retry_after+ dated = SimpleNamespace(response=SimpleNamespace(headers={"retry-after": _http_date_in(90)}))+ seconds = extract(dated)+ assert seconds is not None and 80 <= seconds <= 90+ reset = SimpleNamespace(response=SimpleNamespace(headers={"X-RateLimit-Reset-After": "0.25"}))+ assert extract(reset) == 1.0 # floored: a sub-second hint must not hot-loop+ assert extract(SimpleNamespace(retry_after=12)) == 12.0+ assert extract(SimpleNamespace()) is Nonediff --git a/tests/plugins/platforms/photon/test_overflow_recovery.py b/tests/plugins/platforms/photon/test_overflow_recovery.pyindex 6dff12a131e..ab72732dba1 100644--- a/tests/plugins/platforms/photon/test_overflow_recovery.py+++ b/tests/plugins/platforms/photon/test_overflow_recovery.py@@ -113,7 +113,8 @@ async def test_send_with_retry_uses_structured_retryable_flag(assert result.success is Trueassert result.message_id == "m-2"assert calls == 2- assert sleeps == [0.25]+ # base backoff: base_delay * 2**0 plus up to 1s of jitter+ assert len(sleeps) == 1 and 0.25 <= sleeps[0] <= 1.25# -- Gap 2: typing-indicator cooldown ---------------------------------------