:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(data-imports): honor Anthropic Retry-After on 429s (#70811)
Tom Owers3e00e64f3fa7
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/anthropic/anthropic.py b/products/warehouse_sources/backend/temporal/data_imports/sources/anthropic/anthropic.pyindex 9f6740f4c563..e1c2bf0f341a 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/anthropic/anthropic.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/anthropic/anthropic.py@@ -7,7 +7,7 @@ from urllib.parse import urlencodeimport requestsfrom structlog.types import FilteringBoundLogger-from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter+from tenacity import RetryCallState, retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitterfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.batcher import Batcherfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse@@ -30,7 +30,37 @@ DEFAULT_STARTING_AT = datetime(2023, 1, 1, tzinfo=UTC)class AnthropicRetryableError(Exception):- pass+ def __init__(self, message: str, retry_after: float | None = None) -> None:+ super().__init__(message)+ # Seconds the server asked us to wait (from a 429 `Retry-After`), or None to back off blindly.+ self.retry_after = retry_after+++# The report endpoints (usage_report/cost_report) are strictly rate limited and return a `Retry-After`+# on 429. Cap the honored value so a pathological header can't pin the worker; the pipeline retries the+# activity above us if the window is genuinely longer.+_MAX_RETRY_AFTER_SECONDS = 60+_fallback_wait = wait_exponential_jitter(initial=1, max=30)+++def _parse_retry_after(value: str | None) -> float | None:+ """Parse a `Retry-After` header expressed as delta-seconds (Anthropic's form). Returns None for a+ missing, non-numeric, or negative value so the caller falls back to exponential backoff."""+ if value is None:+ return None+ try:+ seconds = float(value)+ except (TypeError, ValueError):+ return None+ return seconds if seconds >= 0 else None+++def _wait_anthropic(retry_state: RetryCallState) -> float:+ """Honor the server's `Retry-After` on 429s (capped), else fall back to exponential jitter."""+ exc = retry_state.outcome.exception() if retry_state.outcome else None+ if isinstance(exc, AnthropicRetryableError) and exc.retry_after is not None:+ return min(exc.retry_after, _MAX_RETRY_AFTER_SECONDS)+ return _fallback_wait(retry_state)@dataclasses.dataclass@@ -84,14 +114,18 @@ def _build_url(path: str, params: dict[str, Any], multi_params: dict[str, list[s)),stop=stop_after_attempt(5),- wait=wait_exponential_jitter(initial=1, max=30),+ wait=_wait_anthropic,reraise=True,)def _fetch_page(session: requests.Session, url: str, headers: dict[str, str], logger: FilteringBoundLogger) -> dict:response = session.get(url, headers=headers, timeout=60)if response.status_code == 429 or response.status_code >= 500:- raise AnthropicRetryableError(f"Anthropic API error (retryable): status={response.status_code}, url={url}")+ retry_after = _parse_retry_after(response.headers.get("retry-after")) if response.status_code == 429 else None+ raise AnthropicRetryableError(+ f"Anthropic API error (retryable): status={response.status_code}, url={url}",+ retry_after=retry_after,+ )if not response.ok:logger.error(f"Anthropic API error: status={response.status_code}, body={response.text}, url={url}")diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/anthropic/tests/test_anthropic.py b/products/warehouse_sources/backend/temporal/data_imports/sources/anthropic/tests/test_anthropic.pyindex b159e9249c9f..83566a97dd3b 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/anthropic/tests/test_anthropic.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/anthropic/tests/test_anthropic.py@@ -1,20 +1,25 @@from datetime import UTC, datetime-from typing import Any+from typing import Any, castimport pytestfrom unittest.mock import MagicMock, patchimport requestsfrom parameterized import parameterized+from tenacity import RetryCallStatefrom products.warehouse_sources.backend.temporal.data_imports.sources.anthropic import anthropicfrom products.warehouse_sources.backend.temporal.data_imports.sources.anthropic.anthropic import (+ _MAX_RETRY_AFTER_SECONDS,AnthropicResumeConfig,+ AnthropicRetryableError,_build_url,_flatten_cost_result,_flatten_usage_result,+ _parse_retry_after,_report_params,_row_id,+ _wait_anthropic,get_rows,validate_credentials,)@@ -326,3 +331,51 @@ class TestFetchPage:with pytest.raises(requests.HTTPError):anthropic._fetch_page(session, "https://api.anthropic.com/v1/organizations/users", {}, MagicMock())assert session.get.call_count == 1+++class _FakeRetryState:+ def __init__(self, exc: Exception | None, attempt_number: int = 1) -> None:+ self.outcome = MagicMock()+ self.outcome.exception.return_value = exc+ self.attempt_number = attempt_number+++class TestRetryAfter:+ @parameterized.expand(+ [+ ("delta_seconds", "45", 45.0),+ ("zero", "0", 0.0),+ ("missing", None, None),+ ("non_numeric", "in a while", None),+ ("negative", "-5", None),+ ]+ )+ def test_parse_retry_after(self, _name: str, header: str | None, expected: float | None) -> None:+ assert _parse_retry_after(header) == expected++ def test_fetch_page_attaches_retry_after_from_header(self) -> None:+ # The rate-limited report endpoints tell us exactly when the window resets; that value must+ # survive onto the exception so the wait strategy can honor it instead of guessing.+ response = MagicMock(status_code=429, ok=False, headers={"retry-after": "45"})+ session = MagicMock()+ session.get.return_value = response+ with patch.object(anthropic._fetch_page.retry, "sleep", lambda *_: None): # type: ignore[attr-defined]+ with pytest.raises(AnthropicRetryableError) as exc_info:+ anthropic._fetch_page(+ session, "https://api.anthropic.com/v1/organizations/cost_report", {}, MagicMock()+ )+ assert exc_info.value.retry_after == 45.0++ def test_wait_honors_retry_after_capped(self) -> None:+ state = _FakeRetryState(AnthropicRetryableError("rate limited", retry_after=45.0))+ assert _wait_anthropic(cast(RetryCallState, state)) == 45.0+ # A server asking for longer than the cap is clamped so it can't wedge the worker.+ capped = _FakeRetryState(AnthropicRetryableError("rate limited", retry_after=6000.0))+ assert _wait_anthropic(cast(RetryCallState, capped)) == _MAX_RETRY_AFTER_SECONDS++ def test_wait_falls_back_when_no_retry_after(self) -> None:+ # No header (e.g. a 5xx) → blind exponential backoff, never a crash on the missing value.+ state = _FakeRetryState(AnthropicRetryableError("server error"), attempt_number=1)+ wait = _wait_anthropic(cast(RetryCallState, state))+ assert isinstance(wait, float)+ assert wait >= 0