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.

feat(data-warehouse): implement anthropic import source (#69621)

Tom Owersf46988f6cfdf
diff --git a/frontend/public/services/anthropic.svg b/frontend/public/services/anthropic.svg
new file mode 100644
index 000000000000..c917480d3259
--- /dev/null
+++ b/frontend/public/services/anthropic.svg
@@ -0,0 +1 @@
+<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
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index 78e7ac513be8..81f147d1ff54 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -53,6 +53,7 @@ the row lists both.
| alpha_vantage | HTTP | requests | ✅ |
| amazon_ads | HTTP | requests | ✅ |
| amplitude | HTTP | requests | ✅ |
+| anthropic | HTTP | requests | ✅ |
| apify_dataset | HTTP | requests | ✅ |
| apollo | HTTP | requests | ✅ |
| appfigures | HTTP | requests | ✅ |
@@ -454,7 +455,6 @@ doesn't conflict with concurrent PRs.
- amazon_selling_partner
- amazon_sns
- amazon_sqs
-- anthropic
- appcues
- apple_search_ads
- appstack
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
new file mode 100644
index 000000000000..e420e71529f5
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/anthropic/anthropic.py
@@ -0,0 +1,270 @@
+import dataclasses
+from collections.abc import Callable, Iterator
+from datetime import UTC, date, datetime, timedelta
+from typing import Any, Optional
+from urllib.parse import urlencode
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.anthropic.settings import (
+ ANTHROPIC_ENDPOINTS,
+ AnthropicEndpointConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+
+ANTHROPIC_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).
+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 = 5
+
+
+class AnthropicRetryableError(Exception):
+ pass
+
+
+class 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
+
+
+def _get_headers(api_key: str) -> dict[str, str]:
+ return {
+ "x-api-key": api_key,
+ "anthropic-version": ANTHROPIC_VERSION,
+ "accept": "application/json",
+ }
+
+
+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 _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
+
+
+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."""
+ 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
+ except Exception:
+ return False
+
+
+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}")
+
+ 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()
+
+ return fetch_page
+
+
+def _entity_pages(
+ fetch_page: Callable[[str], dict[str, Any]],
+ 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."""
+ while True:
+ params: dict[str, Any] = {**config.params, "limit": ENTITY_PAGE_SIZE}
+ if after_id:
+ params["after_id"] = after_id
+
+ data = fetch_page(_build_url(config.path, params))
+ items = data.get("data") or []
+
+ if items:
+ yield items
+
+ after_id = data.get("last_id")
+ if not data.get("has_more") or not after_id:
+ break
+
+ if on_page_complete is not None:
+ on_page_complete(after_id)
+
+
+def get_rows(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[AnthropicResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+) -> Iterator[list[dict[str, 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,
+ config,
+ after_id,
+ on_page_complete=lambda last_id: resumable_source_manager.save_state(
+ AnthropicResumeConfig(after_id=last_id)
+ ),
+ )
+ 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)
+ 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))
+
+
+def anthropic_source(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[AnthropicResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> SourceResponse:
+ config = ANTHROPIC_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ api_key=api_key,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=should_use_incremental_field,
+ 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.
+ sort_mode="asc",
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime" if config.partition_key else None,
+ partition_format="month" if config.partition_key else None,
+ partition_keys=[config.partition_key] if config.partition_key else None,
+ )
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.py
new file mode 100644
index 000000000000..824a92f39320
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/anthropic/canonical_descriptions.py
@@ -0,0 +1,110 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+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",
+ "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.",
+ },
+ },
+ "invites": {
+ "description": "Pending and historical invitations to join your Anthropic organization.",
+ "docs_url": "https://platform.claude.com/docs/en/api/admin/invites/list",
+ "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.",
+ },
+ },
+ "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",
+ "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.",
+ "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",
+ "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.",
+ },
+ },
+ "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",
+ "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.",
+ },
+ },
+ "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",
+ "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.",
+ },
+ },
+ "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",
+ "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.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/anthropic/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/anthropic/settings.py
new file mode 100644
index 000000000000..99d70031dff2
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/anthropic/settings.py
@@ -0,0 +1,113 @@
+from dataclasses import dataclass, field
+from typing import Literal, Optional
+
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+
+@dataclass
+class AnthropicEndpointConfig:
+ name: str
+ path: 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"]
+ primary_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.
+ partition_key: Optional[str] = None
+
+
+_BUCKET_STARTING_AT_INCREMENTAL: list[IncrementalField] = [
+ {
+ "label": "bucket_starting_at",
+ "type": IncrementalFieldType.DateTime,
+ "field": "bucket_starting_at",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+]
+
+ANTHROPIC_ENDPOINTS: dict[str, AnthropicEndpointConfig] = {
+ "users": AnthropicEndpointConfig(
+ name="users",
+ path="/v1/organizations/users",
+ kind="entity",
+ primary_keys=["id"],
+ ),
+ "invites": AnthropicEndpointConfig(
+ name="invites",
+ path="/v1/organizations/invites",
+ kind="entity",
+ primary_keys=["id"],
+ ),
+ "workspaces": AnthropicEndpointConfig(
+ name="workspaces",
+ path="/v1/organizations/workspaces",
+ kind="entity",
+ 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"],
+ ),
+ "api_keys": AnthropicEndpointConfig(
+ name="api_keys",
+ path="/v1/organizations/api_keys",
+ kind="entity",
+ primary_keys=["id"],
+ ),
+ "usage_report": AnthropicEndpointConfig(
+ name="usage_report",
+ path="/v1/organizations/usage_report/messages",
+ kind="report",
+ 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"],
+ bucket_width="1d",
+ incremental_fields=_BUCKET_STARTING_AT_INCREMENTAL,
+ partition_key="bucket_starting_at",
+ ),
+ "cost_report": AnthropicEndpointConfig(
+ name="cost_report",
+ path="/v1/organizations/cost_report",
+ kind="report",
+ 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",
+ ),
+}
+
+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
+}
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.py
index cb606178bac6..8c4dfdfca5c1 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
@@ -1,31 +1,136 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (
+ SourceInputs,
+ SourceResponse,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.anthropic.anthropic import (
+ AnthropicResumeConfig,
+ anthropic_source,
+ validate_credentials as validate_anthropic_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.anthropic.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchema
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import AnthropicSourceConfig
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class AnthropicSource(SimpleSource[AnthropicSourceConfig]):
+class AnthropicSource(ResumableSource[AnthropicSourceConfig, AnthropicResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def 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.",
+ }
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.ANTHROPIC,
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
label="Anthropic",
- iconPath="/static/services/anthropic.png",
+ 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.
+
+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.""",
+ iconPath="/static/services/anthropic.svg",
+ docsUrl="https://posthog.com/docs/cdp/sources/anthropic",
keywords=["llm", "claude", "ai usage", "cost"],
- fields=cast(list[FieldType], []),
+ releaseStatus=ReleaseStatus.ALPHA,
unreleasedSource=True,
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="Admin API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="sk-ant-admin...",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.anthropic.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: AnthropicSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ supports_incremental=INCREMENTAL_FIELDS.get(endpoint, None) is not None,
+ supports_append=INCREMENTAL_FIELDS.get(endpoint, None) is not None,
+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
+ )
+ for endpoint in list(ENDPOINTS)
+ ]
+
+ if names is not None:
+ names_set = set(names)
+ schemas = [s for s in schemas if s.name in names_set]
+
+ return schemas
+
+ def validate_credentials(
+ self, config: AnthropicSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ if validate_anthropic_credentials(config.api_key):
+ return True, None
+
+ return False, "Invalid Anthropic Admin API key"
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[AnthropicResumeConfig]:
+ return ResumableSourceManager[AnthropicResumeConfig](inputs, AnthropicResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: AnthropicSourceConfig,
+ resumable_source_manager: ResumableSourceManager[AnthropicResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return anthropic_source(
+ api_key=config.api_key,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=inputs.should_use_incremental_field,
+ db_incremental_field_last_value=inputs.db_incremental_field_last_value
+ if inputs.should_use_incremental_field
+ else None,
)
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
new file mode 100644
index 000000000000..2b66d90c935c
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/anthropic/tests/test_anthropic.py
@@ -0,0 +1,420 @@
+from datetime import UTC, date, datetime
+from typing import Any, Optional
+from urllib.parse import parse_qs, urlparse
+
+import pytest
+from unittest import mock
+
+from parameterized import parameterized
+
+from 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,
+ 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"
+
+
+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
+
+
+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 _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 _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 _requested_urls(mock_session: mock.MagicMock) -> list[str]:
+ return [call.args[0] for call in mock_session.return_value.get.call_args_list]
+
+
+def _query(url: str) -> dict[str, list[str]]:
+ return parse_qs(urlparse(url).query)
+
+
+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_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"
+
+ 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_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"
+
+ 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 = [
+ {
+ "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",
+ },
+ ],
+ },
+ ]
+
+ 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),
+ ]
+ )
+ 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")
+
+ 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"
+
+
+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"))
+
+ @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")),
+ ]
+
+ 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")),
+ ]
+
+ 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)),
+ ]
+
+ batches = list(get_rows("key", "users", mock.MagicMock(), manager))
+
+ assert batches == [[{"id": "user_1"}]]
+ assert mock_session.return_value.get.call_count == 1
+
+
+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")),
+ ]
+
+ 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 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))]
+
+ 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",
+ ]
+ 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"]
+
+ @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)),
+ ]
+
+ 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"]
diff --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.py
new file mode 100644
index 000000000000..a637092b9795
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/anthropic/tests/test_anthropic_source.py
@@ -0,0 +1,147 @@
+from unittest import mock
+
+from parameterized import parameterized
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+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 AnthropicSourceConfig
+from 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
+
+ def test_get_source_config(self):
+ config = self.source.get_source_config
+
+ assert config.name.value == "Anthropic"
+ assert config.label == "Anthropic"
+ assert 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"
+
+ 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"]) == []
+
+ @parameterized.expand(
+ [
+ ("valid", True, True, None),
+ ("invalid", False, False, "Invalid Anthropic Admin API key"),
+ ]
+ )
+ 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)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
index c62ee0172661..7423c58aad2f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
@@ -290,7 +290,7 @@ class AmplitudeSourceConfig(config.Config):
@config.config
class AnthropicSourceConfig(config.Config):
- pass
+ api_key: str
@config.config
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/test_postgres.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/test_postgres.py
index 55e7c8c227a4..29080ca34b0a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/test_postgres.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/test_postgres.py
@@ -6486,8 +6486,8 @@ class TestRlsActiveFromConnErrorHandling:
def test_unsupported_statement_timeout_error_is_not_captured(self):
# A Postgres-wire engine that rejects the best-effort `SET statement_timeout` (CrateDB,
- # Materialize, etc.) is an expected shape: degrade to no RLS warnings without flooding
- # error tracking.
+ # Materialize, Aurora DSQL, etc.) is an expected shape: degrade to no RLS warnings without
+ # flooding error tracking.
conn = self._conn_raising(
psycopg.errors.FeatureNotSupported('setting configuration parameter "statement_timeout" not supported')
)