Skip to content

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

fix(data-warehouse): stop Anthropic report syncs failing on 429 and 400 (#78268)

Tom Owers65071a91ae78
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.py
index 29f65952ed3e..64d769608c20 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
@@ -1,13 +1,16 @@
import hashlib
import dataclasses
-from collections.abc import Callable
+from collections.abc import Callable, Iterator
from datetime import UTC, date, datetime, timedelta
+from functools import partial
from typing import Any, Optional
from requests import Request, Response
+from requests.exceptions import HTTPError
from products.warehouse_sources.backend.temporal.data_imports.sources.anthropic.settings import (
ANTHROPIC_ENDPOINTS,
+ USAGE_GROUP_BY_FALLBACKS,
PaginationType,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
@@ -30,6 +33,12 @@ ANTHROPIC_BASE_URL = "https://api.anthropic.com"
ANTHROPIC_VERSION = "2023-06-01"
# Entity list endpoints allow up to 1000 per page.
ENTITY_PAGE_SIZE = 1000
+# Attempts per request before the client gives up and the activity retries. Above the client
+# default because the report endpoints are rate limited per organization and hand back a 429 with
+# no `Retry-After`: the client then falls back to exponential backoff, and five attempts spend the
+# budget in about fifteen seconds — far short of the window a per-minute limit needs to replenish.
+# Each wait stays capped, so this widens the budget without letting a sync stall indefinitely.
+MAX_RETRY_ATTEMPTS = 8
# Floor for the required `starting_at` on a full refresh. Anthropic launched in 2023, so no usage or
# cost data can predate this — starting here rather than the epoch avoids requesting decades of empty
# buckets while still pulling all available history.
@@ -431,6 +440,39 @@ def _entity_paginator() -> AnthropicCursorPaginator:
return AnthropicCursorPaginator(cursor_path="last_id", cursor_param="after_id")
+def _is_bad_request(exc: HTTPError) -> bool:
+ return exc.response is not None and exc.response.status_code == 400
+
+
+def _iter_narrowing_group_by(
+ build_resource: Callable[[list[str], Optional[dict[str, Any]]], Any],
+ group_by_fallbacks: list[list[str]],
+ initial_paginator_state: Optional[dict[str, Any]],
+) -> Iterator[list[dict[str, Any]]]:
+ """Yield the endpoint's pages, retrying with a narrower `group_by` when the API rejects the query.
+
+ The usage report answers 400 for a query that groups more finely than it will serve, which fails
+ the whole sync rather than returning coarser rows. Each fallback is tried in turn until one is
+ accepted, so the sync lands on the finest breakdown that org's report serves.
+
+ Narrowing happens only while no page has been yielded yet: once rows are out, re-running at a
+ coarser grain would re-emit the same buckets under different synthesized ids. A narrowed query
+ also starts from its own first page, since a resume cursor minted by the wider query no longer
+ addresses anything.
+ """
+ for index, group_by in enumerate(group_by_fallbacks):
+ resume_state = initial_paginator_state if index == 0 else None
+ yielded = False
+ try:
+ for page in build_resource(group_by, resume_state):
+ yielded = True
+ yield page
+ return
+ except HTTPError as exc:
+ if yielded or index == len(group_by_fallbacks) - 1 or not _is_bad_request(exc):
+ raise
+
+
def anthropic_source(
api_key: str,
endpoint: str,
@@ -440,11 +482,14 @@ def anthropic_source(
db_incremental_field_last_value: Optional[Any] = None,
) -> SourceResponse:
config = ANTHROPIC_ENDPOINTS[endpoint]
+ # Set only where the rows come from something other than iterating `resource` once.
+ items: Optional[Callable[[], Iterator[list[dict[str, Any]]]]] = None
client_config: ClientConfig = {
"base_url": ANTHROPIC_BASE_URL,
"headers": _version_headers(),
"auth": _auth_config(api_key),
+ "max_retries": MAX_RETRY_ATTEMPTS,
}
resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
@@ -544,47 +589,13 @@ def anthropic_source(
)
resource = next(r for r in resources if r.name == endpoint)
else:
+ is_report = config.pagination == PaginationType.PAGE
data_map: Optional[Callable[[dict[str, Any]], dict[str, Any] | list[dict[str, Any]]]]
- if config.pagination == PaginationType.PAGE:
- # Report endpoints: `starting_at` is required. On an incremental run start from the
- # watermark (already shifted back by the pipeline's lookback); otherwise fall back to
- # the Anthropic launch date to pull all history.
- params: dict[str, Any] = {"bucket_width": config.bucket_width}
- if config.limit is not None:
- params["limit"] = config.limit
- if config.group_by:
- # requests encodes a list value as one repeated query param per element.
- params["group_by[]"] = config.group_by
- params["starting_at"] = {
- "type": "incremental",
- "cursor_path": "starting_at",
- "initial_value": DEFAULT_STARTING_AT,
- "convert": _format_rfc3339,
- }
- paginator = AnthropicCursorPaginator(cursor_path="next_page", cursor_param="page")
+ if is_report:
data_map = _explode_usage_bucket if endpoint == "usage_report" else _explode_cost_bucket
else:
- params = {"limit": ENTITY_PAGE_SIZE, **config.extra_params}
- paginator = _entity_paginator()
data_map = _flatten_created_by if endpoint == "api_keys" else None
- endpoint_resource: EndpointResource = {
- "name": endpoint,
- "endpoint": {
- "path": config.path,
- "params": params,
- "data_selector": "data",
- "paginator": paginator,
- },
- "data_map": data_map,
- }
-
- rest_config = {
- "client": client_config,
- "resource_defaults": None,
- "resources": [endpoint_resource],
- }
-
initial_paginator_state: Optional[dict[str, Any]] = None
if resume is not None and resume.cursor:
initial_paginator_state = {"cursor": resume.cursor}
@@ -596,18 +607,61 @@ def anthropic_source(
if state and state.get("cursor"):
resumable_source_manager.save_state(AnthropicResumeConfig(cursor=state["cursor"]))
- resource = rest_api_resource(
- rest_config,
- team_id,
- job_id,
- db_incremental_field_last_value,
- resume_hook=save_checkpoint,
- initial_paginator_state=initial_paginator_state,
- )
+ def build_resource(group_by: list[str], resume_state: Optional[dict[str, Any]]) -> Any:
+ if is_report:
+ # Report endpoints: `starting_at` is required. On an incremental run start from the
+ # watermark (already shifted back by the pipeline's lookback); otherwise fall back to
+ # the Anthropic launch date to pull all history.
+ params: dict[str, Any] = {"bucket_width": config.bucket_width}
+ if config.limit is not None:
+ params["limit"] = config.limit
+ if group_by:
+ # requests encodes a list value as one repeated query param per element.
+ params["group_by[]"] = group_by
+ params["starting_at"] = {
+ "type": "incremental",
+ "cursor_path": "starting_at",
+ "initial_value": DEFAULT_STARTING_AT,
+ "convert": _format_rfc3339,
+ }
+ paginator: BasePaginator = AnthropicCursorPaginator(cursor_path="next_page", cursor_param="page")
+ else:
+ params = {"limit": ENTITY_PAGE_SIZE, **config.extra_params}
+ paginator = _entity_paginator()
+
+ endpoint_resource: EndpointResource = {
+ "name": endpoint,
+ "endpoint": {
+ "path": config.path,
+ "params": params,
+ "data_selector": "data",
+ "paginator": paginator,
+ },
+ "data_map": data_map,
+ }
+ rest_config: RESTAPIConfig = {
+ "client": client_config,
+ "resource_defaults": None,
+ "resources": [endpoint_resource],
+ }
+ return rest_api_resource(
+ rest_config,
+ team_id,
+ job_id,
+ db_incremental_field_last_value,
+ resume_hook=save_checkpoint,
+ initial_paginator_state=resume_state,
+ )
+
+ if endpoint == "usage_report":
+ resource = build_resource(USAGE_GROUP_BY_FALLBACKS[0], initial_paginator_state)
+ items = partial(_iter_narrowing_group_by, build_resource, USAGE_GROUP_BY_FALLBACKS, initial_paginator_state)
+ else:
+ resource = build_resource(config.group_by, initial_paginator_state)
return SourceResponse(
name=endpoint,
- items=lambda: resource,
+ items=items if items is not None else (lambda: resource),
primary_keys=config.primary_keys,
# Report buckets return oldest-first from `starting_at`, and entity cursors page forward, so
# rows arrive in ascending order — the pipeline checkpoints the watermark after each batch.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/anthropic/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/anthropic/settings.py
index a18a7badf953..29c70689fabe 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/anthropic/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/anthropic/settings.py
@@ -58,21 +58,42 @@ class AnthropicEndpointConfig:
should_sync_default: bool = True
-# The report endpoints support every group_by the API documents. Requesting the full set gives the
-# richest breakdown; unused dimensions come back null and the row's synthesized `id` still stays
-# unique across the group_by combination.
-_USAGE_GROUP_BY = [
- "account_id",
- "api_key_id",
- "service_account_id",
- "workspace_id",
- "model",
- "service_tier",
- "context_window",
- "inference_geo",
+# The usage report rejects a query whose `group_by` fans out further than it will serve, answering
+# 400 for the whole request rather than a truncated page — and the ceiling is not documented, so it
+# can't be picked up front. These are the group_by sets to try in order, richest first: the source
+# drops to the next one when the API rejects the request, so a sync lands on the finest breakdown
+# that org's report will actually serve instead of failing. Unused dimensions come back null and the
+# row's synthesized `id` stays unique across whichever combination was accepted.
+USAGE_GROUP_BY_FALLBACKS: list[list[str]] = [
+ [
+ "account_id",
+ "api_key_id",
+ "service_account_id",
+ "workspace_id",
+ "model",
+ "service_tier",
+ "context_window",
+ "inference_geo",
+ ],
+ # Without the per-actor dimensions, which multiply out fastest.
+ ["workspace_id", "model", "service_tier", "context_window", "inference_geo"],
+ # The breakdown the cost report already serves at this bucket width.
+ ["workspace_id", "model"],
+ # Bucket totals only — the narrowest query the endpoint can be asked for.
+ [],
]
+_USAGE_GROUP_BY = USAGE_GROUP_BY_FALLBACKS[0]
_COST_GROUP_BY = ["workspace_id", "description"]
+# Time buckets per cost report page, at the documented `1d` maximum. The report endpoints are the
+# rate-limited part of this source — Anthropic supports polling them about once a minute for
+# sustained use — and every page is one request, so walking history at the API's default of 7
+# buckets spends more than four times the request budget for the same rows. The usage report keeps
+# the smaller page: its rows are already multiplied out by `group_by`, so a wider window there buys
+# fewer requests at the cost of a coarser breakdown.
+COST_REPORT_PAGE_BUCKETS = 31
+USAGE_REPORT_PAGE_BUCKETS = 7
+
# One day of restated buckets is re-pulled on every incremental run. Anthropic notes usage/cost data
# lands a few minutes after requests complete and a day's bucket keeps accumulating until it closes,
# so a trailing day covers late arrivals; merge dedupes the overlap on the synthesized `id`.
@@ -141,10 +162,7 @@ ANTHROPIC_ENDPOINTS: dict[str, AnthropicEndpointConfig] = {
incremental_fields=[_datetime_incremental_field("starting_at")],
bucket_width="1d",
group_by=_USAGE_GROUP_BY,
- # Grouping by every dimension multiplies the result rows per bucket, so requesting the
- # 31-bucket max overflows the report's per-response result cap and the API 400s. The API
- # default keeps each page small; pagination still walks all history via `next_page`.
- limit=7,
+ limit=USAGE_REPORT_PAGE_BUCKETS,
default_incremental_lookback_seconds=_REPORT_LOOKBACK_SECONDS,
),
"cost_report": AnthropicEndpointConfig(
@@ -157,6 +175,7 @@ ANTHROPIC_ENDPOINTS: dict[str, AnthropicEndpointConfig] = {
incremental_fields=[_datetime_incremental_field("starting_at")],
bucket_width="1d", # cost report only supports daily granularity
group_by=_COST_GROUP_BY,
+ limit=COST_REPORT_PAGE_BUCKETS,
default_incremental_lookback_seconds=_REPORT_LOOKBACK_SECONDS,
),
# Claude Code analytics: one record per user per day. The endpoint windows on a single `starting_at`
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.py
index 6f1dde2ec323..9f6ecf76c297 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
@@ -12,6 +12,7 @@ from requests import Request, Response
from products.warehouse_sources.backend.temporal.data_imports.sources.anthropic.anthropic import (
ANTHROPIC_VERSION,
DEFAULT_CLAUDE_CODE_START,
+ MAX_RETRY_ATTEMPTS,
AnthropicResumeConfig,
ClaudeCodeDayPaginator,
_claude_code_start_day,
@@ -23,7 +24,12 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.anthropic.
anthropic_source,
validate_credentials,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.anthropic.settings import ANTHROPIC_ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.anthropic.settings import (
+ ANTHROPIC_ENDPOINTS,
+ COST_REPORT_PAGE_BUCKETS,
+ USAGE_GROUP_BY_FALLBACKS,
+ USAGE_REPORT_PAGE_BUCKETS,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.anthropic.source import AnthropicSource
# RESTClient builds its session via make_tracked_session in the rest_client module.
@@ -178,7 +184,7 @@ class TestReportParams:
config = ANTHROPIC_ENDPOINTS["usage_report"]
assert params[0]["params"]["starting_at"] == "2026-03-04T00:00:00Z"
assert params[0]["params"]["bucket_width"] == "1d"
- assert params[0]["params"]["limit"] == 7
+ assert params[0]["params"]["limit"] == USAGE_REPORT_PAGE_BUCKETS
# requests encodes the list as one repeated group_by[] query param per dimension.
assert params[0]["params"]["group_by[]"] == config.group_by
@@ -193,13 +199,17 @@ class TestReportParams:
assert params[0]["params"]["starting_at"] == "2023-01-01T00:00:00Z"
- def test_usage_report_page_size_stays_below_bucket_max(self) -> None:
- # Grouping by every dimension multiplies the results per bucket, so requesting the 31-bucket
- # max overflows the per-response result cap and the API 400s. Keep the page small while still
- # grouping by the full set; pagination walks the rest.
- config = ANTHROPIC_ENDPOINTS["usage_report"]
- assert len(config.group_by) == 8
- assert config.limit is not None and config.limit <= 7
+ def test_cost_report_pages_at_the_bucket_max(self) -> None:
+ # Every page is one request against a per-organization rate limit, so leaving the cost
+ # report on the API's default page walks history in four times as many requests.
+ assert ANTHROPIC_ENDPOINTS["cost_report"].limit == COST_REPORT_PAGE_BUCKETS == 31
+
+ def test_usage_group_by_fallbacks_narrow_to_nothing(self) -> None:
+ # The list is walked in order when the API rejects a query, so each step must be strictly
+ # narrower than the last and the final one must be a query the endpoint cannot refuse.
+ steps = list(zip(USAGE_GROUP_BY_FALLBACKS, USAGE_GROUP_BY_FALLBACKS[1:]))
+ assert steps and all(set(later) < set(earlier) for earlier, later in steps)
+ assert USAGE_GROUP_BY_FALLBACKS[-1] == []
@mock.patch(CLIENT_SESSION_PATCH)
def test_version_header_is_set_on_session(self, MockSession) -> None:
@@ -533,6 +543,93 @@ class TestRetries:
_rows(_source("users", _make_manager()))
assert session.send.call_count == 1
+ @mock.patch("tenacity.nap.time.sleep")
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_rate_limit_budget_outlasts_the_default(self, MockSession, _mock_sleep) -> None:
+ # The report endpoints 429 without a Retry-After, so the client falls back to exponential
+ # backoff; the default budget is spent in seconds, well short of a per-minute limit window.
+ session = MockSession.return_value
+ _wire(
+ session,
+ [
+ *[_response({}, status=429) for _ in range(MAX_RETRY_ATTEMPTS - 1)],
+ _entity_page([{"id": "user_1"}], has_more=False, last_id="user_1"),
+ ],
+ )
+
+ rows = _rows(_source("users", _make_manager()))
+
+ assert [r["id"] for r in rows] == ["user_1"]
+ assert session.send.call_count == MAX_RETRY_ATTEMPTS
+
+
+class TestUsageReportGroupByFallback:
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_rejected_query_is_retried_with_a_narrower_group_by(self, MockSession) -> None:
+ # The usage report 400s a query that groups more finely than it will serve. Narrowing must
+ # keep the sync alive and still deliver rows, at the finest breakdown the API accepts.
+ session = MockSession.return_value
+ params = _wire(
+ session,
+ [
+ _response({"error": "bad request"}, status=400),
+ _report_page(
+ [{"starting_at": "2025-08-01T00:00:00Z", "results": [{"workspace_id": "wrkspc_1"}]}],
+ has_more=False,
+ next_page=None,
+ ),
+ ],
+ )
+
+ rows = _rows(_source("usage_report", _make_manager()))
+
+ assert [r["workspace_id"] for r in rows] == ["wrkspc_1"]
+ assert [p["params"]["group_by[]"] for p in params] == USAGE_GROUP_BY_FALLBACKS[:2]
+
+ @parameterized.expand(
+ [
+ # Every fallback rejected: there is nothing narrower left to try.
+ (
+ "all_rejected",
+ [_response({}, status=400) for _ in USAGE_GROUP_BY_FALLBACKS],
+ len(USAGE_GROUP_BY_FALLBACKS),
+ ),
+ # A 404 is not the API refusing the breakdown, so narrowing must not paper over it.
+ ("not_a_bad_request", [_response({}, status=404)], 1),
+ ]
+ )
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_error_propagates_instead_of_narrowing(
+ self, _name: str, responses: list[Response], expected_requests: int, MockSession
+ ) -> None:
+ session = MockSession.return_value
+ _wire(session, responses)
+
+ with pytest.raises(requests.HTTPError):
+ _rows(_source("usage_report", _make_manager()))
+ assert session.send.call_count == expected_requests
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_rejection_after_rows_are_out_is_not_narrowed(self, MockSession) -> None:
+ # Re-running at a coarser grain would re-emit the buckets already yielded under different
+ # synthesized ids, so once rows are out the 400 has to fail the sync instead.
+ session = MockSession.return_value
+ _wire(
+ session,
+ [
+ _report_page(
+ [{"starting_at": "2025-08-01T00:00:00Z", "results": [{"workspace_id": "wrkspc_1"}]}],
+ has_more=True,
+ next_page="page_2",
+ ),
+ _response({"error": "bad request"}, status=400),
+ ],
+ )
+
+ with pytest.raises(requests.HTTPError):
+ _rows(_source("usage_report", _make_manager()))
+ assert session.send.call_count == 2
+
class TestValidateCredentials:
@parameterized.expand([("ok", 200, True), ("forbidden_scope", 403, True), ("unauthorized", 401, False)])
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/rest_client.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/rest_client.py
index a93bd7f3dbc3..05d301769cbd 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/rest_client.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/rest_client.py
@@ -103,16 +103,44 @@ def _effective_port(scheme: str, port: Optional[int]) -> Optional[int]:
return _DEFAULT_PORTS.get(scheme)
+def _seconds_from_epoch_reset(value: str) -> Optional[float]:
+ try:
+ reset_epoch = int(value)
+ except ValueError:
+ return None
+ return reset_epoch - datetime.now(UTC).timestamp()
+
+
+def _seconds_from_rfc3339_reset(value: str) -> Optional[float]:
+ try:
+ reset_at = datetime.fromisoformat(value.strip().replace("Z", "+00:00"))
+ except ValueError:
+ return None
+ if reset_at.tzinfo is None:
+ reset_at = reset_at.replace(tzinfo=UTC)
+ return (reset_at - datetime.now(UTC)).total_seconds()
+
+
+# Rate-limit reset headers to fall back on when a 429 carries no ``Retry-After``, each paired with
+# the parser that turns its value into "seconds from now until the budget replenishes".
+_RATE_LIMIT_RESET_HEADERS: tuple[tuple[str, Callable[[str], Optional[float]]], ...] = (
+ # Anthropic rate limits per organization and documents this RFC 3339 instant as when the request
+ # budget replenishes. Its Admin API (the usage/cost report endpoints an Anthropic source pages
+ # through) answers 429 without a ``Retry-After``, so this is the only delay it advertises.
+ ("anthropic-ratelimit-requests-reset", _seconds_from_rfc3339_reset),
+ # Sentry signals its rate-limit window with a UNIX epoch timestamp rather than ``Retry-After``,
+ # and Sentry's flat / fan-out endpoints (e.g. ``project_users``) sync through this client too.
+ ("X-Sentry-Rate-Limit-Reset", _seconds_from_epoch_reset),
+)
+
+
def _parse_retry_after(response: Response) -> Optional[float]:
"""Best-effort retry delay (seconds) from a rate-limited / erroring response.
- Honors the standard ``Retry-After`` header (delta-seconds or HTTP-date)
- first. When it's absent, falls back to Sentry's ``X-Sentry-Rate-Limit-Reset``
- (a UNIX epoch timestamp): Sentry's API signals its rate-limit window with
- that header rather than ``Retry-After``, and Sentry's flat / fan-out
- endpoints (e.g. ``project_users``) sync through this generic client, so
- without it a 429 backs off on the short exponential fallback and exhausts
- retries while still rate-limited. Capped at ``MAX_RETRY_AFTER_SECONDS``.
+ Honors the standard ``Retry-After`` header (delta-seconds or HTTP-date) first, then the
+ vendor rate-limit reset headers in ``_RATE_LIMIT_RESET_HEADERS``. Without a server-provided
+ delay a 429 backs off on the short exponential fallback and the attempt budget is spent long
+ before the limit window clears. Capped at ``MAX_RETRY_AFTER_SECONDS``.
"""
retry_after_header = response.headers.get("Retry-After")
if retry_after_header:
@@ -125,16 +153,16 @@ def _parse_retry_after(response: Response) -> Optional[float]:
return None
return min(max(0.0, (dt - datetime.now(UTC)).total_seconds()), MAX_RETRY_AFTER_SECONDS)
- reset_header = response.headers.get("X-Sentry-Rate-Limit-Reset")
- if reset_header:
- try:
- reset_epoch = int(reset_header)
- except ValueError:
- return None
- wait_seconds = reset_epoch - int(datetime.now(UTC).timestamp())
- if wait_seconds <= 0:
+ for header, parse in _RATE_LIMIT_RESET_HEADERS:
+ value = response.headers.get(header)
+ if not value:
+ continue
+ wait_seconds = parse(value)
+ # A reset already in the past says the window has cleared — nothing to honor, so fall
+ # through to the caller's exponential backoff rather than retrying with no delay at all.
+ if wait_seconds is None or wait_seconds <= 0:
return None
- return min(float(wait_seconds), MAX_RETRY_AFTER_SECONDS)
+ return min(wait_seconds, MAX_RETRY_AFTER_SECONDS)
return None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_rest_client.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_rest_client.py
index b75c81e62014..7acbe27115d8 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_rest_client.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_rest_client.py
@@ -5,6 +5,7 @@ from typing import Any
import pytest
from unittest.mock import MagicMock, patch
+from parameterized import parameterized
from requests import Response
from requests.exceptions import ChunkedEncodingError, ProxyError, ReadTimeout
@@ -660,6 +661,32 @@ class TestRESTClient:
assert pages == [[{"id": 1}]]
mock_sleep.assert_called_once_with(12.0)
+ @parameterized.expand(
+ [
+ ("rfc3339_utc", "2026-03-06T12:00:45Z", 45.0),
+ ("rfc3339_offset", "2026-03-06T12:01:00+00:00", 60.0),
+ ("capped", "2027-03-06T12:00:00Z", MAX_RETRY_AFTER_SECONDS),
+ # A window that has already cleared, or a value we can't read, tells us nothing — the
+ # caller falls back to exponential backoff rather than retrying with no delay at all.
+ ("already_elapsed", "2026-03-06T11:59:55Z", None),
+ ("unparseable", "in a bit", None),
+ ]
+ )
+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.datetime")
+ def test_parse_retry_after_honors_anthropic_rate_limit_reset(
+ self, _name: str, header_value: str, expected: float | None, mock_datetime
+ ) -> None:
+ # Anthropic rate limits its Admin API per organization but answers 429 without a
+ # ``Retry-After``; this RFC 3339 reset instant is the only delay it advertises, and without
+ # it a rate-limited report sync spends its whole attempt budget inside a few seconds.
+ mock_datetime.now.return_value = datetime(2026, 3, 6, 12, 0, 0, tzinfo=UTC)
+ mock_datetime.fromisoformat = datetime.fromisoformat
+
+ response = _make_response({"error": "rate limited"}, status_code=429)
+ response.headers["anthropic-ratelimit-requests-reset"] = header_value
+
+ assert _parse_retry_after(response) == expected
+
@patch("products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.datetime")
def test_parse_retry_after_caps_sentry_reset_header(self, mock_datetime) -> None:
# A reset far in the future must be clamped to MAX_RETRY_AFTER_SECONDS.