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(warehouse): make anthropic service_accounts and usage_report sync survive (#80258)

posthog[bot]02c53355f7f5
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 64d769608c20..f7d9eac7ec5c 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
@@ -33,12 +33,18 @@ 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.
+# Attempts per request for the entity list endpoints (users, workspaces, api_keys, ...). They are
+# not organization-rate-limited, so a modest budget above the client default is enough to ride out
+# a transient blip without letting a genuinely broken endpoint retry for long.
MAX_RETRY_ATTEMPTS = 8
+# The usage/cost/analytics report endpoints share one organization-level rate limit on Anthropic's
+# Admin API, which answers 429 with no `Retry-After`. The `anthropic-ratelimit-requests-reset`
+# instant is often already stale when we read it, so the client falls back to exponential backoff.
+# A per-minute limit needs a budget that outlasts the window, so give the report endpoints more
+# attempts and a higher backoff ceiling than the entity lists — each wait still stays capped, so a
+# sync never stalls indefinitely.
+REPORT_MAX_RETRY_ATTEMPTS = 12
+REPORT_RETRY_BACKOFF_MAX_SECONDS = 300.0
# 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.
@@ -485,12 +491,17 @@ def anthropic_source(
# Set only where the rows come from something other than iterating `resource` once.
items: Optional[Callable[[], Iterator[list[dict[str, Any]]]]] = None
+ # The report endpoints page the rate-limited Admin API; the entity lists do not. Give the reports
+ # a wider retry budget so it can outlast the organization rate-limit window.
+ is_report_endpoint = config.pagination == PaginationType.PAGE
client_config: ClientConfig = {
"base_url": ANTHROPIC_BASE_URL,
"headers": _version_headers(),
"auth": _auth_config(api_key),
- "max_retries": MAX_RETRY_ATTEMPTS,
+ "max_retries": REPORT_MAX_RETRY_ATTEMPTS if is_report_endpoint else MAX_RETRY_ATTEMPTS,
}
+ if is_report_endpoint:
+ client_config["retry_backoff_max_seconds"] = REPORT_RETRY_BACKOFF_MAX_SECONDS
resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
@@ -564,6 +575,11 @@ def anthropic_source(
},
"data_selector": "data",
"paginator": _entity_paginator(),
+ # A workspace that does not serve this sub-resource (or was archived between
+ # enumeration and the child fetch) answers 404 — skip it rather than fail the
+ # whole schema. 429/5xx are retried by the client before hooks run, and any
+ # other 4xx still raises.
+ "response_actions": [{"status_code": 404, "action": "ignore"}],
},
"include_from_parent": ["id"],
"data_map": _stamp_workspace_id,
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 9f6ecf76c297..ef4ba6b95024 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
@@ -13,6 +13,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.anthropic.
ANTHROPIC_VERSION,
DEFAULT_CLAUDE_CODE_START,
MAX_RETRY_ATTEMPTS,
+ REPORT_MAX_RETRY_ATTEMPTS,
AnthropicResumeConfig,
ClaudeCodeDayPaginator,
_claude_code_start_day,
@@ -500,6 +501,25 @@ class TestWorkspaceMembersFanOut:
assert [(r["workspace_id"], r["user_id"]) for r in rows] == [("wrkspc_1", "u1")]
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_workspace_that_does_not_serve_the_sub_resource_is_skipped(self, MockSession) -> None:
+ # A workspace can 404 on the fan-out child (it does not serve that sub-resource, or was
+ # archived between enumeration and the fetch). Skip only that workspace instead of failing
+ # the whole schema, and still deliver the workspaces that do serve it.
+ session = MockSession.return_value
+ _wire(
+ session,
+ [
+ _entity_page([{"id": "wrkspc_1"}, {"id": "wrkspc_2"}], has_more=False, last_id="wrkspc_2"),
+ _response({"error": "not_found"}, status=404),
+ _entity_page([{"id": "sa_2", "workspace_id": "wrkspc_2"}], has_more=False, last_id="sa_2"),
+ ],
+ )
+
+ rows = _rows(_source("service_accounts", _make_manager()))
+
+ assert [(r["workspace_id"], r["id"]) for r in rows] == [("wrkspc_2", "sa_2")]
+
def test_saved_state_shapes_still_parse(self) -> None:
# ResumableSourceManager._load_json does dataclass(**saved) — every historical shape must
# keep parsing after the migration.
@@ -562,6 +582,26 @@ class TestRetries:
assert [r["id"] for r in rows] == ["user_1"]
assert session.send.call_count == MAX_RETRY_ATTEMPTS
+ @mock.patch("tenacity.nap.time.sleep")
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_report_endpoint_gets_a_wider_retry_budget(self, MockSession, _mock_sleep) -> None:
+ # The report endpoints share one organization rate limit and 429 without a Retry-After, so
+ # they need more attempts than the entity lists to outlast the window. A burst that would
+ # exhaust the entity budget still resolves for a report endpoint.
+ session = MockSession.return_value
+ _wire(
+ session,
+ [
+ *[_response({}, status=429) for _ in range(REPORT_MAX_RETRY_ATTEMPTS - 1)],
+ _report_page([{"starting_at": "2024-01-01", "results": []}], has_more=False, next_page=None),
+ ],
+ )
+
+ _rows(_source("cost_report", _make_manager()))
+
+ assert session.send.call_count == REPORT_MAX_RETRY_ATTEMPTS
+ assert REPORT_MAX_RETRY_ATTEMPTS > MAX_RETRY_ATTEMPTS
+
class TestUsageReportGroupByFallback:
@mock.patch(CLIENT_SESSION_PATCH)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/__init__.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/__init__.py
index c1d3cf7bf8de..60418eaa3013 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/__init__.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/__init__.py
@@ -19,7 +19,7 @@ from .config_setup import (
from .jsonpath_utils import TJsonPath
from .paginators import BasePaginator
from .resource import Resource
-from .rest_client import DEFAULT_RETRY_ATTEMPTS, RESTClient, RESTClientRetryableError
+from .rest_client import DEFAULT_RETRY_ATTEMPTS, DEFAULT_RETRY_BACKOFF_MAX_SECONDS, RESTClient, RESTClientRetryableError
from .typing import ClientConfig, Endpoint, EndpointResource, HTTPMethodBasic, ResolvedParam, RESTAPIConfig
from .utils import exclude_keys # noqa: F401
@@ -294,6 +294,7 @@ def create_resources(
paginator=create_paginator(client_config.get("paginator")),
session=client_config.get("session"),
max_retry_attempts=client_config.get("max_retries", DEFAULT_RETRY_ATTEMPTS),
+ retry_backoff_max_seconds=client_config.get("retry_backoff_max_seconds", DEFAULT_RETRY_BACKOFF_MAX_SECONDS),
allowed_hosts=client_config.get("allowed_hosts"),
allow_redirects=client_config.get("allow_redirects", True),
request_timeout=client_config.get("request_timeout"),
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 2c5f6ccd6461..12eefdc3bb51 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
@@ -167,6 +167,11 @@ MAX_RETRY_AFTER_SECONDS = 300.0
# rate-limited endpoint surfaces an error instead of sleeping on `Retry-After`.
DEFAULT_RETRY_ATTEMPTS = 5
+# Ceiling on the exponential backoff between retries when a response carries no server-provided
+# delay. A source whose rate-limit window is longer than this can raise it per client so the retry
+# budget outlasts the window.
+DEFAULT_RETRY_BACKOFF_MAX_SECONDS = 60.0
+
# Default network ports per scheme, used to compare a request URL's effective port against the
# base origin's when host-pinning is enabled.
_DEFAULT_PORTS = {"http": 80, "https": 443}
@@ -259,7 +264,11 @@ def _stop_after_client_attempts(state: RetryCallState) -> bool:
def _retry_wait_seconds(state: RetryCallState) -> float:
- fallback = min(2 ** (state.attempt_number - 1), 60)
+ # Read the backoff ceiling off the bound instance the same way `_stop_after_client_attempts`
+ # reads the attempt cap, so a client with a longer rate-limit window can widen its own backoff.
+ client = state.args[0] if state.args else None
+ ceiling = getattr(client, "_retry_backoff_max", DEFAULT_RETRY_BACKOFF_MAX_SECONDS)
+ fallback = min(2 ** (state.attempt_number - 1), ceiling)
if state.outcome is None or not state.outcome.failed:
return float(fallback)
exc = state.outcome.exception()
@@ -297,6 +306,7 @@ class RESTClient:
paginator: Optional[BasePaginator] = None,
session: Optional[Session] = None,
max_retry_attempts: int = DEFAULT_RETRY_ATTEMPTS,
+ retry_backoff_max_seconds: float = DEFAULT_RETRY_BACKOFF_MAX_SECONDS,
allowed_hosts: Optional[list[str]] = None,
allow_redirects: bool = True,
request_timeout: Optional[float | tuple[float, float]] = None,
@@ -306,6 +316,7 @@ class RESTClient:
self.auth = auth
self.paginator = paginator
self._max_retry_attempts = max_retry_attempts
+ self._retry_backoff_max = retry_backoff_max_seconds
# Per-request (connect, read) timeout in seconds handed to ``session.send``. Left None,
# a request can hang forever — a source pointed at a server that accepts the connection
# then never responds would hold an import worker indefinitely. Sources talking to a
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 463d43f41bf9..10dcd541f7fd 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
@@ -584,6 +584,30 @@ class TestRESTClient:
assert mock_session.send.call_count == 1
mock_sleep.assert_not_called()
+ @patch("tenacity.nap.time.sleep")
+ @patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"
+ )
+ def test_backoff_ceiling_widens_the_exponential_fallback(self, MockSession, mock_sleep) -> None:
+ # A 429 without a Retry-After backs off on the exponential fallback, capped at the client's
+ # ceiling. Raising the ceiling lets a source whose rate-limit window is longer than the
+ # default 60s cap wait past it — the fallback grows to 128s here instead of stopping at 60s.
+ mock_session = MockSession.return_value
+ mock_session.headers = {}
+ mock_session.prepare_request.return_value = MagicMock()
+
+ rate_limited = _make_response({"error": "rate limited"}, status_code=429)
+ rate_limited.url = "https://api.example.com/items"
+ ok = _make_response({"results": [{"id": 1}]})
+ mock_session.send.side_effect = [*[rate_limited] * 8, ok]
+
+ client = RESTClient(base_url="https://api.example.com", max_retry_attempts=9, retry_backoff_max_seconds=300.0)
+ pages = list(client.paginate(path="/items", data_selector="results", paginator=SinglePagePaginator()))
+
+ assert pages == [[{"id": 1}]]
+ waits = [call.args[0] for call in mock_sleep.call_args_list]
+ assert waits == [1.0, 2.0, 4.0, 8.0, 16.0, 32.0, 64.0, 128.0]
+
@patch("tenacity.nap.time.sleep")
@patch(
"products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/typing.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/typing.py
index 7fc58c9a78d2..90a715018a7b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/typing.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/typing.py
@@ -170,6 +170,10 @@ class ClientConfig(TypedDict, total=False):
# Cap on retry attempts per request. Left unset, RESTClient uses its default;
# the inline preview sets 1 so a rate-limited endpoint errors instead of sleeping.
max_retries: int
+ # Ceiling (seconds) on the exponential backoff between retries when the response carries no
+ # server-provided delay. Left unset, RESTClient uses its default. Raise it for an endpoint whose
+ # rate-limit window is longer than the default ceiling, so the retry budget can outlast the window.
+ retry_backoff_max_seconds: float
# SSRF host-pinning. When set (even to an empty list), every outgoing request URL —
# including paginator next-page links and seeded resume URLs — must resolve to one of
# these hosts; the base_url host is always implicitly allowed. Off-host URLs are rejected