: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
feat(data-warehouse): implement anthropic import source (#70017)
Tom Owersa8b74347628c
diff --git a/frontend/public/services/anthropic.svg b/frontend/public/services/anthropic.svgindex c917480d3259..e40b23e0ca67 100644--- a/frontend/public/services/anthropic.svg+++ b/frontend/public/services/anthropic.svg@@ -1 +1,7 @@-<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>Anthropic</title><path d="M17.3041 3.541h-3.6718l6.696 16.918H24Zm-10.6082 0L0 20.459h3.7442l1.3693-3.5527h7.0052l1.3693 3.5528h3.7442L10.5363 3.5409Zm-.3712 10.2232 2.2914-5.9456 2.2914 5.9456Z"/></svg>\ No newline at end of file+<svg viewBox="0 0 92.2 65" xmlns="http://www.w3.org/2000/svg">+ <title>Anthropic logo</title>+ <path+ d="M66.5,0H52.4l25.7,65h14.1L66.5,0z M25.7,0L0,65h14.4l5.3-13.6h26.9L51.8,65h14.4L40.5,0C40.5,0,25.7,0,25.7,0z M24.3,39.3l8.8-22.8l8.8,22.8H24.3z"+ fill="#181818"+ />+</svg>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 e420e71529f5..9f6740f4c563 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,6 +1,7 @@+import hashlibimport dataclasses-from collections.abc import Callable, Iterator-from datetime import UTC, date, datetime, timedelta+from collections.abc import Iterator+from datetime import UTC, date, datetimefrom typing import Any, Optionalfrom urllib.parse import urlencode@@ -8,28 +9,24 @@ import requestsfrom structlog.types import FilteringBoundLoggerfrom tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.batcher import Batcherfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.anthropic.settings import (ANTHROPIC_ENDPOINTS,AnthropicEndpointConfig,+ PaginationType,)from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_sessionfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManagerANTHROPIC_BASE_URL = "https://api.anthropic.com"ANTHROPIC_VERSION = "2023-06-01"-# Entity list endpoints accept limit 1-1000.-ENTITY_PAGE_SIZE = 500-# Report endpoints cap buckets per page; at 1d width the max is 31.-REPORT_BUCKET_LIMIT = 31-# Earliest window start when there is no incremental watermark yet (the Anthropic API launched-# in 2023, so no usage or cost data can predate this).+# Entity list endpoints allow up to 1000 per page.+ENTITY_PAGE_SIZE = 1000+# 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.DEFAULT_STARTING_AT = datetime(2023, 1, 1, tzinfo=UTC)-# Usage/cost data lands up to ~5 minutes after a request completes, and the current day's bucket-# is always partial, so incremental syncs re-fetch a trailing window and rely on merge dedupe.-INCREMENTAL_LOOKBACK = timedelta(days=1)-REQUEST_TIMEOUT_SECONDS = 60-MAX_RETRIES = 5class AnthropicRetryableError(Exception):@@ -38,12 +35,13 @@ class AnthropicRetryableError(Exception):@dataclasses.dataclassclass AnthropicResumeConfig:- # Cursor (last_id) into an after_id-paginated entity list.- after_id: Optional[str] = None- # Report endpoints: the window start of the in-flight request chain plus the opaque- # next_page token to continue from.- starting_at: Optional[str] = None- page: Optional[str] = None+ # Opaque pagination cursor: an `after_id` for CURSOR endpoints or a `next_page` token for PAGE+ # endpoints. None means "start at the first page".+ cursor: str | None = None+ # workspace_members fan-out only: the workspace whose members we were paging when we saved state.+ # A stable id (not a positional index) so workspaces added/removed between a crash and the retry+ # can't resume us into the wrong workspace.+ workspace_id: str | None = Nonedef _get_headers(api_key: str) -> dict[str, str]:@@ -54,125 +52,318 @@ def _get_headers(api_key: str) -> dict[str, str]:}-def _build_url(path: str, params: dict[str, Any]) -> str:- clean_params = {key: value for key, value in params.items() if value is not None}- if not clean_params:- return f"{ANTHROPIC_BASE_URL}{path}"- # doseq expands the group_by[] list into repeated params.- return f"{ANTHROPIC_BASE_URL}{path}?{urlencode(clean_params, doseq=True)}"+def _format_rfc3339(value: Any) -> str:+ """Format a datetime/date as an RFC 3339 UTC timestamp with a Z suffix (Anthropic's format)."""+ if isinstance(value, datetime):+ dt = value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)+ elif isinstance(value, date):+ dt = datetime.combine(value, datetime.min.time(), tzinfo=UTC)+ else:+ return str(value)+ return dt.strftime("%Y-%m-%dT%H:%M:%SZ")+++def _build_url(path: str, params: dict[str, Any], multi_params: dict[str, list[str]] | None = None) -> str:+ """Build a fully-encoded URL. `multi_params` values are repeated (e.g. group_by[]=a&group_by[]=b)."""+ query: list[tuple[str, str]] = [(k, str(v)) for k, v in params.items() if v is not None]+ if multi_params:+ for key, values in multi_params.items():+ query.extend((key, v) for v in values)+ encoded = urlencode(query)+ url = f"{ANTHROPIC_BASE_URL}{path}"+ return f"{url}?{encoded}" if encoded else url+++@retry(+ retry=retry_if_exception_type(+ (+ AnthropicRetryableError,+ requests.ReadTimeout,+ requests.ConnectionError,+ requests.exceptions.ChunkedEncodingError,+ )+ ),+ stop=stop_after_attempt(5),+ wait=wait_exponential_jitter(initial=1, max=30),+ 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}")-def _to_start_datetime(value: Any) -> Optional[datetime]:- """Coerce a persisted incremental watermark into an aware UTC datetime."""- if value is None:- return None- if isinstance(value, datetime):- return value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)- if isinstance(value, date):- return datetime.combine(value, datetime.min.time(), tzinfo=UTC)- if isinstance(value, str):- try:- parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))- except ValueError:- return None- return parsed.replace(tzinfo=UTC) if parsed.tzinfo is None else parsed.astimezone(UTC)- return None---def _format_rfc3339(value: datetime) -> str:- return value.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%SZ")---def _compute_starting_at(db_incremental_field_last_value: Any) -> str:- """Window start for a report request: the watermark minus a lookback, floored to midnight UTC- (buckets snap to day boundaries), or the default backfill start on the first sync."""- last_value = _to_start_datetime(db_incremental_field_last_value)- if last_value is None:- return _format_rfc3339(DEFAULT_STARTING_AT)- start = (last_value - INCREMENTAL_LOOKBACK).replace(hour=0, minute=0, second=0, microsecond=0)- return _format_rfc3339(max(start, DEFAULT_STARTING_AT))---def _flatten_report_buckets(buckets: list[dict[str, Any]], config: AnthropicEndpointConfig) -> list[dict[str, Any]]:- """Flatten time buckets into one row per (bucket, group-by combination) with a synthetic- primary key, so re-fetched windows merge instead of duplicating."""- rows: list[dict[str, Any]] = []- for bucket in buckets:- # Direct access: a missing bucket boundary must fail loudly rather than seed rows with a- # None primary key, watermark, and partition key.- bucket_starting_at = bucket["starting_at"]- bucket_ending_at = bucket["ending_at"]- for result in bucket.get("results") or []:- row = dict(result)- row["bucket_starting_at"] = bucket_starting_at- row["bucket_ending_at"] = bucket_ending_at- row["id"] = "|".join([str(bucket_starting_at), *(str(result.get(key)) for key in config.key_fields)])- rows.append(row)- return rows+ if not response.ok:+ logger.error(f"Anthropic API error: status={response.status_code}, body={response.text}, url={url}")+ response.raise_for_status()++ return response.json()def validate_credentials(api_key: str) -> bool:- """Confirm the Admin API key works. Listing one organization user is the cheapest- authenticated probe every admin key can perform."""+ # A single cheap probe against the smallest list endpoint confirms the admin key is genuine.+ url = _build_url("/v1/organizations/users", {"limit": 1})try:- response = make_tracked_session().get(- _build_url("/v1/organizations/users", {"limit": 1}),- headers=_get_headers(api_key),- timeout=10,- )- return response.status_code == 200+ response = make_tracked_session().get(url, headers=_get_headers(api_key), timeout=10)except Exception:return False+ # 200 => valid. 403 => valid key without a scope we probed here; still a real key, so accept it at+ # create time (sync-time 403s are caught by get_non_retryable_errors). 401 => bad key.+ return response.status_code in (200, 403)+++def _flatten_created_by(item: dict[str, Any]) -> dict[str, Any]:+ """api_keys carry a nested `created_by: {id, type}`; surface it as flat columns."""+ created_by = item.get("created_by")+ if isinstance(created_by, dict):+ item = {**item}+ item.pop("created_by")+ item["created_by_id"] = created_by.get("id")+ item["created_by_type"] = created_by.get("type")+ return item+++def _normalize_entity(endpoint: str, item: dict[str, Any]) -> dict[str, Any]:+ if endpoint == "api_keys":+ return _flatten_created_by(item)+ return item+++def _row_id(*parts: Any) -> str:+ """Deterministic surrogate id for a report row.++ Hashes only the identity/dimension fields (never the metric values), so a bucket whose metrics+ get restated between runs keeps the same id and merge updates it in place rather than inserting a+ duplicate.+ """+ # Use a sentinel for None so a missing dimension can never collide with an empty-string value.+ joined = "|".join("\x00" if p is None else str(p) for p in parts)+ return hashlib.sha256(joined.encode()).hexdigest()+++def _flatten_usage_result(bucket: dict[str, Any], result: dict[str, Any]) -> dict[str, Any]:+ starting_at = bucket.get("starting_at")+ cache_creation = result.get("cache_creation") or {}+ server_tool_use = result.get("server_tool_use") or {}+ row = {+ "id": _row_id(+ starting_at,+ result.get("account_id"),+ result.get("api_key_id"),+ result.get("service_account_id"),+ result.get("workspace_id"),+ result.get("model"),+ result.get("service_tier"),+ result.get("context_window"),+ result.get("inference_geo"),+ ),+ "starting_at": starting_at,+ "ending_at": bucket.get("ending_at"),+ "account_id": result.get("account_id"),+ "api_key_id": result.get("api_key_id"),+ "service_account_id": result.get("service_account_id"),+ "workspace_id": result.get("workspace_id"),+ "model": result.get("model"),+ "service_tier": result.get("service_tier"),+ "context_window": result.get("context_window"),+ "inference_geo": result.get("inference_geo"),+ "uncached_input_tokens": result.get("uncached_input_tokens"),+ "cache_read_input_tokens": result.get("cache_read_input_tokens"),+ "cache_creation_ephemeral_1h_input_tokens": cache_creation.get("ephemeral_1h_input_tokens"),+ "cache_creation_ephemeral_5m_input_tokens": cache_creation.get("ephemeral_5m_input_tokens"),+ "output_tokens": result.get("output_tokens"),+ "web_search_requests": server_tool_use.get("web_search_requests"),+ }+ return row-def _make_fetch_page(headers: dict[str, str], logger: FilteringBoundLogger) -> Callable[[str], dict[str, Any]]:- @retry(- retry=retry_if_exception_type((AnthropicRetryableError, requests.ReadTimeout, requests.ConnectionError)),- stop=stop_after_attempt(MAX_RETRIES),- wait=wait_exponential_jitter(initial=1, max=60),- reraise=True,- )- def fetch_page(url: str) -> dict[str, Any]:- response = make_tracked_session().get(url, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS)-- # The Admin API rate limit is sustained-per-minute with burst allowance; exponential- # backoff on 429 is sufficient.- if response.status_code == 429 or response.status_code >= 500:- raise AnthropicRetryableError(f"Anthropic API error (retryable): status={response.status_code}, url={url}")+def _flatten_cost_result(bucket: dict[str, Any], result: dict[str, Any]) -> dict[str, Any]:+ starting_at = bucket.get("starting_at")+ return {+ "id": _row_id(+ starting_at,+ result.get("workspace_id"),+ result.get("description"),+ result.get("cost_type"),+ result.get("model"),+ result.get("service_tier"),+ result.get("token_type"),+ result.get("context_window"),+ ),+ "starting_at": starting_at,+ "ending_at": bucket.get("ending_at"),+ "workspace_id": result.get("workspace_id"),+ "description": result.get("description"),+ "cost_type": result.get("cost_type"),+ "model": result.get("model"),+ "service_tier": result.get("service_tier"),+ "token_type": result.get("token_type"),+ "context_window": result.get("context_window"),+ "currency": result.get("currency"),+ "amount": result.get("amount"),+ }- if not response.ok:- logger.error(f"Anthropic API error: status={response.status_code}, body={response.text}, url={url}")- response.raise_for_status()- return response.json()+def _report_params(+ config: AnthropicEndpointConfig,+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+) -> tuple[dict[str, Any], dict[str, list[str]]]:+ params: dict[str, Any] = {"bucket_width": config.bucket_width}+ if config.limit is not None:+ params["limit"] = config.limit++ # `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.+ if should_use_incremental_field and db_incremental_field_last_value:+ params["starting_at"] = _format_rfc3339(db_incremental_field_last_value)+ else:+ params["starting_at"] = _format_rfc3339(DEFAULT_STARTING_AT)- return fetch_page+ multi_params = {"group_by[]": config.group_by} if config.group_by else {}+ return params, multi_params-def _entity_pages(- fetch_page: Callable[[str], dict[str, Any]],+def _iter_report_rows(+ session: requests.Session,+ headers: dict[str, str],+ logger: FilteringBoundLogger,+ batcher: Batcher,+ resumable_source_manager: ResumableSourceManager[AnthropicResumeConfig],config: AnthropicEndpointConfig,- after_id: Optional[str],- on_page_complete: Optional[Callable[[str], None]] = None,-) -> Iterator[list[dict[str, Any]]]:- """Iterate an after_id-cursor list endpoint, yielding each page's items."""+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+) -> Iterator[Any]:+ params, multi_params = _report_params(config, should_use_incremental_field, db_incremental_field_last_value)+ flatten = _flatten_usage_result if config.name == "usage_report" else _flatten_cost_result++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ if resume is not None and resume.cursor:+ params["page"] = resume.cursor+ logger.debug(f"Anthropic: resuming {config.name} from page cursor")+while True:- params: dict[str, Any] = {**config.params, "limit": ENTITY_PAGE_SIZE}+ url = _build_url(config.path, params, multi_params)+ data = _fetch_page(session, url, headers, logger)+ next_page = data.get("next_page")+ has_more = bool(data.get("has_more"))++ for bucket in data.get("data", []):+ for result in bucket.get("results", []):+ batcher.batch(flatten(bucket, result))+ # A single batch can split into several ready chunks, so drain them all before+ # the next batch() call (which raises if `_ready` is still populated).+ while batcher.should_yield():+ yield batcher.get_table()+ # Save only when a batch is actually committed, pointing at the next page. A crash+ # then resumes from a page whose predecessors are all in the yielded batch, so no+ # buffered rows are skipped; the overlap merge dedupes on the primary key.+ if has_more and next_page:+ resumable_source_manager.save_state(AnthropicResumeConfig(cursor=next_page))++ if not has_more or not next_page:+ break+ params["page"] = next_page+++def _iter_cursor_pages(+ session: requests.Session,+ headers: dict[str, str],+ logger: FilteringBoundLogger,+ path: str,+ base_params: dict[str, Any],+ start_after_id: str | None = None,+) -> Iterator[tuple[list[dict[str, Any]], str | None]]:+ """Yield (items, last_id) for each page of a cursor-paginated entity endpoint."""+ after_id = start_after_id+ while True:+ params = {**base_params, "limit": ENTITY_PAGE_SIZE}if after_id:params["after_id"] = after_id+ url = _build_url(path, params)+ data = _fetch_page(session, url, headers, logger)- data = fetch_page(_build_url(config.path, params))- items = data.get("data") or []-- if items:- yield items+ items = data.get("data", [])+ last_id = data.get("last_id")+ yield items, last_id- after_id = data.get("last_id")- if not data.get("has_more") or not after_id:+ if not data.get("has_more") or not last_id:break+ after_id = last_id- if on_page_complete is not None:- on_page_complete(after_id)++def _iter_entity_rows(+ session: requests.Session,+ headers: dict[str, str],+ logger: FilteringBoundLogger,+ batcher: Batcher,+ resumable_source_manager: ResumableSourceManager[AnthropicResumeConfig],+ config: AnthropicEndpointConfig,+) -> Iterator[Any]:+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ start_after_id = resume.cursor if resume is not None else None++ for items, last_id in _iter_cursor_pages(+ session, headers, logger, config.path, config.extra_params, start_after_id+ ):+ for item in items:+ batcher.batch(_normalize_entity(config.name, item))+ while batcher.should_yield():+ yield batcher.get_table()+ if last_id:+ resumable_source_manager.save_state(AnthropicResumeConfig(cursor=last_id))+++def _iter_workspace_member_rows(+ session: requests.Session,+ headers: dict[str, str],+ logger: FilteringBoundLogger,+ batcher: Batcher,+ resumable_source_manager: ResumableSourceManager[AnthropicResumeConfig],+ config: AnthropicEndpointConfig,+) -> Iterator[Any]:+ """Fan out over every workspace, emitting one row per (workspace_id, user_id) membership."""+ workspace_ids = _list_all_workspace_ids(session, headers, logger)++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ remaining = workspace_ids+ resume_after_id: str | None = None+ if resume is not None and resume.workspace_id and resume.workspace_id in workspace_ids:+ remaining = workspace_ids[workspace_ids.index(resume.workspace_id) :]+ resume_after_id = resume.cursor+ logger.debug(f"Anthropic: resuming workspace_members from workspace_id={resume.workspace_id}")++ for index, workspace_id in enumerate(remaining):+ path = config.path.format(workspace_id=workspace_id)+ after_id = resume_after_id+ resume_after_id = None # only the resumed-into workspace uses the saved cursor++ for items, last_id in _iter_cursor_pages(session, headers, logger, path, {}, after_id):+ for item in items:+ # The member object already carries workspace_id, but set it defensively so the+ # composite primary key is always populated.+ row = {**item, "workspace_id": item.get("workspace_id") or workspace_id}+ batcher.batch(row)+ while batcher.should_yield():+ yield batcher.get_table()+ if last_id:+ resumable_source_manager.save_state(+ AnthropicResumeConfig(cursor=last_id, workspace_id=workspace_id)+ )++ if index + 1 < len(remaining):+ resumable_source_manager.save_state(AnthropicResumeConfig(cursor=None, workspace_id=remaining[index + 1]))+++def _list_all_workspace_ids(+ session: requests.Session, headers: dict[str, str], logger: FilteringBoundLogger+) -> list[str]:+ workspace_ids: list[str] = []+ for items, _ in _iter_cursor_pages(+ session, headers, logger, "/v1/organizations/workspaces", {"include_archived": "true"}+ ):+ workspace_ids.extend(item["id"] for item in items if item.get("id"))+ return workspace_idsdef get_rows(@@ -182,60 +373,30 @@ def get_rows(resumable_source_manager: ResumableSourceManager[AnthropicResumeConfig],should_use_incremental_field: bool = False,db_incremental_field_last_value: Any = None,-) -> Iterator[list[dict[str, Any]]]:+) -> Iterator[Any]:config = ANTHROPIC_ENDPOINTS[endpoint]- fetch_page = _make_fetch_page(_get_headers(api_key), logger)- resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None- if resume_config is not None:- logger.debug(f"Anthropic: resuming {endpoint} from saved state: {resume_config}")-- if config.kind == "entity":- after_id = resume_config.after_id if resume_config else None- yield from _entity_pages(- fetch_page,+ headers = _get_headers(api_key)+ batcher = Batcher(logger=logger, chunk_size=5000, chunk_size_bytes=100 * 1024 * 1024)+ session = make_tracked_session()++ if config.pagination == PaginationType.PAGE:+ yield from _iter_report_rows(+ session,+ headers,+ logger,+ batcher,+ resumable_source_manager,config,- after_id,- on_page_complete=lambda last_id: resumable_source_manager.save_state(- AnthropicResumeConfig(after_id=last_id)- ),+ should_use_incremental_field,+ db_incremental_field_last_value,)- elif config.kind == "workspace_members":- # Fan-out over the (small) workspace list. Rows merge on (workspace_id, user_id), so no- # intermediate resume state is saved — a resumed sync restarts the fan-out cleanly.- workspaces_config = ANTHROPIC_ENDPOINTS["workspaces"]- for workspace_page in _entity_pages(fetch_page, workspaces_config, None):- for workspace in workspace_page:- member_config = dataclasses.replace(config, path=config.path.format(workspace_id=workspace["id"]))- yield from _entity_pages(fetch_page, member_config, None)+ elif config.fan_out_over_workspaces:+ yield from _iter_workspace_member_rows(session, headers, logger, batcher, resumable_source_manager, config)else:- if resume_config is not None and resume_config.starting_at is not None:- starting_at = resume_config.starting_at- page = resume_config.page- else:- starting_at = _compute_starting_at(- db_incremental_field_last_value if should_use_incremental_field else None- )- page = None-- while True:- params: dict[str, Any] = {- "starting_at": starting_at,- "limit": REPORT_BUCKET_LIMIT,- "bucket_width": config.bucket_width,- "group_by[]": config.group_by or None,- "page": page,- }- data = fetch_page(_build_url(config.path, params))-- rows = _flatten_report_buckets(data.get("data") or [], config)- if rows:- yield rows-- page = data.get("next_page")- if not data.get("has_more") or not page:- break-- resumable_source_manager.save_state(AnthropicResumeConfig(starting_at=starting_at, page=page))+ yield from _iter_entity_rows(session, headers, logger, batcher, resumable_source_manager, config)++ while batcher.should_yield(include_incomplete_chunk=True):+ yield batcher.get_table()def anthropic_source(@@ -259,8 +420,8 @@ def anthropic_source(db_incremental_field_last_value=db_incremental_field_last_value,),primary_keys=config.primary_keys,- # Report time buckets are returned in chronological order; entity lists are full refresh- # where ordering does not affect the watermark.+ # 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.sort_mode="asc",partition_count=1,partition_size=1,diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/anthropic/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/anthropic/canonical_descriptions.pyindex 824a92f39320..e6c03fb3d04b 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/anthropic/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/anthropic/canonical_descriptions.py@@ -2,109 +2,110 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.canCanonicalDescriptions,)+_ADMIN_API_DOCS = "https://platform.claude.com/docs/en/api/admin-api"+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"users": {- "description": "Members of your Anthropic organization and their organization-level roles.",- "docs_url": "https://platform.claude.com/docs/en/api/admin/users/list",+ "description": "Members of your Anthropic organization.",+ "docs_url": f"{_ADMIN_API_DOCS}/users/list-users","columns": {- "id": "ID of the user.",- "type": "Object type. Always 'user'.",- "email": "Email of the user.",- "name": "Name of the user.",- "role": "Organization role of the user: admin, billing, claude_code_user, developer, or user.",- "added_at": "RFC 3339 datetime string indicating when the user joined the organization.",+ "id": "Unique identifier for the user.",+ "type": 'Object type, always "user".',+ "email": "Email address of the user.",+ "name": "Display name of the user.",+ "role": "Organization role: admin, billing, claude_code_user, developer, or user.",+ "added_at": "RFC 3339 timestamp of when the user joined the organization.",},},"invites": {"description": "Pending and historical invitations to join your Anthropic organization.",- "docs_url": "https://platform.claude.com/docs/en/api/admin/invites/list",+ "docs_url": f"{_ADMIN_API_DOCS}/invites/list-invites","columns": {- "id": "ID of the invite.",- "type": "Object type. Always 'invite'.",- "email": "Email of the user being invited.",- "role": "Organization role the invited user will receive: admin, billing, claude_code_user, developer, or user.",- "invited_at": "RFC 3339 datetime string indicating when the invite was created.",- "expires_at": "RFC 3339 datetime string indicating when the invite expires.",- "status": "Status of the invite: accepted, deleted, expired, or pending.",+ "id": "Unique identifier for the invite.",+ "type": 'Object type, always "invite".',+ "email": "Email address the invite was sent to.",+ "role": "Organization role the invited user will receive.",+ "invited_at": "RFC 3339 timestamp of when the invite was created.",+ "expires_at": "RFC 3339 timestamp of when the invite expires.",+ "status": "Invite status: accepted, deleted, expired, or pending.",},},"workspaces": {- "description": "Workspaces in your Anthropic organization, used to segment API usage, spend limits, and access. Includes archived workspaces.",- "docs_url": "https://platform.claude.com/docs/en/api/admin/workspaces/list",+ "description": "Workspaces in your Anthropic organization (includes archived workspaces).",+ "docs_url": f"{_ADMIN_API_DOCS}/workspaces/list-workspaces","columns": {- "id": "ID of the workspace.",- "type": "Object type. Always 'workspace'.",- "name": "Name of the workspace.",- "created_at": "RFC 3339 datetime string indicating when the workspace was created.",- "archived_at": "RFC 3339 datetime string indicating when the workspace was archived, or null if not archived.",+ "id": "Unique identifier for the workspace.",+ "type": 'Object type, always "workspace".',+ "name": "Display name of the workspace.",+ "created_at": "RFC 3339 timestamp of when the workspace was created.",+ "archived_at": "RFC 3339 timestamp of when the workspace was archived, or null if active.","display_color": "Hex color code representing the workspace in the Anthropic Console.",- "compartment_id": "Identifier for this workspace's encryption compartment, referenced by customer-managed encryption key (CMEK) configurations.",- "data_residency": "Data residency configuration: allowed inference geos, default inference geo, and workspace geo.",},},- "workspace_members": {- "description": "Membership of users in each workspace, with their workspace-level role. One row per user per workspace.",- "docs_url": "https://platform.claude.com/docs/en/api/admin/workspace-members/list",+ "api_keys": {+ "description": "API keys provisioned across your Anthropic organization's workspaces.",+ "docs_url": f"{_ADMIN_API_DOCS}/apikeys/list-api-keys","columns": {- "type": "Object type. Always 'workspace_member'.",- "user_id": "ID of the user.",- "workspace_id": "ID of the workspace.",- "workspace_role": "Role of the member within the workspace: workspace_admin, workspace_billing, workspace_developer, workspace_restricted_developer, or workspace_user.",+ "id": "Unique identifier for the API key.",+ "type": 'Object type, always "api_key".',+ "name": "Display name of the API key.",+ "workspace_id": "ID of the workspace the key belongs to, or null for the default workspace.",+ "created_at": "RFC 3339 timestamp of when the API key was created.",+ "created_by_id": "ID of the actor that created the API key.",+ "created_by_type": "Type of the actor that created the API key.",+ "partial_key_hint": "Partially redacted hint for the API key value.",+ "status": "Key status: active, archived, expired, or inactive.",},},- "api_keys": {- "description": "API keys provisioned in your Anthropic organization, with their status, owning workspace, and creator.",- "docs_url": "https://platform.claude.com/docs/en/api/admin/api-keys/list",+ "workspace_members": {+ "description": "Membership rows mapping users to the workspaces they belong to, one row per (workspace, user).",+ "docs_url": f"{_ADMIN_API_DOCS}/workspace_members/list-workspace-members","columns": {- "id": "ID of the API key.",- "type": "Object type. Always 'api_key'.",- "name": "Name of the API key.",- "status": "Status of the API key: active, inactive, or archived.",- "workspace_id": "ID of the workspace the API key belongs to, or null for the default workspace.",- "created_at": "RFC 3339 datetime string indicating when the API key was created.",- "created_by": "The ID and type of the actor that created the API key.",- "partial_key_hint": "Partially redacted hint for the API key.",+ "type": 'Object type, always "workspace_member".',+ "user_id": "ID of the member user.",+ "workspace_id": "ID of the workspace the user is a member of.",+ "workspace_role": "Role within the workspace (workspace_admin, workspace_developer, ...).",},},"usage_report": {- "description": "Daily Claude API token usage for your organization, broken down by API key, workspace, model, service tier, context window, and inference geo. One row per day per unique combination of those dimensions.",- "docs_url": "https://platform.claude.com/docs/en/api/admin/usage-report/messages",+ "description": "Claude Messages API token usage aggregated into daily buckets, broken down by model, workspace, API key, service tier, context window, and inference geo.",+ "docs_url": f"{_ADMIN_API_DOCS}/usage-cost/get-messages-usage-report","columns": {- "id": "Synthetic unique key combining the time bucket start and the grouping dimensions.",- "bucket_starting_at": "Start of the daily time bucket (inclusive) in RFC 3339 format.",- "bucket_ending_at": "End of the daily time bucket (exclusive) in RFC 3339 format.",- "api_key_id": "ID of the API key used, or null for usage in the Anthropic Console.",- "workspace_id": "ID of the workspace used, or null for the default workspace.",- "model": "Model used (e.g. claude-sonnet-4-5).",- "service_tier": "Service tier used: batch, flex, flex_discount, priority, priority_on_demand, or standard.",- "context_window": "Context window used: 0-200k or 200k-1M.",- "inference_geo": "Inference geo used, or not_available for models that do not support specifying one.",- "account_id": "ID of the user account that made the request. Null unless grouping by account.",- "service_account_id": "ID of the service account that made the request. Null unless grouping by service account.",- "uncached_input_tokens": "The number of uncached input tokens processed.",- "cache_creation": "Input tokens used to create 1 hour and 5 minute cache entries.",- "cache_read_input_tokens": "The number of input tokens read from the cache.",- "output_tokens": "The number of output tokens generated.",- "server_tool_use": "Server-side tool usage metrics, e.g. the number of web search requests made.",+ "id": "Synthesized surrogate key: a hash of the bucket start and every grouping dimension.",+ "starting_at": "Start of the time bucket (inclusive) in RFC 3339 format.",+ "ending_at": "End of the time bucket (exclusive) in RFC 3339 format.",+ "account_id": "ID of the user account that made the requests, or null.",+ "api_key_id": "ID of the API key used, or null.",+ "service_account_id": "ID of the service account that made the requests, or null.",+ "workspace_id": "ID of the workspace, or null for the default workspace.",+ "model": "Model used, or null.",+ "service_tier": "Service tier used (standard, batch, priority, ...), or null.",+ "context_window": "Context window bucket used (0-200k or 200k-1M), or null.",+ "inference_geo": "Inference geo used (global, us, not_available), or null.",+ "uncached_input_tokens": "Number of uncached input tokens processed.",+ "cache_read_input_tokens": "Number of input tokens read from the cache.",+ "cache_creation_ephemeral_1h_input_tokens": "Input tokens used to create the 1-hour cache entry.",+ "cache_creation_ephemeral_5m_input_tokens": "Input tokens used to create the 5-minute cache entry.",+ "output_tokens": "Number of output tokens generated.",+ "web_search_requests": "Number of server-side web search requests made.",},},"cost_report": {- "description": "Daily costs for your Anthropic organization in USD, broken down by workspace and line-item description. One row per day per unique cost line item.",- "docs_url": "https://platform.claude.com/docs/en/api/admin/cost-report/get",+ "description": "Daily cost in USD for your Anthropic organization, broken down by workspace and cost description.",+ "docs_url": f"{_ADMIN_API_DOCS}/usage-cost/get-cost-report","columns": {- "id": "Synthetic unique key combining the time bucket start and the cost breakdown dimensions.",- "bucket_starting_at": "Start of the daily time bucket (inclusive) in RFC 3339 format.",- "bucket_ending_at": "End of the daily time bucket (exclusive) in RFC 3339 format.",- "workspace_id": "ID of the workspace this cost is associated with, or null for the default workspace.",- "description": "Description of the cost item (e.g. 'Claude Sonnet 4.5 Usage - Input Tokens').",- "amount": "Cost amount in lowest currency units (e.g. cents) as a decimal string. For example, '123.45' in USD represents $1.23.",- "currency": "Currency code for the cost amount. Currently always USD.",- "cost_type": "Type of cost: code_execution, session_usage, tokens, or web_search. Null for costs not grouped by description.",- "model": "Model name used, or null for non-token costs.",- "service_tier": "Service tier used: batch or standard. Null for non-token costs.",- "token_type": "Type of token the cost applies to (e.g. uncached_input_tokens, output_tokens, cache_read_input_tokens).",- "context_window": "Input context window used: 0-200k or 200k-1M. Null for non-token costs.",- "inference_geo": "Inference geo used, or not_available for models that do not support specifying one.",+ "id": "Synthesized surrogate key: a hash of the bucket start and every grouping dimension.",+ "starting_at": "Start of the time bucket (inclusive) in RFC 3339 format.",+ "ending_at": "End of the time bucket (exclusive) in RFC 3339 format.",+ "workspace_id": "ID of the workspace the cost is associated with, or null for the default workspace.",+ "description": "Human-readable description of the cost item.",+ "cost_type": "Type of cost: tokens, web_search, code_execution, or session_usage.",+ "model": "Model the cost is attributed to, or null for non-token costs.",+ "service_tier": "Service tier the cost is attributed to (standard or batch), or null.",+ "token_type": "Token type the cost is attributed to (e.g. output_tokens), or null.",+ "context_window": "Input context window the cost is attributed to, or null.",+ "currency": 'Currency code for the amount, currently always "USD".',+ "amount": 'Cost amount in the lowest currency unit (cents) as a decimal string, e.g. "123.45".',},},}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.pyindex 99d70031dff2..0d1a20482a99 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@@ -1,113 +1,151 @@from dataclasses import dataclass, field-from typing import Literal, Optional+from enum import Enum+from typing import Optionalfrom products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType+class PaginationType(Enum):+ # Entity list endpoints (users, workspaces, api_keys, ...) page with after_id/before_id cursors+ # and signal continuation via has_more + last_id.+ CURSOR = "cursor"+ # The usage_report/cost_report endpoints page with an opaque `page` token echoed back as+ # `next_page`, alongside has_more.+ PAGE = "page"+++def _datetime_incremental_field(name: str) -> IncrementalField:+ return {+ "label": name,+ "type": IncrementalFieldType.DateTime,+ "field": name,+ "field_type": IncrementalFieldType.DateTime,+ }++@dataclassclass AnthropicEndpointConfig:name: strpath: str- # "entity" = after_id-cursor list endpoint; "workspace_members" = per-workspace fan-out of- # an entity list; "report" = time-bucketed usage/cost report paginated with a `page` token.- kind: Literal["entity", "workspace_members", "report"]+ pagination: PaginationTypeprimary_keys: list[str]- # Static extra query params sent on every request.- params: dict[str, str] = field(default_factory=dict)- # Report endpoints: dimensions requested via `group_by[]`.- group_by: list[str] = field(default_factory=list)- # Report endpoints: result fields that, together with the bucket start, uniquely identify a- # row. Used to build the synthetic `id` primary key.- key_fields: list[str] = field(default_factory=list)- # Usage report accepts 1m/1h/1d; cost report is daily-only and rejects other widths, so it- # sends no bucket_width at all.- bucket_width: Optional[str] = None- incremental_fields: list[IncrementalField] = field(default_factory=list)- # Stable creation-time field used for datetime partitioning. Report buckets never move once- # written, so the bucket start is safe.+ # Stable creation-style timestamp used for datetime partitioning. Never an `updated_at`-style+ # field (Anthropic entities don't expose one anyway).partition_key: Optional[str] = None+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ # `supports_incremental` is only ever True where the API exposes a genuine server-side time+ # filter (the report endpoints via `starting_at`). Entity lists have no updated-since filter, so+ # they are full-refresh only.+ supports_incremental: bool = False+ # Report buckets get restated as late usage lands, so append would materialize duplicate rows;+ # they are merge-only. Entity lists are full refresh (no append either).+ supports_append: bool = False+ # Report-only: bucket granularity and the dimensions we group each bucket by.+ bucket_width: Optional[str] = None+ group_by: list[str] = field(default_factory=list)+ limit: Optional[int] = None+ # Re-read window (seconds) applied to the incremental watermark by the pipeline before it reaches+ # the source, so each run re-pulls recently-restated buckets. Merge dedupes them on the primary key.+ default_incremental_lookback_seconds: Optional[int] = None+ # workspace_members has no org-wide list endpoint; it fans out one request per workspace.+ fan_out_over_workspaces: bool = False+ # Extra static query params merged into every request (e.g. include_archived on workspaces).+ extra_params: dict[str, str] = field(default_factory=dict)+ should_sync_default: bool = True-_BUCKET_STARTING_AT_INCREMENTAL: list[IncrementalField] = [- {- "label": "bucket_starting_at",- "type": IncrementalFieldType.DateTime,- "field": "bucket_starting_at",- "field_type": IncrementalFieldType.DateTime,- },+# 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",]+_COST_GROUP_BY = ["workspace_id", "description"]++# 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`.+_REPORT_LOOKBACK_SECONDS = 60 * 60 * 24ANTHROPIC_ENDPOINTS: dict[str, AnthropicEndpointConfig] = {"users": AnthropicEndpointConfig(name="users",path="/v1/organizations/users",- kind="entity",+ pagination=PaginationType.CURSOR,primary_keys=["id"],+ partition_key="added_at",),"invites": AnthropicEndpointConfig(name="invites",path="/v1/organizations/invites",- kind="entity",+ pagination=PaginationType.CURSOR,primary_keys=["id"],+ partition_key="invited_at",),"workspaces": AnthropicEndpointConfig(name="workspaces",path="/v1/organizations/workspaces",- kind="entity",+ pagination=PaginationType.CURSOR,primary_keys=["id"],- params={"include_archived": "true"},- ),- "workspace_members": AnthropicEndpointConfig(- name="workspace_members",- path="/v1/organizations/workspaces/{workspace_id}/members",- kind="workspace_members",- # No id field on the API object; user_id is only unique within a workspace.- primary_keys=["workspace_id", "user_id"],+ partition_key="created_at",+ # Include archived workspaces so the dimension table stays complete (archived workspaces are+ # still referenced by historical usage/cost rows).+ extra_params={"include_archived": "true"},),"api_keys": AnthropicEndpointConfig(name="api_keys",path="/v1/organizations/api_keys",- kind="entity",+ pagination=PaginationType.CURSOR,primary_keys=["id"],+ partition_key="created_at",+ ),+ # No org-wide member list exists; fan out over every workspace's /members endpoint. The key must+ # carry the workspace id since one user can be a member of many workspaces.+ "workspace_members": AnthropicEndpointConfig(+ name="workspace_members",+ path="/v1/organizations/workspaces/{workspace_id}/members",+ pagination=PaginationType.CURSOR,+ primary_keys=["workspace_id", "user_id"],+ fan_out_over_workspaces=True,),"usage_report": AnthropicEndpointConfig(name="usage_report",path="/v1/organizations/usage_report/messages",- kind="report",+ pagination=PaginationType.PAGE,+ # `id` is synthesized from the bucket start + every group_by dimension (see anthropic.py):+ # a non-null, stable key so merge updates a bucket in place as its metrics get restated.primary_keys=["id"],- group_by=["api_key_id", "workspace_id", "model", "service_tier", "context_window", "inference_geo"],- key_fields=["api_key_id", "workspace_id", "model", "service_tier", "context_window", "inference_geo"],+ partition_key="starting_at",+ supports_incremental=True,+ incremental_fields=[_datetime_incremental_field("starting_at")],bucket_width="1d",- incremental_fields=_BUCKET_STARTING_AT_INCREMENTAL,- partition_key="bucket_starting_at",+ group_by=_USAGE_GROUP_BY,+ limit=31, # API max for the 1d bucket width+ default_incremental_lookback_seconds=_REPORT_LOOKBACK_SECONDS,),"cost_report": AnthropicEndpointConfig(name="cost_report",path="/v1/organizations/cost_report",- kind="report",+ pagination=PaginationType.PAGE,primary_keys=["id"],- group_by=["workspace_id", "description"],- # Grouping by description populates the cost breakdown fields (cost_type, model,- # token_type, ...), and one description can span several of those combinations, so they- # all take part in the synthetic key.- key_fields=[- "workspace_id",- "description",- "cost_type",- "model",- "service_tier",- "token_type",- "context_window",- "inference_geo",- "currency",- ],- incremental_fields=_BUCKET_STARTING_AT_INCREMENTAL,- partition_key="bucket_starting_at",+ partition_key="starting_at",+ supports_incremental=True,+ incremental_fields=[_datetime_incremental_field("starting_at")],+ bucket_width="1d", # cost report only supports daily granularity+ group_by=_COST_GROUP_BY,+ default_incremental_lookback_seconds=_REPORT_LOOKBACK_SECONDS,),}ENDPOINTS = tuple(ANTHROPIC_ENDPOINTS.keys())INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {- name: config.incremental_fields for name, config in ANTHROPIC_ENDPOINTS.items() if config.incremental_fields+ name: config.incremental_fields for name, config in ANTHROPIC_ENDPOINTS.items()}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/anthropic/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/anthropic/source.pyindex 8c4dfdfca5c1..806654ba755d 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/anthropic/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/anthropic/source.py@@ -19,6 +19,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.anthropic.validate_credentials as validate_anthropic_credentials,)from products.warehouse_sources.backend.temporal.data_imports.sources.anthropic.settings import (+ ANTHROPIC_ENDPOINTS,ENDPOINTS,INCREMENTAL_FIELDS,)@@ -41,26 +42,19 @@ class AnthropicSource(ResumableSource[AnthropicSourceConfig, AnthropicResumeConfdef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.ANTHROPIC- def get_non_retryable_errors(self) -> dict[str, str | None]:- return {- "401 Client Error: Unauthorized for url: https://api.anthropic.com": "Anthropic authentication failed. Please check that your Admin API key (sk-ant-admin...) is valid and has not been revoked.",- "403 Client Error: Forbidden for url: https://api.anthropic.com": "Anthropic denied access. Please check that you are using an Admin API key (sk-ant-admin...), not a regular API key.",- }-@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.ANTHROPIC,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,label="Anthropic",- caption="""Enter your Anthropic Admin API key to pull your organization's Claude API usage, costs, members, workspaces, and API keys into the PostHog Data warehouse.+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter your Anthropic Admin API key to pull your organization's Claude usage, cost, and admin data into the PostHog Data warehouse.-You need an **Admin API key** (starts with `sk-ant-admin...`), which only organization admins can create in the [Anthropic Console](https://console.anthropic.com/settings/admin-keys). Regular API keys (`sk-ant-api...`) do not work. The Admin API is not available for individual (non-organization) accounts.""",+Create an Admin API key (prefixed `sk-ant-admin...`) in your [Anthropic Console](https://console.anthropic.com/settings/admin-keys). Only organization admins can create one, and the Admin API is not available for individual accounts.""",iconPath="/static/services/anthropic.svg",docsUrl="https://posthog.com/docs/cdp/sources/anthropic",keywords=["llm", "claude", "ai usage", "cost"],- releaseStatus=ReleaseStatus.ALPHA,- unreleasedSource=True,fields=cast(list[FieldType],[@@ -83,6 +77,12 @@ You need an **Admin API key** (starts with `sk-ant-admin...`), which only organireturn CANONICAL_DESCRIPTIONS+ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error: Unauthorized for url: https://api.anthropic.com": "Your Anthropic Admin API key is invalid or has been revoked. Create a new Admin API key in the Anthropic Console, then reconnect.",+ "403 Client Error: Forbidden for url: https://api.anthropic.com": "Your Anthropic API key does not have organization admin access. Use an Admin API key (prefixed sk-ant-admin) created by an organization admin, then reconnect.",+ }+def get_schemas(self,config: AnthropicSourceConfig,@@ -91,20 +91,21 @@ You need an **Admin API key** (starts with `sk-ant-admin...`), which only organinames: list[str] | None = None,force_refresh: bool = False,) -> list[SourceSchema]:- schemas = [- SourceSchema(+ def _build_schema(endpoint: str) -> SourceSchema:+ endpoint_config = ANTHROPIC_ENDPOINTS[endpoint]+ return SourceSchema(name=endpoint,- supports_incremental=INCREMENTAL_FIELDS.get(endpoint, None) is not None,- supports_append=INCREMENTAL_FIELDS.get(endpoint, None) is not None,+ supports_incremental=endpoint_config.supports_incremental,+ supports_append=endpoint_config.supports_append,incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ should_sync_default=endpoint_config.should_sync_default,+ default_incremental_lookback_seconds=endpoint_config.default_incremental_lookback_seconds,)- for endpoint in list(ENDPOINTS)- ]+ schemas = [_build_schema(endpoint) for endpoint in ENDPOINTS]if names is not None:names_set = set(names)schemas = [s for s in schemas if s.name in names_set]-return schemasdef validate_credentials(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 2b66d90c935c..5a1c6c0374f8 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,420 +1,319 @@-from datetime import UTC, date, datetime-from typing import Any, Optional-from urllib.parse import parse_qs, urlparse+from datetime import UTC, datetime+from typing import Anyimport pytest-from unittest import mock+from unittest.mock import MagicMock, patch+import requestsfrom parameterized import parameterized+from products.warehouse_sources.backend.temporal.data_imports.sources.anthropic import anthropicfrom products.warehouse_sources.backend.temporal.data_imports.sources.anthropic.anthropic import (AnthropicResumeConfig,_build_url,- _compute_starting_at,- _flatten_report_buckets,- _to_start_datetime,- anthropic_source,+ _flatten_cost_result,+ _flatten_usage_result,+ _report_params,+ _row_id,get_rows,validate_credentials,)-from products.warehouse_sources.backend.temporal.data_imports.sources.anthropic.settings import (- ANTHROPIC_ENDPOINTS,- ENDPOINTS,-)--MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.anthropic.anthropic"+from products.warehouse_sources.backend.temporal.data_imports.sources.anthropic.source import AnthropicSource-def _make_manager(resume_state: AnthropicResumeConfig | None = None) -> mock.MagicMock:- manager = mock.MagicMock()- manager.can_resume.return_value = resume_state is not None- manager.load_state.return_value = resume_state- return manager+class _FakeResumableManager:+ def __init__(self, state: AnthropicResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[AnthropicResumeConfig] = []+ def can_resume(self) -> bool:+ return self._state is not None-def _response(payload: dict[str, Any], status_code: int = 200) -> mock.MagicMock:- response = mock.MagicMock()- response.status_code = status_code- response.ok = status_code < 400- response.json.return_value = payload- return response+ def load_state(self) -> AnthropicResumeConfig | None:+ return self._state+ def save_state(self, data: AnthropicResumeConfig) -> None:+ self.saved.append(data)-def _entity_page(items: list[dict[str, Any]], has_more: bool = False, last_id: Optional[str] = None) -> dict[str, Any]:- return {"data": items, "has_more": has_more, "first_id": None, "last_id": last_id}+def _collect(+ manager: _FakeResumableManager, monkeypatch: Any, responses: list[dict], endpoint: str, **kw: Any+) -> list[dict]:+ calls: list[str] = []-def _report_page(- buckets: list[dict[str, Any]], has_more: bool = False, next_page: Optional[str] = None-) -> dict[str, Any]:- return {"data": buckets, "has_more": has_more, "next_page": next_page}+ def fake_fetch(session: Any, url: str, headers: dict[str, str], logger: Any) -> dict:+ calls.append(url)+ return responses[len(calls) - 1]+ monkeypatch.setattr(anthropic, "_fetch_page", fake_fetch)-def _requested_urls(mock_session: mock.MagicMock) -> list[str]:- return [call.args[0] for call in mock_session.return_value.get.call_args_list]+ rows: list[dict] = []+ for table in get_rows(+ api_key="sk-ant-admin-test",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ **kw,+ ):+ rows.extend(table.to_pylist())+ manager._captured_calls = calls # type: ignore[attr-defined]+ return rows-def _query(url: str) -> dict[str, list[str]]:- return parse_qs(urlparse(url).query)+class TestRowId:+ def test_id_is_stable_across_metric_changes(self) -> None:+ # The surrogate key must depend only on identity dims, never metric values — otherwise a+ # restated bucket would get a new id and merge would insert a duplicate instead of updating.+ a = _row_id("2025-08-01T00:00:00Z", "wrkspc_1", "claude-opus-4-6")+ b = _row_id("2025-08-01T00:00:00Z", "wrkspc_1", "claude-opus-4-6")+ assert a == b+ def test_id_differs_by_dimension(self) -> None:+ a = _row_id("2025-08-01T00:00:00Z", "wrkspc_1", "claude-opus-4-6")+ b = _row_id("2025-08-01T00:00:00Z", "wrkspc_2", "claude-opus-4-6")+ assert a != b-class TestHelpers:- @parameterized.expand(- [- ("none", None, None),- ("aware_datetime", datetime(2026, 7, 1, 12, 0, tzinfo=UTC), datetime(2026, 7, 1, 12, 0, tzinfo=UTC)),- ("naive_datetime", datetime(2026, 7, 1, 12, 0), datetime(2026, 7, 1, 12, 0, tzinfo=UTC)),- ("date", date(2026, 7, 1), datetime(2026, 7, 1, tzinfo=UTC)),- ("iso_z_string", "2026-07-01T12:00:00Z", datetime(2026, 7, 1, 12, 0, tzinfo=UTC)),- ("iso_offset_string", "2026-07-01T12:00:00+00:00", datetime(2026, 7, 1, 12, 0, tzinfo=UTC)),- ("garbage_string", "not-a-date", None),- ("int", 12345, None),- ]- )- def test_to_start_datetime(self, _name, value, expected):- assert _to_start_datetime(value) == expected+ def test_none_and_empty_string_distinguished_positionally(self) -> None:+ # A missing dimension (None) must not collide with an empty-string value at the same position,+ # and positions stay aligned so distinct dimension tuples never collide either.+ assert _row_id(None, "x") != _row_id("", "x")+ assert _row_id(None, "x") != _row_id("x", None)- def test_compute_starting_at_defaults_on_first_sync(self):- assert _compute_starting_at(None) == "2023-01-01T00:00:00Z"- def test_compute_starting_at_applies_lookback_and_floors_to_midnight(self):- assert _compute_starting_at("2026-07-08T15:30:00Z") == "2026-07-07T00:00:00Z"+class TestBuildUrl:+ def test_repeats_multi_params(self) -> None:+ url = _build_url(+ "/v1/organizations/usage_report/messages", {"limit": 31}, {"group_by[]": ["model", "workspace_id"]}+ )+ assert url.count("group_by") == 2+ assert "limit=31" in url- def test_compute_starting_at_never_predates_default(self):- assert _compute_starting_at("2022-06-01T00:00:00Z") == "2023-01-01T00:00:00Z"+ def test_drops_none_values(self) -> None:+ url = _build_url("/v1/organizations/users", {"limit": 1000, "after_id": None})+ assert "after_id" not in url- def test_build_url_drops_none_values(self):- url = _build_url("/v1/organizations/users", {"limit": 500, "after_id": None})- assert url == "https://api.anthropic.com/v1/organizations/users?limit=500"- def test_build_url_no_params(self):- assert _build_url("/v1/organizations/users", {}) == "https://api.anthropic.com/v1/organizations/users"+class TestReportParams:+ def test_incremental_uses_watermark_as_starting_at(self) -> None:+ config = anthropic.ANTHROPIC_ENDPOINTS["usage_report"]+ params, multi = _report_params(+ config,+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 3, 4, 0, 0, 0, tzinfo=UTC),+ )+ assert params["starting_at"] == "2026-03-04T00:00:00Z"+ assert params["bucket_width"] == "1d"+ assert params["limit"] == 31+ assert multi == {"group_by[]": config.group_by}++ def test_full_refresh_falls_back_to_launch_date(self) -> None:+ # Without a watermark we must still send the required starting_at; the Anthropic launch date+ # pulls all available history without requesting decades of empty pre-launch buckets.+ config = anthropic.ANTHROPIC_ENDPOINTS["cost_report"]+ params, _ = _report_params(config, should_use_incremental_field=False, db_incremental_field_last_value=None)+ assert params["starting_at"] == "2023-01-01T00:00:00Z"+++class TestFlattenUsage:+ def test_flattens_nested_objects_and_adds_id(self) -> None:+ bucket = {"starting_at": "2025-08-01T00:00:00Z", "ending_at": "2025-08-02T00:00:00Z"}+ result = {+ "workspace_id": "wrkspc_1",+ "model": "claude-opus-4-6",+ "uncached_input_tokens": 1500,+ "output_tokens": 500,+ "cache_creation": {"ephemeral_1h_input_tokens": 1000, "ephemeral_5m_input_tokens": 500},+ "server_tool_use": {"web_search_requests": 10},+ }+ row = _flatten_usage_result(bucket, result)+ assert row["starting_at"] == "2025-08-01T00:00:00Z"+ assert row["cache_creation_ephemeral_1h_input_tokens"] == 1000+ assert row["cache_creation_ephemeral_5m_input_tokens"] == 500+ assert row["web_search_requests"] == 10+ assert row["id"]++ def test_missing_nested_objects_yield_none_not_crash(self) -> None:+ row = _flatten_usage_result({"starting_at": "s", "ending_at": "e"}, {"model": "m"})+ assert row["cache_creation_ephemeral_1h_input_tokens"] is None+ assert row["web_search_requests"] is None+++class TestFlattenCost:+ def test_amount_kept_as_string_and_id_added(self) -> None:+ # amount is a decimal string in cents; coercing it would lose precision.+ row = _flatten_cost_result(+ {"starting_at": "2025-08-01T00:00:00Z", "ending_at": "2025-08-02T00:00:00Z"},+ {"workspace_id": "wrkspc_1", "amount": "123.78912", "currency": "USD", "cost_type": "tokens"},+ )+ assert row["amount"] == "123.78912"+ assert row["currency"] == "USD"+ assert row["id"]- def test_build_url_expands_group_by_list(self):- url = _build_url("/v1/organizations/cost_report", {"group_by[]": ["workspace_id", "description"]})- assert _query(url)["group_by[]"] == ["workspace_id", "description"]- def test_flatten_report_buckets_builds_rows_with_synthetic_id(self):- config = ANTHROPIC_ENDPOINTS["cost_report"]- buckets = [+class TestReportPagination:+ def test_follows_next_page_until_has_more_false(self, monkeypatch: Any) -> None:+ responses = [{- "starting_at": "2026-07-01T00:00:00Z",- "ending_at": "2026-07-02T00:00:00Z",- "results": [- {- "amount": "123.45",- "currency": "USD",- "workspace_id": "wrkspc_1",- "description": "Claude Sonnet 4.5 Usage - Input Tokens",- "cost_type": "tokens",- "model": "claude-sonnet-4-5",- "service_tier": "standard",- "token_type": "uncached_input_tokens",- "context_window": "0-200k",- "inference_geo": "global",- },- ],+ "data": [{"starting_at": "d1", "ending_at": "d2", "results": [{"model": "a"}]}],+ "has_more": True,+ "next_page": "PAGE2",+ },+ {+ "data": [{"starting_at": "d2", "ending_at": "d3", "results": [{"model": "b"}]}],+ "has_more": False,+ "next_page": None,},]-- rows = _flatten_report_buckets(buckets, config)-- assert len(rows) == 1- row = rows[0]- assert row["bucket_starting_at"] == "2026-07-01T00:00:00Z"- assert row["bucket_ending_at"] == "2026-07-02T00:00:00Z"- assert row["amount"] == "123.45"- assert row["id"].startswith("2026-07-01T00:00:00Z|wrkspc_1|Claude Sonnet 4.5 Usage - Input Tokens|tokens")-- def test_flatten_report_buckets_distinguishes_rows_in_same_bucket(self):- config = ANTHROPIC_ENDPOINTS["usage_report"]- bucket = {- "starting_at": "2026-07-01T00:00:00Z",- "ending_at": "2026-07-02T00:00:00Z",- "results": [- {"model": "claude-sonnet-4-5", "workspace_id": "wrkspc_1", "output_tokens": 10},- {"model": "claude-opus-4-6", "workspace_id": "wrkspc_1", "output_tokens": 20},- ],- }-- rows = _flatten_report_buckets([bucket], config)-- assert len(rows) == 2- assert rows[0]["id"] != rows[1]["id"]-- def test_flatten_report_buckets_skips_empty_buckets(self):- config = ANTHROPIC_ENDPOINTS["usage_report"]- buckets = [{"starting_at": "2026-07-01T00:00:00Z", "ending_at": "2026-07-02T00:00:00Z", "results": []}]- assert _flatten_report_buckets(buckets, config) == []---class TestValidateCredentials:- @parameterized.expand(- [- ("ok", 200, True),- ("unauthorized", 401, False),- ("forbidden", 403, False),- ("server_error", 500, False),+ manager = _FakeResumableManager()+ rows = _collect(manager, monkeypatch, responses, "usage_report")+ assert [r["model"] for r in rows] == ["a", "b"]+ # Second request must carry the page token from the first response.+ assert "page=PAGE2" in manager._captured_calls[1] # type: ignore[attr-defined]++ def test_resumes_from_saved_page_cursor(self, monkeypatch: Any) -> None:+ responses = [+ {+ "data": [{"starting_at": "d2", "ending_at": "d3", "results": [{"model": "b"}]}],+ "has_more": False,+ "next_page": None,+ },]- )- def test_validate_credentials_status_mapping(self, _name, status_code, expected):- response = mock.MagicMock()- response.status_code = status_code-- with mock.patch(f"{MODULE}.make_tracked_session") as mock_session:- mock_session.return_value.get.return_value = response- assert validate_credentials("sk-ant-admin-test") is expected-- @mock.patch(f"{MODULE}.make_tracked_session")- def test_validate_credentials_swallows_exceptions(self, mock_session):- mock_session.return_value.get.side_effect = Exception("boom")- assert validate_credentials("sk-ant-admin-test") is False-- @mock.patch(f"{MODULE}.make_tracked_session")- def test_validate_credentials_sends_admin_headers(self, mock_session):- response = mock.MagicMock()- response.status_code = 200- mock_session.return_value.get.return_value = response-- validate_credentials("sk-ant-admin-test")+ manager = _FakeResumableManager(AnthropicResumeConfig(cursor="PAGE2"))+ rows = _collect(manager, monkeypatch, responses, "usage_report")+ assert [r["model"] for r in rows] == ["b"]+ assert "page=PAGE2" in manager._captured_calls[0] # type: ignore[attr-defined]- headers = mock_session.return_value.get.call_args.kwargs["headers"]- assert headers["x-api-key"] == "sk-ant-admin-test"- assert headers["anthropic-version"] == "2023-06-01"+ def test_drains_every_chunk_when_a_batch_splits(self, monkeypatch: Any) -> None:+ # A batch can split into several ready chunks (byte/offset caps). Force it with tiny limits:+ # if the loop only pops one chunk per batch, the next batch() raises and rows go missing.+ real_batcher = anthropic.Batcher+ def tiny_batcher(**_: Any) -> anthropic.Batcher:+ return real_batcher(logger=MagicMock(), chunk_size=4, chunk_size_bytes=10**12, max_table_bytes=1)-class TestEntityEndpoints:- @mock.patch(f"{MODULE}.make_tracked_session")- def test_paginates_with_after_id_and_saves_state_after_each_page(self, mock_session):- manager = _make_manager()- mock_session.return_value.get.side_effect = [- _response(_entity_page([{"id": "user_1"}], has_more=True, last_id="user_1")),- _response(_entity_page([{"id": "user_2"}], has_more=False, last_id="user_2")),- ]-- batches = list(get_rows("key", "users", mock.MagicMock(), manager))-- assert batches == [[{"id": "user_1"}], [{"id": "user_2"}]]- urls = _requested_urls(mock_session)- assert "after_id" not in _query(urls[0])- assert _query(urls[1])["after_id"] == ["user_1"]- # State is only saved when there is another page to fetch.- manager.save_state.assert_called_once_with(AnthropicResumeConfig(after_id="user_1"))+ monkeypatch.setattr(anthropic, "Batcher", tiny_batcher)- @mock.patch(f"{MODULE}.make_tracked_session")- def test_resumes_entity_list_from_saved_cursor(self, mock_session):- manager = _make_manager(AnthropicResumeConfig(after_id="user_5"))- mock_session.return_value.get.side_effect = [- _response(_entity_page([{"id": "user_6"}], has_more=False, last_id="user_6")),+ results = [{"model": f"m{i}"} for i in range(8)]+ responses = [+ {+ "data": [{"starting_at": "d1", "ending_at": "d2", "results": results}],+ "has_more": False,+ "next_page": None,+ }]+ rows = _collect(_FakeResumableManager(), monkeypatch, responses, "usage_report")+ assert sorted(r["model"] for r in rows) == [f"m{i}" for i in range(8)]- batches = list(get_rows("key", "users", mock.MagicMock(), manager))-- assert batches == [[{"id": "user_6"}]]- assert _query(_requested_urls(mock_session)[0])["after_id"] == ["user_5"]- @mock.patch(f"{MODULE}.make_tracked_session")- def test_workspaces_requests_archived_workspaces(self, mock_session):- manager = _make_manager()- mock_session.return_value.get.side_effect = [- _response(_entity_page([{"id": "wrkspc_1"}], has_more=False, last_id="wrkspc_1")),+class TestEntityPagination:+ def test_cursor_pagination_uses_last_id_and_stops(self, monkeypatch: Any) -> None:+ responses = [+ {"data": [{"id": "user_1"}], "has_more": True, "last_id": "user_1"},+ {"data": [{"id": "user_2"}], "has_more": False, "last_id": "user_2"},]+ manager = _FakeResumableManager()+ rows = _collect(manager, monkeypatch, responses, "users")+ assert [r["id"] for r in rows] == ["user_1", "user_2"]+ assert "after_id=user_1" in manager._captured_calls[1] # type: ignore[attr-defined]- list(get_rows("key", "workspaces", mock.MagicMock(), manager))-- assert _query(_requested_urls(mock_session)[0])["include_archived"] == ["true"]-- @mock.patch(f"{MODULE}.make_tracked_session")- def test_empty_list_yields_no_batches(self, mock_session):- manager = _make_manager()- mock_session.return_value.get.side_effect = [_response(_entity_page([], has_more=False))]-- assert list(get_rows("key", "invites", mock.MagicMock(), manager)) == []-- @mock.patch(f"{MODULE}.make_tracked_session")- def test_stops_when_has_more_but_no_last_id(self, mock_session):- manager = _make_manager()- mock_session.return_value.get.side_effect = [- _response(_entity_page([{"id": "user_1"}], has_more=True, last_id=None)),+ def test_api_keys_flatten_created_by(self, monkeypatch: Any) -> None:+ responses = [+ {+ "data": [{"id": "apikey_1", "created_by": {"id": "user_1", "type": "user"}}],+ "has_more": False,+ "last_id": "apikey_1",+ }]-- batches = list(get_rows("key", "users", mock.MagicMock(), manager))-- assert batches == [[{"id": "user_1"}]]- assert mock_session.return_value.get.call_count == 1+ rows = _collect(_FakeResumableManager(), monkeypatch, responses, "api_keys")+ assert rows[0]["created_by_id"] == "user_1"+ assert rows[0]["created_by_type"] == "user"+ assert "created_by" not in rows[0]class TestWorkspaceMembersFanOut:- @mock.patch(f"{MODULE}.make_tracked_session")- def test_fans_out_over_each_workspace(self, mock_session):- manager = _make_manager()- member_1 = {"type": "workspace_member", "user_id": "user_1", "workspace_id": "wrkspc_1"}- member_2 = {"type": "workspace_member", "user_id": "user_1", "workspace_id": "wrkspc_2"}- mock_session.return_value.get.side_effect = [- _response(_entity_page([{"id": "wrkspc_1"}, {"id": "wrkspc_2"}], has_more=False, last_id="wrkspc_2")),- _response(_entity_page([member_1], has_more=False)),- _response(_entity_page([member_2], has_more=False)),- ]-- batches = list(get_rows("key", "workspace_members", mock.MagicMock(), manager))-- assert batches == [[member_1], [member_2]]- urls = _requested_urls(mock_session)- assert urls[0].startswith("https://api.anthropic.com/v1/organizations/workspaces?")- assert urls[1].startswith("https://api.anthropic.com/v1/organizations/workspaces/wrkspc_1/members")- assert urls[2].startswith("https://api.anthropic.com/v1/organizations/workspaces/wrkspc_2/members")-- @mock.patch(f"{MODULE}.make_tracked_session")- def test_fan_out_paginates_members_within_a_workspace(self, mock_session):- manager = _make_manager()- mock_session.return_value.get.side_effect = [- _response(_entity_page([{"id": "wrkspc_1"}], has_more=False, last_id="wrkspc_1")),- _response(_entity_page([{"user_id": "user_1", "workspace_id": "wrkspc_1"}], True, "user_1")),- _response(_entity_page([{"user_id": "user_2", "workspace_id": "wrkspc_1"}], False, "user_2")),+ def test_emits_one_row_per_workspace_member_with_composite_key(self, monkeypatch: Any) -> None:+ # First response lists workspaces, then one members page per workspace.+ responses = [+ {"data": [{"id": "wrkspc_1"}, {"id": "wrkspc_2"}], "has_more": False, "last_id": "wrkspc_2"},+ {+ "data": [{"type": "workspace_member", "user_id": "u1", "workspace_id": "wrkspc_1"}],+ "has_more": False,+ "last_id": "u1",+ },+ {+ "data": [{"type": "workspace_member", "user_id": "u2", "workspace_id": "wrkspc_2"}],+ "has_more": False,+ "last_id": "u2",+ },]+ rows = _collect(_FakeResumableManager(), monkeypatch, responses, "workspace_members")+ assert [(r["workspace_id"], r["user_id"]) for r in rows] == [("wrkspc_1", "u1"), ("wrkspc_2", "u2")]- batches = list(get_rows("key", "workspace_members", mock.MagicMock(), manager))-- assert len(batches) == 2- assert _query(_requested_urls(mock_session)[2])["after_id"] == ["user_1"]+class TestValidateCredentials:+ @parameterized.expand([("ok", 200, True), ("forbidden_scope", 403, True), ("unauthorized", 401, False)])+ def test_status_mapping(self, _name: str, status: int, expected: bool) -> None:+ # 403 is accepted at create time (real key, unprobed scope); 401 means a bad key.+ response = MagicMock(status_code=status)+ session = MagicMock()+ session.get.return_value = response+ with patch.object(anthropic, "make_tracked_session", return_value=session):+ assert validate_credentials("sk-ant-admin-test") is expected-class TestReportEndpoints:- @mock.patch(f"{MODULE}.make_tracked_session")- def test_usage_report_request_params(self, mock_session):- manager = _make_manager()- mock_session.return_value.get.side_effect = [_response(_report_page([], has_more=False))]+ def test_network_error_is_invalid(self) -> None:+ session = MagicMock()+ session.get.side_effect = requests.ConnectionError("boom")+ with patch.object(anthropic, "make_tracked_session", return_value=session):+ assert validate_credentials("sk-ant-admin-test") is False- list(get_rows("key", "usage_report", mock.MagicMock(), manager))- query = _query(_requested_urls(mock_session)[0])- assert query["starting_at"] == ["2023-01-01T00:00:00Z"]- assert query["bucket_width"] == ["1d"]- assert query["limit"] == ["31"]- assert query["group_by[]"] == [- "api_key_id",- "workspace_id",- "model",- "service_tier",- "context_window",- "inference_geo",+class TestNonRetryableErrors:+ @parameterized.expand(+ [+ (+ "unauthorized",+ "401 Client Error: Unauthorized for url: https://api.anthropic.com/v1/organizations/users?limit=1",+ ),+ (+ "forbidden",+ "403 Client Error: Forbidden for url: https://api.anthropic.com/v1/organizations/cost_report",+ ),]- assert "page" not in query-- @mock.patch(f"{MODULE}.make_tracked_session")- def test_cost_report_omits_bucket_width_and_groups_by_workspace_and_description(self, mock_session):- manager = _make_manager()- mock_session.return_value.get.side_effect = [_response(_report_page([], has_more=False))]-- list(get_rows("key", "cost_report", mock.MagicMock(), manager))-- query = _query(_requested_urls(mock_session)[0])- # The cost report is daily-only; sending bucket_width is unnecessary.- assert "bucket_width" not in query- assert query["group_by[]"] == ["workspace_id", "description"]-- @mock.patch(f"{MODULE}.make_tracked_session")- def test_incremental_sync_starts_from_watermark_with_lookback(self, mock_session):- manager = _make_manager()- mock_session.return_value.get.side_effect = [_response(_report_page([], has_more=False))]-- list(- get_rows(- "key",- "usage_report",- mock.MagicMock(),- manager,- should_use_incremental_field=True,- db_incremental_field_last_value="2026-07-08T00:00:00Z",- )- )-- assert _query(_requested_urls(mock_session)[0])["starting_at"] == ["2026-07-07T00:00:00Z"]+ )+ def test_credential_errors_are_non_retryable(self, _name: str, observed_error: str) -> None:+ non_retryable = AnthropicSource().get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable)- @mock.patch(f"{MODULE}.make_tracked_session")- def test_paginates_with_page_token_and_saves_state_after_each_page(self, mock_session):- manager = _make_manager()- bucket_1 = {- "starting_at": "2026-07-01T00:00:00Z",- "ending_at": "2026-07-02T00:00:00Z",- "results": [{"model": "claude-sonnet-4-5", "output_tokens": 10}],- }- bucket_2 = {- "starting_at": "2026-07-02T00:00:00Z",- "ending_at": "2026-07-03T00:00:00Z",- "results": [{"model": "claude-sonnet-4-5", "output_tokens": 20}],- }- mock_session.return_value.get.side_effect = [- _response(_report_page([bucket_1], has_more=True, next_page="page_2")),- _response(_report_page([bucket_2], has_more=False)),+ @parameterized.expand(+ [+ ("read_timeout", "HTTPSConnectionPool(host='api.anthropic.com', port=443): Read timed out."),+ (+ "server_error",+ "500 Server Error: Internal Server Error for url: https://api.anthropic.com/v1/organizations/users",+ ),]-- batches = list(get_rows("key", "usage_report", mock.MagicMock(), manager))-- assert len(batches) == 2- assert batches[0][0]["bucket_starting_at"] == "2026-07-01T00:00:00Z"- assert batches[1][0]["bucket_starting_at"] == "2026-07-02T00:00:00Z"- assert _query(_requested_urls(mock_session)[1])["page"] == ["page_2"]- manager.save_state.assert_called_once_with(- AnthropicResumeConfig(starting_at="2023-01-01T00:00:00Z", page="page_2")- )-- @mock.patch(f"{MODULE}.make_tracked_session")- def test_resumes_report_from_saved_window_and_page(self, mock_session):- manager = _make_manager(AnthropicResumeConfig(starting_at="2026-06-01T00:00:00Z", page="page_9"))- mock_session.return_value.get.side_effect = [_response(_report_page([], has_more=False))]-- list(get_rows("key", "usage_report", mock.MagicMock(), manager))-- query = _query(_requested_urls(mock_session)[0])- assert query["starting_at"] == ["2026-06-01T00:00:00Z"]- assert query["page"] == ["page_9"]-- @mock.patch(f"{MODULE}.make_tracked_session")- def test_stops_when_has_more_but_no_next_page(self, mock_session):- manager = _make_manager()- mock_session.return_value.get.side_effect = [_response(_report_page([], has_more=True, next_page=None))]-- assert list(get_rows("key", "usage_report", mock.MagicMock(), manager)) == []- assert mock_session.return_value.get.call_count == 1---class TestErrorHandling:- @mock.patch(f"{MODULE}.make_tracked_session")- def test_client_error_raises(self, mock_session):- manager = _make_manager()- response = _response({}, status_code=400)- response.raise_for_status.side_effect = Exception("400 Client Error")- mock_session.return_value.get.return_value = response-- with pytest.raises(Exception, match="400 Client Error"):- list(get_rows("key", "users", mock.MagicMock(), manager))---class TestAnthropicSource:- @parameterized.expand(ENDPOINTS)- def test_source_response_shape(self, endpoint):- response = anthropic_source("key", endpoint, mock.MagicMock(), _make_manager())-- assert response.name == endpoint- assert response.primary_keys == ANTHROPIC_ENDPOINTS[endpoint].primary_keys- assert response.sort_mode == "asc"-- @parameterized.expand(["usage_report", "cost_report"])- def test_report_endpoints_partition_on_bucket_start(self, endpoint):- response = anthropic_source("key", endpoint, mock.MagicMock(), _make_manager())-- assert response.partition_mode == "datetime"- assert response.partition_format == "month"- assert response.partition_keys == ["bucket_starting_at"]-- @parameterized.expand(["users", "invites", "workspaces", "workspace_members", "api_keys"])- def test_entity_endpoints_are_not_partitioned(self, endpoint):- response = anthropic_source("key", endpoint, mock.MagicMock(), _make_manager())-- assert response.partition_mode is None- assert response.partition_keys is None-- def test_workspace_members_uses_composite_primary_key(self):- response = anthropic_source("key", "workspace_members", mock.MagicMock(), _make_manager())- assert response.primary_keys == ["workspace_id", "user_id"]+ )+ def test_transient_errors_remain_retryable(self, _name: str, other_error: str) -> None:+ non_retryable = AnthropicSource().get_non_retryable_errors()+ assert not any(key in other_error for key in non_retryable)+++class TestFetchPage:+ @parameterized.expand([("rate_limited", 429), ("server_error", 503)])+ def test_retryable_statuses_raise_retryable_error(self, _name: str, status: int) -> None:+ response = MagicMock(status_code=status, ok=False)+ session = MagicMock()+ session.get.return_value = response+ with patch.object(anthropic._fetch_page.retry, "sleep", lambda *_: None): # type: ignore[attr-defined]+ with pytest.raises(anthropic.AnthropicRetryableError):+ anthropic._fetch_page(session, "https://api.anthropic.com/v1/organizations/users", {}, MagicMock())+ assert session.get.call_count == 5 # exhausts the retry budget++ def test_client_error_raises_for_status_without_retry(self) -> None:+ response = MagicMock(status_code=401, ok=False, text="unauthorized")+ response.raise_for_status.side_effect = requests.HTTPError("401 Client Error", response=response)+ session = MagicMock()+ session.get.return_value = response+ with pytest.raises(requests.HTTPError):+ anthropic._fetch_page(session, "https://api.anthropic.com/v1/organizations/users", {}, MagicMock())+ assert session.get.call_count == 1diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/anthropic/tests/test_anthropic_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/anthropic/tests/test_anthropic_source.pyindex a637092b9795..8626f0e39728 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/anthropic/tests/test_anthropic_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/anthropic/tests/test_anthropic_source.py@@ -1,147 +1,110 @@-from unittest import mock+from unittest.mock import MagicMockfrom parameterized import parameterized-from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType+from posthog.schema import (+ ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,+ SourceFieldInputConfig,+)from products.warehouse_sources.backend.temporal.data_imports.sources.anthropic.anthropic import AnthropicResumeConfig-from products.warehouse_sources.backend.temporal.data_imports.sources.anthropic.settings import (- ENDPOINTS,- INCREMENTAL_FIELDS,-)from products.warehouse_sources.backend.temporal.data_imports.sources.anthropic.source import AnthropicSource-from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager-from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import AnthropicSourceConfigfrom products.warehouse_sources.backend.types import ExternalDataSourceType-class TestAnthropicSource:- def setup_method(self):- self.source = AnthropicSource()- self.team_id = 123- self.config = AnthropicSourceConfig(api_key="sk-ant-admin-test")-- def test_source_type(self):- assert self.source.source_type == ExternalDataSourceType.ANTHROPIC+class TestAnthropicSourceConfig:+ def test_source_type(self) -> None:+ assert AnthropicSource().source_type == ExternalDataSourceType.ANTHROPIC- def test_get_source_config(self):- config = self.source.get_source_config-- assert config.name.value == "Anthropic"- assert config.label == "Anthropic"+ def test_config_exposes_single_secret_api_key_field(self) -> None:+ config = AnthropicSource().get_source_config+ assert config.name == SchemaExternalDataSourceType.ANTHROPICassert config.releaseStatus == ReleaseStatus.ALPHA- assert config.unreleasedSource is True- assert config.iconPath == "/static/services/anthropic.svg"assert config.docsUrl == "https://posthog.com/docs/cdp/sources/anthropic"+ assert config.unreleasedSource is None+ fields = [f for f in config.fields if isinstance(f, SourceFieldInputConfig)]+ assert [f.name for f in fields] == ["api_key"]+ assert fields[0].secret is True and fields[0].required is True+++class TestAnthropicSchemas:+ def test_all_endpoints_present(self) -> None:+ names = {s.name for s in AnthropicSource().get_schemas(MagicMock(), team_id=1)}+ assert names == {+ "users",+ "invites",+ "workspaces",+ "api_keys",+ "workspace_members",+ "usage_report",+ "cost_report",+ }++ @parameterized.expand([("usage_report",), ("cost_report",)])+ def test_report_endpoints_are_incremental_on_starting_at(self, endpoint: str) -> None:+ # Only the report endpoints have a genuine server-side time filter (starting_at).+ schema = next(s for s in AnthropicSource().get_schemas(MagicMock(), team_id=1) if s.name == endpoint)+ assert schema.supports_incremental is True+ assert schema.supports_append is False # buckets get restated; append would duplicate+ assert [f["field"] for f in schema.incremental_fields] == ["starting_at"]+ assert schema.default_incremental_lookback_seconds == 60 * 60 * 24++ @parameterized.expand([("users",), ("workspaces",), ("api_keys",), ("workspace_members",), ("invites",)])+ def test_entity_endpoints_are_full_refresh_only(self, endpoint: str) -> None:+ # No updated-since filter exists on the entity lists, so they must not advertise incremental.+ schema = next(s for s in AnthropicSource().get_schemas(MagicMock(), team_id=1) if s.name == endpoint)+ assert schema.supports_incremental is False+ assert schema.supports_append is False++ def test_names_filter(self) -> None:+ schemas = AnthropicSource().get_schemas(MagicMock(), team_id=1, names=["usage_report"])+ assert [s.name for s in schemas] == ["usage_report"]+++class TestAnthropicResumableManager:+ def test_manager_bound_to_resume_config(self) -> None:+ inputs = MagicMock()+ manager = AnthropicSource().get_resumable_source_manager(inputs)+ assert manager._data_class is AnthropicResumeConfig- field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]- assert field_names == ["api_key"]-- def test_api_key_field_is_secret_password(self):- config = self.source.get_source_config- key_field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_key")- assert key_field.type == SourceFieldInputConfigType.PASSWORD- assert key_field.secret is True- assert key_field.required is True-- @parameterized.expand(- [- "401 Client Error: Unauthorized for url: https://api.anthropic.com/v1/organizations/users?limit=500",- "403 Client Error: Forbidden for url: https://api.anthropic.com/v1/organizations/cost_report",- ]- )- def test_non_retryable_errors_match_auth_failures(self, observed_error):- non_retryable_errors = self.source.get_non_retryable_errors()- assert any(key in observed_error for key in non_retryable_errors)-- @parameterized.expand(- [- "401 Client Error: Unauthorized for url: https://api.stripe.com/v1/customers",- "500 Server Error for url: https://api.anthropic.com/v1/organizations/users",- ]- )- def test_non_retryable_errors_does_not_match_unrelated(self, other_vendor_error):- non_retryable_errors = self.source.get_non_retryable_errors()- assert not any(key in other_vendor_error for key in non_retryable_errors)-- def test_get_schemas(self):- schemas = self.source.get_schemas(self.config, self.team_id)-- assert {schema.name for schema in schemas} == set(ENDPOINTS)- incremental = {schema.name for schema in schemas if schema.supports_incremental}- # Only the report endpoints expose a server-side starting_at filter.- assert incremental == {"usage_report", "cost_report"}-- def test_incremental_schemas_advertise_their_fields(self):- schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}-- assert schemas["usage_report"].incremental_fields == INCREMENTAL_FIELDS["usage_report"]- assert schemas["cost_report"].incremental_fields == INCREMENTAL_FIELDS["cost_report"]- assert schemas["users"].incremental_fields == []- assert schemas["users"].supports_append is False-- def test_get_schemas_filtered_by_names(self):- schemas = self.source.get_schemas(self.config, self.team_id, names=["usage_report"])- assert len(schemas) == 1- assert schemas[0].name == "usage_report"- def test_get_schemas_filtered_unknown_name_returns_empty(self):- assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []+class TestAnthropicSourceForPipeline:+ def _response(self, endpoint: str) -> object:+ inputs = MagicMock()+ inputs.schema_name = endpoint+ inputs.logger = MagicMock()+ inputs.should_use_incremental_field = True+ inputs.db_incremental_field_last_value = None+ config = MagicMock(api_key="sk-ant-admin-test")+ return AnthropicSource().source_for_pipeline(config, MagicMock(), inputs)@parameterized.expand([- ("valid", True, True, None),- ("invalid", False, False, "Invalid Anthropic Admin API key"),+ ("usage_report", ["id"], "datetime"),+ ("cost_report", ["id"], "datetime"),+ ("users", ["id"], "datetime"),+ ("workspace_members", ["workspace_id", "user_id"], None),])- def test_validate_credentials(self, _name, mock_return, expected_valid, expected_message):- with mock.patch(- "products.warehouse_sources.backend.temporal.data_imports.sources.anthropic.source.validate_anthropic_credentials"- ) as mock_validate:- mock_validate.return_value = mock_return-- is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)-- assert is_valid is expected_valid- assert error_message == expected_message- mock_validate.assert_called_once_with(self.config.api_key)-- def test_get_resumable_source_manager_binds_resume_config(self):- inputs = mock.MagicMock()- manager = self.source.get_resumable_source_manager(inputs)-- assert isinstance(manager, ResumableSourceManager)- assert manager._data_class is AnthropicResumeConfig-- @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.anthropic.source.anthropic_source")- def test_source_for_pipeline_plumbs_arguments(self, mock_anthropic_source):- inputs = mock.MagicMock()- inputs.schema_name = "usage_report"- inputs.should_use_incremental_field = True- inputs.db_incremental_field_last_value = "2026-07-01T00:00:00Z"- manager = mock.MagicMock()-- self.source.source_for_pipeline(self.config, manager, inputs)-- mock_anthropic_source.assert_called_once()- kwargs = mock_anthropic_source.call_args.kwargs- assert kwargs["api_key"] == "sk-ant-admin-test"- assert kwargs["endpoint"] == "usage_report"- assert kwargs["resumable_source_manager"] is manager- assert kwargs["should_use_incremental_field"] is True- assert kwargs["db_incremental_field_last_value"] == "2026-07-01T00:00:00Z"-- @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.anthropic.source.anthropic_source")- def test_source_for_pipeline_omits_last_value_on_full_refresh(self, mock_anthropic_source):- inputs = mock.MagicMock()- inputs.schema_name = "users"- inputs.should_use_incremental_field = False- inputs.db_incremental_field_last_value = "2026-07-01T00:00:00Z"-- self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)-- assert mock_anthropic_source.call_args.kwargs["db_incremental_field_last_value"] is None-- def test_canonical_descriptions_cover_every_endpoint(self):- descriptions = self.source.get_canonical_descriptions()- assert set(descriptions.keys()) == set(ENDPOINTS)+ def test_primary_keys_and_partitioning(+ self, endpoint: str, primary_keys: list[str], partition_mode: str | None+ ) -> None:+ response = self._response(endpoint)+ assert response.name == endpoint # type: ignore[attr-defined]+ assert response.primary_keys == primary_keys # type: ignore[attr-defined]+ assert response.sort_mode == "asc" # type: ignore[attr-defined]+ # workspace_members has no stable timestamp field, so it is not partitioned.+ assert response.partition_mode == partition_mode # type: ignore[attr-defined]+++class TestDocumentedTables:+ def test_lists_tables_without_credentials(self) -> None:+ # Static endpoint catalog => the source opts into publishing its table list to public docs.+ assert AnthropicSource().lists_tables_without_credentials is True+ tables = AnthropicSource().get_documented_tables()+ names = {t["name"] for t in tables}+ assert "usage_report" in names and "cost_report" in names+ usage = next(t for t in tables if t["name"] == "usage_report")+ assert "Incremental" in usage["sync_methods"]+ assert usage["description"] # canonical description is surfaced