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(warehouse_sources): add Anthropic per-seat activity, cost and usage tables (#98328)

Tom Owers0254275e94d4
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
index 2fce5cdeb4d0..082dfaab7e7e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
@@ -294,14 +294,14 @@ Note: Endpoint paths confirmed by reading https://amplitude.com/docs/apis/analyt
## Anthropic — gaps
-Today (9): `api_keys`, `claude_code_analytics`, `claude_code_model_breakdown`, `cost_report`, `invites`, `usage_report`, `users`, `workspace_members`, `workspaces`
+Today (12): `analytics_user_activity`, `analytics_user_cost`, `analytics_user_usage`, `api_keys`, `claude_code_analytics`, `claude_code_model_breakdown`, `cost_report`, `invites`, `usage_report`, `users`, `workspace_members`, `workspaces`
Diffed against: <https://platform.claude.com/llms.txt>
-- [ ] `GET /v1/models` — model catalog - lookup resolving the model IDs already synced in usage_report, cost_report and claude_code_model_breakdown (high)
-- [ ] `GET /v1/organizations/analytics/users (List User Activity)` — per-seat activity, the core seat-utilization table (high)
-- [ ] `GET /v1/organizations/analytics/cost by user (Get Per-User Cost)` — cost attribution per user rather than only org-level cost_report (high)
-- [ ] `GET /v1/organizations/analytics/usage by user (Get Per-User Token Usage)` — token usage per user, needed for chargeback and adoption analysis (high)
+- ~~`GET /v1/models`~~ — not reachable: the Models API sits outside the Admin section, so the Admin API key this source collects cannot call it. Wiring it would mean also storing a regular API key, which can spend money on the Messages API, for a static model catalog.
+- [x] `GET /v1/organizations/analytics/users (List User Activity)` — per-seat activity, the core seat-utilization table (high)
+- [x] `GET /v1/organizations/analytics/user_cost_report (Get Per-User Cost)` — cost attribution per user rather than only org-level cost_report (high)
+- [x] `GET /v1/organizations/analytics/user_usage_report (Get Per-User Token Usage)` — token usage per user, needed for chargeback and adoption analysis (high)
- [ ] `GET /v1/organizations/rbac_groups and .../rbac_groups/{id}/members` — group definitions plus the membership join for the users already synced (high)
- [ ] `GET /v1/organizations/rbac_roles and .../rbac_roles/{id}/permissions` — lookup resolving the role identifiers carried on users and workspace_members (medium)
- [ ] `GET /v1/organizations/analytics/summaries (Get Activity Summaries)` — rolled-up org activity as the vendor reports it (medium)
@@ -311,7 +311,7 @@ Diffed against: <https://platform.claude.com/llms.txt>
- [ ] `GET /v1/organizations/analytics/chat_projects and /analytics/artifacts` — Claude project and artifact usage breakdown (low)
- [ ] `GET /v1/organizations/me` — organization lookup row to anchor the org-scoped tables (low)
-Note: Admin API coverage of the identity objects is good. The whole /v1/organizations/analytics/\* family (the newer per-seat Claude and Claude Code analytics) is missing except the two claude_code\_\* tables, and there is no model lookup for the model IDs already carried in usage_report/cost_report. The Compliance API (chats, projects, code artifacts, organization users) is a separate auth-gated surface for Enterprise plans and would need its own credential.
+Note: Admin API coverage of the identity objects is good. The three per-seat tables from the /v1/organizations/analytics/\* family are covered; the rest of that family (summaries, connectors, plugins, skills, chat projects, artifacts) is not. Those endpoints need a Claude Enterprise key carrying the `read:analytics` scope, which is a different key from the Claude Console Admin API key, so they stay off by default and `get_endpoint_permissions` reports whether the configured key can reach them. There is still no model lookup for the model IDs carried in usage_report/cost_report. The Compliance API (chats, projects, code artifacts, organization users) is a separate auth-gated surface for Enterprise plans and would need its own credential.
## ApifyDataset — **thin**
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/anthropic/anthropic.py b/products/warehouse_sources/backend/temporal/data_imports/sources/anthropic/anthropic.py
index 23540476bf1f..b4e553a151ac 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,5 +1,4 @@
import hashlib
-import dataclasses
from collections.abc import Callable, Iterator
from datetime import UTC, date, datetime, timedelta
from functools import partial
@@ -11,9 +10,13 @@ from requests.exceptions import HTTPError
from posthog.dataclasses import frozen
from products.warehouse_sources.backend.temporal.data_imports.sources.anthropic.settings import (
+ ANALYTICS_DATA_FLOOR,
+ ANALYTICS_PATH_PREFIX,
ANTHROPIC_ENDPOINTS,
ENDPOINT_RETIRED_ERROR,
USAGE_GROUP_BY_FALLBACKS,
+ AnalyticsWindowKind,
+ AnthropicEndpointConfig,
PaginationType,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
@@ -56,9 +59,16 @@ DEFAULT_STARTING_AT = datetime(2023, 1, 1, tzinfo=UTC)
# day per request). Claude Code became available in 2025, so earlier days only return empty pages —
# starting here avoids fanning out over hundreds of pre-launch days on a full refresh.
DEFAULT_CLAUDE_CODE_START = date(2025, 1, 1)
+# Shown against the Claude Enterprise Analytics tables in the schema picker when the configured key
+# cannot reach them, so the customer deselects those tables instead of watching them fail to sync.
+ANALYTICS_ACCESS_MISSING = (
+ "This table comes from the Claude Enterprise Analytics API, which this key can't reach. It needs "
+ "a Claude Enterprise key with the read:analytics scope, created in claude.ai organization "
+ "settings by your primary owner."
+)
+@frozen
class AnthropicResumeConfig:
# Opaque pagination cursor: an `after_id` for CURSOR endpoints or a `next_page` token for PAGE
# endpoints. None means "start at the first page".
@@ -72,6 +82,11 @@ class AnthropicResumeConfig:
fanout_state: dict | None = None
# Claude Code day fan-out checkpoint: {"date": "YYYY-MM-DD", "cursor": next_page | None}.
day_fanout_state: dict | None = None
+ # Claude Enterprise Analytics day fan-out checkpoint: {"start": "YYYY-MM-DD"}, the first day not
+ # yet fully yielded. The within-day page cursor is deliberately not saved: it is bound to the
+ # query that minted it and expires when the underlying export refreshes, so replaying a whole
+ # day costs one extra request set and can never hand the API a cursor it has since rejected.
+ analytics_window_state: dict | None = None
class AnthropicCursorPaginator(BasePaginator):
@@ -108,7 +123,11 @@ class AnthropicCursorPaginator(BasePaginator):
self._has_next_page = False
return
token = body.get(self.cursor_path)
- if body.get("has_more") and token:
+ # `/organizations/analytics/users` omits `has_more` and marks its last page with a null
+ # `next_page`. Every other endpoint sends both, and there `has_more` stays authoritative
+ # because the entity lists echo `last_id` on the final page too.
+ has_more = body.get("has_more", token is not None)
+ if has_more and token:
self._cursor_value = token
self._has_next_page = True
else:
@@ -228,6 +247,26 @@ def validate_credentials(api_key: str) -> bool:
return ok
+def check_analytics_access(api_key: str) -> Optional[str]:
+ """Report whether the configured key can read the Claude Enterprise Analytics API.
+
+ Returns None when it can, or the reason to show against the tables that need it. Only a real
+ denial counts as missing access: a throttle, a server error, or a network failure leaves those
+ tables reported as reachable, so a blip during schema discovery never hides a table the customer
+ can sync. A 401 is left to `validate_credentials`, which reports a bad key for the whole source.
+ """
+ _ok, status = validate_via_probe(
+ lambda: make_tracked_session(redact_values=(api_key,)),
+ f"{ANTHROPIC_BASE_URL}{ANALYTICS_PATH_PREFIX}users?limit=1",
+ headers={"x-api-key": api_key, **_version_headers()},
+ )
+ # 404 as well as 403: an organization that is not on a Claude Enterprise plan does not serve
+ # these routes at all.
+ if status in (403, 404):
+ return ANALYTICS_ACCESS_MISSING
+ return None
+
+
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")
@@ -332,12 +371,9 @@ def _parse_iso_date(value: str) -> date:
return date.fromisoformat(value.strip()[:10])
-def _claude_code_start_day(db_incremental_field_last_value: Any) -> date:
- """Resolve the first day to request: the incremental watermark (already shifted back by the
- pipeline's lookback) on an incremental run, else the Claude Code launch-era floor."""
- value = db_incremental_field_last_value
- if value is None:
- return DEFAULT_CLAUDE_CODE_START
+def _as_date(value: Any) -> date:
+ """Resolve an incremental watermark to the UTC calendar day it falls in."""
+ # datetime subclasses date, so it has to be tested first.
if isinstance(value, datetime):
return (value.astimezone(UTC) if value.tzinfo else value.replace(tzinfo=UTC)).date()
if isinstance(value, date):
@@ -345,6 +381,14 @@ def _claude_code_start_day(db_incremental_field_last_value: Any) -> date:
return _parse_iso_date(str(value))
+def _claude_code_start_day(db_incremental_field_last_value: Any) -> date:
+ """Resolve the first day to request: the incremental watermark (already shifted back by the
+ pipeline's lookback) on an incremental run, else the Claude Code launch-era floor."""
+ if db_incremental_field_last_value is None:
+ return DEFAULT_CLAUDE_CODE_START
+ return _as_date(db_incremental_field_last_value)
+
+
@frozen
class ClaudeCodeActor:
date: Any
@@ -446,6 +490,170 @@ def _flatten_claude_code_models(item: dict[str, Any]) -> list[dict[str, Any]]:
return rows
+@frozen
+class AnalyticsWindow:
+ start: date
+ # Exclusive end of the requested range. None for an endpoint that takes a single `date` instead.
+ end: Optional[date] = None
+
+
+def _analytics_windows(
+ config: AnthropicEndpointConfig,
+ db_incremental_field_last_value: Optional[Any],
+ today: date,
+ resume_from: Optional[date] = None,
+) -> list[AnalyticsWindow]:
+ """Resolve the UTC days to request, oldest first.
+
+ A full refresh starts at the oldest day the endpoint serves; an incremental run starts at the
+ watermark (already shifted back by the pipeline's lookback), and a resumed run at its checkpoint.
+ A start past the newest available day is clamped onto that day, so a run always re-pulls the most
+ recent day rather than requesting a day the endpoint would reject.
+ """
+ floor = ANALYTICS_DATA_FLOOR
+ if config.analytics_max_history_days is not None:
+ floor = max(floor, today - timedelta(days=config.analytics_max_history_days))
+ start = floor
+ if db_incremental_field_last_value is not None:
+ start = max(start, _as_date(db_incremental_field_last_value))
+ if resume_from is not None:
+ start = max(start, resume_from)
+
+ last_day = today - timedelta(days=config.analytics_lag_days)
+ day = min(start, last_day)
+ windows: list[AnalyticsWindow] = []
+ while day <= last_day:
+ if config.analytics_window == AnalyticsWindowKind.DATE:
+ windows.append(AnalyticsWindow(start=day))
+ else:
+ windows.append(AnalyticsWindow(start=day, end=day + timedelta(days=1)))
+ day = day + timedelta(days=1)
+ return windows
+
+
+def _analytics_resume_day(resume: Optional[AnthropicResumeConfig]) -> Optional[date]:
+ saved = resume.analytics_window_state if resume is not None else None
+ start = saved.get("start") if isinstance(saved, dict) else None
+ return _parse_iso_date(str(start)) if start else None
+
+
+def _analytics_params(config: AnthropicEndpointConfig, window: AnalyticsWindow) -> dict[str, Any]:
+ params: dict[str, Any] = {"limit": config.limit}
+ if window.end is None:
+ params["date"] = window.start.isoformat()
+ return params
+ params["starting_at"] = _format_rfc3339(window.start)
+ params["ending_at"] = _format_rfc3339(window.end)
+ params["bucket_width"] = config.bucket_width
+ return params
+
+
+def _iter_analytics_windows(
+ build_resource: Callable[[AnalyticsWindow], Any],
+ windows: list[AnalyticsWindow],
+ save_checkpoint: Callable[[date], None],
+) -> Iterator[list[dict[str, Any]]]:
+ """Yield every day's pages in ascending day order, checkpointing once a day is fully yielded.
+
+ The checkpoint names the first day not yet yielded, so a restart replays at most the day that was
+ in progress and merge dedupes it on the synthesized `id`.
+ """
+ for index, window in enumerate(windows):
+ yield from build_resource(window)
+ if index + 1 < len(windows):
+ save_checkpoint(windows[index + 1].start)
+
+
+def _flatten_metrics(prefix: str, value: dict[str, Any], row: dict[str, Any]) -> None:
+ """Flatten a nested metric object into `prefix_key` columns, one segment per nesting level.
+
+ Anthropic adds per-product metric blocks to the activity record as it ships products, so
+ flattening whatever the response carries picks up a new product's metrics with no change here.
+ """
+ for key, item in value.items():
+ name = f"{prefix}_{key}" if prefix else key
+ if isinstance(item, dict):
+ _flatten_metrics(name, item, row)
+ else:
+ row[name] = item
+
+
+def _flatten_analytics_user_activity(day: date, item: dict[str, Any]) -> dict[str, Any]:
+ """One row per (day, user): every per-product engagement metric the activity record carries."""
+ user = item.get("user") or {}
+ row: dict[str, Any] = {
+ # The record carries no day of its own, so stamp the day the request asked for.
+ "date": _format_rfc3339(day),
+ "user_id": user.get("id"),
+ "user_email_address": user.get("email_address"),
+ }
+ for key, value in item.items():
+ if key == "user":
+ continue
+ if isinstance(value, dict):
+ # `chat_metrics` becomes `chat_message_count`, `office_metrics.excel` becomes
+ # `office_excel_message_count`, and so on.
+ _flatten_metrics(key.removesuffix("_metrics"), value, row)
+ else:
+ row[key] = value
+ row["id"] = _row_id(row["date"], row["user_id"])
+ return row
+
+
+def _analytics_actor_columns(item: dict[str, Any]) -> dict[str, Any]:
+ """Surface the seat user a per-user report row is attributed to as flat columns."""
+ actor = item.get("actor") or {}
+ return {
+ "user_id": actor.get("user_id"),
+ "user_email": actor.get("email"),
+ "user_name": actor.get("name"),
+ "user_deleted": actor.get("deleted"),
+ }
+
+
+# The per-user report requests carry no `group_by`, so the dimension fields Anthropic populates only
+# for a grouped query (model, product, cost_type, token_type, context_window, inference_geo, speed,
+# rbac_group_id, and the Claude Tag and Slack fields) are null on every row and are left out below.
+def _flatten_analytics_user_cost(item: dict[str, Any]) -> dict[str, Any]:
+ """One row per (day, user): cost attributed to that seat user for that day."""
+ starting_at = item.get("starting_at")
+ actor = _analytics_actor_columns(item)
+ return {
+ "id": _row_id(starting_at, actor["user_id"]),
+ "starting_at": starting_at,
+ "ending_at": item.get("ending_at"),
+ **actor,
+ # Fractional cents as a decimal string, kept as the API sends it. The values can run past
+ # what binary floating point represents exactly, so converting them belongs in a query.
+ "amount": item.get("amount"),
+ "list_amount": item.get("list_amount"),
+ "currency": item.get("currency"),
+ "requests": item.get("requests"),
+ }
+
+
+def _flatten_analytics_user_usage(item: dict[str, Any]) -> dict[str, Any]:
+ """One row per (day, user): token usage attributed to that seat user for that day."""
+ starting_at = item.get("starting_at")
+ actor = _analytics_actor_columns(item)
+ cache_creation = item.get("cache_creation") or {}
+ server_tool_use = item.get("server_tool_use") or {}
+ return {
+ "id": _row_id(starting_at, actor["user_id"]),
+ "starting_at": starting_at,
+ "ending_at": item.get("ending_at"),
+ **actor,
+ "uncached_input_tokens": item.get("uncached_input_tokens"),
+ "cache_read_input_tokens": item.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": item.get("output_tokens"),
+ "total_tokens": item.get("total_tokens"),
+ "requests": item.get("requests"),
+ "web_search_requests": server_tool_use.get("web_search_requests"),
+ }
+
+
def _stamp_workspace_id(row: dict[str, Any]) -> dict[str, Any]:
# The member object already carries workspace_id, but fall back to the parent workspace's id
# (injected by the fan-out as `_workspaces_id`) so the composite primary key is always populated.
@@ -522,7 +730,62 @@ def anthropic_source(
resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
- if config.fan_out_over_days:
+ if config.analytics_window is not None:
+ # Claude Enterprise Analytics: one request per UTC day, each day its own resource so the
+ # requested day is available to the row mapper. One day per request is also what keeps the
+ # rows ascending by day: within a wider range the per-user reports rank rows by spend rather
+ # than by time, which the pipeline's `sort_mode="asc"` watermark could not follow.
+ analytics_windows = _analytics_windows(
+ config,
+ db_incremental_field_last_value,
+ datetime.now(UTC).date(),
+ resume_from=_analytics_resume_day(resume),
+ )
+ # One tracked session shared by every day's client, so a backfill reuses a single connection
+ # pool instead of opening one per day.
+ client_config["session"] = make_tracked_session(redact_values=(api_key,))
+
+ def analytics_row_map(
+ window: AnalyticsWindow,
+ ) -> Callable[[dict[str, Any]], dict[str, Any] | list[dict[str, Any]]]:
+ if config.analytics_window == AnalyticsWindowKind.DATE:
+ # The engagement record carries no day, so bind the day this request asks for.
+ return partial(_flatten_analytics_user_activity, window.start)
+ return _flatten_analytics_user_cost if endpoint == "analytics_user_cost" else _flatten_analytics_user_usage
+
+ def save_analytics_checkpoint(next_start: date) -> None:
+ resumable_source_manager.save_state(
+ AnthropicResumeConfig(analytics_window_state={"start": next_start.isoformat()})
+ )
+
+ def build_analytics_resource(window: AnalyticsWindow) -> Any:
+ analytics_resource: EndpointResource = {
+ "name": endpoint,
+ "endpoint": {
+ "path": config.path,
+ "params": _analytics_params(config, window),
+ "data_selector": "data",
+ "paginator": AnthropicCursorPaginator(cursor_path="next_page", cursor_param="page"),
+ },
+ "data_map": analytics_row_map(window),
+ }
+ analytics_rest_config: RESTAPIConfig = {
+ "client": client_config,
+ "resource_defaults": None,
+ "resources": [analytics_resource],
+ }
+ return rest_api_resource(
+ analytics_rest_config,
+ team_id,
+ job_id,
+ db_incremental_field_last_value,
+ )
+
+ # Built for the first day only to carry the resource's column hints; the fan-out below
+ # rebuilds a resource per day.
+ resource = build_analytics_resource(analytics_windows[0])
+ items = partial(_iter_analytics_windows, build_analytics_resource, analytics_windows, save_analytics_checkpoint)
+ elif config.fan_out_over_days:
# Claude Code analytics: one windowed request per calendar day, driven entirely by the
# paginator (there is no parent API resource to resolve days from).
start_day = _claude_code_start_day(db_incremental_field_last_value)
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
index e94fe6f28cbb..83306b09b3c2 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
@@ -3,6 +3,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.can
)
_ADMIN_API_DOCS = "https://platform.claude.com/docs/en/api/admin-api"
+_ANALYTICS_API_DOCS = "https://platform.claude.com/docs/en/api/admin/analytics"
CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"users": {
@@ -157,4 +158,79 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"estimated_cost_currency": 'Currency code for the estimated cost, currently always "USD".',
},
},
+ "analytics_user_activity": {
+ "description": (
+ "Per-seat engagement across Claude products, one row per organization member per UTC day. "
+ "Metric columns are prefixed by the product surface they measure: chat, claude_code, "
+ "cowork, design, office (per Office app) and science."
+ ),
+ "docs_url": f"{_ANALYTICS_API_DOCS}/users/list",
+ "columns": {
+ "id": "Synthesized surrogate key: a hash of the day and the user id.",
+ "date": "UTC day the metrics are aggregated over, in RFC 3339 format.",
+ "user_id": "Tagged identifier of the organization member the activity belongs to.",
+ "user_email_address": "Email address of the organization member.",
+ "last_activity_date": "Most recent UTC day the member had any counted activity, or null if that reporting is off for the organization.",
+ "web_search_count": "Web searches the member performed.",
+ "distinct_user_count": "Distinct active members represented by the row. Null on per-member rows.",
+ "rbac_group_id": "Tagged RBAC group identifier. Null unless the request grouped by group.",
+ "rbac_group_name": "Display name of the RBAC group, alongside rbac_group_id when it resolves.",
+ "chat_message_count": "Messages the member sent in Claude chat.",
+ "chat_distinct_conversation_count": "Distinct chat conversations the member took part in.",
+ "chat_thinking_message_count": "Chat messages that used extended thinking.",
+ "claude_code_core_metrics_distinct_session_count": "Distinct Claude Code sessions.",
+ "claude_code_core_metrics_commit_count": "Commits made through Claude Code.",
+ "claude_code_core_metrics_pull_request_count": "Pull requests created through Claude Code.",
+ "claude_code_core_metrics_lines_of_code_added_count": "Lines of code added through Claude Code.",
+ "claude_code_core_metrics_lines_of_code_removed_count": "Lines of code removed through Claude Code.",
+ "cowork_message_count": "Messages the member sent in Cowork sessions.",
+ "cowork_distinct_session_count": "Distinct Cowork sessions.",
+ "design_message_count": "Messages the member sent in Claude Design sessions.",
+ "science_message_count": "Messages the member sent in Claude Science sessions.",
+ },
+ },
+ "analytics_user_cost": {
+ "description": (
+ "Cost attributed to a seat user, one row per member per UTC day. Covers only cost that "
+ "belongs to a seat user; org-wide totals including direct API-key traffic are in cost_report."
+ ),
+ "docs_url": f"{_ANALYTICS_API_DOCS}/cost/list_by_user",
+ "columns": {
+ "id": "Synthesized surrogate key: a hash of the day and the user id.",
+ "starting_at": "Start of the day the cost is bucketed into, in RFC 3339 format.",
+ "ending_at": "End of the bucket (exclusive), in RFC 3339 format.",
+ "user_id": "Tagged identifier of the member the cost is attributed to.",
+ "user_email": "Email address of the member, or null once the account is deleted.",
+ "user_name": "Full name of the member, or null if unset or hidden for a removed member.",
+ "user_deleted": "True when the account is deleted or the member has left the organization.",
+ "amount": "Post-discount, pre-credit cost in fractional cents, as a decimal string. Divide by 100 for dollars.",
+ "list_amount": "List-price (pre-discount) cost in fractional cents, as a decimal string.",
+ "currency": 'Currency code for the cost amounts, currently always "USD".',
+ "requests": "API requests in the row's scope. Counts execution spans for code execution.",
+ },
+ },
+ "analytics_user_usage": {
+ "description": (
+ "Token usage attributed to a seat user, one row per member per UTC day. Covers only usage "
+ "that belongs to a seat user; org-wide totals including direct API-key traffic are in usage_report."
+ ),
+ "docs_url": f"{_ANALYTICS_API_DOCS}/usage/list_by_user",
+ "columns": {
+ "id": "Synthesized surrogate key: a hash of the day and the user id.",
+ "starting_at": "Start of the day the usage is bucketed into, in RFC 3339 format.",
+ "ending_at": "End of the bucket (exclusive), in RFC 3339 format.",
+ "user_id": "Tagged identifier of the member the usage is attributed to.",
+ "user_email": "Email address of the member, or null once the account is deleted.",
+ "user_name": "Full name of the member, or null if unset or hidden for a removed member.",
+ "user_deleted": "True when the account is deleted or the member has left the organization.",
+ "uncached_input_tokens": "Input tokens processed without a cache hit.",
+ "cache_read_input_tokens": "Input tokens read from the prompt cache.",
+ "cache_creation_ephemeral_1h_input_tokens": "Input tokens used to create 1-hour prompt-cache entries.",
+ "cache_creation_ephemeral_5m_input_tokens": "Input tokens used to create 5-minute prompt-cache entries.",
+ "output_tokens": "Output tokens generated.",
+ "total_tokens": "Total tokens across every token type.",
+ "requests": "API requests in the row's scope. Counts execution spans for code execution.",
+ "web_search_requests": "Web search requests made through server-side tool use.",
+ },
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/anthropic/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/anthropic/settings.py
index 35a84a88c472..04596f2fe17d 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,4 +1,5 @@
from dataclasses import field
+from datetime import date
from enum import Enum
from typing import Optional
@@ -16,6 +17,13 @@ class PaginationType(Enum):
PAGE = "page"
+class AnalyticsWindowKind(Enum):
+ # `/organizations/analytics/users` answers for one `date`.
+ DATE = "date"
+ # The per-user cost and token usage reports answer for a `starting_at`/`ending_at` range.
+ RANGE = "range"
+
+
def _datetime_incremental_field(name: str) -> IncrementalField:
return {
"label": name,
@@ -56,6 +64,14 @@ class AnthropicEndpointConfig:
fan_out_over_days: 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)
+ # The Claude Enterprise Analytics endpoints answer for one date (or one date range) per request,
+ # so the source fans out one request per UTC day. Set to the window shape the endpoint takes.
+ analytics_window: Optional[AnalyticsWindowKind] = None
+ # Days by which the newest requestable day trails today. The engagement endpoints answer 400 for
+ # a day their export has not covered yet, so their fan-out has to stop short of today.
+ analytics_lag_days: int = 0
+ # Oldest `starting_at` the endpoint accepts, in days before today. None means no such limit.
+ analytics_max_history_days: Optional[int] = None
should_sync_default: bool = True
@@ -100,6 +116,27 @@ USAGE_REPORT_PAGE_BUCKETS = 7
# so a trailing day covers late arrivals; merge dedupes the overlap on the synthesized `id`.
_REPORT_LOOKBACK_SECONDS = 60 * 60 * 24
+# The Claude Enterprise Analytics API serves no data before this date, and answers 400 for an
+# earlier one, so the day fan-out starts here on a full refresh.
+ANALYTICS_DATA_FLOOR = date(2026, 1, 1)
+# Rows per analytics page, at the documented maximum. Each page is one request against an
+# organization-wide 60-requests-per-minute limit, so ask for as many rows per request as allowed.
+ANALYTICS_PAGE_SIZE = 1000
+# Engagement data for a day lands about a day later, and the most recent available day is often two
+# days back. Requesting a day the export has not covered yet fails the whole request with a 400 that
+# names the latest available day, so the engagement fan-out stops two days short of today.
+ANALYTICS_ENGAGEMENT_LAG_DAYS = 2
+# The per-user cost and usage reports reject a `starting_at` more than 365 days old. Stop a day
+# inside that bound so a long-running full refresh cannot age past it mid-sync.
+ANALYTICS_REPORT_MAX_HISTORY_DAYS = 364
+# Engagement metrics for a day may be revised by a few percent over the following days, so re-pull a
+# trailing window on every incremental run; merge dedupes the overlap on the synthesized `id`.
+_ANALYTICS_ENGAGEMENT_LOOKBACK_SECONDS = 60 * 60 * 24 * 3
+# Per-user cost and usage are refreshed about every four hours and stay open to revision for around
+# 30 days as late events arrive and reconciliation runs. A week of re-pulled days keeps the recent
+# tail accurate at a bounded request cost; run a full refresh for invoicing-grade totals.
+_ANALYTICS_REPORT_LOOKBACK_SECONDS = 60 * 60 * 24 * 7
+
ANTHROPIC_ENDPOINTS: dict[str, AnthropicEndpointConfig] = {
"users": AnthropicEndpointConfig(
name="users",
@@ -203,6 +240,59 @@ ANTHROPIC_ENDPOINTS: dict[str, AnthropicEndpointConfig] = {
limit=1000,
default_incremental_lookback_seconds=_REPORT_LOOKBACK_SECONDS,
),
+ # Claude Enterprise Analytics API: per-seat engagement, and cost and token usage attributed to a
+ # seat user. These need a Claude Enterprise key carrying the `read:analytics` scope, which a
+ # Claude Console Admin API key is not, so they stay off by default and `get_endpoint_permissions`
+ # reports whether the configured key can reach them.
+ "analytics_user_activity": AnthropicEndpointConfig(
+ name="analytics_user_activity",
+ path="/v1/organizations/analytics/users",
+ pagination=PaginationType.PAGE,
+ # `id` is synthesized from the requested day and the user id (see anthropic.py). The response
+ # carries no day of its own, so the source stamps the day it asked for onto every row.
+ primary_keys=["id"],
+ partition_key="date",
+ supports_incremental=True,
+ incremental_fields=[_datetime_incremental_field("date")],
+ analytics_window=AnalyticsWindowKind.DATE,
+ analytics_lag_days=ANALYTICS_ENGAGEMENT_LAG_DAYS,
+ limit=ANALYTICS_PAGE_SIZE,
+ default_incremental_lookback_seconds=_ANALYTICS_ENGAGEMENT_LOOKBACK_SECONDS,
+ should_sync_default=False,
+ ),
+ "analytics_user_cost": AnthropicEndpointConfig(
+ name="analytics_user_cost",
+ path="/v1/organizations/analytics/user_cost_report",
+ pagination=PaginationType.PAGE,
+ primary_keys=["id"],
+ partition_key="starting_at",
+ supports_incremental=True,
+ incremental_fields=[_datetime_incremental_field("starting_at")],
+ analytics_window=AnalyticsWindowKind.RANGE,
+ analytics_max_history_days=ANALYTICS_REPORT_MAX_HISTORY_DAYS,
+ # A row only carries its own `starting_at` when a bucket width is set. Without one the whole
+ # requested range collapses into a single undated row per user, whose grain would then depend
+ # on how wide a window the sync happened to ask for.
+ bucket_width="1d",
+ limit=ANALYTICS_PAGE_SIZE,
+ default_incremental_lookback_seconds=_ANALYTICS_REPORT_LOOKBACK_SECONDS,
+ should_sync_default=False,
+ ),
+ "analytics_user_usage": AnthropicEndpointConfig(
+ name="analytics_user_usage",
+ path="/v1/organizations/analytics/user_usage_report",
+ pagination=PaginationType.PAGE,
+ primary_keys=["id"],
+ partition_key="starting_at",
+ supports_incremental=True,
+ incremental_fields=[_datetime_incremental_field("starting_at")],
+ analytics_window=AnalyticsWindowKind.RANGE,
+ analytics_max_history_days=ANALYTICS_REPORT_MAX_HISTORY_DAYS,
+ bucket_width="1d",
+ limit=ANALYTICS_PAGE_SIZE,
+ default_incremental_lookback_seconds=_ANALYTICS_REPORT_LOOKBACK_SECONDS,
+ should_sync_default=False,
+ ),
}
ENDPOINTS = tuple(ANTHROPIC_ENDPOINTS.keys())
@@ -211,6 +301,11 @@ ENDPOINTS = tuple(ANTHROPIC_ENDPOINTS.keys())
# `get_non_retryable_errors` so the sync retires the row rather than retrying.
ENDPOINT_RETIRED_ERROR = "Table no longer available from Anthropic"
+# Path prefix shared by every Claude Enterprise Analytics endpoint. A 403 from one of these means the
+# key lacks the `read:analytics` scope rather than organization admin access, so the source maps it to
+# its own message in `get_non_retryable_errors`.
+ANALYTICS_PATH_PREFIX = "/v1/organizations/analytics/"
+
INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
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.py
index 9d1fc34d6e27..5621bd5da080 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
@@ -12,9 +12,11 @@ from posthog.schema import (
from products.warehouse_sources.backend.temporal.data_imports.sources.anthropic.anthropic import (
AnthropicResumeConfig,
anthropic_source,
+ check_analytics_access,
validate_credentials as validate_anthropic_credentials,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.anthropic.settings import (
+ ANALYTICS_PATH_PREFIX,
ANTHROPIC_ENDPOINTS,
ENDPOINT_RETIRED_ERROR,
ENDPOINTS,
@@ -54,7 +56,9 @@ class AnthropicSource(ResumableSource[AnthropicSourceConfig, AnthropicResumeConf
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.
-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.""",
+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.
+
+The per-seat activity, cost, and token usage tables come from the Claude Enterprise Analytics API, which needs a different key: a Claude Enterprise key carrying the `read:analytics` scope, created by your primary owner in [claude.ai organization settings](https://claude.ai/admin-settings/api-access). A key works with one of the two APIs, so pick the one that matches the tables you want.""",
iconPath="/static/services/anthropic.svg",
docsUrl="https://posthog.com/docs/cdp/sources/anthropic",
keywords=["llm", "claude", "ai usage", "cost"],
@@ -82,6 +86,9 @@ Create an Admin API key (prefixed `sk-ant-admin...`) in your [Anthropic Console]
def get_non_retryable_errors(self) -> dict[str, str | None]:
return {
+ # Matched before the generic 403 below, because the first matching pattern supplies the
+ # message and a denial from this path is about a missing scope, not admin access.
+ f"403 Client Error: Forbidden for url: https://api.anthropic.com{ANALYTICS_PATH_PREFIX}": "This table comes from the Claude Enterprise Analytics API, which your key can't reach. Reconnect the source with a Claude Enterprise key carrying the read:analytics scope, or turn this table's sync off.",
"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.",
ENDPOINT_RETIRED_ERROR: "Anthropic no longer offers this table, so it can't sync. PostHog has turned its sync off for you, and any rows already imported stay in your warehouse.",
@@ -113,6 +120,28 @@ Create an Admin API key (prefixed `sk-ant-admin...`) in your [Anthropic Console]
schemas = [s for s in schemas if s.name in names_set]
return schemas
+ def get_endpoint_permissions(
+ self,
+ config: AnthropicSourceConfig,
+ team_id: int,
+ endpoints: list[str],
+ api_version: str | None = None,
+ ) -> dict[str, str | None]:
+ permissions: dict[str, str | None] = dict.fromkeys(endpoints)
+ analytics_endpoints = [
+ name
+ for name in endpoints
+ if name in ANTHROPIC_ENDPOINTS and ANTHROPIC_ENDPOINTS[name].analytics_window is not None
+ ]
+ if not analytics_endpoints:
+ return permissions
+ # Every analytics endpoint needs the same scope on the same plan, so one probe answers for
+ # all of them.
+ reason = check_analytics_access(config.api_key)
+ for name in analytics_endpoints:
+ permissions[name] = reason
+ return permissions
+
def validate_credentials(
self,
config: AnthropicSourceConfig,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/anthropic/tests/test_anthropic.py b/products/warehouse_sources/backend/temporal/data_imports/sources/anthropic/tests/test_anthropic.py
index d0f611938fb0..1f146e15aa01 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
@@ -10,22 +10,32 @@ from parameterized import parameterized
from requests import Request, Response
from products.warehouse_sources.backend.temporal.data_imports.sources.anthropic.anthropic import (
+ ANALYTICS_ACCESS_MISSING,
ANTHROPIC_VERSION,
DEFAULT_CLAUDE_CODE_START,
MAX_RETRY_ATTEMPTS,
REPORT_MAX_RETRY_ATTEMPTS,
AnthropicResumeConfig,
ClaudeCodeDayPaginator,
+ _analytics_windows,
_claude_code_start_day,
+ _flatten_analytics_user_activity,
+ _flatten_analytics_user_cost,
+ _flatten_analytics_user_usage,
_flatten_claude_code_core,
_flatten_claude_code_models,
_flatten_cost_result,
_flatten_usage_result,
_row_id,
anthropic_source,
+ check_analytics_access,
validate_credentials,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.anthropic.settings import (
+ ANALYTICS_DATA_FLOOR,
+ ANALYTICS_ENGAGEMENT_LAG_DAYS,
+ ANALYTICS_PATH_PREFIX,
+ ANALYTICS_REPORT_MAX_HISTORY_DAYS,
ANTHROPIC_ENDPOINTS,
COST_REPORT_PAGE_BUCKETS,
USAGE_GROUP_BY_FALLBACKS,
@@ -935,3 +945,269 @@ class TestRetiredEndpoint:
with pytest.raises(ValueError) as exc:
_source("service_accounts", _make_manager())
assert error_message_matches(str(exc.value), AnthropicSource().get_non_retryable_errors().keys())
+
+
+def _analytics_page(rows: list[dict[str, Any]], *, next_page: str | None) -> Response:
+ # `/organizations/analytics/users` sends no `has_more`: a null `next_page` is the last page.
+ return _response({"data": rows, "next_page": next_page})
+
+
+def _activity_record(email: str = "[email protected]") -> dict[str, Any]:
+ return {
+ "user": {"id": "user_1", "email_address": email, "type": "user"},
+ "chat_metrics": {"message_count": 7, "distinct_conversation_count": 2},
+ "claude_code_metrics": {
+ "core_metrics": {"commit_count": 3, "lines_of_code": {"added_count": 120, "removed_count": 30}},
+ "tool_actions": {"edit_tool": {"accepted_count": 10, "rejected_count": 2}},
+ },
+ "office_metrics": {"excel": {"message_count": 1}},
+ "web_search_count": 4,
+ }
+
+
+def _user_report_row(user_id: str = "user_1", starting_at: str = "2026-03-04T00:00:00Z") -> dict[str, Any]:
+ return {
+ "actor": {
+ "user_id": user_id,
+ "email": "[email protected]",
+ "name": "Dev",
+ "deleted": False,
+ "type": "user_actor",
+ },
+ "starting_at": starting_at,
+ "ending_at": "2026-03-05T00:00:00Z",
+ "amount": "41280.000000",
+ "list_amount": "51600.000000",
+ "currency": "USD",
+ "requests": 128,
+ "uncached_input_tokens": 1284500,
+ "cache_read_input_tokens": 3200000,
+ "cache_creation": {"ephemeral_1h_input_tokens": 1000, "ephemeral_5m_input_tokens": 500},
+ "output_tokens": 891000,
+ "total_tokens": 5377000,
+ "server_tool_use": {"web_search_requests": 10},
+ }
+
+
+class TestAnalyticsWindows:
+ def test_full_refresh_starts_at_the_data_floor(self) -> None:
+ config = ANTHROPIC_ENDPOINTS["analytics_user_activity"]
+ windows = _analytics_windows(config, None, ANALYTICS_DATA_FLOOR + timedelta(days=4))
+ assert windows[0].start == ANALYTICS_DATA_FLOOR
+ # The engagement export lags, so the newest requested day stops short of today. Asking for a
+ # day it has not covered fails the whole request with a 400.
+ assert windows[-1].start == ANALYTICS_DATA_FLOOR + timedelta(days=4 - ANALYTICS_ENGAGEMENT_LAG_DAYS)
+
+ def test_report_floor_stays_inside_the_history_bound(self) -> None:
+ # The per-user reports reject a starting_at older than a year, so a full refresh cannot start
+ # at the data floor once the floor has aged past that bound.
+ config = ANTHROPIC_ENDPOINTS["analytics_user_cost"]
+ today = ANALYTICS_DATA_FLOOR + timedelta(days=500)
+ windows = _analytics_windows(config, None, today)
+ assert windows[0].start == today - timedelta(days=ANALYTICS_REPORT_MAX_HISTORY_DAYS)
+
+ @parameterized.expand(
+ [
+ ("datetime", datetime(2026, 3, 4, 12, 0, 0, tzinfo=UTC)),
+ ("rfc3339_string", "2026-03-04T12:00:00Z"),
+ ("date", date(2026, 3, 4)),
+ ]
+ )
+ def test_incremental_watermark_starts_the_fan_out(self, _name: str, watermark: Any) -> None:
+ config = ANTHROPIC_ENDPOINTS["analytics_user_cost"]
+ windows = _analytics_windows(config, watermark, date(2026, 3, 6))
+ assert [w.start for w in windows] == [date(2026, 3, 4), date(2026, 3, 5), date(2026, 3, 6)]
+ # The report endpoints take an exclusive end, so each window covers exactly its own day.
+ assert windows[0].end == date(2026, 3, 5)
+
+ def test_watermark_past_the_newest_available_day_re_pulls_that_day(self) -> None:
+ # A watermark at or after the newest available day must not request a day the endpoint
+ # rejects, and must still return work so the run keeps the recent day fresh.
+ config = ANTHROPIC_ENDPOINTS["analytics_user_activity"]
+ today = date(2026, 3, 10)
+ windows = _analytics_windows(config, today, today)
+ assert [w.start for w in windows] == [today - timedelta(days=ANALYTICS_ENGAGEMENT_LAG_DAYS)]
+
+ def test_resume_checkpoint_skips_days_already_yielded(self) -> None:
+ config = ANTHROPIC_ENDPOINTS["analytics_user_cost"]
+ windows = _analytics_windows(config, date(2026, 3, 1), date(2026, 3, 4), resume_from=date(2026, 3, 3))
+ assert [w.start for w in windows] == [date(2026, 3, 3), date(2026, 3, 4)]
+
+
+class TestFlattenAnalyticsRows:
+ def test_activity_flattens_product_blocks_and_stamps_the_day(self) -> None:
+ row = _flatten_analytics_user_activity(date(2026, 3, 4), _activity_record())
+ # The record carries no day, so the requested day is the only source for it.
+ assert row["date"] == "2026-03-04T00:00:00Z"
+ assert row["user_id"] == "user_1"
+ assert row["user_email_address"] == "[email protected]"
+ assert row["chat_message_count"] == 7
+ assert row["claude_code_core_metrics_lines_of_code_added_count"] == 120
+ assert row["claude_code_tool_actions_edit_tool_accepted_count"] == 10
+ assert row["office_excel_message_count"] == 1
+ assert row["web_search_count"] == 4
+ assert "user" not in row
+
+ def test_activity_id_is_stable_across_metric_changes(self) -> None:
+ record = _activity_record()
+ busier = {**record, "web_search_count": 99, "chat_metrics": {"message_count": 100}}
+ assert (
+ _flatten_analytics_user_activity(date(2026, 3, 4), record)["id"]
+ == (_flatten_analytics_user_activity(date(2026, 3, 4), busier)["id"])
+ )
+
+ def test_activity_id_differs_by_day_and_user(self) -> None:
+ base = _flatten_analytics_user_activity(date(2026, 3, 4), _activity_record())
+ other_day = _flatten_analytics_user_activity(date(2026, 3, 5), _activity_record())
+ other_user = _activity_record()
+ other_user["user"] = {"id": "user_2", "email_address": "[email protected]"}
+ assert (
+ len({base["id"], other_day["id"], _flatten_analytics_user_activity(date(2026, 3, 4), other_user)["id"]})
+ == 3
+ )
+
+ def test_cost_surfaces_the_actor_and_keeps_amounts_as_strings(self) -> None:
+ row = _flatten_analytics_user_cost(_user_report_row())
+ assert row["user_id"] == "user_1"
+ assert row["user_email"] == "[email protected]"
+ assert row["user_deleted"] is False
+ # Fractional cents can exceed exact float range, so the decimal string must survive intact.
+ assert row["amount"] == "41280.000000"
+ assert row["list_amount"] == "51600.000000"
+ assert row["starting_at"] == "2026-03-04T00:00:00Z"
+
+ def test_usage_flattens_nested_token_objects(self) -> None:
+ row = _flatten_analytics_user_usage(_user_report_row())
+ 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["total_tokens"] == 5377000
+
+ def test_usage_missing_nested_objects_yield_none_not_crash(self) -> None:
+ row = _flatten_analytics_user_usage({"actor": {"user_id": "user_1"}, "starting_at": "2026-03-04T00:00:00Z"})
+ assert row["cache_creation_ephemeral_1h_input_tokens"] is None
+ assert row["web_search_requests"] is None
+
+ def test_cost_and_usage_rows_for_the_same_day_and_user_share_an_id(self) -> None:
+ # Both reports key on (day, user), so a bucket restated between runs merges in place.
+ assert (
+ _flatten_analytics_user_cost(_user_report_row())["id"]
+ == (_flatten_analytics_user_usage(_user_report_row())["id"])
+ )
+
+
+class TestAnalyticsFanOut:
+ @mock.patch(ANTHROPIC_SESSION_PATCH)
+ def test_activity_fans_out_one_dated_request_per_day(self, MockSession) -> None:
+ session = MockSession.return_value
+ today = datetime.now(UTC).date()
+ watermark = _midnight(today - timedelta(days=ANALYTICS_ENGAGEMENT_LAG_DAYS + 2))
+ params = _wire(session, [_analytics_page([_activity_record()], next_page=None) for _ in range(3)])
+ rows = _rows(_source("analytics_user_activity", _make_manager(), last_value=watermark))
+ assert len(rows) == 3
+ assert [p["params"]["date"] for p in params] == [
+ (watermark.date() + timedelta(days=i)).isoformat() for i in range(3)
+ ]
+ assert [r["date"] for r in rows] == [
+ f"{(watermark.date() + timedelta(days=i)).isoformat()}T00:00:00Z" for i in range(3)
+ ]
+
+ @parameterized.expand([("analytics_user_cost",), ("analytics_user_usage",)])
+ @mock.patch(ANTHROPIC_SESSION_PATCH)
+ def test_report_requests_carry_a_single_day_range_and_daily_buckets(self, endpoint: str, MockSession) -> None:
+ session = MockSession.return_value
+ today = datetime.now(UTC).date()
+ params = _wire(session, [_report_page([_user_report_row()], has_more=False, next_page=None)])
+ _rows(_source(endpoint, _make_manager(), last_value=_midnight(today)))
+ # A row only carries its own starting_at when a bucket width is set, and the range has to be
+ # one day wide so a row's day is unambiguous and rows arrive in ascending day order.
+ assert params[0]["params"]["starting_at"] == f"{today.isoformat()}T00:00:00Z"
+ assert params[0]["params"]["ending_at"] == f"{(today + timedelta(days=1)).isoformat()}T00:00:00Z"
+ assert params[0]["params"]["bucket_width"] == "1d"
+
+ @mock.patch(ANTHROPIC_SESSION_PATCH)
+ def test_paginates_within_a_day_on_next_page_alone(self, MockSession) -> None:
+ # The activity endpoint omits has_more, so a null next_page is the only stop signal.
+ session = MockSession.return_value
+ today = datetime.now(UTC).date()
+ params = _wire(
+ session,
+ [
+ _analytics_page([_activity_record("[email protected]")], next_page="P2"),
+ _analytics_page([_activity_record("[email protected]")], next_page=None),
+ ],
+ )
+ rows = _rows(_source("analytics_user_activity", _make_manager(), last_value=_midnight(today)))
+ assert {r["user_email_address"] for r in rows} == {"[email protected]", "[email protected]"}
+ assert "page" not in params[0]["params"]
+ assert params[1]["params"]["page"] == "P2"
+ assert params[1]["params"]["date"] == params[0]["params"]["date"]
+
+ @mock.patch(ANTHROPIC_SESSION_PATCH)
+ def test_checkpoints_the_next_day_after_a_day_is_yielded(self, MockSession) -> None:
+ session = MockSession.return_value
+ today = datetime.now(UTC).date()
+ first_day = today - timedelta(days=ANALYTICS_ENGAGEMENT_LAG_DAYS + 1)
+ manager = _make_manager()
+ _wire(session, [_analytics_page([_activity_record()], next_page=None) for _ in range(2)])
+ _rows(_source("analytics_user_activity", manager, last_value=_midnight(first_day)))
+ saved = [call.args[0].analytics_window_state for call in manager.save_state.call_args_list]
+ # Only the day still to come is checkpointed; the final day saves nothing to resume to.
+ assert saved == [{"start": (first_day + timedelta(days=1)).isoformat()}]
+
+ @mock.patch(ANTHROPIC_SESSION_PATCH)
+ def test_resumes_from_the_saved_day(self, MockSession) -> None:
+ session = MockSession.return_value
+ today = datetime.now(UTC).date()
+ last_day = today - timedelta(days=ANALYTICS_ENGAGEMENT_LAG_DAYS)
+ manager = _make_manager(AnthropicResumeConfig(analytics_window_state={"start": last_day.isoformat()}))
+ params = _wire(session, [_analytics_page([_activity_record()], next_page=None)])
+ _rows(_source("analytics_user_activity", manager, last_value=_midnight(today - timedelta(days=30))))
+ assert [p["params"]["date"] for p in params] == [last_day.isoformat()]
+
+ @mock.patch(ANTHROPIC_SESSION_PATCH)
+ def test_legacy_resume_state_restarts_the_fan_out(self, MockSession) -> None:
+ # A resume state saved before this endpoint existed carries no analytics checkpoint; the run
+ # must restart from the watermark rather than fail reading it.
+ session = MockSession.return_value
+ today = datetime.now(UTC).date()
+ watermark = today - timedelta(days=ANALYTICS_ENGAGEMENT_LAG_DAYS)
+ manager = _make_manager(AnthropicResumeConfig(cursor="OLD"))
+ params = _wire(session, [_analytics_page([_activity_record()], next_page=None)])
+ _rows(_source("analytics_user_activity", manager, last_value=_midnight(watermark)))
+ assert [p["params"]["date"] for p in params] == [watermark.isoformat()]
+
+
+class TestAnalyticsAccessProbe:
+ @parameterized.expand(
+ [
+ ("granted", 200, None),
+ ("scope_missing", 403, ANALYTICS_ACCESS_MISSING),
+ ("route_absent_off_enterprise", 404, ANALYTICS_ACCESS_MISSING),
+ # A bad key is reported once for the whole source by validate_credentials.
+ ("bad_key", 401, None),
+ # A blip during schema discovery must not hide a table the customer can sync.
+ ("throttled", 429, None),
+ ("server_error", 500, None),
+ ]
+ )
+ @mock.patch(ANTHROPIC_SESSION_PATCH)
+ def test_status_mapping(self, _name: str, status: int, expected: str | None, MockSession) -> None:
+ MockSession.return_value.get.return_value = _response({}, status=status)
+ assert check_analytics_access("sk-ant-admin-test") == expected
+
+ @mock.patch(ANTHROPIC_SESSION_PATCH)
+ def test_network_error_leaves_the_tables_reachable(self, MockSession) -> None:
+ MockSession.return_value.get.side_effect = requests.ConnectionError("boom")
+ assert check_analytics_access("sk-ant-admin-test") is None
+
+
+class TestAnalyticsNonRetryableError:
+ def test_analytics_forbidden_reports_the_scope_not_admin_access(self) -> None:
+ # Both the analytics pattern and the generic api.anthropic.com 403 match this error, and the
+ # first matching entry supplies the message the customer reads.
+ errors = AnthropicSource().get_non_retryable_errors()
+ observed = f"403 Client Error: Forbidden for url: https://api.anthropic.com{ANALYTICS_PATH_PREFIX}users?limit=1"
+ matched = [message for pattern, message in errors.items() if error_message_matches(observed, [pattern])]
+ assert len(matched) == 2
+ assert "read:analytics" in (matched[0] or "")
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
index 2ccc3e205124..89d6d5f40aae 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,10 +1,14 @@
-from unittest.mock import MagicMock
+from unittest.mock import MagicMock, patch
from parameterized import parameterized
from products.warehouse_sources.backend.temporal.data_imports.sources.anthropic.settings import ANTHROPIC_ENDPOINTS
from products.warehouse_sources.backend.temporal.data_imports.sources.anthropic.source import AnthropicSource
+_CHECK_ANALYTICS_ACCESS = (
+ "products.warehouse_sources.backend.temporal.data_imports.sources.anthropic.source.check_analytics_access"
+)
+
class TestAnthropicSchemas:
def test_all_endpoints_present(self) -> None:
@@ -19,6 +23,9 @@ class TestAnthropicSchemas:
"cost_report",
"claude_code_analytics",
"claude_code_model_breakdown",
+ "analytics_user_activity",
+ "analytics_user_cost",
+ "analytics_user_usage",
}
@parameterized.expand([("usage_report",), ("cost_report",)])
@@ -80,6 +87,9 @@ class TestAnthropicSourceForPipeline:
("workspace_members", ["workspace_id", "user_id"], None),
("claude_code_analytics", ["id"], "datetime"),
("claude_code_model_breakdown", ["id"], "datetime"),
+ ("analytics_user_activity", ["id"], "datetime"),
+ ("analytics_user_cost", ["id"], "datetime"),
+ ("analytics_user_usage", ["id"], "datetime"),
]
)
def test_primary_keys_and_partitioning(
@@ -103,3 +113,21 @@ class TestDocumentedTables:
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
+
+
+class TestAnalyticsEndpointPermissions:
+ @patch(_CHECK_ANALYTICS_ACCESS, return_value="needs read:analytics")
+ def test_only_the_analytics_tables_carry_the_probe_result(self, _probe) -> None:
+ permissions = AnthropicSource().get_endpoint_permissions(
+ MagicMock(api_key="sk-ant-admin-test"), team_id=1, endpoints=["users", "analytics_user_cost"]
+ )
+ assert permissions == {"users": None, "analytics_user_cost": "needs read:analytics"}
+
+ @patch(_CHECK_ANALYTICS_ACCESS)
+ def test_no_probe_when_no_analytics_table_is_requested(self, probe) -> None:
+ # The probe is a live request, so schema discovery must not pay for it unless a table needs it.
+ permissions = AnthropicSource().get_endpoint_permissions(
+ MagicMock(api_key="sk-ant-admin-test"), team_id=1, endpoints=["users", "cost_report"]
+ )
+ assert permissions == {"users": None, "cost_report": None}
+ probe.assert_not_called()