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): expand OpenAI and Anthropic usage/cost coverage (#73075)

Tom Owers9681b0d62639
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 8a4c43577c33..dc46f3e93894 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,7 +1,7 @@
import hashlib
import dataclasses
from collections.abc import Callable
-from datetime import UTC, date, datetime
+from datetime import UTC, date, datetime, timedelta
from typing import Any, Optional
from requests import Request, Response
@@ -34,6 +34,10 @@ ENTITY_PAGE_SIZE = 1000
# cost data can predate this — starting here rather than the epoch avoids requesting decades of empty
# buckets while still pulling all available history.
DEFAULT_STARTING_AT = datetime(2023, 1, 1, tzinfo=UTC)
+# Floor for the day-by-day fan-out of the Claude Code analytics endpoint (one required `starting_at`
+# 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)
@dataclasses.dataclass
@@ -48,6 +52,8 @@ class AnthropicResumeConfig:
# workspace_members fan-out checkpoint from the framework:
# {"completed": [child_path, ...], "current": child_path | None, "child_state": {...} | None}.
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
class AnthropicCursorPaginator(BasePaginator):
@@ -106,6 +112,70 @@ class AnthropicCursorPaginator(BasePaginator):
return f"AnthropicCursorPaginator(cursor_path={self.cursor_path}, cursor_param={self.cursor_param})"
+class ClaudeCodeDayPaginator(BasePaginator):
+ """Day-by-day fan-out for the Claude Code analytics endpoint.
+
+ The endpoint windows on a single required `starting_at` day (not a range) and page-cursors within
+ that day via `page`/`next_page`+`has_more`. This paginator walks each day's pages, then advances
+ `starting_at` to the next day, stopping once it passes today — so the whole history is one resource
+ driven entirely by the paginator (there is no parent API resource to resolve days from).
+ """
+
+ def __init__(self, start_day: date, today: date) -> None:
+ super().__init__()
+ # Never request a future day: if the watermark is at/after today, re-pull today only.
+ self._current_day = min(start_day, today)
+ self._today = today
+ self._page: Optional[str] = None
+
+ def _apply(self, request: Request) -> None:
+ if request.params is None:
+ request.params = {}
+ request.params["starting_at"] = self._current_day.isoformat()
+ if self._page is not None:
+ request.params["page"] = self._page
+ else:
+ request.params.pop("page", None)
+
+ def init_request(self, request: Request) -> None:
+ self._apply(request)
+
+ def update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:
+ try:
+ body = response.json()
+ except Exception:
+ body = None
+ next_page = body.get("next_page") if isinstance(body, dict) else None
+ has_more = bool(body.get("has_more")) if isinstance(body, dict) else False
+ if has_more and next_page and data:
+ # More pages within the current day.
+ self._page = next_page
+ self._has_next_page = True
+ return
+ # Day exhausted — advance to the next day, or stop once we pass today.
+ self._current_day = self._current_day + timedelta(days=1)
+ self._page = None
+ self._has_next_page = self._current_day <= self._today
+
+ def update_request(self, request: Request) -> None:
+ self._apply(request)
+
+ def get_resume_state(self) -> Optional[dict[str, Any]]:
+ if not self._has_next_page:
+ return None
+ return {"date": self._current_day.isoformat(), "cursor": self._page}
+
+ def set_resume_state(self, state: dict[str, Any]) -> None:
+ saved_date = state.get("date")
+ if saved_date:
+ self._current_day = _parse_iso_date(str(saved_date))
+ self._page = state.get("cursor")
+ self._has_next_page = True
+
+ def __str__(self) -> str:
+ return f"ClaudeCodeDayPaginator(current_day={self._current_day}, today={self._today})"
+
+
def _version_headers() -> dict[str, str]:
# Auth (x-api-key) is supplied via the framework auth config so its value is redacted from
# logs; only the non-secret version/accept headers are set here.
@@ -221,6 +291,9 @@ def _flatten_cost_result(bucket: dict[str, Any], result: dict[str, Any]) -> dict
"service_tier": result.get("service_tier"),
"token_type": result.get("token_type"),
"context_window": result.get("context_window"),
+ # Data-residency dimension parsed from `description`; kept out of the id (description already
+ # disambiguates it) so existing rows' surrogate keys stay stable.
+ "inference_geo": result.get("inference_geo"),
"currency": result.get("currency"),
"amount": result.get("amount"),
}
@@ -236,6 +309,116 @@ def _explode_cost_bucket(bucket: dict[str, Any]) -> list[dict[str, Any]]:
return [_flatten_cost_result(bucket, result) for result in bucket.get("results") or []]
+def _parse_iso_date(value: str) -> date:
+ # Accept a bare date or a full RFC 3339 timestamp; only the calendar day matters for the fan-out.
+ 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
+ if isinstance(value, datetime):
+ return (value.astimezone(UTC) if value.tzinfo else value.replace(tzinfo=UTC)).date()
+ if isinstance(value, date):
+ return value
+ return _parse_iso_date(str(value))
+
+
+def _claude_code_actor_dims(item: dict[str, Any]) -> tuple[Any, str | None, str | None, str | None, str | None]:
+ """Pull the shared (date, actor, terminal) dimensions every Claude Code row carries.
+
+ `actor` is either a user (`email_address`) or an API actor (`api_key_name`); surface both as flat
+ columns so the grain is queryable without unpacking a nested object.
+ """
+ actor = item.get("actor") or {}
+ return (
+ item.get("date"),
+ actor.get("type"),
+ actor.get("email_address"),
+ actor.get("api_key_name"),
+ item.get("terminal_type"),
+ )
+
+
+def _flatten_claude_code_core(item: dict[str, Any]) -> dict[str, Any]:
+ """One row per (day, actor): Claude Code core productivity metrics and tool-action counts."""
+ date_value, actor_type, actor_email, actor_api_key_name, terminal_type = _claude_code_actor_dims(item)
+ core = item.get("core_metrics") or {}
+ lines_of_code = core.get("lines_of_code") or {}
+ tool_actions = item.get("tool_actions") or {}
+
+ def _tool(name: str) -> tuple[Any, Any]:
+ action = tool_actions.get(name) or {}
+ return action.get("accepted"), action.get("rejected")
+
+ edit_accepted, edit_rejected = _tool("edit_tool")
+ multi_edit_accepted, multi_edit_rejected = _tool("multi_edit_tool")
+ write_accepted, write_rejected = _tool("write_tool")
+ notebook_edit_accepted, notebook_edit_rejected = _tool("notebook_edit_tool")
+
+ return {
+ "id": _row_id(date_value, actor_type, actor_email, actor_api_key_name, terminal_type),
+ "date": date_value,
+ "organization_id": item.get("organization_id"),
+ "actor_type": actor_type,
+ "actor_email_address": actor_email,
+ "actor_api_key_name": actor_api_key_name,
+ "customer_type": item.get("customer_type"),
+ "terminal_type": terminal_type,
+ "num_sessions": core.get("num_sessions"),
+ "lines_of_code_added": lines_of_code.get("added"),
+ "lines_of_code_removed": lines_of_code.get("removed"),
+ "commits_by_claude_code": core.get("commits_by_claude_code"),
+ "pull_requests_by_claude_code": core.get("pull_requests_by_claude_code"),
+ "edit_tool_accepted": edit_accepted,
+ "edit_tool_rejected": edit_rejected,
+ "multi_edit_tool_accepted": multi_edit_accepted,
+ "multi_edit_tool_rejected": multi_edit_rejected,
+ "write_tool_accepted": write_accepted,
+ "write_tool_rejected": write_rejected,
+ "notebook_edit_tool_accepted": notebook_edit_accepted,
+ "notebook_edit_tool_rejected": notebook_edit_rejected,
+ }
+
+
+def _flatten_claude_code_models(item: dict[str, Any]) -> list[dict[str, Any]]:
+ """One row per (day, actor, model): the per-model token and estimated-cost breakdown.
+
+ Split out from the core metrics because tokens/cost are at a finer grain (per model) than sessions
+ and commits (per day) — keeping them in one table would either duplicate the core metrics across a
+ day's models or bury the per-model cost in a nested column.
+ """
+ date_value, actor_type, actor_email, actor_api_key_name, terminal_type = _claude_code_actor_dims(item)
+ rows: list[dict[str, Any]] = []
+ for entry in item.get("model_breakdown") or []:
+ model = entry.get("model")
+ tokens = entry.get("tokens") or {}
+ estimated_cost = entry.get("estimated_cost") or {}
+ rows.append(
+ {
+ "id": _row_id(date_value, actor_type, actor_email, actor_api_key_name, terminal_type, model),
+ "date": date_value,
+ "organization_id": item.get("organization_id"),
+ "actor_type": actor_type,
+ "actor_email_address": actor_email,
+ "actor_api_key_name": actor_api_key_name,
+ "customer_type": item.get("customer_type"),
+ "terminal_type": terminal_type,
+ "model": model,
+ "input_tokens": tokens.get("input"),
+ "output_tokens": tokens.get("output"),
+ "cache_read_tokens": tokens.get("cache_read"),
+ "cache_creation_tokens": tokens.get("cache_creation"),
+ "estimated_cost_amount": estimated_cost.get("amount"),
+ "estimated_cost_currency": estimated_cost.get("currency"),
+ }
+ )
+ return rows
+
+
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.
@@ -266,7 +449,50 @@ def anthropic_source(
resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
- if config.fan_out_over_workspaces:
+ if 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)
+ # Annotated to the shared base so the other branches can rebind it to AnthropicCursorPaginator.
+ paginator: BasePaginator = ClaudeCodeDayPaginator(start_day, datetime.now(UTC).date())
+ day_data_map: Callable[[dict[str, Any]], dict[str, Any] | list[dict[str, Any]]] = (
+ _flatten_claude_code_models if endpoint == "claude_code_model_breakdown" else _flatten_claude_code_core
+ )
+ day_params: dict[str, Any] = {}
+ if config.limit is not None:
+ day_params["limit"] = config.limit
+
+ cc_endpoint_resource: EndpointResource = {
+ "name": endpoint,
+ "endpoint": {
+ "path": config.path,
+ "params": day_params,
+ "data_selector": "data",
+ "paginator": paginator,
+ },
+ "data_map": day_data_map,
+ }
+ cc_rest_config: RESTAPIConfig = {
+ "client": client_config,
+ "resource_defaults": None,
+ "resources": [cc_endpoint_resource],
+ }
+
+ initial_day_state = resume.day_fanout_state if resume is not None else None
+
+ def save_day_checkpoint(state: Optional[dict[str, Any]]) -> None:
+ if state:
+ resumable_source_manager.save_state(AnthropicResumeConfig(day_fanout_state=state))
+
+ resource = rest_api_resource(
+ cc_rest_config,
+ team_id,
+ job_id,
+ db_incremental_field_last_value,
+ resume_hook=save_day_checkpoint,
+ initial_paginator_state=initial_day_state,
+ )
+ elif config.fan_out_over_workspaces:
# No org-wide member list exists; enumerate every workspace (archived included, since they
# are still referenced by historical usage/cost rows) and fetch its /members per workspace.
workspaces_config = ANTHROPIC_ENDPOINTS["workspaces"]
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 e6c03fb3d04b..8d5b21a2f8ea 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
@@ -104,8 +104,68 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"service_tier": "Service tier the cost is attributed to (standard or batch), or null.",
"token_type": "Token type the cost is attributed to (e.g. output_tokens), or null.",
"context_window": "Input context window the cost is attributed to, or null.",
+ "inference_geo": "Data-residency region the cost is attributed to (global, us, not_available), or null.",
"currency": 'Currency code for the amount, currently always "USD".',
"amount": 'Cost amount in the lowest currency unit (cents) as a decimal string, e.g. "123.45".',
},
},
+ "service_accounts": {
+ "description": "Service accounts (non-human API principals) across your Anthropic organization's workspaces, one row per (workspace, service account).",
+ "docs_url": f"{_ADMIN_API_DOCS}/service_accounts/list-service-accounts",
+ "columns": {
+ "id": "Unique identifier for the service account.",
+ "type": 'Object type, always "service_account".',
+ "name": "Display name of the service account.",
+ "workspace_id": "ID of the workspace the service account belongs to.",
+ "created_at": "RFC 3339 timestamp of when the service account was created.",
+ },
+ },
+ "claude_code_analytics": {
+ "description": "Claude Code productivity metrics, one row per user per day: sessions, lines of code, commits, pull requests, and tool-action accept/reject counts.",
+ "docs_url": f"{_ADMIN_API_DOCS}/usage-cost/get-claude-code-analytics",
+ "columns": {
+ "id": "Synthesized surrogate key: a hash of the day and every actor/terminal dimension.",
+ "date": "UTC day the metrics are aggregated over, in RFC 3339 format.",
+ "organization_id": "ID of the organization the activity belongs to.",
+ "actor_type": "Type of actor: user_actor (a person) or api_actor (an API key).",
+ "actor_email_address": "Email address of the user actor, or null for API actors.",
+ "actor_api_key_name": "Name of the API key for an API actor, or null for user actors.",
+ "customer_type": "Billing relationship: api (pay-as-you-go) or subscription (Pro/Team).",
+ "terminal_type": "Terminal the sessions ran in (e.g. vscode, iTerm.app, tmux).",
+ "num_sessions": "Number of Claude Code sessions that day.",
+ "lines_of_code_added": "Lines of code added by Claude Code.",
+ "lines_of_code_removed": "Lines of code removed by Claude Code.",
+ "commits_by_claude_code": "Number of git commits created by Claude Code.",
+ "pull_requests_by_claude_code": "Number of pull requests created by Claude Code.",
+ "edit_tool_accepted": "Edit tool actions the user accepted.",
+ "edit_tool_rejected": "Edit tool actions the user rejected.",
+ "multi_edit_tool_accepted": "Multi-edit tool actions the user accepted.",
+ "multi_edit_tool_rejected": "Multi-edit tool actions the user rejected.",
+ "write_tool_accepted": "Write tool actions the user accepted.",
+ "write_tool_rejected": "Write tool actions the user rejected.",
+ "notebook_edit_tool_accepted": "Notebook-edit tool actions the user accepted.",
+ "notebook_edit_tool_rejected": "Notebook-edit tool actions the user rejected.",
+ },
+ },
+ "claude_code_model_breakdown": {
+ "description": "Per-model token usage and estimated cost for Claude Code, one row per user per day per model.",
+ "docs_url": f"{_ADMIN_API_DOCS}/usage-cost/get-claude-code-analytics",
+ "columns": {
+ "id": "Synthesized surrogate key: a hash of the day, actor/terminal dimensions, and model.",
+ "date": "UTC day the metrics are aggregated over, in RFC 3339 format.",
+ "organization_id": "ID of the organization the activity belongs to.",
+ "actor_type": "Type of actor: user_actor (a person) or api_actor (an API key).",
+ "actor_email_address": "Email address of the user actor, or null for API actors.",
+ "actor_api_key_name": "Name of the API key for an API actor, or null for user actors.",
+ "customer_type": "Billing relationship: api (pay-as-you-go) or subscription (Pro/Team).",
+ "terminal_type": "Terminal the sessions ran in (e.g. vscode, iTerm.app, tmux).",
+ "model": "Model the tokens and cost are attributed to (e.g. claude-opus-4-8).",
+ "input_tokens": "Uncached input tokens used against this model.",
+ "output_tokens": "Output tokens generated by this model.",
+ "cache_read_tokens": "Input tokens read from the prompt cache.",
+ "cache_creation_tokens": "Input tokens used to create prompt-cache entries.",
+ "estimated_cost_amount": "Estimated cost in the lowest currency unit (cents) as a decimal string.",
+ "estimated_cost_currency": 'Currency code for the estimated cost, currently always "USD".',
+ },
+ },
}
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 e8f445efea50..a18a7badf953 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
@@ -47,8 +47,12 @@ class AnthropicEndpointConfig:
# Re-read window (seconds) applied to the incremental watermark by the pipeline before it reaches
# the source, so each run re-pulls recently-restated buckets. Merge dedupes them on the primary key.
default_incremental_lookback_seconds: Optional[int] = None
- # workspace_members has no org-wide list endpoint; it fans out one request per workspace.
+ # workspace_members / service_accounts have no org-wide list endpoint; they fan out one request
+ # per workspace.
fan_out_over_workspaces: bool = False
+ # Claude Code analytics takes a single `starting_at` day per request, so it fans out one windowed
+ # request per calendar day from the watermark (or launch floor) to today.
+ 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)
should_sync_default: bool = True
@@ -115,6 +119,16 @@ ANTHROPIC_ENDPOINTS: dict[str, AnthropicEndpointConfig] = {
primary_keys=["workspace_id", "user_id"],
fan_out_over_workspaces=True,
),
+ # Like workspace_members, service accounts are workspace-scoped with no org-wide list. Their ids
+ # resolve the `service_account_id` dimension on the usage report.
+ "service_accounts": AnthropicEndpointConfig(
+ name="service_accounts",
+ path="/v1/organizations/workspaces/{workspace_id}/service_accounts",
+ pagination=PaginationType.CURSOR,
+ primary_keys=["workspace_id", "id"],
+ partition_key="created_at",
+ fan_out_over_workspaces=True,
+ ),
"usage_report": AnthropicEndpointConfig(
name="usage_report",
path="/v1/organizations/usage_report/messages",
@@ -145,6 +159,37 @@ ANTHROPIC_ENDPOINTS: dict[str, AnthropicEndpointConfig] = {
group_by=_COST_GROUP_BY,
default_incremental_lookback_seconds=_REPORT_LOOKBACK_SECONDS,
),
+ # Claude Code analytics: one record per user per day. The endpoint windows on a single `starting_at`
+ # day (page-cursored within the day), so the source fans out day by day. Split into two tables — the
+ # per-day productivity metrics here, the per-model token/cost breakdown below — because those two
+ # sit at different grains.
+ "claude_code_analytics": AnthropicEndpointConfig(
+ name="claude_code_analytics",
+ path="/v1/organizations/usage_report/claude_code",
+ pagination=PaginationType.PAGE,
+ # `id` is synthesized from the day and every actor/terminal dimension (see anthropic.py).
+ primary_keys=["id"],
+ partition_key="date",
+ supports_incremental=True,
+ incremental_fields=[_datetime_incremental_field("date")],
+ fan_out_over_days=True,
+ limit=1000,
+ # The current day keeps accruing (up to a 1-hour delay), so re-pull the trailing day; merge
+ # dedupes the overlap on the synthesized `id`.
+ default_incremental_lookback_seconds=_REPORT_LOOKBACK_SECONDS,
+ ),
+ "claude_code_model_breakdown": AnthropicEndpointConfig(
+ name="claude_code_model_breakdown",
+ path="/v1/organizations/usage_report/claude_code",
+ pagination=PaginationType.PAGE,
+ primary_keys=["id"],
+ partition_key="date",
+ supports_incremental=True,
+ incremental_fields=[_datetime_incremental_field("date")],
+ fan_out_over_days=True,
+ limit=1000,
+ default_incremental_lookback_seconds=_REPORT_LOOKBACK_SECONDS,
+ ),
}
ENDPOINTS = tuple(ANTHROPIC_ENDPOINTS.keys())
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 95a5866d168c..6f1dde2ec323 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/anthropic/tests/test_anthropic.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/anthropic/tests/test_anthropic.py
@@ -1,5 +1,5 @@
import json
-from datetime import UTC, datetime
+from datetime import UTC, date, datetime, timedelta
from typing import Any, cast
import pytest
@@ -7,11 +7,16 @@ from unittest import mock
import requests
from parameterized import parameterized
-from requests import Response
+from requests import Request, Response
from products.warehouse_sources.backend.temporal.data_imports.sources.anthropic.anthropic import (
ANTHROPIC_VERSION,
+ DEFAULT_CLAUDE_CODE_START,
AnthropicResumeConfig,
+ ClaudeCodeDayPaginator,
+ _claude_code_start_day,
+ _flatten_claude_code_core,
+ _flatten_claude_code_models,
_flatten_cost_result,
_flatten_usage_result,
_row_id,
@@ -144,6 +149,23 @@ class TestFlattenCost:
assert row["currency"] == "USD"
assert row["id"]
+ def test_inference_geo_surfaced(self) -> None:
+ # The data-residency dimension is parsed into cost results when grouped by description; surface
+ # it as its own column rather than dropping it on the floor.
+ row = _flatten_cost_result(
+ {"starting_at": "2025-08-01T00:00:00Z", "ending_at": "2025-08-02T00:00:00Z"},
+ {"workspace_id": "wrkspc_1", "amount": "1.0", "inference_geo": "us"},
+ )
+ assert row["inference_geo"] == "us"
+
+ def test_id_stable_when_inference_geo_added(self) -> None:
+ # inference_geo is deliberately kept out of the surrogate key (description already disambiguates
+ # it), so surfacing it must not change the id of a row that existed before the column was added.
+ base = {"starting_at": "s", "ending_at": "e", "workspace_id": "w", "description": "d", "amount": "1"}
+ without_geo = _flatten_cost_result({"starting_at": "s", "ending_at": "e"}, base)
+ with_geo = _flatten_cost_result({"starting_at": "s", "ending_at": "e"}, {**base, "inference_geo": "us"})
+ assert without_geo["id"] == with_geo["id"]
+
class TestReportParams:
@mock.patch(CLIENT_SESSION_PATCH)
@@ -557,3 +579,229 @@ class TestNonRetryableErrors:
def test_transient_errors_remain_retryable(self, _name: str, other_error: str) -> None:
non_retryable = AnthropicSource().get_non_retryable_errors()
assert not any(key in other_error for key in non_retryable)
+
+
+def _cc_record(actor_email: str = "[email protected]") -> dict[str, Any]:
+ return {
+ "date": "2025-09-01T00:00:00Z",
+ "organization_id": "org_1",
+ "actor": {"type": "user_actor", "email_address": actor_email},
+ "customer_type": "subscription",
+ "terminal_type": "vscode",
+ "core_metrics": {
+ "num_sessions": 1,
+ "lines_of_code": {"added": 1, "removed": 0},
+ "commits_by_claude_code": 0,
+ "pull_requests_by_claude_code": 0,
+ },
+ "tool_actions": {},
+ "model_breakdown": [
+ {"model": "claude-opus-4-8", "tokens": {"input": 1}, "estimated_cost": {"amount": "1", "currency": "USD"}}
+ ],
+ }
+
+
+def _cc_page(records: list[dict[str, Any]], *, has_more: bool, next_page: str | None) -> Response:
+ return _response({"data": records, "has_more": has_more, "next_page": next_page})
+
+
+def _midnight(day: date) -> datetime:
+ return datetime.combine(day, datetime.min.time(), tzinfo=UTC)
+
+
+class TestFlattenClaudeCode:
+ _RECORD = {
+ "date": "2025-09-01T00:00:00Z",
+ "organization_id": "org_1",
+ "actor": {"type": "user_actor", "email_address": "[email protected]"},
+ "customer_type": "subscription",
+ "terminal_type": "vscode",
+ "core_metrics": {
+ "num_sessions": 4,
+ "lines_of_code": {"added": 120, "removed": 30},
+ "commits_by_claude_code": 3,
+ "pull_requests_by_claude_code": 1,
+ },
+ "tool_actions": {
+ "edit_tool": {"accepted": 10, "rejected": 2},
+ "write_tool": {"accepted": 5, "rejected": 0},
+ },
+ "model_breakdown": [
+ {
+ "model": "claude-opus-4-8",
+ "tokens": {"input": 1000, "output": 500, "cache_read": 200, "cache_creation": 100},
+ "estimated_cost": {"amount": "12.50", "currency": "USD"},
+ },
+ {
+ "model": "claude-haiku-4-5",
+ "tokens": {"input": 50, "output": 20, "cache_read": 0, "cache_creation": 0},
+ "estimated_cost": {"amount": "0.10", "currency": "USD"},
+ },
+ ],
+ }
+
+ def test_core_flattens_metrics_and_tool_actions(self) -> None:
+ row = _flatten_claude_code_core(self._RECORD)
+ assert row["actor_type"] == "user_actor"
+ assert row["actor_email_address"] == "[email protected]"
+ assert row["actor_api_key_name"] is None
+ assert row["num_sessions"] == 4
+ assert row["lines_of_code_added"] == 120
+ assert row["lines_of_code_removed"] == 30
+ assert row["edit_tool_accepted"] == 10
+ assert row["edit_tool_rejected"] == 2
+ assert row["write_tool_accepted"] == 5
+ # A tool the record omits yields nulls, never a crash.
+ assert row["multi_edit_tool_accepted"] is None
+ assert row["id"]
+
+ def test_api_actor_surfaces_key_name_not_email(self) -> None:
+ record = {**self._RECORD, "actor": {"type": "api_actor", "api_key_name": "ci-key"}}
+ row = _flatten_claude_code_core(record)
+ assert row["actor_api_key_name"] == "ci-key"
+ assert row["actor_email_address"] is None
+
+ def test_models_explode_one_row_per_model_with_distinct_ids(self) -> None:
+ rows = _flatten_claude_code_models(self._RECORD)
+ assert [r["model"] for r in rows] == ["claude-opus-4-8", "claude-haiku-4-5"]
+ assert rows[0]["input_tokens"] == 1000
+ assert rows[0]["cache_creation_tokens"] == 100
+ assert rows[0]["estimated_cost_amount"] == "12.50"
+ # Per-model rows for the same (day, actor) must have distinct ids so merge keeps them apart.
+ assert rows[0]["id"] != rows[1]["id"]
+
+ def test_empty_model_breakdown_yields_no_rows(self) -> None:
+ assert _flatten_claude_code_models({**self._RECORD, "model_breakdown": []}) == []
+
+
+class TestClaudeCodeStartDay:
+ def test_full_refresh_uses_launch_floor(self) -> None:
+ assert _claude_code_start_day(None) == DEFAULT_CLAUDE_CODE_START
+
+ @parameterized.expand(
+ [
+ ("datetime", datetime(2026, 3, 4, 12, 0, 0, tzinfo=UTC)),
+ ("rfc3339_string", "2026-03-04T12:00:00Z"),
+ ("bare_date_string", "2026-03-04"),
+ ("date", date(2026, 3, 4)),
+ ]
+ )
+ def test_incremental_watermark_resolves_to_calendar_day(self, _name: str, watermark: Any) -> None:
+ assert _claude_code_start_day(watermark) == date(2026, 3, 4)
+
+
+class TestClaudeCodeDayPaginator:
+ def test_advances_day_when_exhausted_and_stops_past_today(self) -> None:
+ paginator = ClaudeCodeDayPaginator(date(2025, 1, 1), date(2025, 1, 3))
+ req = Request()
+ paginator.init_request(req)
+ assert req.params["starting_at"] == "2025-01-01"
+
+ paginator.update_state(_cc_page([_cc_record()], has_more=False, next_page=None), data=[{"x": 1}])
+ assert paginator.has_next_page is True
+ req2 = Request()
+ paginator.update_request(req2)
+ assert req2.params["starting_at"] == "2025-01-02"
+ assert "page" not in req2.params
+
+ paginator.update_state(_cc_page([], has_more=False, next_page=None), data=[]) # day 2 -> day 3
+ assert paginator.has_next_page is True
+ paginator.update_state(_cc_page([], has_more=False, next_page=None), data=[]) # day 3 -> past today
+ assert paginator.has_next_page is False
+
+ def test_stays_on_day_across_pages(self) -> None:
+ paginator = ClaudeCodeDayPaginator(date(2025, 1, 1), date(2025, 1, 1))
+ paginator.update_state(_cc_page([_cc_record()], has_more=True, next_page="P2"), data=[{"x": 1}])
+ assert paginator.has_next_page is True
+ req = Request()
+ paginator.update_request(req)
+ assert req.params["starting_at"] == "2025-01-01"
+ assert req.params["page"] == "P2"
+
+ def test_resume_state_roundtrip(self) -> None:
+ paginator = ClaudeCodeDayPaginator(date(2025, 1, 1), date(2025, 1, 5))
+ paginator.set_resume_state({"date": "2025-01-04", "cursor": "PX"})
+ req = Request()
+ paginator.init_request(req)
+ assert req.params["starting_at"] == "2025-01-04"
+ assert req.params["page"] == "PX"
+ assert paginator.get_resume_state() == {"date": "2025-01-04", "cursor": "PX"}
+
+ def test_clamps_future_start_day_to_today(self) -> None:
+ # A watermark at/after today must re-pull today, never request a future day.
+ paginator = ClaudeCodeDayPaginator(date(2025, 6, 1), date(2025, 1, 1))
+ req = Request()
+ paginator.init_request(req)
+ assert req.params["starting_at"] == "2025-01-01"
+
+
+class TestClaudeCodeDayFanOut:
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_fans_out_one_windowed_request_per_day(self, MockSession) -> None:
+ session = MockSession.return_value
+ today = datetime.now(UTC).date()
+ watermark = _midnight(today - timedelta(days=2))
+ params = _wire(session, [_cc_page([_cc_record()], has_more=False, next_page=None) for _ in range(3)])
+ rows = _rows(_source("claude_code_analytics", _make_manager(), last_value=watermark))
+ assert len(rows) == 3 # one per-day core row
+ days = [(watermark.date() + timedelta(days=i)).isoformat() for i in range(3)]
+ assert [p["params"]["starting_at"] for p in params] == days
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_model_breakdown_endpoint_explodes_per_model(self, MockSession) -> None:
+ session = MockSession.return_value
+ today = datetime.now(UTC).date()
+ record = _cc_record()
+ record["model_breakdown"] = [
+ {"model": "m1", "tokens": {"input": 1}, "estimated_cost": {"amount": "1", "currency": "USD"}},
+ {"model": "m2", "tokens": {"input": 2}, "estimated_cost": {"amount": "2", "currency": "USD"}},
+ ]
+ _wire(session, [_cc_page([record], has_more=False, next_page=None)])
+ rows = _rows(_source("claude_code_model_breakdown", _make_manager(), last_value=_midnight(today)))
+ assert sorted(r["model"] for r in rows) == ["m1", "m2"]
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_paginates_within_a_day(self, MockSession) -> None:
+ session = MockSession.return_value
+ today = datetime.now(UTC).date()
+ params = _wire(
+ session,
+ [
+ _cc_page([_cc_record("[email protected]")], has_more=True, next_page="P2"),
+ _cc_page([_cc_record("[email protected]")], has_more=False, next_page=None),
+ ],
+ )
+ rows = _rows(_source("claude_code_analytics", _make_manager(), last_value=_midnight(today)))
+ assert {r["actor_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"]["starting_at"] == today.isoformat()
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_resumes_from_saved_day_and_page_cursor(self, MockSession) -> None:
+ session = MockSession.return_value
+ today = datetime.now(UTC).date()
+ manager = _make_manager(AnthropicResumeConfig(day_fanout_state={"date": today.isoformat(), "cursor": "P2"}))
+ params = _wire(session, [_cc_page([_cc_record()], has_more=False, next_page=None)])
+ rows = _rows(_source("claude_code_analytics", manager, last_value=_midnight(today)))
+ assert len(rows) == 1
+ assert params[0]["params"]["page"] == "P2"
+ assert params[0]["params"]["starting_at"] == today.isoformat()
+
+
+class TestServiceAccountsFanOut:
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_emits_one_row_per_service_account_with_composite_key(self, MockSession) -> None:
+ session = MockSession.return_value
+ # Service account objects here don't carry workspace_id, so the fan-out must inject it or the
+ # composite key's workspace_id lands null.
+ _wire(
+ session,
+ [
+ _entity_page([{"id": "wrkspc_1"}, {"id": "wrkspc_2"}], has_more=False, last_id="wrkspc_2"),
+ _entity_page([{"id": "svac_1", "type": "service_account"}], has_more=False, last_id="svac_1"),
+ _entity_page([{"id": "svac_2", "type": "service_account"}], has_more=False, last_id="svac_2"),
+ ],
+ )
+ rows = _rows(_source("service_accounts", _make_manager()))
+ assert [(r["workspace_id"], r["id"]) for r in rows] == [("wrkspc_1", "svac_1"), ("wrkspc_2", "svac_2")]
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 8626f0e39728..497080bf210b 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
@@ -37,8 +37,11 @@ class TestAnthropicSchemas:
"workspaces",
"api_keys",
"workspace_members",
+ "service_accounts",
"usage_report",
"cost_report",
+ "claude_code_analytics",
+ "claude_code_model_breakdown",
}
@parameterized.expand([("usage_report",), ("cost_report",)])
@@ -50,7 +53,18 @@ class TestAnthropicSchemas:
assert [f["field"] for f in schema.incremental_fields] == ["starting_at"]
assert schema.default_incremental_lookback_seconds == 60 * 60 * 24
- @parameterized.expand([("users",), ("workspaces",), ("api_keys",), ("workspace_members",), ("invites",)])
+ @parameterized.expand([("claude_code_analytics",), ("claude_code_model_breakdown",)])
+ def test_claude_code_endpoints_are_incremental_on_date(self, endpoint: str) -> None:
+ # The Claude Code endpoint windows on a single `starting_at` day, so `date` is the watermark.
+ schema = next(s for s in AnthropicSource().get_schemas(MagicMock(), team_id=1) if s.name == endpoint)
+ assert schema.supports_incremental is True
+ assert schema.supports_append is False # the current day keeps accruing; append would duplicate
+ assert [f["field"] for f in schema.incremental_fields] == ["date"]
+ assert schema.default_incremental_lookback_seconds == 60 * 60 * 24
+
+ @parameterized.expand(
+ [("users",), ("workspaces",), ("api_keys",), ("workspace_members",), ("invites",), ("service_accounts",)]
+ )
def test_entity_endpoints_are_full_refresh_only(self, endpoint: str) -> None:
# No updated-since filter exists on the entity lists, so they must not advertise incremental.
schema = next(s for s in AnthropicSource().get_schemas(MagicMock(), team_id=1) if s.name == endpoint)
@@ -85,6 +99,9 @@ class TestAnthropicSourceForPipeline:
("cost_report", ["id"], "datetime"),
("users", ["id"], "datetime"),
("workspace_members", ["workspace_id", "user_id"], None),
+ ("service_accounts", ["workspace_id", "id"], "datetime"),
+ ("claude_code_analytics", ["id"], "datetime"),
+ ("claude_code_model_breakdown", ["id"], "datetime"),
]
)
def test_primary_keys_and_partitioning(
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/openai/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/openai/canonical_descriptions.py
index d3e68e3fa958..974185b5cc11 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/openai/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/openai/canonical_descriptions.py
@@ -99,6 +99,30 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"num_sessions": "Number of code interpreter sessions.",
},
},
+ "usage_web_search_calls": {
+ "description": "Web search tool-call usage aggregated into daily buckets, broken down by project, user, API key, model, and context level.",
+ "docs_url": f"{_API_DOCS}/usage/web_search_calls",
+ "columns": {
+ **_USAGE_DIMENSION_COLUMNS,
+ "context_level": "Search context size the tool call used (low, medium, or high), or null.",
+ "num_requests": "Number of web search tool calls made.",
+ "num_model_requests": "Count of requests made to the model.",
+ },
+ },
+ "usage_file_search_calls": {
+ "description": "File search tool-call usage aggregated into daily buckets, broken down by project, user, API key, and vector store.",
+ "docs_url": f"{_API_DOCS}/usage/file_search_calls",
+ "columns": {
+ "id": "Synthesized surrogate key: a hash of the bucket start and every grouping dimension.",
+ "start_time": "Start of the time bucket (inclusive) as a UTC timestamp.",
+ "end_time": "End of the time bucket (exclusive) as a UTC timestamp.",
+ "project_id": "ID of the project the usage is attributed to, or null.",
+ "user_id": "ID of the user the usage is attributed to, or null.",
+ "api_key_id": "ID of the API key used, or null.",
+ "vector_store_id": "ID of the vector store the search ran against, or null.",
+ "num_requests": "Number of file search tool calls made.",
+ },
+ },
"costs": {
"description": "Daily spend for your OpenAI organization, broken down by project, line item, and API key.",
"docs_url": f"{_API_DOCS}/usage/costs",
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/openai/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/openai/settings.py
index cfa3898f3d18..674f495e6ab5 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/openai/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/openai/settings.py
@@ -66,6 +66,9 @@ class OpenAIEndpointConfig:
_USAGE_GROUP_BY = ["project_id", "user_id", "api_key_id", "model"]
_COMPLETIONS_GROUP_BY = [*_USAGE_GROUP_BY, "batch", "service_tier"]
_IMAGES_GROUP_BY = [*_USAGE_GROUP_BY, "size", "source"]
+_WEB_SEARCH_GROUP_BY = [*_USAGE_GROUP_BY, "context_level"]
+# File search groups by the vector store it ran against, not the model (there is no model dimension).
+_FILE_SEARCH_GROUP_BY = ["project_id", "user_id", "api_key_id", "vector_store_id"]
# The costs endpoint only accepts project_id and line_item. The SDK types also list api_key_id,
# but requesting it makes the live API reject the whole request with a 400.
_COSTS_GROUP_BY = ["project_id", "line_item"]
@@ -111,6 +114,8 @@ OPENAI_ENDPOINTS: dict[str, OpenAIEndpointConfig] = {
"usage_code_interpreter_sessions": _usage_endpoint(
"usage_code_interpreter_sessions", "code_interpreter_sessions", ["project_id"]
),
+ "usage_web_search_calls": _usage_endpoint("usage_web_search_calls", "web_search_calls", _WEB_SEARCH_GROUP_BY),
+ "usage_file_search_calls": _usage_endpoint("usage_file_search_calls", "file_search_calls", _FILE_SEARCH_GROUP_BY),
"costs": OpenAIEndpointConfig(
name="costs",
path="/v1/organization/costs",
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/openai/tests/test_openai.py b/products/warehouse_sources/backend/temporal/data_imports/sources/openai/tests/test_openai.py
index e37700f535a8..9d71ab6b8960 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/openai/tests/test_openai.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/openai/tests/test_openai.py
@@ -640,3 +640,19 @@ class TestNonRetryableErrors:
def test_transient_errors_remain_retryable(self, _name: str, other_error: str) -> None:
non_retryable = OpenAISource().get_non_retryable_errors()
assert not any(key in other_error for key in non_retryable)
+
+
+class TestToolCallUsageGroupBy:
+ # Each tool-usage endpoint advertises a distinct group_by set; requesting a dimension the endpoint
+ # does not support (e.g. `model` on file_search) makes the live API 400, so guard the composition.
+ @parameterized.expand(
+ [
+ ("usage_web_search_calls", ["project_id", "user_id", "api_key_id", "model", "context_level"]),
+ ("usage_file_search_calls", ["project_id", "user_id", "api_key_id", "vector_store_id"]),
+ ]
+ )
+ def test_group_by_matches_supported_dimensions(self, endpoint: str, expected: list[str]) -> None:
+ assert OPENAI_ENDPOINTS[endpoint].group_by == expected
+
+ def test_file_search_does_not_group_by_model(self) -> None:
+ assert "model" not in OPENAI_ENDPOINTS["usage_file_search_calls"].group_by
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/openai/tests/test_openai_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/openai/tests/test_openai_source.py
index 3e8295025e27..502394270a13 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/openai/tests/test_openai_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/openai/tests/test_openai_source.py
@@ -21,6 +21,8 @@ _USAGE_ENDPOINTS = [
"usage_audio_transcriptions",
"usage_vector_stores",
"usage_code_interpreter_sessions",
+ "usage_web_search_calls",
+ "usage_file_search_calls",
]
_ENTITY_ENDPOINTS = [