: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(data-warehouse): implement amplitude import source (#61667)
Tom Owers70d293f733cd
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.mdindex 5fb2b87ce0bc..0b364fa97af3 100644--- a/posthog/temporal/data_imports/sources/SOURCES.md+++ b/posthog/temporal/data_imports/sources/SOURCES.md@@ -45,6 +45,7 @@ the row lists both.| Source | Comm method | Primary library | Tracked transport || ---------------- | --------------------------- | --------------------------------------------------------------- | --------------------------- || aircall | HTTP | requests | ✅ |+| amplitude | HTTP | requests | ✅ || asana | HTTP | requests | ✅ || ashby | HTTP | requests | ✅ || attio | HTTP | requests + `rest_source.RESTClient` | ✅ |@@ -178,7 +179,6 @@ doesn't conflict with concurrent PRs.- adjust- airtable- amazon_ads-- amplitude- apple_search_ads- appsflyer- auth0diff --git a/posthog/temporal/data_imports/sources/amplitude/amplitude.py b/posthog/temporal/data_imports/sources/amplitude/amplitude.pynew file mode 100644index 000000000000..6a8d52d91351--- /dev/null+++ b/posthog/temporal/data_imports/sources/amplitude/amplitude.py@@ -0,0 +1,310 @@+import gzip+import json+import base64+import zipfile+import tempfile+import dataclasses+from collections.abc import Iterator+from datetime import UTC, datetime, timedelta+from typing import Any, Optional+from urllib.parse import urlencode++import requests+from structlog.types import FilteringBoundLogger+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter++from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from posthog.temporal.data_imports.sources.amplitude.settings import (+ AMPLITUDE_ENDPOINTS,+ AMPLITUDE_HOSTS,+ EVENTS_DEFAULT_LOOKBACK_DAYS,+ EVENTS_EXPORT_LATENCY_HOURS,+ EVENTS_EXPORT_WINDOW_HOURS,+ AmplitudeEndpointConfig,+)+from posthog.temporal.data_imports.sources.common.http import make_tracked_session+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager++REQUEST_TIMEOUT_SECONDS = 600+RETRY_MAX_ATTEMPTS = 5++# Stream export archives to disk rather than buffering the whole compressed body in memory.+# A 24h window can be gigabytes, so we spool to a temporary file that rolls over to disk once+# it exceeds this in-memory threshold, keeping worker memory bounded regardless of export size.+EXPORT_DOWNLOAD_CHUNK_BYTES = 1024 * 1024+EXPORT_SPOOL_MAX_BYTES = 32 * 1024 * 1024++# Amplitude export timestamps are UTC strings formatted as "yyyy-MM-dd HH:mm:ss.SSSSSS"+# (and occasionally without the microsecond component). We normalize them to real datetimes+# so the incremental cursor and partition columns are typed as timestamps in the warehouse.+_AMPLITUDE_TS_FIELDS = (+ "event_time",+ "server_upload_time",+ "server_received_time",+ "client_event_time",+ "client_upload_time",+ "processed_time",+)+_AMPLITUDE_TS_FORMATS = ("%Y-%m-%d %H:%M:%S.%f", "%Y-%m-%d %H:%M:%S")+++class AmplitudeRetryableError(Exception):+ pass+++class AmplitudeResumeConfig:+ # ISO 8601 UTC timestamp marking the start of the next export window to fetch.+ window_start: str+++def _host(region: str) -> str:+ return AMPLITUDE_HOSTS.get(region, AMPLITUDE_HOSTS["us"])+++def _auth_headers(api_key: str, secret_key: str) -> dict[str, str]:+ token = base64.b64encode(f"{api_key}:{secret_key}".encode("ascii")).decode("ascii")+ return {"Authorization": f"Basic {token}", "Accept": "application/json"}+++def _parse_amplitude_ts(value: Any) -> Optional[datetime]:+ if not isinstance(value, str):+ return None+ for fmt in _AMPLITUDE_TS_FORMATS:+ try:+ return datetime.strptime(value, fmt).replace(tzinfo=UTC)+ except ValueError:+ continue+ return None+++def _normalize_event(event: dict[str, Any]) -> dict[str, Any]:+ for ts_field in _AMPLITUDE_TS_FIELDS:+ if ts_field in event:+ parsed = _parse_amplitude_ts(event[ts_field])+ if parsed is not None:+ event[ts_field] = parsed+ return event+++def _coerce_datetime(value: Any) -> Optional[datetime]:+ if isinstance(value, datetime):+ return value if value.tzinfo else value.replace(tzinfo=UTC)+ parsed = _parse_amplitude_ts(value)+ if parsed is not None:+ return parsed+ if isinstance(value, str):+ try:+ dt = datetime.fromisoformat(value)+ return dt if dt.tzinfo else dt.replace(tzinfo=UTC)+ except ValueError:+ return None+ return None+++def _floor_to_hour(dt: datetime) -> datetime:+ return dt.replace(minute=0, second=0, microsecond=0)+++def validate_credentials(api_key: str, secret_key: str, region: str) -> tuple[bool, Optional[str]]:+ # Probe the lightweight annotations endpoint: it returns a small JSON body, uses the same+ # API key + secret key as the Export API, and is available to every project.+ url = f"{_host(region)}/api/2/annotations"+ try:+ response = make_tracked_session().get(url, headers=_auth_headers(api_key, secret_key), timeout=30)+ except Exception as e:+ return False, f"Could not reach Amplitude ({e}). Please check your network and selected region, then retry."++ if response.status_code == 200:+ return True, None+ if response.status_code in (401, 403):+ return (+ False,+ "Amplitude rejected the credentials. Check the API key and secret key (Settings → "+ "Organization settings → Projects in Amplitude) and that the selected region matches your project.",+ )+ return False, f"Unexpected response from Amplitude (status {response.status_code})."+++@retry(+ retry=retry_if_exception_type((AmplitudeRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(RETRY_MAX_ATTEMPTS),+ wait=wait_exponential_jitter(initial=2, max=60),+ reraise=True,+)+def _get(session: requests.Session, url: str, headers: dict[str, str], stream: bool = False) -> requests.Response:+ response = session.get(url, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS, stream=stream)++ if response.status_code == 429 or response.status_code >= 500:+ raise AmplitudeRetryableError(f"Amplitude API error (retryable): status={response.status_code}, url={url}")++ return response+++def _iter_export_window(+ session: requests.Session,+ host: str,+ headers: dict[str, str],+ start_param: str,+ end_param: str,+ logger: FilteringBoundLogger,+) -> Iterator[dict[str, Any]]:+ url = f"{host}/api/2/export?{urlencode({'start': start_param, 'end': end_param})}"+ response = _get(session, url, headers, stream=True)++ # Amplitude returns 404 (not an empty 200) when a window contains no events. That is a+ # normal outcome for sparse windows, not an error — skip the window and continue.+ if response.status_code == 404:+ logger.debug(f"Amplitude: no events for window {start_param}-{end_param}")+ return++ if not response.ok:+ logger.error(f"Amplitude export error: status={response.status_code}, body={response.text[:500]}, url={url}")+ response.raise_for_status()++ # The export response is a zip archive of gzipped JSON-lines files (one event per line).+ # Spool it to a temporary file (in memory up to EXPORT_SPOOL_MAX_BYTES, then on disk) so a+ # large 24h window never has to be held entirely in memory before rows are yielded.+ with tempfile.SpooledTemporaryFile(max_size=EXPORT_SPOOL_MAX_BYTES) as buffer:+ for chunk in response.iter_content(chunk_size=EXPORT_DOWNLOAD_CHUNK_BYTES):+ buffer.write(chunk)+ buffer.seek(0)+ with zipfile.ZipFile(buffer) as archive:+ for entry in archive.namelist():+ with archive.open(entry) as raw, gzip.open(raw) as decompressed:+ for line in decompressed:+ if not line.strip():+ continue+ yield _normalize_event(json.loads(line))+++def _get_events_rows(+ api_key: str,+ secret_key: str,+ region: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[AmplitudeResumeConfig],+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+) -> Iterator[dict[str, Any]]:+ host = _host(region)+ headers = _auth_headers(api_key, secret_key)+ session = make_tracked_session()++ end_boundary = _floor_to_hour(datetime.now(UTC) - timedelta(hours=EVENTS_EXPORT_LATENCY_HOURS))++ last_value = _coerce_datetime(db_incremental_field_last_value) if should_use_incremental_field else None+ if last_value is not None:+ start = _floor_to_hour(last_value)+ else:+ start = _floor_to_hour(end_boundary - timedelta(days=EVENTS_DEFAULT_LOOKBACK_DAYS))++ # A persisted resume cursor takes precedence so a heartbeat-timed-out activity picks up+ # at the window it was processing rather than recomputing from the incremental value.+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ if resume is not None:+ resumed = _coerce_datetime(resume.window_start)+ if resumed is not None:+ start = _floor_to_hour(resumed)+ logger.debug(f"Amplitude: resuming events export from {start.isoformat()}")++ cursor = start+ while cursor <= end_boundary:+ # `end` is inclusive at hour granularity, so a 24h window spans `cursor` .. `cursor + 23h`.+ window_last_hour = min(cursor + timedelta(hours=EVENTS_EXPORT_WINDOW_HOURS - 1), end_boundary)+ start_param = cursor.strftime("%Y%m%dT%H")+ end_param = window_last_hour.strftime("%Y%m%dT%H")++ yield from _iter_export_window(session, host, headers, start_param, end_param, logger)++ cursor = window_last_hour + timedelta(hours=1)+ # Save state after a window is fully yielded. On resume we re-fetch from this window+ # start; merge semantics on `uuid` dedupe any rows seen twice.+ resumable_source_manager.save_state(AmplitudeResumeConfig(window_start=cursor.isoformat()))+++def _get_list_rows(+ api_key: str,+ secret_key: str,+ region: str,+ config: AmplitudeEndpointConfig,+ logger: FilteringBoundLogger,+) -> Iterator[dict[str, Any]]:+ 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()++ 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 = []++ yield from items+++def _get_rows(+ api_key: str,+ secret_key: str,+ region: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[AmplitudeResumeConfig],+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+) -> Iterator[Any]:+ config = AMPLITUDE_ENDPOINTS[endpoint]+ if config.is_export:+ yield from _get_events_rows(+ api_key=api_key,+ secret_key=secret_key,+ region=region,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ )+ else:+ yield from _get_list_rows(api_key, secret_key, region, config, logger)+++def amplitude_source(+ api_key: str,+ secret_key: str,+ region: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[AmplitudeResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ config = AMPLITUDE_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: _get_rows(+ api_key=api_key,+ secret_key=secret_key,+ region=region,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ ),+ primary_keys=config.primary_keys,+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if config.partition_key else None,+ partition_format="week" if config.partition_key else None,+ partition_keys=[config.partition_key] if config.partition_key else None,+ sort_mode="asc",+ )diff --git a/posthog/temporal/data_imports/sources/amplitude/api_inventory.md b/posthog/temporal/data_imports/sources/amplitude/api_inventory.mdnew file mode 100644index 000000000000..6bb4cef7c034--- /dev/null+++ b/posthog/temporal/data_imports/sources/amplitude/api_inventory.md@@ -0,0 +1,49 @@+# Amplitude API inventory++Auth: HTTP Basic with the project **API key** + **secret key** (`base64(api_key:secret_key)`).+Regional hosts: US `https://amplitude.com`, EU `https://analytics.eu.amplitude.com`.++Verified with unauthenticated / bad-credential curls (no live project credentials were available):++- No credentials → `401`.+- Bad credentials → `403` with body `{"error": {..., "metadata": {"details": "Invalid API Key"}}}`.+- Both US and EU hosts reachable; both `401` without auth.++So `401`/`403` are permanent auth failures (wired into `get_non_retryable_errors`).++## Endpoints++### `events` — `/api/2/export`++- Grain: one event. Primary key: `uuid`. Sync mode: incremental (append-only).+- Export API. Returns a **zip of gzipped JSON-lines** archives, not a JSON body.+- `start`/`end` are hour-granular `YYYYMMDDTHH` and filter on **server upload time**.+- ~2h ingestion latency; max 365-day window; max 4GB per response.+- Returns **404 (not an empty 200)** for windows with no events.++### `cohorts` — `/api/3/cohorts`++- Grain: one cohort. Primary key: `id`. Sync mode: full refresh.+- Behavioral Cohorts API. Response wrapped in `{"cohorts": [...]}`.++### `annotations` — `/api/2/annotations`++- Grain: one annotation. Primary key: `id`. Sync mode: full refresh.+- Dashboard REST API. Response wrapped in `{"data": [...]}`.++## Incremental design (events)++The Export API's only server-side filter is the `start`/`end` window on **server upload time**, so+`server_upload_time` is the incremental cursor — an event's `event_time` can be backdated by offline/late+clients, but the window is bounded by when Amplitude received the event. We page forward in 24h windows from+the stored cursor (or a 30-day lookback on first sync) to `now - 2h`, saving the next window start to the+resumable state after each window. Re-fetched windows dedupe on `uuid` via merge semantics. Partitioning uses+the stable `event_time` 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+ key is absent.+- The Export JSON field set (timestamp field names, `uuid` presence) is taken from Amplitude's documented+ export schema. Timestamp normalization tolerates both `%Y-%m-%d %H:%M:%S.%f` and `%Y-%m-%d %H:%M:%S`.diff --git a/posthog/temporal/data_imports/sources/amplitude/settings.py b/posthog/temporal/data_imports/sources/amplitude/settings.pynew file mode 100644index 000000000000..020e03258bfb--- /dev/null+++ b/posthog/temporal/data_imports/sources/amplitude/settings.py@@ -0,0 +1,84 @@+from dataclasses import dataclass, field++from products.data_warehouse.backend.types import IncrementalField, IncrementalFieldType++# Amplitude exposes regional deployments. The project's API key + secret key authenticate+# against a single project that lives in one region, so the host is chosen by the `region`+# form field rather than by a user-supplied URL (no SSRF surface — the set is fixed).+AMPLITUDE_HOSTS: dict[str, str] = {+ "us": "https://amplitude.com",+ "eu": "https://analytics.eu.amplitude.com",+}++# The Export API enforces a ~2 hour ingestion latency (events uploaded in the last couple of+# hours may not be queryable yet) and rejects windows longer than 365 days. We page through+# history one day at a time using the hour-granular `start`/`end` params (YYYYMMDDTHH).+EVENTS_EXPORT_LATENCY_HOURS = 2+EVENTS_EXPORT_WINDOW_HOURS = 24+# Bound the first sync to a recent window so an initial backfill of a high-volume project does+# not attempt to pull years of raw events in one run. Subsequent incremental syncs only fetch+# windows newer than the stored cursor.+EVENTS_DEFAULT_LOOKBACK_DAYS = 30++EVENTS_ENDPOINT = "events"+COHORTS_ENDPOINT = "cohorts"+ANNOTATIONS_ENDPOINT = "annotations"+++@dataclass+class AmplitudeEndpointConfig:+ name: str+ path: str+ primary_keys: list[str]+ # The Export API (events) returns a zip of gzipped JSON archives rather than a JSON body,+ # so it has no data selector. The Dashboard REST endpoints wrap their list in a JSON key.+ is_export: bool = False+ data_selector: str | None = None+ supports_incremental: bool = False+ supports_append: bool = False+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ # Must be a STABLE datetime field (never `updated_at`/`last_seen`) so partitions don't+ # rewrite on every sync.+ partition_key: str | None = None+++AMPLITUDE_ENDPOINTS: dict[str, AmplitudeEndpointConfig] = {+ EVENTS_ENDPOINT: AmplitudeEndpointConfig(+ name=EVENTS_ENDPOINT,+ path="/api/2/export",+ primary_keys=["uuid"],+ is_export=True,+ supports_incremental=True,+ supports_append=True,+ # The Export API filters on server upload time, so that is the only correct cursor —+ # an event's `event_time` can be backdated by offline/late clients, but the window we+ # ask for is bounded by when Amplitude received the event.+ incremental_fields=[+ {+ "label": "server_upload_time",+ "type": IncrementalFieldType.DateTime,+ "field": "server_upload_time",+ "field_type": IncrementalFieldType.DateTime,+ },+ ],+ partition_key="event_time",+ ),+ COHORTS_ENDPOINT: AmplitudeEndpointConfig(+ name=COHORTS_ENDPOINT,+ path="/api/3/cohorts",+ primary_keys=["id"],+ data_selector="cohorts",+ ),+ ANNOTATIONS_ENDPOINT: AmplitudeEndpointConfig(+ name=ANNOTATIONS_ENDPOINT,+ path="/api/2/annotations",+ primary_keys=["id"],+ data_selector="data",+ ),+}++ENDPOINTS = tuple(AMPLITUDE_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in AMPLITUDE_ENDPOINTS.items()+}diff --git a/posthog/temporal/data_imports/sources/amplitude/source.py b/posthog/temporal/data_imports/sources/amplitude/source.pyindex a3afa1328036..060c7d32974c 100644--- a/posthog/temporal/data_imports/sources/amplitude/source.py+++ b/posthog/temporal/data_imports/sources/amplitude/source.py@@ -1,29 +1,145 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+ SourceFieldSelectConfig,+ SourceFieldSelectConfigOption,)-from posthog.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs, SourceResponse+from posthog.temporal.data_imports.sources.amplitude.amplitude import (+ AmplitudeResumeConfig,+ amplitude_source,+ validate_credentials as validate_amplitude_credentials,+)+from posthog.temporal.data_imports.sources.amplitude.settings import AMPLITUDE_ENDPOINTS, EVENTS_ENDPOINT+from posthog.temporal.data_imports.sources.common.base import FieldType, ResumableSourcefrom posthog.temporal.data_imports.sources.common.registry import SourceRegistry+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from posthog.temporal.data_imports.sources.common.schema import SourceSchemafrom posthog.temporal.data_imports.sources.generated_configs import AmplitudeSourceConfigfrom products.data_warehouse.backend.types import ExternalDataSourceType@SourceRegistry.register-class AmplitudeSource(SimpleSource[AmplitudeSourceConfig]):+class AmplitudeSource(ResumableSource[AmplitudeSourceConfig, AmplitudeResumeConfig]):@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.AMPLITUDE+ def get_non_retryable_errors(self) -> dict[str, str | None]:+ message = (+ "Amplitude rejected the credentials. Generate a fresh API key and secret key in Amplitude "+ "(Settings → Organization settings → Projects) and reconnect."+ )+ return {+ "401 Client Error: Unauthorized": message,+ "403 Client Error: Forbidden": message,+ "Invalid API Key": message,+ }++ def get_schemas(+ self,+ config: AmplitudeSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ schemas = [+ SourceSchema(+ name=endpoint.name,+ supports_incremental=endpoint.supports_incremental,+ supports_append=endpoint.supports_append,+ incremental_fields=endpoint.incremental_fields,+ description="Only syncs the last 30 days on initial sync" if endpoint.name == EVENTS_ENDPOINT else None,+ )+ for endpoint in AMPLITUDE_ENDPOINTS.values()+ ]++ if names is not None:+ names_set = set(names)+ schemas = [s for s in schemas if s.name in names_set]++ return schemas++ def validate_credentials(+ self, config: AmplitudeSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ return validate_amplitude_credentials(config.api_key, config.secret_key, config.region)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[AmplitudeResumeConfig]:+ return ResumableSourceManager[AmplitudeResumeConfig](inputs, AmplitudeResumeConfig)++ def source_for_pipeline(+ self,+ config: AmplitudeSourceConfig,+ resumable_source_manager: ResumableSourceManager[AmplitudeResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return amplitude_source(+ api_key=config.api_key,+ secret_key=config.secret_key,+ region=config.region,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=inputs.should_use_incremental_field,+ db_incremental_field_last_value=inputs.db_incremental_field_last_value+ if inputs.should_use_incremental_field+ else None,+ )+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.AMPLITUDE,label="Amplitude",+ caption=(+ "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 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."+ ),+ docsUrl="https://posthog.com/docs/cdp/sources/amplitude",iconPath="/static/services/amplitude.png",- fields=cast(list[FieldType], []),+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ SourceFieldInputConfig(+ name="secret_key",+ label="Secret key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ SourceFieldSelectConfig(+ name="region",+ label="Region",+ required=True,+ defaultValue="us",+ options=[+ SourceFieldSelectConfigOption(label="US (amplitude.com)", value="us"),+ SourceFieldSelectConfigOption(label="EU (analytics.eu.amplitude.com)", value="eu"),+ ],+ ),+ ],+ ),+ releaseStatus=ReleaseStatus.ALPHA,unreleasedSource=True,)diff --git a/posthog/temporal/data_imports/sources/amplitude/tests/test_amplitude.py b/posthog/temporal/data_imports/sources/amplitude/tests/test_amplitude.pynew file mode 100644index 000000000000..ac8d2473db40--- /dev/null+++ b/posthog/temporal/data_imports/sources/amplitude/tests/test_amplitude.py@@ -0,0 +1,379 @@+import io+import gzip+import json+import base64+import zipfile+from datetime import UTC, datetime+from typing import Any++import pytest+from freezegun import freeze_time+from unittest import mock++import requests+from parameterized import parameterized++from posthog.temporal.data_imports.sources.amplitude.amplitude import (+ AmplitudeResumeConfig,+ _auth_headers,+ _coerce_datetime,+ _get_events_rows,+ _get_list_rows,+ _iter_export_window,+ _normalize_event,+ _parse_amplitude_ts,+ amplitude_source,+ validate_credentials,+)+from posthog.temporal.data_imports.sources.amplitude.settings import (+ AMPLITUDE_ENDPOINTS,+ ANNOTATIONS_ENDPOINT,+ COHORTS_ENDPOINT,+ EVENTS_ENDPOINT,+)+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager++MODULE = "posthog.temporal.data_imports.sources.amplitude.amplitude"+++def _make_export_zip(files: list[list[dict[str, Any]]]) -> bytes:+ buf = io.BytesIO()+ with zipfile.ZipFile(buf, "w") as archive:+ for idx, events in enumerate(files):+ gz_buf = io.BytesIO()+ with gzip.GzipFile(fileobj=gz_buf, mode="wb") as gz:+ gz.write("\n".join(json.dumps(event) for event in events).encode())+ archive.writestr(f"part_{idx}.json.gz", gz_buf.getvalue())+ return buf.getvalue()+++def _response(status: int = 200, content: bytes = b"", json_body: Any = None, text: str = "") -> mock.MagicMock:+ response = mock.MagicMock(spec=requests.Response)+ response.status_code = status+ response.ok = 200 <= status < 300+ response.content = content+ response.text = text+ # Export downloads are streamed via iter_content; chunk the body so the spooled-file path is exercised.+ response.iter_content.side_effect = lambda chunk_size=None: iter(+ [+ content[i : i + (chunk_size or len(content) or 1)]+ for i in range(0, len(content), chunk_size or len(content) or 1)+ ]+ )+ if json_body is not None:+ response.json.return_value = json_body+ return response+++class TestParseAmplitudeTimestamp:+ @parameterized.expand(+ [+ ("with_micros", "2026-03-04 02:58:14.123000", datetime(2026, 3, 4, 2, 58, 14, 123000, tzinfo=UTC)),+ ("without_micros", "2026-03-04 02:58:14", datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC)),+ ]+ )+ def test_parses_known_formats(self, _name: str, value: str, expected: datetime) -> None:+ assert _parse_amplitude_ts(value) == expected++ @parameterized.expand([("none", None), ("number", 12345), ("garbage", "not-a-date")])+ def test_returns_none_for_unparseable(self, _name: str, value: Any) -> None:+ assert _parse_amplitude_ts(value) is None+++class TestNormalizeEvent:+ def test_converts_timestamp_fields_to_datetimes(self) -> None:+ event = _normalize_event(+ {+ "uuid": "abc",+ "event_type": "click",+ "event_time": "2026-03-04 02:58:14.000000",+ "server_upload_time": "2026-03-04 02:58:15.000000",+ "amplitude_id": 42,+ }+ )++ assert event["event_time"] == datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC)+ assert event["server_upload_time"] == datetime(2026, 3, 4, 2, 58, 15, tzinfo=UTC)+ # Non-timestamp fields are passed through untouched.+ assert event["uuid"] == "abc"+ assert event["event_type"] == "click"+ assert event["amplitude_id"] == 42++ def test_leaves_unparseable_timestamps_in_place(self) -> None:+ event = _normalize_event({"event_time": ""})+ assert event["event_time"] == ""+++class TestCoerceDatetime:+ def test_passes_through_aware_datetime(self) -> None:+ dt = datetime(2026, 1, 1, tzinfo=UTC)+ assert _coerce_datetime(dt) == dt++ def test_adds_utc_to_naive_datetime(self) -> None:+ assert _coerce_datetime(datetime(2026, 1, 1)) == datetime(2026, 1, 1, tzinfo=UTC)++ def test_parses_iso_string(self) -> None:+ assert _coerce_datetime("2026-01-01T05:00:00+00:00") == datetime(2026, 1, 1, 5, tzinfo=UTC)+++class TestAuthHeaders:+ def test_builds_basic_auth_header(self) -> None:+ headers = _auth_headers("my-key", "my-secret")+ expected = base64.b64encode(b"my-key:my-secret").decode("ascii")+ assert headers["Authorization"] == f"Basic {expected}"+ assert headers["Accept"] == "application/json"+++class TestValidateCredentials:+ @parameterized.expand(+ [+ ("ok", 200, True),+ ("unauthorized", 401, False),+ ("forbidden", 403, False),+ ("server_error", 500, False),+ ]+ )+ def test_status_mapping(self, _name: str, status: int, expected_valid: bool) -> None:+ with mock.patch(f"{MODULE}.make_tracked_session") as make_session:+ make_session.return_value.get.return_value = _response(status=status)+ is_valid, message = validate_credentials("key", "secret", "us")++ assert is_valid is expected_valid+ if expected_valid:+ assert message is None+ else:+ assert message is not None++ def test_network_error_is_not_valid(self) -> None:+ with mock.patch(f"{MODULE}.make_tracked_session") as make_session:+ make_session.return_value.get.side_effect = requests.ConnectionError("boom")+ is_valid, message = validate_credentials("key", "secret", "us")++ assert is_valid is False+ assert message is not None++ def test_uses_eu_host_when_region_is_eu(self) -> None:+ with mock.patch(f"{MODULE}.make_tracked_session") as make_session:+ make_session.return_value.get.return_value = _response(status=200)+ validate_credentials("key", "secret", "eu")++ called_url = make_session.return_value.get.call_args.args[0]+ assert called_url.startswith("https://analytics.eu.amplitude.com")+++class TestIterExportWindow:+ def _session_returning(self, response: mock.MagicMock) -> mock.MagicMock:+ session = mock.MagicMock(spec=requests.Session)+ session.get.return_value = response+ return session++ def test_parses_zipped_gzipped_events(self) -> None:+ zip_bytes = _make_export_zip(+ [+ [{"uuid": "a", "event_time": "2026-01-01 00:00:00.000000"}],+ [{"uuid": "b", "event_time": "2026-01-01 01:00:00.000000"}],+ ]+ )+ session = self._session_returning(_response(status=200, content=zip_bytes))++ rows = list(+ _iter_export_window(session, "https://amplitude.com", {}, "20260101T00", "20260101T23", mock.MagicMock())+ )++ assert [row["uuid"] for row in rows] == ["a", "b"]+ # Timestamps are normalized to datetimes during parsing.+ assert rows[0]["event_time"] == datetime(2026, 1, 1, 0, 0, 0, tzinfo=UTC)++ def test_404_yields_no_rows(self) -> None:+ session = self._session_returning(_response(status=404, text="no data"))+ rows = list(+ _iter_export_window(session, "https://amplitude.com", {}, "20260101T00", "20260101T23", mock.MagicMock())+ )+ assert rows == []++ def test_skips_blank_lines(self) -> None:+ buf = io.BytesIO()+ with zipfile.ZipFile(buf, "w") as archive:+ gz_buf = io.BytesIO()+ with gzip.GzipFile(fileobj=gz_buf, mode="wb") as gz:+ gz.write(b'{"uuid": "a"}\n\n{"uuid": "b"}\n')+ archive.writestr("part.json.gz", gz_buf.getvalue())+ session = self._session_returning(_response(status=200, content=buf.getvalue()))++ rows = list(+ _iter_export_window(session, "https://amplitude.com", {}, "20260101T00", "20260101T23", mock.MagicMock())+ )+ assert [row["uuid"] for row in rows] == ["a", "b"]++ def test_non_ok_status_raises(self) -> None:+ response = _response(status=400, text="bad request")+ # Assign the class (not an instance) so the requests-stubs `response` arg isn't required;+ # the mock raises `HTTPError()` when `raise_for_status` is called.+ response.raise_for_status.side_effect = requests.HTTPError+ session = self._session_returning(response)++ with pytest.raises(requests.HTTPError):+ list(+ _iter_export_window(+ session, "https://amplitude.com", {}, "20260101T00", "20260101T23", mock.MagicMock()+ )+ )+++class TestEventsWindowing:+ @freeze_time("2026-06-04 12:00:00")+ def test_windows_advance_and_state_is_saved_per_window(self) -> None:+ manager = mock.MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ windows: list[tuple[str, str]] = []++ def fake_iter(session, host, headers, start_param, end_param, logger):+ windows.append((start_param, end_param))+ yield {"uuid": f"{start_param}"}++ with mock.patch(f"{MODULE}.make_tracked_session"), mock.patch(f"{MODULE}._iter_export_window", fake_iter):+ rows = list(+ _get_events_rows(+ api_key="key",+ secret_key="secret",+ region="us",+ logger=mock.MagicMock(),+ resumable_source_manager=manager,+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 6, 2, 9, 30, tzinfo=UTC),+ )+ )++ # now=12:00, latency 2h => end boundary floored to 10:00. Cursor floored from last value to 09:00.+ assert windows == [+ ("20260602T09", "20260603T08"),+ ("20260603T09", "20260604T08"),+ ("20260604T09", "20260604T10"),+ ]+ assert len(rows) == 3++ saved = [call.args[0].window_start for call in manager.save_state.call_args_list]+ assert saved == [+ datetime(2026, 6, 3, 9, tzinfo=UTC).isoformat(),+ datetime(2026, 6, 4, 9, tzinfo=UTC).isoformat(),+ datetime(2026, 6, 4, 11, tzinfo=UTC).isoformat(),+ ]++ @freeze_time("2026-06-04 12:00:00")+ def test_resume_state_takes_precedence_over_incremental_value(self) -> None:+ manager = mock.MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = True+ manager.load_state.return_value = AmplitudeResumeConfig(window_start="2026-06-04T09:00:00+00:00")++ windows: list[tuple[str, str]] = []++ def fake_iter(session, host, headers, start_param, end_param, logger):+ windows.append((start_param, end_param))+ return iter(())++ with mock.patch(f"{MODULE}.make_tracked_session"), mock.patch(f"{MODULE}._iter_export_window", fake_iter):+ list(+ _get_events_rows(+ api_key="key",+ secret_key="secret",+ region="us",+ logger=mock.MagicMock(),+ resumable_source_manager=manager,+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 1, 1, tzinfo=UTC),+ )+ )++ manager.load_state.assert_called_once()+ assert windows == [("20260604T09", "20260604T10")]++ @freeze_time("2026-06-04 12:00:00")+ def test_full_refresh_starts_from_lookback_window(self) -> None:+ manager = mock.MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ windows: list[tuple[str, str]] = []++ def fake_iter(session, host, headers, start_param, end_param, logger):+ windows.append((start_param, end_param))+ return iter(())++ with mock.patch(f"{MODULE}.make_tracked_session"), mock.patch(f"{MODULE}._iter_export_window", fake_iter):+ list(+ _get_events_rows(+ api_key="key",+ secret_key="secret",+ region="us",+ logger=mock.MagicMock(),+ resumable_source_manager=manager,+ should_use_incremental_field=False,+ db_incremental_field_last_value=None,+ )+ )++ # 30-day lookback from the 10:00 boundary => first window starts 30 days earlier at 10:00.+ assert windows[0][0] == "20260505T10"+++class TestListRows:+ @parameterized.expand(+ [+ (COHORTS_ENDPOINT, {"cohorts": [{"id": "c1"}, {"id": "c2"}]}, ["c1", "c2"]),+ (ANNOTATIONS_ENDPOINT, {"data": [{"id": 1}]}, [1]),+ (COHORTS_ENDPOINT, {"cohorts": []}, []),+ (COHORTS_ENDPOINT, {"unexpected": []}, []),+ ]+ )+ def test_data_selector_extraction(self, endpoint: str, body: Any, expected_ids: list[Any]) -> None:+ config = AMPLITUDE_ENDPOINTS[endpoint]+ with mock.patch(f"{MODULE}.make_tracked_session") as make_session:+ make_session.return_value.get.return_value = _response(status=200, json_body=body)+ rows = list(_get_list_rows("key", "secret", "us", config, mock.MagicMock()))++ assert [row["id"] for row in rows] == expected_ids++ def test_bare_list_response_is_yielded(self) -> None:+ config = AMPLITUDE_ENDPOINTS[ANNOTATIONS_ENDPOINT]+ with mock.patch(f"{MODULE}.make_tracked_session") as make_session:+ make_session.return_value.get.return_value = _response(status=200, json_body=[{"id": 7}])+ rows = list(_get_list_rows("key", "secret", "us", config, mock.MagicMock()))++ assert [row["id"] for row in rows] == [7]+++class TestAmplitudeSourceResponse:+ def test_events_response_metadata(self) -> None:+ manager = mock.MagicMock(spec=ResumableSourceManager)+ response = amplitude_source(+ api_key="key",+ secret_key="secret",+ region="us",+ endpoint=EVENTS_ENDPOINT,+ logger=mock.MagicMock(),+ resumable_source_manager=manager,+ )++ assert response.name == EVENTS_ENDPOINT+ assert response.primary_keys == ["uuid"]+ assert response.partition_mode == "datetime"+ assert response.partition_keys == ["event_time"]+ assert response.partition_format == "week"+ assert response.sort_mode == "asc"++ @parameterized.expand([(COHORTS_ENDPOINT,), (ANNOTATIONS_ENDPOINT,)])+ def test_list_response_metadata(self, endpoint: str) -> None:+ manager = mock.MagicMock(spec=ResumableSourceManager)+ response = amplitude_source(+ api_key="key",+ secret_key="secret",+ region="us",+ endpoint=endpoint,+ logger=mock.MagicMock(),+ resumable_source_manager=manager,+ )++ assert response.name == endpoint+ assert response.primary_keys == ["id"]+ assert response.partition_mode is None+ assert response.partition_keys is Nonediff --git a/posthog/temporal/data_imports/sources/amplitude/tests/test_amplitude_source.py b/posthog/temporal/data_imports/sources/amplitude/tests/test_amplitude_source.pynew file mode 100644index 000000000000..62510658873b--- /dev/null+++ b/posthog/temporal/data_imports/sources/amplitude/tests/test_amplitude_source.py@@ -0,0 +1,167 @@+from types import SimpleNamespace+from typing import cast++import pytest+from unittest import mock++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType, SourceFieldSelectConfig++from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs+from posthog.temporal.data_imports.sources.amplitude.amplitude import AmplitudeResumeConfig+from posthog.temporal.data_imports.sources.amplitude.settings import (+ ANNOTATIONS_ENDPOINT,+ COHORTS_ENDPOINT,+ ENDPOINTS,+ EVENTS_ENDPOINT,+)+from posthog.temporal.data_imports.sources.amplitude.source import AmplitudeSource+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from posthog.temporal.data_imports.sources.generated_configs import AmplitudeSourceConfig++from products.data_warehouse.backend.types import ExternalDataSourceType++FULL_REFRESH_ENDPOINTS = [COHORTS_ENDPOINT, ANNOTATIONS_ENDPOINT]+++class TestAmplitudeSource:+ def setup_method(self):+ self.source = AmplitudeSource()+ self.team_id = 123+ self.config = AmplitudeSourceConfig(api_key="key", secret_key="secret", region="us")++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.AMPLITUDE++ def test_get_source_config(self):+ config = self.source.get_source_config++ assert config.name.value == "Amplitude"+ assert config.label == "Amplitude"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.unreleasedSource is True+ assert config.iconPath == "/static/services/amplitude.png"+ assert len(config.fields) == 3++ api_key_field = config.fields[0]+ assert isinstance(api_key_field, SourceFieldInputConfig)+ assert api_key_field.name == "api_key"+ assert api_key_field.type == SourceFieldInputConfigType.PASSWORD+ assert api_key_field.required is True+ assert api_key_field.secret is True++ secret_key_field = config.fields[1]+ assert isinstance(secret_key_field, SourceFieldInputConfig)+ assert secret_key_field.name == "secret_key"+ assert secret_key_field.type == SourceFieldInputConfigType.PASSWORD+ assert secret_key_field.secret is True++ region_field = config.fields[2]+ assert isinstance(region_field, SourceFieldSelectConfig)+ assert region_field.name == "region"+ assert region_field.defaultValue == "us"+ assert {option.value for option in region_field.options} == {"us", "eu"}++ @pytest.mark.parametrize(+ "expected_key",+ ["401 Client Error: Unauthorized", "403 Client Error: Forbidden", "Invalid API Key"],+ )+ def test_non_retryable_errors_includes_auth_keys(self, expected_key):+ assert expected_key in self.source.get_non_retryable_errors()++ def test_get_schemas_returns_every_endpoint(self):+ schemas = self.source.get_schemas(self.config, self.team_id)+ assert {schema.name for schema in schemas} == set(ENDPOINTS)++ def test_events_endpoint_advertises_incremental(self):+ schema = next(s for s in self.source.get_schemas(self.config, self.team_id) if s.name == EVENTS_ENDPOINT)+ assert schema.supports_incremental is True+ assert schema.supports_append is True+ assert {field["field"] for field in schema.incremental_fields} == {"server_upload_time"}+ assert schema.description == "Only syncs the last 30 days on initial sync"++ @pytest.mark.parametrize("endpoint", FULL_REFRESH_ENDPOINTS)+ def test_full_refresh_endpoints_do_not_advertise_incremental(self, endpoint):+ schema = next(s for s in self.source.get_schemas(self.config, self.team_id) if s.name == endpoint)+ assert schema.supports_incremental is False+ assert schema.supports_append is False+ assert schema.incremental_fields == []++ def test_get_schemas_filtered_by_names(self):+ schemas = self.source.get_schemas(self.config, self.team_id, names=[EVENTS_ENDPOINT])+ assert len(schemas) == 1+ assert schemas[0].name == EVENTS_ENDPOINT++ def test_get_schemas_filtered_unknown_name_returns_empty(self):+ assert self.source.get_schemas(self.config, self.team_id, names=["nonexistent"]) == []++ @pytest.mark.parametrize(+ "mock_return, expected_valid, expected_message",+ [+ ((True, None), True, None),+ ((False, "Amplitude rejected the credentials."), False, "Amplitude rejected the credentials."),+ ],+ )+ @mock.patch("posthog.temporal.data_imports.sources.amplitude.source.validate_amplitude_credentials")+ def test_validate_credentials(self, mock_validate, mock_return, expected_valid, expected_message):+ mock_validate.return_value = mock_return++ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)++ assert is_valid is expected_valid+ assert error_message == expected_message+ mock_validate.assert_called_once_with(self.config.api_key, self.config.secret_key, self.config.region)++ def test_get_resumable_source_manager_is_bound_to_resume_config(self):+ inputs = mock.MagicMock()+ manager = self.source.get_resumable_source_manager(inputs)++ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is AmplitudeResumeConfig++ @mock.patch("posthog.temporal.data_imports.sources.amplitude.source.amplitude_source")+ def test_source_for_pipeline_plumbs_inputs(self, mock_amplitude_source):+ mock_amplitude_source.return_value = SimpleNamespace(name=EVENTS_ENDPOINT)+ manager = mock.MagicMock(spec=ResumableSourceManager)+ logger = mock.MagicMock()+ inputs = SimpleNamespace(+ schema_name=EVENTS_ENDPOINT,+ team_id=self.team_id,+ job_id="job-1",+ logger=logger,+ should_use_incremental_field=True,+ incremental_field="server_upload_time",+ db_incremental_field_last_value="2026-01-01T00:00:00Z",+ )++ response = self.source.source_for_pipeline(self.config, manager, cast(SourceInputs, inputs))++ mock_amplitude_source.assert_called_once_with(+ api_key="key",+ secret_key="secret",+ region="us",+ endpoint=EVENTS_ENDPOINT,+ logger=logger,+ resumable_source_manager=manager,+ should_use_incremental_field=True,+ db_incremental_field_last_value="2026-01-01T00:00:00Z",+ )+ assert response is mock_amplitude_source.return_value++ @mock.patch("posthog.temporal.data_imports.sources.amplitude.source.amplitude_source")+ def test_source_for_pipeline_drops_last_value_on_full_refresh(self, mock_amplitude_source):+ mock_amplitude_source.return_value = SimpleNamespace(name=COHORTS_ENDPOINT)+ manager = mock.MagicMock(spec=ResumableSourceManager)+ inputs = SimpleNamespace(+ schema_name=COHORTS_ENDPOINT,+ team_id=self.team_id,+ job_id="job-2",+ logger=mock.MagicMock(),+ should_use_incremental_field=False,+ incremental_field=None,+ db_incremental_field_last_value="2026-01-01T00:00:00Z",+ )++ self.source.source_for_pipeline(self.config, manager, cast(SourceInputs, inputs))++ # When the user isn't running incrementally, no watermark should leak through.+ assert mock_amplitude_source.call_args.kwargs["db_incremental_field_last_value"] is Nonediff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.pyindex 4300db23ad8e..341c45f0eb73 100644--- a/posthog/temporal/data_imports/sources/generated_configs.py+++ b/posthog/temporal/data_imports/sources/generated_configs.py@@ -128,7 +128,9 @@ class AmazonAdsSourceConfig(config.Config):@config.configclass AmplitudeSourceConfig(config.Config):- pass+ api_key: str+ secret_key: str+ region: Literal["us", "eu"] = config.value(default="us")@config.config