:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(data-warehouse): drop unsyncable anthropic service_accounts table (#82595)
posthog[bot]473523fba187
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.mdindex 4bcdcc79ee5d..62c27c8f6c17 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,7 +294,7 @@ Note: Endpoint paths confirmed by reading https://amplitude.com/docs/apis/analyt## Anthropic — gaps-Today (10): `api_keys`, `claude_code_analytics`, `claude_code_model_breakdown`, `cost_report`, `invites`, `service_accounts`, `usage_report`, `users`, `workspace_members`, `workspaces`+Today (9): `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>@@ -305,7 +305,7 @@ Diffed against: <https://platform.claude.com/llms.txt>- [ ] `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)-- [ ] `GET /v1/organizations/service_accounts/{id}/workspaces and /workspaces/{id}/service_accounts` — service-account-to-workspace membership join for the service_accounts already synced (medium)+- ~~`GET /v1/organizations/service_accounts/{id}/workspaces and /workspaces/{id}/service_accounts`~~ — not reachable: Anthropic serves the service-account endpoints only to an `org:admin` OAuth token, which this source never holds- [ ] `GET /v1/organizations/analytics/connectors, /plugins, /skills` — adoption breakdown by connector, plugin and skill (medium)- [ ] `GET /v1/messages/batches` — batch job history with request counts and status, for batch spend analysis (medium)- [ ] `GET /v1/organizations/analytics/chat_projects and /analytics/artifacts` — Claude project and artifact usage breakdown (low)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/anthropic/anthropic.py b/products/warehouse_sources/backend/temporal/data_imports/sources/anthropic/anthropic.pyindex dea02ea91e8d..23540476bf1f 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@@ -12,6 +12,7 @@ from posthog.dataclasses import frozenfrom products.warehouse_sources.backend.temporal.data_imports.sources.anthropic.settings import (ANTHROPIC_ENDPOINTS,+ ENDPOINT_RETIRED_ERROR,USAGE_GROUP_BY_FALLBACKS,PaginationType,)@@ -498,7 +499,12 @@ def anthropic_source(resumable_source_manager: ResumableSourceManager[AnthropicResumeConfig],db_incremental_field_last_value: Optional[Any] = None,) -> SourceResponse:- config = ANTHROPIC_ENDPOINTS[endpoint]+ config = ANTHROPIC_ENDPOINTS.get(endpoint)+ if config is None:+ # A schema row outlives the catalog entry it was discovered from when an endpoint is+ # dropped. Raise the message `get_non_retryable_errors` keys on, so the run disables the+ # schema and pauses its schedule instead of retrying a KeyError forever.+ raise ValueError(f"{ENDPOINT_RETIRED_ERROR}: {endpoint}")# Set only where the rows come from something other than iterating `resource` once.items: Optional[Callable[[], Iterator[list[dict[str, Any]]]]] = Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/anthropic/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/anthropic/canonical_descriptions.pyindex 8d5b21a2f8ea..e94fe6f28cbb 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@@ -109,17 +109,6 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"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",diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/anthropic/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/anthropic/settings.pyindex 29c70689fabe..35a84a88c472 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,7 +1,9 @@-from dataclasses import dataclass, field+from dataclasses import fieldfrom enum import Enumfrom typing import Optional+from posthog.dataclasses import frozen+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType@@ -23,7 +25,7 @@ def _datetime_incremental_field(name: str) -> IncrementalField:}-@dataclass+@frozenclass AnthropicEndpointConfig:name: strpath: str@@ -47,8 +49,7 @@ 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 / service_accounts have no org-wide list endpoint; they fan out one request- # per workspace.+ # workspace_members has no org-wide list endpoint, so it fans 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.@@ -140,16 +141,9 @@ 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,- ),+ # No service_accounts endpoint: Anthropic serves service accounts only to an org:admin OAuth+ # token and rejects the Admin API key this source authenticates with, so the table can never+ # sync. `service_account_id` still resolves as a usage_report group_by dimension below."usage_report": AnthropicEndpointConfig(name="usage_report",path="/v1/organizations/usage_report/messages",@@ -213,6 +207,10 @@ ANTHROPIC_ENDPOINTS: dict[str, AnthropicEndpointConfig] = {ENDPOINTS = tuple(ANTHROPIC_ENDPOINTS.keys())+# Raised when a schema row names an endpoint the catalog no longer has, and matched by+# `get_non_retryable_errors` so the sync retires the row rather than retrying.+ENDPOINT_RETIRED_ERROR = "Table no longer available from Anthropic"+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.pyindex 77aee55d71f6..9d1fc34d6e27 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@@ -16,6 +16,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.anthropic.)from products.warehouse_sources.backend.temporal.data_imports.sources.anthropic.settings import (ANTHROPIC_ENDPOINTS,+ ENDPOINT_RETIRED_ERROR,ENDPOINTS,INCREMENTAL_FIELDS,)@@ -83,6 +84,7 @@ Create an Admin API key (prefixed `sk-ant-admin...`) in your [Anthropic Console]return {"401 Client Error: Unauthorized for url: https://api.anthropic.com": "Your Anthropic Admin API key is invalid or has been revoked. Create a new Admin API key in the Anthropic Console, then reconnect.","403 Client Error: Forbidden for url: https://api.anthropic.com": "Your Anthropic API key does not have organization admin access. Use an Admin API key (prefixed sk-ant-admin) created by an organization admin, then reconnect.",+ 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.",}def get_schemas(diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/anthropic/tests/test_anthropic.py b/products/warehouse_sources/backend/temporal/data_imports/sources/anthropic/tests/test_anthropic.pyindex ef4ba6b95024..d0f611938fb0 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@@ -32,6 +32,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.anthropic.USAGE_REPORT_PAGE_BUCKETS,)from products.warehouse_sources.backend.temporal.data_imports.sources.anthropic.source import AnthropicSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import error_message_matches# RESTClient builds its session via make_tracked_session in the rest_client module.CLIENT_SESSION_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"@@ -512,13 +513,13 @@ class TestWorkspaceMembersFanOut:[_entity_page([{"id": "wrkspc_1"}, {"id": "wrkspc_2"}], has_more=False, last_id="wrkspc_2"),_response({"error": "not_found"}, status=404),- _entity_page([{"id": "sa_2", "workspace_id": "wrkspc_2"}], has_more=False, last_id="sa_2"),+ _entity_page([{"user_id": "u2", "workspace_id": "wrkspc_2"}], has_more=False, last_id="u2"),],)- rows = _rows(_source("service_accounts", _make_manager()))+ rows = _rows(_source("workspace_members", _make_manager()))- assert [(r["workspace_id"], r["id"]) for r in rows] == [("wrkspc_2", "sa_2")]+ assert [(r["workspace_id"], r["user_id"]) for r in rows] == [("wrkspc_2", "u2")]def test_saved_state_shapes_still_parse(self) -> None:# ResumableSourceManager._load_json does dataclass(**saved) — every historical shape must@@ -926,19 +927,11 @@ class TestClaudeCodeDayFanOut: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")]+class TestRetiredEndpoint:+ def test_a_dropped_endpoint_fails_non_retryably(self) -> None:+ # A schema row discovered before an endpoint was dropped still names it, and its schedule+ # keeps firing. The run must fail with a message the source classifies as non-retryable, so+ # it disables the schema and pauses the schedule instead of retrying a KeyError forever.+ with pytest.raises(ValueError) as exc:+ _source("service_accounts", _make_manager())+ assert error_message_matches(str(exc.value), AnthropicSource().get_non_retryable_errors().keys())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.pyindex 0016cea0ca2e..2ccc3e205124 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@@ -2,6 +2,7 @@ from unittest.mock import MagicMockfrom parameterized import parameterized+from products.warehouse_sources.backend.temporal.data_imports.sources.anthropic.settings import ANTHROPIC_ENDPOINTSfrom products.warehouse_sources.backend.temporal.data_imports.sources.anthropic.source import AnthropicSource@@ -14,7 +15,6 @@ class TestAnthropicSchemas:"workspaces","api_keys","workspace_members",- "service_accounts","usage_report","cost_report","claude_code_analytics",@@ -39,9 +39,7 @@ class TestAnthropicSchemas: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",)]- )+ @parameterized.expand([("users",), ("workspaces",), ("api_keys",), ("workspace_members",), ("invites",)])def test_entity_endpoints_are_full_refresh_only(self, endpoint: str) -> None:# No updated-since filter exists on the entity lists, so they must not advertise incremental.schema = next(s for s in AnthropicSource().get_schemas(MagicMock(), team_id=1) if s.name == endpoint)@@ -52,6 +50,17 @@ class TestAnthropicSchemas:schemas = AnthropicSource().get_schemas(MagicMock(), team_id=1, names=["usage_report"])assert [s.name for s in schemas] == ["usage_report"]+ def test_no_endpoint_targets_an_admin_key_forbidden_path(self) -> None:+ # This source authenticates with an Admin API key, which Anthropic does not accept on its+ # service-account or federation endpoints (those require an org:admin OAuth token). An+ # endpoint targeting one of those paths would fail every sync, so the catalog must exclude it.+ offenders = [+ name+ for name, config in ANTHROPIC_ENDPOINTS.items()+ if "service_accounts" in config.path or "/federation" in config.path+ ]+ assert offenders == []+class TestAnthropicSourceForPipeline:def _response(self, endpoint: str) -> object:@@ -69,7 +78,6 @@ 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"),]