:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(warehouse_sources): add Amplitude taxonomy tables (#98307)
Tom Owers40184a9290b2
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 9af584b6b8a7..964342428896 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@@ -273,14 +273,14 @@ Note: Static schema list. The Amazon Ads docs site is a Redocly SPA; the real sp## Amplitude — gaps-Today (3): `annotations`, `cohorts`, `events`+Today (7): `annotations`, `cohorts`, `event_categories`, `event_properties`, `event_types`, `events`, `user_properties`Diffed against: <https://amplitude.com/docs/apis>-- [ ] `GET /api/2/taxonomy/event` — event type catalog - the lookup that names and describes the event stream already synced (high)-- [ ] `GET /api/2/taxonomy/event-property` — event property definitions and types, needed to interpret the events table (high)-- [ ] `GET /api/2/taxonomy/user-property` — user property catalog with types and descriptions (high)-- [ ] `GET /api/2/taxonomy/category` — event category lookup resolving the category IDs on event types (medium)+- [x] `GET /api/2/taxonomy/event` — event type catalog - the lookup that names and describes the event stream already synced (high)+- [x] `GET /api/2/taxonomy/event-property` — event property definitions and types, needed to interpret the events table (high)+- [x] `GET /api/2/taxonomy/user-property` — user property catalog with types and descriptions (high)+- [x] `GET /api/2/taxonomy/category` — event category lookup resolving the category IDs on event types (medium)- [ ] `GET /api/2/taxonomy/group-property` — group property catalog for account-level analysis (medium)- [ ] `GET /api/2/release` — release markers to join against event timestamps, the sibling of the annotations table already synced (medium)- [ ] `GET /api/2/audit-logs/{ORG_ID}` — org-level change history for charts, cohorts and permissions (medium)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/amplitude/amplitude.py b/products/warehouse_sources/backend/temporal/data_imports/sources/amplitude/amplitude.pyindex aa9ddb138458..eef82e2802f9 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/amplitude/amplitude.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/amplitude/amplitude.py@@ -223,6 +223,33 @@ def _get_events_rows(resumable_source_manager.save_state(AmplitudeResumeConfig(window_start=cursor.isoformat()))+def _fetch_list(+ session: requests.Session,+ host: str,+ path: str,+ headers: dict[str, str],+ data_selector: str | None,+ name: str,+ logger: FilteringBoundLogger,+ params: Optional[dict[str, str]] = None,+) -> list[Any]:+ url = f"{host}{path}"+ if params:+ url = f"{url}?{urlencode(params)}"++ response = _get(session, url, headers)+ if not response.ok:+ logger.error(f"Amplitude {name} error: status={response.status_code}, body={response.text[:500]}")+ response.raise_for_status()++ body = response.json()+ if data_selector is not None and isinstance(body, dict):+ return body.get(data_selector, [])+ if isinstance(body, list):+ return body+ return []++def _get_list_rows(api_key: str,secret_key: str,@@ -230,25 +257,68 @@ def _get_list_rows(config: AmplitudeEndpointConfig,logger: FilteringBoundLogger,) -> Iterator[dict[str, Any]]:+ session = make_tracked_session()+ yield from _fetch_list(+ session,+ _host(region),+ config.path,+ _auth_headers(api_key, secret_key),+ config.data_selector,+ config.name,+ logger,+ )+++def _get_fanout_rows(+ api_key: str,+ secret_key: str,+ region: str,+ config: AmplitudeEndpointConfig,+ logger: FilteringBoundLogger,+) -> Iterator[dict[str, Any]]:+ fanout = config.fanout+ assert fanout is not None+host = _host(region)headers = _auth_headers(api_key, secret_key)session = make_tracked_session()- url = f"{host}{config.path}"- response = _get(session, url, headers)- if not response.ok:- logger.error(f"Amplitude {config.name} error: status={response.status_code}, body={response.text[:500]}")- response.raise_for_status()+ parents = _fetch_list(session, host, fanout.parent_path, headers, fanout.parent_data_selector, config.name, logger)- body = response.json()- if config.data_selector is not None and isinstance(body, dict):- items = body.get(config.data_selector, [])- elif isinstance(body, list):- items = body- else:- items = []+ for parent in parents:+ if not isinstance(parent, dict):+ continue+ parent_value = parent.get(fanout.join_field)+ if not isinstance(parent_value, str) or not parent_value:+ continue- yield from items+ try:+ rows = _fetch_list(+ session,+ host,+ config.path,+ headers,+ config.data_selector,+ config.name,+ logger,+ params={fanout.join_field: parent_value},+ )+ except requests.HTTPError as e:+ # Amplitude answers 400 "Not found" for an event type deleted between listing the+ # parents and querying it. Skip that parent instead of failing the whole table.+ if e.response is not None and e.response.status_code == 400:+ logger.warning(+ f"Amplitude {config.name}: skipping {fanout.join_field}={parent_value} (Amplitude returned 400)"+ )+ continue+ raise++ for row in rows:+ if not isinstance(row, dict):+ continue+ # Amplitude omits this on shared properties, so set it from the value we queried with.+ row[fanout.join_field] = parent_value+ yield rowdef _get_rows(@@ -272,6 +342,8 @@ def _get_rows(should_use_incremental_field=should_use_incremental_field,db_incremental_field_last_value=db_incremental_field_last_value,)+ elif config.fanout is not None:+ yield from _get_fanout_rows(api_key, secret_key, region, config, logger)else:yield from _get_list_rows(api_key, secret_key, region, config, logger)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/amplitude/api_inventory.md b/products/warehouse_sources/backend/temporal/data_imports/sources/amplitude/api_inventory.mdindex 6bb4cef7c034..f73d7015590d 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/amplitude/api_inventory.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/amplitude/api_inventory.md@@ -31,6 +31,35 @@ So `401`/`403` are permanent auth failures (wired into `get_non_retryable_errors- Grain: one annotation. Primary key: `id`. Sync mode: full refresh.- Dashboard REST API. Response wrapped in `{"data": [...]}`.+### `event_types` — `/api/2/taxonomy/event`++- Grain: one event type in the tracking plan. Primary key: `event_type`. Sync mode: full refresh.+- Taxonomy API. Response wrapped in `{"success": true, "data": [...]}`.+- Hidden events are omitted; deleted ones need `?showDeleted=true`, which we do not pass.++### `event_properties` — `/api/2/taxonomy/event-property`++- Grain: one property definition on one event type. Primary key: `["event_type", "event_property"]`.+ Sync mode: full refresh.+- Only lists properties for a single event type at a time, so the table is built by fanning out over+ `/api/2/taxonomy/event` and querying `?event_type=<name>` per event type. Each child row is stamped+ with the event type we queried, so the composite key is always populated.+- A property name is only unique within its event type, which is why the key is composite.+- Amplitude answers `400` with `"Not found"` for a parent it cannot resolve; those parents are skipped+ with a warning rather than failing the whole table.++### `user_properties` — `/api/2/taxonomy/user-property`++- Grain: one user property definition. Primary key: `user_property`. Sync mode: full refresh.+- Taxonomy API. Response wrapped in `{"success": true, "data": [...]}`.+- Custom group properties appear with a `gp:` prefix.++### `event_categories` — `/api/2/taxonomy/category`++- Grain: one event category. Primary key: `id`. Sync mode: full refresh.+- Taxonomy API. Response wrapped in `{"success": true, "data": [...]}`.+- Resolves the `category` object carried on each event type.+## Incremental design (events)The Export API's only server-side filter is the `start`/`end` window on **server upload time**, so@@ -40,10 +69,19 @@ the stored cursor (or a 30-day lookback on first sync) to `now - 2h`, saving theresumable state after each window. Re-fetched windows dedupe on `uuid` via merge semantics. Partitioning usesthe stable `event_time` field.+## Incremental design (taxonomy)++No Taxonomy endpoint documents a timestamp filter, a cursor, or any pagination parameter — each "get all"+call returns the complete array. So all four taxonomy tables are full refresh, and none advertise an+incremental field.+## Unverified (no credentials to curl)- Exact wrapper keys for `cohorts` (`cohorts`) and `annotations` (`data`) come from the public docs, not a- live 200 response. `_get_list_rows` falls back to treating a bare-list body as the row list if the wrapper+ live 200 response. `_fetch_list` falls back to treating a bare-list body as the row list if the wrapperkey is absent.+- Amplitude's Taxonomy docs show `event_type` sent to `/api/2/taxonomy/event-property` as a urlencoded+ request body on a `GET`, while the single-property examples on the same page use a query string. We send+ it as a query string.- The Export JSON field set (timestamp field names, `uuid` presence) is taken from Amplitude's documentedexport schema. Timestamp normalization tolerates both `%Y-%m-%d %H:%M:%S.%f` and `%Y-%m-%d %H:%M:%S`.diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/amplitude/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/amplitude/canonical_descriptions.pyindex 287b537eb5d2..dbd99ac5cc54 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/amplitude/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/amplitude/canonical_descriptions.py@@ -1,7 +1,8 @@"""Canonical, documentation-sourced descriptions for Amplitude endpoints and columns.Sourced from the official Amplitude HTTP API reference (https://amplitude.com/docs/apis), covering the-Export API (events) and the Dashboard REST APIs (cohorts, annotations). Keyed by the endpoint names in+Export API (events), the Dashboard REST APIs (cohorts, annotations), and the Taxonomy API (event types,+event properties, user properties, event categories). Keyed by the endpoint names in`settings.py` `AMPLITUDE_ENDPOINTS`, which match the `ExternalDataSchema.name` of a synced Amplitudetable. Columns absent here fall back to LLM enrichment."""@@ -63,4 +64,60 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"details": "Longer description of the annotation.",},},+ "event_types": {+ "description": "An event type in the project's tracking plan, naming and describing one kind of tracked event.",+ "docs_url": "https://amplitude.com/docs/apis/analytics/taxonomy",+ "columns": {+ "event_type": "Name of the event as sent by your instrumentation — joins to `event_type` on the events table.",+ "display_name": "Human-readable name shown for the event in the Amplitude UI.",+ "description": "Description of what the event means, from the tracking plan.",+ "category": "Event category the event belongs to, as an object carrying the category name.",+ "is_active": "Whether the event is active in the tracking plan.",+ "is_hidden_from_dropdowns": "Whether the event is hidden from event pickers in the Amplitude UI.",+ "is_hidden_from_persona_results": "Whether the event is excluded from persona results.",+ "is_hidden_from_pathfinder": "Whether the event is excluded from Pathfinder charts.",+ "is_hidden_from_timeline": "Whether the event is excluded from the user timeline.",+ "tags": "Tags applied to the event in the tracking plan.",+ "owner": "User who owns the event definition.",+ },+ },+ "event_properties": {+ "description": "An event property definition from the tracking plan, describing one property carried by an event type.",+ "docs_url": "https://amplitude.com/docs/apis/analytics/taxonomy",+ "columns": {+ "event_type": "Event type the property belongs to — joins to `event_type` on the event_types and events tables.",+ "event_property": "Name of the property as it appears inside the event's `event_properties`.",+ "description": "Description of what the property means, from the tracking plan.",+ "type": "Declared value type of the property (for example string, number, boolean, enum).",+ "regex": "Regular expression the property value must match, if one is set.",+ "enum_values": "Allowed values when the property is declared as an enum.",+ "is_array_type": "Whether the property holds an array of values.",+ "is_required": "Whether the tracking plan requires the property on this event.",+ "is_hidden": "Whether the property is hidden from pickers in the Amplitude UI.",+ "classifications": "Data classification labels applied to the property.",+ },+ },+ "user_properties": {+ "description": "A user property definition from the tracking plan, describing one property carried on users.",+ "docs_url": "https://amplitude.com/docs/apis/analytics/taxonomy",+ "columns": {+ "user_property": "Name of the property as it appears inside an event's `user_properties`. Custom group properties carry a `gp:` prefix.",+ "description": "Description of what the property means, from the tracking plan.",+ "type": "Declared value type of the property (for example string, number, boolean, enum).",+ "regex": "Regular expression the property value must match, if one is set.",+ "enum_values": "Allowed values when the property is declared as an enum.",+ "is_array_type": "Whether the property holds an array of values.",+ "is_hidden": "Whether the property is hidden from pickers in the Amplitude UI.",+ "classifications": "Data classification labels applied to the property.",+ "deleted": "Whether the property has been deleted from the tracking plan.",+ },+ },+ "event_categories": {+ "description": "An event category in the tracking plan, used to group event types.",+ "docs_url": "https://amplitude.com/docs/apis/analytics/taxonomy",+ "columns": {+ "id": "Unique identifier for the category.",+ "name": "Name of the category — matches the category name carried on event types.",+ },+ },}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/amplitude/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/amplitude/settings.pyindex e6f7fc6d3974..a91a2ec00e9b 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/amplitude/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/amplitude/settings.py@@ -1,4 +1,6 @@-from dataclasses import dataclass, field+from dataclasses import field++from posthog.dataclasses import frozenfrom products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType@@ -23,9 +25,23 @@ EVENTS_DEFAULT_LOOKBACK_DAYS = 30EVENTS_ENDPOINT = "events"COHORTS_ENDPOINT = "cohorts"ANNOTATIONS_ENDPOINT = "annotations"+EVENT_TYPES_ENDPOINT = "event_types"+EVENT_PROPERTIES_ENDPOINT = "event_properties"+USER_PROPERTIES_ENDPOINT = "user_properties"+EVENT_CATEGORIES_ENDPOINT = "event_categories"++TAXONOMY_EVENT_PATH = "/api/2/taxonomy/event"+++@frozen+class AmplitudeFanoutConfig:+ parent_path: str+ parent_data_selector: str+ # Stamped onto every child row, so the composite primary key is never half null.+ join_field: str-@dataclass+@frozenclass AmplitudeEndpointConfig:name: strpath: str@@ -40,6 +56,8 @@ class AmplitudeEndpointConfig:# Must be a STABLE datetime field (never `updated_at`/`last_seen`) so partitions don't# rewrite on every sync.partition_key: str | None = None+ # Set when the endpoint only lists rows for one parent at a time.+ fanout: AmplitudeFanoutConfig | None = NoneAMPLITUDE_ENDPOINTS: dict[str, AmplitudeEndpointConfig] = {@@ -75,6 +93,37 @@ AMPLITUDE_ENDPOINTS: dict[str, AmplitudeEndpointConfig] = {primary_keys=["id"],data_selector="data",),+ # Taxonomy API lookups. None expose a timestamp filter or a cursor, so all are full refresh.+ EVENT_TYPES_ENDPOINT: AmplitudeEndpointConfig(+ name=EVENT_TYPES_ENDPOINT,+ path=TAXONOMY_EVENT_PATH,+ primary_keys=["event_type"],+ data_selector="data",+ ),+ EVENT_PROPERTIES_ENDPOINT: AmplitudeEndpointConfig(+ name=EVENT_PROPERTIES_ENDPOINT,+ path="/api/2/taxonomy/event-property",+ # A property name is only unique within its event type, so the event type is part of the key.+ primary_keys=["event_type", "event_property"],+ data_selector="data",+ fanout=AmplitudeFanoutConfig(+ parent_path=TAXONOMY_EVENT_PATH,+ parent_data_selector="data",+ join_field="event_type",+ ),+ ),+ USER_PROPERTIES_ENDPOINT: AmplitudeEndpointConfig(+ name=USER_PROPERTIES_ENDPOINT,+ path="/api/2/taxonomy/user-property",+ primary_keys=["user_property"],+ data_selector="data",+ ),+ EVENT_CATEGORIES_ENDPOINT: AmplitudeEndpointConfig(+ name=EVENT_CATEGORIES_ENDPOINT,+ path="/api/2/taxonomy/category",+ primary_keys=["id"],+ data_selector="data",+ ),}ENDPOINTS = tuple(AMPLITUDE_ENDPOINTS.keys())diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/amplitude/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/amplitude/source.pyindex 3f927b9cf0db..1a8546f80382 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/amplitude/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/amplitude/source.py@@ -128,7 +128,7 @@ class AmplitudeSource(ResumableSource[AmplitudeSourceConfig, AmplitudeResumeConfcaption=("Connect Amplitude with your project's **API key** and **secret key**, found in Amplitude under ""**Settings → Organization settings → Projects**. These authenticate the Export API (raw events), "- "the Cohorts API, and the Annotations API.\n\n"+ "the Cohorts API, the Annotations API, and the Taxonomy API (event and property definitions).\n\n""The events stream uses Amplitude's Export API, which enforces a ~2 hour data latency and only ""syncs the last 30 days on the initial sync."),diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/amplitude/tests/test_amplitude.py b/products/warehouse_sources/backend/temporal/data_imports/sources/amplitude/tests/test_amplitude.pyindex f2c6304a0ea3..ab7edb550da4 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/amplitude/tests/test_amplitude.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/amplitude/tests/test_amplitude.py@@ -18,6 +18,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.amplitude._auth_headers,_coerce_datetime,_get_events_rows,+ _get_fanout_rows,_get_list_rows,_iter_export_window,_normalize_event,@@ -29,6 +30,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.amplitude.AMPLITUDE_ENDPOINTS,ANNOTATIONS_ENDPOINT,COHORTS_ENDPOINT,+ EVENT_PROPERTIES_ENDPOINT,EVENTS_ENDPOINT,)from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager@@ -342,6 +344,71 @@ class TestListRows:assert [row["id"] for row in rows] == [7]+class TestFanoutRows:+ config = AMPLITUDE_ENDPOINTS[EVENT_PROPERTIES_ENDPOINT]++ def _run(self, responses: list[mock.MagicMock]) -> tuple[list[dict[str, Any]], list[str]]:+ urls: list[str] = []++ def get(url: str, **kwargs: Any) -> mock.MagicMock:+ urls.append(url)+ return responses[len(urls) - 1]++ with mock.patch(f"{MODULE}.make_tracked_session") as make_session:+ make_session.return_value.get.side_effect = get+ rows = list(_get_fanout_rows("key", "secret", "us", self.config, mock.MagicMock()))++ return rows, urls++ def test_queries_each_event_type_and_stamps_it_onto_child_rows(self) -> None:+ parents = _response(+ status=200,+ json_body={+ "success": True,+ "data": [+ {"event_type": "Play Song"},+ {"event_type": "Onboard Start"},+ # A parent with no usable name must not be queried.+ {"category": {"name": "Attribution"}},+ ],+ },+ )+ # Amplitude omits `event_type` on shared properties, so the fan-out has to supply it.+ song_props = _response(status=200, json_body={"success": True, "data": [{"event_property": "genre"}]})+ onboard_props = _response(status=200, json_body={"success": True, "data": [{"event_property": "step"}]})++ rows, urls = self._run([parents, song_props, onboard_props])++ assert [(row["event_type"], row["event_property"]) for row in rows] == [+ ("Play Song", "genre"),+ ("Onboard Start", "step"),+ ]+ assert len(urls) == 3+ assert urls[0].endswith("/api/2/taxonomy/event")+ assert "/api/2/taxonomy/event-property?event_type=Play+Song" in urls[1]+ assert "/api/2/taxonomy/event-property?event_type=Onboard+Start" in urls[2]++ def test_400_on_one_event_type_skips_it_and_keeps_going(self) -> None:+ parents = _response(+ status=200, json_body={"data": [{"event_type": "Deleted Event"}, {"event_type": "Play Song"}]}+ )+ not_found = _response(status=400, text='{"success": false, "errors": [{"message": "Not found"}]}')+ not_found.raise_for_status.side_effect = requests.HTTPError(response=not_found)+ song_props = _response(status=200, json_body={"data": [{"event_property": "genre"}]})++ rows, _urls = self._run([parents, not_found, song_props])++ assert [row["event_type"] for row in rows] == ["Play Song"]++ def test_other_http_errors_propagate(self) -> None:+ parents = _response(status=200, json_body={"data": [{"event_type": "Play Song"}]})+ forbidden = _response(status=403, text="Forbidden")+ forbidden.raise_for_status.side_effect = requests.HTTPError(response=forbidden)++ with pytest.raises(requests.HTTPError):+ self._run([parents, forbidden])++class TestAmplitudeSourceResponse:def test_events_response_metadata(self) -> None:manager = mock.MagicMock(spec=ResumableSourceManager)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/amplitude/tests/test_amplitude_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/amplitude/tests/test_amplitude_source.pyindex 94b938dbc1a3..ab0994d2d13d 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/amplitude/tests/test_amplitude_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/amplitude/tests/test_amplitude_source.py@@ -8,7 +8,11 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.amplitude.ANNOTATIONS_ENDPOINT,COHORTS_ENDPOINT,ENDPOINTS,+ EVENT_CATEGORIES_ENDPOINT,+ EVENT_PROPERTIES_ENDPOINT,+ EVENT_TYPES_ENDPOINT,EVENTS_ENDPOINT,+ USER_PROPERTIES_ENDPOINT,)from products.warehouse_sources.backend.temporal.data_imports.sources.amplitude.source import AmplitudeSourcefrom products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager@@ -17,7 +21,14 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_AmplitudeSourceConfig,)-FULL_REFRESH_ENDPOINTS = [COHORTS_ENDPOINT, ANNOTATIONS_ENDPOINT]+FULL_REFRESH_ENDPOINTS = [+ COHORTS_ENDPOINT,+ ANNOTATIONS_ENDPOINT,+ EVENT_TYPES_ENDPOINT,+ EVENT_PROPERTIES_ENDPOINT,+ USER_PROPERTIES_ENDPOINT,+ EVENT_CATEGORIES_ENDPOINT,+]class TestAmplitudeSource: