: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 snowplow import source (#71211)
Tom Owers065468045dda
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 1a4ddfbf25aa..0fbcb70cb57e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -439,6 +439,7 @@ the row lists both.| smartwaiver | HTTP | requests | ✅ || snapchat_ads | HTTP | requests + `rest_source.RESTClient` | ✅ || snowflake | DB protocol | snowflake-connector-python | ➖ |+| snowplow | HTTP | requests | ✅ || solarwinds_service_desk | HTTP | requests | ✅ || sparkpost | HTTP | requests | ✅ || split_io | HTTP | requests | ✅ |@@ -902,7 +903,6 @@ doesn't conflict with concurrent PRs.- smaily- smartengage- smartwaiver-- snowplow- snyk- solarwinds_service_desk- sonar_clouddiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.pyindex 257ddbf2270e..998b71c6a87f 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py@@ -3953,7 +3953,9 @@ class SnowflakeSourceConfig(config.Config):@config.configclass SnowplowSourceConfig(config.Config):- pass+ organization_id: str+ api_key_id: str+ api_key: str@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/snowplow/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/snowplow/canonical_descriptions.pynew file mode 100644index 000000000000..b4b3ee5fe395--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/snowplow/canonical_descriptions.py@@ -0,0 +1,101 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++# Sourced from the Snowplow BDP Console API OpenAPI spec+# (https://console.snowplowanalytics.com/api/msc/v1/docs/docs.yaml).+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "pipelines": {+ "description": "The Snowplow pipelines in your organization.",+ "docs_url": "https://docs.snowplow.io/docs/using-the-snowplow-console/managing-console-api-authentication/",+ "columns": {+ "id": "UUID of the pipeline.",+ "name": "Name of the pipeline.",+ "status": "Deployment status of the pipeline stack.",+ "label": "Pipeline label (e.g. production, sandbox).",+ "workspaceId": "UUID of the workspace the pipeline belongs to.",+ },+ },+ "users": {+ "description": "Users of your Snowplow BDP Console organization.",+ "docs_url": "https://docs.snowplow.io/docs/using-the-snowplow-console/managing-users/",+ "columns": {+ "id": "UUID of the user.",+ "email": "Email address of the user.",+ "organizationId": "UUID of the organization the user belongs to.",+ "firstName": "First name of the user.",+ "lastName": "Last name of the user.",+ "jobTitle": "Job title of the user.",+ "lastLogin": "When the user last logged in to the Console.",+ "permissions": "Permission sets granted to the user, as capability objects.",+ },+ },+ "data_models": {+ "description": "Data models (dbt or SQL Runner) configured to run against your warehouse.",+ "docs_url": "https://docs.snowplow.io/docs/modeling-your-data/running-data-models-via-snowplow-bdp/",+ "columns": {+ "name": "Name of the data model.",+ "description": "Description of the data model.",+ "status": "Whether the data model is enabled or disabled.",+ "owners": "Email addresses of the model's owners.",+ "schedules": "Cron schedules the model runs on.",+ "runner": "The runner executing the model (dbt or sql-runner).",+ "runnerVersion": "Version of the runner.",+ "changeLog": "History of changes made to the model configuration.",+ },+ },+ "data_structures": {+ "description": "Data structures (event and entity schemas) registered in your organization, with the most recent deployment per environment.",+ "docs_url": "https://docs.snowplow.io/docs/understanding-tracking-design/managing-your-data-structures/api/",+ "columns": {+ "hash": "Stable hash identifying the data structure.",+ "organizationId": "UUID of the organization the data structure belongs to.",+ "vendor": "Vendor of the schema (e.g. com.acme).",+ "name": "Name of the schema.",+ "format": "Schema format (e.g. jsonschema).",+ "deployments": "Most recent deployment of the schema per environment.",+ },+ },+ "job_runs": {+ "description": "Executions of data modeling jobs. Snowplow retains only about the preceding week of run history.",+ "docs_url": "https://docs.snowplow.io/docs/modeling-your-data/running-data-models-via-snowplow-bdp/retrieving-job-execution-data-via-the-api/",+ "columns": {+ "runId": "Unique identifier of the job run.",+ "jobId": "Identifier of the job this run belongs to.",+ "jobName": "Name of the job (e.g. the data model name).",+ "environment": "Environment the job ran against.",+ "state": "Run state: FAILED, RUNNING, SKIPPED, SUCCEEDED, or WAITING.",+ "startTime": "When the run started.",+ "duration": "Duration of the run (ISO 8601 duration).",+ "failureReason": "Reason the run failed, when it did.",+ },+ },+ "job_run_steps": {+ "description": "Per-step execution detail for each data modeling job run, one row per (run, step).",+ "docs_url": "https://docs.snowplow.io/docs/modeling-your-data/running-data-models-via-snowplow-bdp/retrieving-job-execution-data-via-the-api/",+ "columns": {+ "runId": "Identifier of the job run the step belongs to.",+ "name": "Name of the step.",+ "state": "Step state: FAILED, RUNNING, SKIPPED, SUCCEEDED, SUCCEEDED_NO_OP, or WAITING.",+ "dependencies": "Names of the steps this step depends on.",+ "duration": "Duration of the step (ISO 8601 duration).",+ "jobId": "Identifier of the job the parent run belongs to.",+ "jobName": "Name of the job the parent run belongs to.",+ "environment": "Environment the parent run ran against.",+ "runStartTime": "When the parent run started.",+ },+ },+ "failed_event_metrics": {+ "description": "Failed-event counts per pipeline, error, and time bucket, for monitoring data quality.",+ "docs_url": "https://docs.snowplow.io/docs/managing-data-quality/monitoring-failed-events/",+ "columns": {+ "pipelineId": "UUID of the pipeline the failed events occurred on.",+ "errorId": "Identifier of the failed-event error.",+ "schemaKey": "Schema of the events that failed.",+ "classification": "Failure classification: Enrichment or Validation.",+ "window": "Start of the time bucket the count applies to.",+ "count": "Number of failed events in the bucket.",+ "lastSeen": "When a failed event for this error was last seen in the bucket.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/snowplow/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/snowplow/settings.pynew file mode 100644index 000000000000..4a8d68ef0316--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/snowplow/settings.py@@ -0,0 +1,119 @@+from dataclasses import dataclass, field+from typing import Optional++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType+++@dataclass+class SnowplowEndpointConfig:+ name: str+ path: str+ # Primary key columns for the merge upsert. Fan-out endpoints aggregate rows from every+ # parent (job run / pipeline), so their keys include the parent identifier to stay unique+ # table-wide — a bare step `name` or metric `window` would collide across parents.+ primary_keys: list[str]+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ # Stable field to partition by (a run's start time / a metric bucket never changes).+ partition_key: Optional[str] = None+ # Key of the wrapping object holding the row list ({"pipelines": [...]}); None for bare arrays.+ data_key: Optional[str] = None+ # When True the endpoint is queried with a from/to time window sliced into bounded chunks+ # (the jobs API caps a window at 96 hours and only retains about the last week of runs).+ windowed: bool = False+ # When True the endpoint is called once per job run discovered in the time window.+ fan_out_over_runs: bool = False+ # When True the endpoint is called once per pipeline discovered via GET /pipelines/v1.+ fan_out_over_pipelines: bool = False+ # Whether the table is selected for sync by default in the schema picker.+ should_sync_default: bool = True+++# Endpoint catalog. Snowplow's BDP Console API lives at console.snowplowanalytics.com/api/msc/v1+# and is authenticated with a short-lived JWT minted from an API key + key ID+# (GET /organizations/{orgId}/credentials/v3/token, then `Authorization: Bearer`).+#+# Only the time-windowed endpoints are synced incrementally: GET /jobs/v1/runs requires a from/to+# window (a genuine server-side filter), and the failed-events metrics endpoint accepts the same+# window params. Snowplow retains job runs for only about the preceding week and caps a query+# window at 96 hours with at most 10,000 rows, so incremental sync advances a rolling window+# rather than backfilling deep history. The remaining endpoints are small current-state catalogs+# with no server-side timestamp filter, so they ship as full refresh.+SNOWPLOW_ENDPOINTS: dict[str, SnowplowEndpointConfig] = {+ "pipelines": SnowplowEndpointConfig(+ name="pipelines",+ path="/pipelines/v1",+ primary_keys=["id"],+ data_key="pipelines",+ ),+ "users": SnowplowEndpointConfig(+ name="users",+ path="/users",+ primary_keys=["id"],+ ),+ "data_models": SnowplowEndpointConfig(+ name="data_models",+ path="/data-models/v1/models",+ # Data models have no id; GET /data-models/v1/models/{modelName} addresses them by name.+ primary_keys=["name"],+ ),+ "data_structures": SnowplowEndpointConfig(+ name="data_structures",+ path="/data-structures/v1",+ primary_keys=["hash"],+ ),+ "job_runs": SnowplowEndpointConfig(+ name="job_runs",+ path="/jobs/v1/runs",+ primary_keys=["runId"],+ partition_key="startTime",+ windowed=True,+ incremental_fields=[+ {+ "label": "startTime",+ "type": IncrementalFieldType.DateTime,+ "field": "startTime",+ "field_type": IncrementalFieldType.DateTime,+ },+ ],+ ),+ "job_run_steps": SnowplowEndpointConfig(+ name="job_run_steps",+ path="/jobs/v1/runs/{runId}/steps",+ # Step names are unique only within a run, so the injected runId keeps the key unique+ # table-wide across the fan-out.+ primary_keys=["runId", "name"],+ partition_key="runStartTime",+ windowed=True,+ fan_out_over_runs=True,+ incremental_fields=[+ {+ "label": "runStartTime",+ "type": IncrementalFieldType.DateTime,+ "field": "runStartTime",+ "field_type": IncrementalFieldType.DateTime,+ },+ ],+ ),+ "failed_event_metrics": SnowplowEndpointConfig(+ name="failed_event_metrics",+ path="/metrics/v1/pipelines/{pipelineId}/failed-events",+ # One row per (pipeline, failed-event error, time bucket).+ primary_keys=["pipelineId", "errorId", "window"],+ partition_key="window",+ fan_out_over_pipelines=True,+ incremental_fields=[+ {+ "label": "window",+ "type": IncrementalFieldType.DateTime,+ "field": "window",+ "field_type": IncrementalFieldType.DateTime,+ },+ ],+ ),+}++ENDPOINTS = tuple(SNOWPLOW_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in SNOWPLOW_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/snowplow/snowplow.posthog-doc.mdx b/products/warehouse_sources/backend/temporal/data_imports/sources/snowplow/snowplow.posthog-doc.mdxnew file mode 100644index 000000000000..ea0af706a672--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/snowplow/snowplow.posthog-doc.mdx@@ -0,0 +1,78 @@+<!--+This is the user-facing source documentation. It belongs in the posthog.com repo at+contents/docs/cdp/sources/snowplow.md (served at /docs/cdp/sources/snowplow). It is kept here only+because a posthog.com checkout was not available when the source was implemented — copy it across and+delete this file from this repo. Run `python manage.py audit_source_docs --docs-dir <posthog.com>/contents/docs/cdp/sources`+once it lands.+-->++---++title: Linking Snowplow as a source+sidebar: Docs+showTitle: true+availability: { free: full, selfServe: full, enterprise: full }+sourceId: Snowplow+beta: true++---++import SourceSetupIntro from '../_snippets/source-setup-intro.mdx'+import SyncModes from '../_snippets/sync-modes.mdx'+import TroubleshootingLink from '../_snippets/dw-troubleshooting-link.mdx'+import AlphaRelease from '../_snippets/alpha-release.mdx'++<AlphaRelease />++[Snowplow](https://snowplow.io/) is a behavioral data platform built around a customer-run event pipeline.+This connector pulls the monitoring data from your Snowplow BDP Console — pipelines, failed-event metrics,+data modeling job runs and their steps, data structures, data models, and Console users — into the PostHog+Data warehouse so you can track pipeline health and modeling SLAs alongside your product data.++It syncs the Console (management) API, not your Snowplow event stream itself — your enriched events already+land in your own warehouse, which you can connect to PostHog directly (e.g. via the Snowflake or BigQuery source).++## Prerequisites++You need a Snowplow BDP account and a Console API key. All Snowplow Console API keys carry admin+privileges, so treat the key like a password.++## Adding a data source++<SourceSetupIntro />++Snowplow authenticates with three values:++1. **Organization ID** — shown on the Console's **Manage organization** page (also visible in your Console URL).+2. **API key ID** and **API key** — create a key pair under **Console settings → API keys**. The key secret is+ only shown once, at creation time.++The connector exchanges the key pair for a short-lived access token automatically, so no further setup is needed.+It talks to the standard BDP Console host (`console.snowplowanalytics.com`); privately-hosted Console deployments+are not supported yet.++## Sync modes++<SyncModes />++**Job runs**, **Job run steps**, and **Failed event metrics** support incremental sync — each run advances a+rolling time window. Note that Snowplow only retains about the preceding week of job run history and+failed-event aggregates, so schedule syncs at least weekly to avoid gaps, and expect the first sync to+backfill at most a week. The other tables are small current-state catalogs synced as full refresh.++## Configuration++<SourceParameters />++## Supported tables++<SourceTables />++## Troubleshooting++- **Snowplow API authentication failed** — the organization ID, API key ID, or API key is wrong or has been+ revoked. Check the values in your Snowplow Console settings and reconnect.+- **Missing older job runs** — Snowplow's API only serves roughly the last week of runs; history beyond that+ cannot be backfilled. Rows already synced to PostHog are kept.++<TroubleshootingLink />diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/snowplow/snowplow.py b/products/warehouse_sources/backend/temporal/data_imports/sources/snowplow/snowplow.pynew file mode 100644index 000000000000..9ce4069a1431--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/snowplow/snowplow.py@@ -0,0 +1,461 @@+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime, timedelta+from typing import Any, Optional++import requests+from structlog.types import FilteringBoundLogger+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.snowplow.settings import (+ SNOWPLOW_ENDPOINTS,+ SnowplowEndpointConfig,+)++SNOWPLOW_BASE_URL = "https://console.snowplowanalytics.com/api/msc/v1"++# The jobs API only retains runs for about the preceding week and rejects windows outside it;+# the small margin keeps the clamped `from` inside the allowed range while requests are in flight.+JOB_RUNS_RETENTION = timedelta(days=7) - timedelta(minutes=10)+# Query windows are capped at 96 hours by the API; 24h slices stay well under that and bound the+# per-window 10,000-row result cap.+JOB_RUNS_WINDOW = timedelta(hours=24)+# The jobs API caps a window's results at 10,000 rows with no pagination; a full window means+# rows were probably dropped.+JOB_RUNS_WINDOW_ROW_CAP = 10_000+# Re-pull a trailing window each incremental run: a run listed while RUNNING changes state (and a+# recent failed-events bucket keeps accumulating) after we first fetch it. Merge dedupes the+# re-pulled rows on the primary key.+INCREMENTAL_LOOKBACK = timedelta(hours=24)+# GET /data-structures/v1 pages with from/size offset params.+DATA_STRUCTURES_PAGE_SIZE = 100+# Bound the offset paginator so a misbehaving API can't loop forever.+DATA_STRUCTURES_MAX_PAGES = 1000+++class SnowplowRetryableError(Exception):+ pass+++class SnowplowAuthError(Exception):+ """Credential problem (bad org ID, key ID, or key) — permanent, never retried."""+++class SnowplowResumeConfig:+ # End of the last fully-yielded time window (ISO 8601) for the windowed jobs endpoints. The+ # resumed attempt restarts from here; the in-flight window is re-fetched and merge dedupes.+ window_from: str | None = None+ # Pipeline UUIDs already fully processed in an earlier attempt of the failed-events fan-out.+ # Keyed on stable IDs (not a positional index) so a pipeline added between a crash and the+ # retry is still processed rather than skipped.+ completed_pipeline_ids: list[str] = dataclasses.field(default_factory=list)+++def _format_datetime(dt: datetime) -> str:+ """Format as the Z-suffixed ISO 8601 the API documents; from/to must share one format."""+ return dt.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%SZ")+++def _parse_datetime(value: Any) -> datetime:+ if isinstance(value, datetime):+ return value if value.tzinfo is not None else value.replace(tzinfo=UTC)+ if isinstance(value, date):+ return datetime.combine(value, datetime.min.time(), tzinfo=UTC)+ text = str(value).replace("Z", "+00:00")+ parsed = datetime.fromisoformat(text)+ return parsed if parsed.tzinfo is not None else parsed.replace(tzinfo=UTC)+++def _iter_windows(start: datetime, end: datetime, step: timedelta) -> Iterator[tuple[datetime, datetime]]:+ window_start = start+ while window_start < end:+ window_end = min(window_start + step, end)+ yield window_start, window_end+ window_start = window_end+++class SnowplowClient:+ """Console API client handling the two-step auth: the API key + key ID mint a JWT+ (valid ~24h) which authenticates every data request; a mid-sync 401 re-mints it once."""++ def __init__(self, organization_id: str, api_key_id: str, api_key: str, logger: FilteringBoundLogger) -> None:+ self._organization_id = organization_id+ self._api_key_id = api_key_id+ self._api_key = api_key+ self._logger = logger+ # One session reused across every request so urllib3 keeps the connection alive. Register+ # the API key for value-based redaction and disable sample capture: responses carry+ # customer data (user emails, schema definitions, job metadata) and the token exchange+ # returns a bearer token in the body, neither of which may reach the HTTP sample bucket.+ # Never follow redirects: the token exchange carries the admin-capable API key in custom+ # X-API-Key headers, which requests preserves across redirects (unlike Authorization), so a+ # 30x could replay the key to another host. The API serves these endpoints directly.+ self._session = make_tracked_session(redact_values=(api_key,), capture=False, allow_redirects=False)+ self._access_token: str | None = None++ @property+ def _org_base_url(self) -> str:+ return f"{SNOWPLOW_BASE_URL}/organizations/{self._organization_id}"++ @retry(+ retry=retry_if_exception_type(+ (+ SnowplowRetryableError,+ requests.ReadTimeout,+ requests.ConnectionError,+ requests.exceptions.ChunkedEncodingError,+ )+ ),+ stop=stop_after_attempt(5),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+ )+ def _mint_token(self) -> str:+ url = f"{self._org_base_url}/credentials/v3/token"+ response = self._session.get(+ url,+ headers={"X-API-Key-Id": self._api_key_id, "X-API-Key": self._api_key},+ timeout=30,+ )+ if response.status_code == 429 or response.status_code >= 500:+ raise SnowplowRetryableError(f"Snowplow token endpoint error (retryable): status={response.status_code}")+ if response.status_code in (401, 403):+ raise SnowplowAuthError(+ "Snowplow API authentication failed: the API key or API key ID is invalid or has been revoked."+ )+ # The token endpoint 404s when the organization ID doesn't exist.+ if response.status_code == 404:+ raise SnowplowAuthError(+ "Snowplow API authentication failed: no organization found with this organization ID."+ )+ response.raise_for_status()+ token = response.json().get("accessToken")+ if not token:+ raise SnowplowAuthError("Snowplow API authentication failed: the token response had no access token.")+ return token++ @retry(+ retry=retry_if_exception_type(+ (+ SnowplowRetryableError,+ requests.ReadTimeout,+ requests.ConnectionError,+ requests.exceptions.ChunkedEncodingError,+ )+ ),+ stop=stop_after_attempt(5),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+ )+ def _request(self, path: str, params: Optional[dict[str, Any]]) -> requests.Response:+ response = self._session.get(+ f"{self._org_base_url}{path}",+ headers={"Authorization": f"Bearer {self._access_token}", "Accept": "application/json"},+ params=params,+ timeout=60,+ )+ if response.status_code == 429 or response.status_code >= 500:+ raise SnowplowRetryableError(f"Snowplow API error (retryable): status={response.status_code}, path={path}")+ return response++ def get(self, path: str, params: Optional[dict[str, Any]] = None) -> Any:+ if self._access_token is None:+ self._access_token = self._mint_token()+ response = self._request(path, params)+ if response.status_code == 401:+ # The JWT expired mid-sync (24h validity) — re-mint once and retry the request.+ self._access_token = self._mint_token()+ response = self._request(path, params)+ if not response.ok:+ # Log only status and path — never the response body, which can echo customer data.+ self._logger.error(f"Snowplow API error: status={response.status_code}, path={path}")+ response.raise_for_status()+ return response.json()+++def validate_credentials(+ organization_id: str, api_key_id: str, api_key: str, logger: FilteringBoundLogger+) -> tuple[bool, str | None]:+ """Probe the credentials by minting a token — one cheap call validating all three inputs."""+ client = SnowplowClient(organization_id, api_key_id, api_key, logger)+ try:+ client._mint_token()+ return True, None+ except SnowplowAuthError as e:+ return False, str(e)+ except Exception:+ return False, "Could not reach the Snowplow Console API. Check the credentials and try again."+++def _jobs_window_bounds(+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+ resume_window_from: str | None,+ now: datetime,+) -> tuple[datetime, datetime]:+ """Compute the overall (from, to) range to slice for the jobs endpoints.++ Runs are only retained for about a week, so both first syncs and stale watermarks clamp to+ the retention floor — deeper backfill is not possible.+ """+ floor = now - JOB_RUNS_RETENTION+ if resume_window_from is not None:+ start = _parse_datetime(resume_window_from)+ elif should_use_incremental_field and db_incremental_field_last_value:+ start = _parse_datetime(db_incremental_field_last_value) - INCREMENTAL_LOOKBACK+ else:+ start = floor+ start = max(start, floor)+ if start > now:+ start = now+ return start, now+++def _get_windowed_job_rows(+ client: SnowplowClient,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[SnowplowResumeConfig],+ config: SnowplowEndpointConfig,+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+) -> Iterator[list[dict[str, Any]]]:+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ start, end = _jobs_window_bounds(+ should_use_incremental_field,+ db_incremental_field_last_value,+ resume.window_from if resume else None,+ now=datetime.now(UTC),+ )++ for window_start, window_end in _iter_windows(start, end, JOB_RUNS_WINDOW):+ runs = client.get(+ "/jobs/v1/runs", params={"from": _format_datetime(window_start), "to": _format_datetime(window_end)}+ )+ if not isinstance(runs, list):+ runs = []+ if len(runs) >= JOB_RUNS_WINDOW_ROW_CAP:+ logger.warning(+ f"Snowplow: jobs window {_format_datetime(window_start)}..{_format_datetime(window_end)} returned "+ f"{len(runs)} rows — the API caps a window at {JOB_RUNS_WINDOW_ROW_CAP} rows, data may be truncated"+ )++ if config.fan_out_over_runs:+ yield from _get_step_rows_for_runs(client, logger, runs)+ elif runs:+ yield runs++ # Save AFTER the window's batches were consumed, so a crash re-fetches the in-flight+ # window (merge dedupes on the primary key) rather than skipping it.+ resumable_source_manager.save_state(SnowplowResumeConfig(window_from=_format_datetime(window_end)))+++def _get_step_rows_for_runs(+ client: SnowplowClient, logger: FilteringBoundLogger, runs: list[dict[str, Any]]+) -> Iterator[list[dict[str, Any]]]:+ for run in runs:+ run_id = run.get("runId")+ if not run_id:+ # runId is part of the (runId, name) primary key; a null-keyed row would collapse+ # steps from every such run into one persisted row, so skip it.+ logger.warning("Snowplow: skipping job run without a runId in the steps fan-out")+ continue+ try:+ steps = client.get(f"/jobs/v1/runs/{run_id}/steps")+ except requests.HTTPError as exc:+ # A run that aged out of retention between the window listing and this fetch 404s;+ # its steps are genuinely gone, so skip it rather than failing the whole sync.+ if exc.response is not None and exc.response.status_code == 404:+ logger.warning(f"Snowplow: job run {run_id} not found while fetching steps, skipping")+ continue+ raise+ rows = [+ {+ **step,+ "runId": run_id,+ "jobId": run.get("jobId"),+ "jobName": run.get("jobName"),+ "environment": run.get("environment"),+ "runStartTime": run.get("startTime"),+ }+ for step in steps+ if isinstance(step, dict) and step.get("name")+ ]+ if rows:+ yield rows+++def _flatten_failed_event_aggregates(+ pipeline_id: str, aggregates: list[dict[str, Any]], logger: FilteringBoundLogger+) -> list[dict[str, Any]]:+ """Flatten each aggregate's per-bucket metrics into one row per (pipeline, error, window)."""+ rows: list[dict[str, Any]] = []+ for aggregate in aggregates:+ error_id = aggregate.get("errorId")+ if not error_id:+ # errorId is part of the primary key; a null-keyed row would collapse every such+ # aggregate for the pipeline into one persisted row, so skip it.+ logger.warning(f"Snowplow: skipping failed-event aggregate without an errorId for pipeline {pipeline_id}")+ continue+ for point in aggregate.get("metrics") or []:+ if not isinstance(point, dict) or not point.get("window"):+ continue+ rows.append(+ {+ "pipelineId": pipeline_id,+ "errorId": error_id,+ "schemaKey": aggregate.get("schemaKey"),+ "classification": aggregate.get("classification"),+ "window": point.get("window"),+ "count": point.get("count"),+ "lastSeen": point.get("lastSeen"),+ }+ )+ return rows+++def _get_failed_event_metric_rows(+ client: SnowplowClient,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[SnowplowResumeConfig],+ config: SnowplowEndpointConfig,+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+) -> Iterator[list[dict[str, Any]]]:+ now = datetime.now(UTC)+ if should_use_incremental_field and db_incremental_field_last_value:+ start = _parse_datetime(db_incremental_field_last_value) - INCREMENTAL_LOOKBACK+ else:+ # The metrics store keeps about a week of failed-event aggregates (the API's own default+ # range is the preceding week), so that is the deepest useful first sync.+ start = now - JOB_RUNS_RETENTION+ if start > now:+ start = now+ params = {"from": _format_datetime(start), "to": _format_datetime(now)}++ pipelines = client.get("/pipelines/v1")+ pipeline_list = pipelines.get("pipelines", []) if isinstance(pipelines, dict) else []++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ completed_pipeline_ids = list(resume.completed_pipeline_ids) if resume is not None else []+ completed = set(completed_pipeline_ids)++ for pipeline in pipeline_list:+ pipeline_id = pipeline.get("id")+ if not pipeline_id or pipeline_id in completed:+ continue+ aggregates = client.get(config.path.format(pipelineId=pipeline_id), params=params)+ if not isinstance(aggregates, list):+ aggregates = []+ rows = _flatten_failed_event_aggregates(pipeline_id, aggregates, logger)+ if rows:+ yield rows++ # Mark this pipeline done AFTER its rows were consumed, so a crash mid-pipeline+ # re-processes it (merge dedupes) rather than skipping it.+ completed_pipeline_ids.append(pipeline_id)+ completed.add(pipeline_id)+ resumable_source_manager.save_state(SnowplowResumeConfig(completed_pipeline_ids=list(completed_pipeline_ids)))+++def _get_list_rows(+ client: SnowplowClient, logger: FilteringBoundLogger, endpoint: str, config: SnowplowEndpointConfig+) -> Iterator[list[dict[str, Any]]]:+ if endpoint == "data_structures":+ offset = 0+ for _ in range(DATA_STRUCTURES_MAX_PAGES):+ page = client.get(config.path, params={"from": offset, "size": DATA_STRUCTURES_PAGE_SIZE})+ items = page if isinstance(page, list) else []+ if items:+ yield items+ if len(items) < DATA_STRUCTURES_PAGE_SIZE:+ return+ offset += len(items)+ logger.warning(+ f"Snowplow: data_structures hit the page cap ({DATA_STRUCTURES_MAX_PAGES}), data may be truncated"+ )+ return++ data = client.get(config.path)+ if config.data_key is not None:+ items = data.get(config.data_key, []) if isinstance(data, dict) else []+ else:+ items = data if isinstance(data, list) else []+ if items:+ yield items+++def get_rows(+ organization_id: str,+ api_key_id: str,+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[SnowplowResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> Iterator[list[dict[str, Any]]]:+ config = SNOWPLOW_ENDPOINTS[endpoint]+ client = SnowplowClient(organization_id, api_key_id, api_key, logger)++ if config.windowed:+ yield from _get_windowed_job_rows(+ client,+ logger,+ resumable_source_manager,+ config,+ should_use_incremental_field,+ db_incremental_field_last_value,+ )+ elif config.fan_out_over_pipelines:+ yield from _get_failed_event_metric_rows(+ client,+ logger,+ resumable_source_manager,+ config,+ should_use_incremental_field,+ db_incremental_field_last_value,+ )+ else:+ yield from _get_list_rows(client, logger, endpoint, config)+++def snowplow_source(+ organization_id: str,+ api_key_id: str,+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[SnowplowResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ config = SNOWPLOW_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ organization_id=organization_id,+ api_key_id=api_key_id,+ api_key=api_key,+ 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,+ # Incremental endpoints persist the watermark only at successful job end (desc mode): the+ # API documents no intra-window ordering, and fan-out partial runs say nothing about+ # parents they never reached, so per-batch persistence could advance the watermark past+ # rows a crashed run still owes.+ sort_mode="desc" if config.incremental_fields else "asc",+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if config.partition_key else None,+ partition_format="month" if config.partition_key else None,+ partition_keys=[config.partition_key] if config.partition_key else None,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/snowplow/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/snowplow/source.pyindex 3ebfeaa54889..4b186a981049 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/snowplow/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/snowplow/source.py@@ -1,30 +1,182 @@-from typing import cast+from typing import Optional, cast++import structlogfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (+ SourceInputs,+ SourceResponse,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import SnowplowSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.snowplow.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ SNOWPLOW_ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.snowplow.snowplow import (+ SnowplowResumeConfig,+ snowplow_source,+ validate_credentials as validate_snowplow_credentials,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class SnowplowSource(SimpleSource[SnowplowSourceConfig]):+class SnowplowSource(ResumableSource[SnowplowSourceConfig, SnowplowResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.SNOWPLOW+ @property+ def connection_host_fields(self) -> list[str]:+ # `organization_id` selects the org path the stored API key is sent to; a multi-org key+ # could otherwise be retargeted at another org's data without re-entering the secret.+ return ["organization_id"]+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.SNOWPLOW,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,label="Snowplow Analytics",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter your Snowplow BDP Console API credentials to pull your pipeline health and data modeling job data into the PostHog Data warehouse.++Find your **Organization ID** on the Console's *Manage organization* page, then create an API key (a key ID + key secret pair) under **Console settings → API keys**. Note that all Snowplow Console API keys carry admin privileges, so store them carefully.++This connector talks to the standard BDP Console host (`console.snowplowanalytics.com`); privately-hosted Console deployments are not supported yet.""",iconPath="/static/services/snowplow.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/snowplow",+ keywords=["bdp", "behavioral data", "failed events", "data quality"],+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="organization_id",+ label="Organization ID",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="9e884a10-51c9-4632-9c05-01ba4c2b521a",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="api_key_id",+ label="API key ID",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="a1b2c3d4-0000-0000-0000-000000000000",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.snowplow.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "Snowplow API authentication failed": "Your Snowplow credentials are invalid. Check the organization ID, API key ID, and API key in your Snowplow Console settings, then reconnect.",+ "401 Client Error: Unauthorized for url: https://console.snowplowanalytics.com": "Your Snowplow API key is invalid or has been revoked. Create a new API key in your Snowplow Console settings, then reconnect.",+ "403 Client Error: Forbidden for url: https://console.snowplowanalytics.com": "Your Snowplow API key does not have access to this data. Check the key in your Snowplow Console settings, then reconnect.",+ }++ def get_schemas(+ self,+ config: SnowplowSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ def _description(endpoint: str) -> str | None:+ if endpoint in ("job_runs", "job_run_steps"):+ return (+ "Snowplow only retains job run history for about the preceding week, "+ "so historical backfill beyond that is not possible"+ )+ if endpoint == "failed_event_metrics":+ return (+ "Failed-event counts per pipeline, error, and time bucket. "+ "Snowplow keeps about a week of these aggregates"+ )+ return None++ def _build_schema(endpoint: str) -> SourceSchema:+ endpoint_config = SNOWPLOW_ENDPOINTS[endpoint]+ has_incremental = bool(INCREMENTAL_FIELDS.get(endpoint))+ return SourceSchema(+ name=endpoint,+ supports_incremental=has_incremental,+ # Rows get revised upstream (run states transition, failed-event buckets keep+ # accumulating) and incremental re-pulls a trailing window that merge dedupes,+ # so append — which would materialize the re-pulls as duplicates — is never offered.+ supports_append=False,+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ should_sync_default=endpoint_config.should_sync_default,+ description=_description(endpoint),+ )++ schemas = [_build_schema(endpoint) for endpoint in ENDPOINTS]+ 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: SnowplowSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ return validate_snowplow_credentials(+ config.organization_id, config.api_key_id, config.api_key, structlog.get_logger(__name__)+ )++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[SnowplowResumeConfig]:+ return ResumableSourceManager[SnowplowResumeConfig](inputs, SnowplowResumeConfig)++ def source_for_pipeline(+ self,+ config: SnowplowSourceConfig,+ resumable_source_manager: ResumableSourceManager[SnowplowResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return snowplow_source(+ organization_id=config.organization_id,+ api_key_id=config.api_key_id,+ api_key=config.api_key,+ 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,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/snowplow/tests/test_snowplow.py b/products/warehouse_sources/backend/temporal/data_imports/sources/snowplow/tests/test_snowplow.pynew file mode 100644index 000000000000..11b236da8e80--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/snowplow/tests/test_snowplow.py@@ -0,0 +1,539 @@+from datetime import UTC, datetime, timedelta+from typing import Any++import pytest+from freezegun import freeze_time+from unittest.mock import MagicMock, patch++import requests+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.snowplow import snowplow+from products.warehouse_sources.backend.temporal.data_imports.sources.snowplow.settings import SNOWPLOW_ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.snowplow.snowplow import (+ SnowplowAuthError,+ SnowplowClient,+ SnowplowResumeConfig,+ _flatten_failed_event_aggregates,+ _iter_windows,+ _jobs_window_bounds,+ get_rows,+ snowplow_source,+ validate_credentials,+)+++class _FakeResumableManager:+ def __init__(self, state: SnowplowResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[SnowplowResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> SnowplowResumeConfig | None:+ return self._state++ def save_state(self, data: SnowplowResumeConfig) -> None:+ self.saved.append(data)+++class _FakeClient:+ def __init__(self, handler: Any) -> None:+ self._handler = handler+ self.calls: list[tuple[str, dict | None]] = []++ def get(self, path: str, params: dict | None = None) -> Any:+ self.calls.append((path, params))+ return self._handler(path, params)+++def _run_endpoint(+ endpoint: str,+ handler: Any,+ manager: _FakeResumableManager,+ monkeypatch: Any,+ **incremental: Any,+) -> tuple[list[dict], _FakeClient]:+ client = _FakeClient(handler)+ monkeypatch.setattr(snowplow, "SnowplowClient", lambda *a, **k: client)+ rows: list[dict] = []+ for batch in get_rows(+ organization_id="org-1",+ api_key_id="key-id",+ api_key="key",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ **incremental,+ ):+ rows.extend(batch)+ return rows, client+++class TestWindows:+ @parameterized.expand(+ [+ (+ "exact_multiple",+ datetime(2026, 7, 13, tzinfo=UTC),+ datetime(2026, 7, 15, tzinfo=UTC),+ [("2026-07-13", "2026-07-14"), ("2026-07-14", "2026-07-15")],+ ),+ (+ "partial_last_window",+ datetime(2026, 7, 14, tzinfo=UTC),+ datetime(2026, 7, 15, 6, tzinfo=UTC),+ [("2026-07-14", "2026-07-15"), ("2026-07-15", "2026-07-15")],+ ),+ ("empty_range", datetime(2026, 7, 15, tzinfo=UTC), datetime(2026, 7, 15, tzinfo=UTC), []),+ ]+ )+ def test_iter_windows(self, _name: str, start: datetime, end: datetime, expected_days: list[tuple]) -> None:+ windows = list(_iter_windows(start, end, timedelta(hours=24)))+ assert [(w[0].strftime("%Y-%m-%d"), w[1].strftime("%Y-%m-%d")) for w in windows] == expected_days+ # A window must never extend past the requested end (the API rejects future/oversized windows).+ assert all(w_end <= end for _, w_end in windows)++ @freeze_time("2026-07-15T12:00:00Z")+ def test_first_sync_starts_at_the_retention_floor(self) -> None:+ # Snowplow only keeps about a week of runs; asking for more gets the window rejected.+ start, end = _jobs_window_bounds(+ should_use_incremental_field=False,+ db_incremental_field_last_value=None,+ resume_window_from=None,+ now=datetime.now(UTC),+ )+ assert end == datetime(2026, 7, 15, 12, tzinfo=UTC)+ assert start == end - snowplow.JOB_RUNS_RETENTION++ @freeze_time("2026-07-15T12:00:00Z")+ def test_incremental_run_rewinds_watermark_by_lookback(self) -> None:+ # A run listed while RUNNING changes state after we fetch it; advancing straight from the+ # watermark would freeze it at RUNNING forever.+ start, _ = _jobs_window_bounds(+ should_use_incremental_field=True,+ db_incremental_field_last_value="2026-07-15T00:00:00Z",+ resume_window_from=None,+ now=datetime.now(UTC),+ )+ assert start == datetime(2026, 7, 14, tzinfo=UTC)++ @freeze_time("2026-07-15T12:00:00Z")+ def test_stale_watermark_is_clamped_to_the_retention_floor(self) -> None:+ # A watermark older than the retention window would produce a from the API rejects.+ start, end = _jobs_window_bounds(+ should_use_incremental_field=True,+ db_incremental_field_last_value="2026-06-01T00:00:00Z",+ resume_window_from=None,+ now=datetime.now(UTC),+ )+ assert start == end - snowplow.JOB_RUNS_RETENTION++ @freeze_time("2026-07-15T12:00:00Z")+ def test_future_watermark_is_clamped_to_now(self) -> None:+ start, end = _jobs_window_bounds(+ should_use_incremental_field=True,+ db_incremental_field_last_value="2026-08-01T00:00:00Z",+ resume_window_from=None,+ now=datetime.now(UTC),+ )+ assert start == end++ @freeze_time("2026-07-15T12:00:00Z")+ def test_resume_window_takes_precedence_over_the_watermark(self) -> None:+ # On resume the saved window marks what was already yielded; restarting from the watermark+ # would re-fetch (and re-merge) everything the crashed attempt already produced.+ start, _ = _jobs_window_bounds(+ should_use_incremental_field=True,+ db_incremental_field_last_value="2026-07-10T00:00:00Z",+ resume_window_from="2026-07-14T12:00:00Z",+ now=datetime.now(UTC),+ )+ assert start == datetime(2026, 7, 14, 12, tzinfo=UTC)+++class TestJobRuns:+ @freeze_time("2026-07-15T12:00:00Z")+ def test_windows_are_requested_and_state_saved_after_each(self, monkeypatch: Any) -> None:+ run = {"runId": "r1", "state": "SUCCEEDED", "startTime": "2026-07-14T00:10:00Z"}++ def handler(path: str, params: dict | None) -> Any:+ assert path == "/jobs/v1/runs"+ assert params is not None and set(params) == {"from", "to"}+ return [run] if params["from"] == "2026-07-14T12:00:00Z" else []++ manager = _FakeResumableManager()+ rows, client = _run_endpoint(+ "job_runs",+ handler,+ manager,+ monkeypatch,+ should_use_incremental_field=True,+ db_incremental_field_last_value="2026-07-15T12:00:00Z",+ )++ # Watermark minus the 24h lookback => one 24h window [07-14T12, 07-15T12].+ assert [p for _, p in client.calls] == [{"from": "2026-07-14T12:00:00Z", "to": "2026-07-15T12:00:00Z"}]+ assert rows == [run]+ # State advances to the window end AFTER the batch was consumed, so a crash re-fetches the+ # in-flight window instead of skipping it.+ assert [s.window_from for s in manager.saved] == ["2026-07-15T12:00:00Z"]++ @freeze_time("2026-07-15T12:00:00Z")+ def test_resume_restarts_from_the_saved_window(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager(SnowplowResumeConfig(window_from="2026-07-15T00:00:00Z"))+ _, client = _run_endpoint("job_runs", lambda path, params: [], manager, monkeypatch)+ assert [p for _, p in client.calls] == [{"from": "2026-07-15T00:00:00Z", "to": "2026-07-15T12:00:00Z"}]++ @freeze_time("2026-07-15T12:00:00Z")+ def test_full_window_logs_a_truncation_warning(self, monkeypatch: Any) -> None:+ # The API silently caps a window at 10k rows; without the warning a truncated sync looks complete.+ logger = MagicMock()+ client = _FakeClient(lambda path, params: [{"runId": f"r{i}"} for i in range(10_000)])+ monkeypatch.setattr(snowplow, "SnowplowClient", lambda *a, **k: client)+ list(+ get_rows(+ organization_id="org-1",+ api_key_id="key-id",+ api_key="key",+ endpoint="job_runs",+ logger=logger,+ resumable_source_manager=_FakeResumableManager(+ SnowplowResumeConfig(window_from="2026-07-15T00:00:00Z")+ ), # type: ignore[arg-type]+ )+ )+ assert logger.warning.called+++class TestJobRunSteps:+ @freeze_time("2026-07-15T12:00:00Z")+ def test_steps_carry_parent_run_fields(self, monkeypatch: Any) -> None:+ # Step names are unique only within a run; the injected runId is what makes the composite+ # primary key unique table-wide, and runStartTime is the advertised incremental field.+ run = {+ "runId": "r1",+ "jobId": "j1",+ "jobName": "webmodel",+ "environment": "com.acme-prod1",+ "state": "SUCCEEDED",+ "startTime": "2026-07-15T00:10:00Z",+ }++ def handler(path: str, params: dict | None) -> Any:+ if path == "/jobs/v1/runs":+ return [run]+ assert path == "/jobs/v1/runs/r1/steps"+ return [{"name": "run-page-views", "state": "SUCCEEDED", "dependencies": ["other"], "duration": "PT1M"}]++ manager = _FakeResumableManager(SnowplowResumeConfig(window_from="2026-07-15T00:00:00Z"))+ rows, _ = _run_endpoint("job_run_steps", handler, manager, monkeypatch)+ assert rows == [+ {+ "name": "run-page-views",+ "state": "SUCCEEDED",+ "dependencies": ["other"],+ "duration": "PT1M",+ "runId": "r1",+ "jobId": "j1",+ "jobName": "webmodel",+ "environment": "com.acme-prod1",+ "runStartTime": "2026-07-15T00:10:00Z",+ }+ ]++ @freeze_time("2026-07-15T12:00:00Z")+ def test_run_that_404s_is_skipped(self, monkeypatch: Any) -> None:+ # A run that aged out of retention between the window listing and the steps fetch must not+ # fail the whole sync.+ not_found = requests.Response()+ not_found.status_code = 404++ def handler(path: str, params: dict | None) -> Any:+ if path == "/jobs/v1/runs":+ return [+ {"runId": "gone", "startTime": "2026-07-15T00:10:00Z"},+ {"runId": "r2", "startTime": "2026-07-15T00:20:00Z"},+ ]+ if path == "/jobs/v1/runs/gone/steps":+ raise requests.HTTPError(response=not_found)+ return [{"name": "step", "state": "SUCCEEDED"}]++ manager = _FakeResumableManager(SnowplowResumeConfig(window_from="2026-07-15T00:00:00Z"))+ rows, _ = _run_endpoint("job_run_steps", handler, manager, monkeypatch)+ assert [r["runId"] for r in rows] == ["r2"]++ @freeze_time("2026-07-15T12:00:00Z")+ def test_run_without_run_id_is_skipped(self, monkeypatch: Any) -> None:+ # runId is part of the (runId, name) primary key; a null-keyed row would collapse steps+ # from every such run into one persisted row.+ def handler(path: str, params: dict | None) -> Any:+ if path == "/jobs/v1/runs":+ return [{"state": "SUCCEEDED"}, {"runId": "r1", "startTime": "2026-07-15T00:10:00Z"}]+ return [{"name": "step", "state": "SUCCEEDED"}]++ manager = _FakeResumableManager(SnowplowResumeConfig(window_from="2026-07-15T00:00:00Z"))+ rows, client = _run_endpoint("job_run_steps", handler, manager, monkeypatch)+ assert [r["runId"] for r in rows] == ["r1"]+ assert ("/jobs/v1/runs/r1/steps", None) in client.calls+++class TestFlattenFailedEventAggregates:+ def test_flattens_one_row_per_error_and_window(self) -> None:+ aggregates = [+ {+ "errorId": "e1",+ "schemaKey": "iglu:com.acme/checkout/jsonschema/1-0-0",+ "classification": "Validation",+ "metrics": [+ {"window": "2026-07-14T00:00:00Z", "count": 12, "lastSeen": "2026-07-14T18:00:00Z"},+ {"window": "2026-07-15T00:00:00Z", "count": 3, "lastSeen": "2026-07-15T09:00:00Z"},+ ],+ }+ ]+ rows = _flatten_failed_event_aggregates("p1", aggregates, MagicMock())+ assert rows == [+ {+ "pipelineId": "p1",+ "errorId": "e1",+ "schemaKey": "iglu:com.acme/checkout/jsonschema/1-0-0",+ "classification": "Validation",+ "window": "2026-07-14T00:00:00Z",+ "count": 12,+ "lastSeen": "2026-07-14T18:00:00Z",+ },+ {+ "pipelineId": "p1",+ "errorId": "e1",+ "schemaKey": "iglu:com.acme/checkout/jsonschema/1-0-0",+ "classification": "Validation",+ "window": "2026-07-15T00:00:00Z",+ "count": 3,+ "lastSeen": "2026-07-15T09:00:00Z",+ },+ ]++ def test_rows_without_key_fields_are_skipped(self) -> None:+ # errorId and window are primary key columns; null-keyed rows would collapse distinct+ # aggregates into one persisted row on merge.+ aggregates: list[dict[str, Any]] = [+ {"schemaKey": "s", "metrics": [{"window": "2026-07-14T00:00:00Z", "count": 1}]},+ {"errorId": "e1", "metrics": [{"count": 2}, {"window": "2026-07-15T00:00:00Z", "count": 3}]},+ {"errorId": "e2", "metrics": None},+ ]+ rows = _flatten_failed_event_aggregates("p1", aggregates, MagicMock())+ assert [(r["errorId"], r["window"]) for r in rows] == [("e1", "2026-07-15T00:00:00Z")]+++class TestFailedEventMetricsFanOut:+ def _handler(self, path: str, params: dict | None) -> Any:+ if path == "/pipelines/v1":+ return {"pipelines": [{"id": "p1", "name": "prod"}, {"id": "p2", "name": "qa"}]}+ return [+ {+ "errorId": "e1",+ "schemaKey": "s",+ "classification": "Enrichment",+ "metrics": [{"window": "2026-07-15T00:00:00Z", "count": 5, "lastSeen": "2026-07-15T01:00:00Z"}],+ }+ ]++ @freeze_time("2026-07-15T12:00:00Z")+ def test_fans_out_over_pipelines_with_incremental_window(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ rows, client = _run_endpoint(+ "failed_event_metrics",+ self._handler,+ manager,+ monkeypatch,+ should_use_incremental_field=True,+ db_incremental_field_last_value="2026-07-15T00:00:00Z",+ )+ expected_params = {"from": "2026-07-14T00:00:00Z", "to": "2026-07-15T12:00:00Z"}+ assert client.calls[0] == ("/pipelines/v1", None)+ assert client.calls[1:] == [+ ("/metrics/v1/pipelines/p1/failed-events", expected_params),+ ("/metrics/v1/pipelines/p2/failed-events", expected_params),+ ]+ assert [r["pipelineId"] for r in rows] == ["p1", "p2"]+ # Completed pipelines accumulate AFTER each pipeline's rows are consumed, so a crash+ # mid-pipeline re-processes it (merge dedupes) rather than skipping it.+ assert [s.completed_pipeline_ids for s in manager.saved] == [["p1"], ["p1", "p2"]]++ @freeze_time("2026-07-15T12:00:00Z")+ def test_resume_skips_completed_pipelines(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager(SnowplowResumeConfig(completed_pipeline_ids=["p1"]))+ rows, client = _run_endpoint("failed_event_metrics", self._handler, manager, monkeypatch)+ assert [r["pipelineId"] for r in rows] == ["p2"]+ assert ("/metrics/v1/pipelines/p1/failed-events", None) not in [(p, None) for p, _ in client.calls[1:]]+++class TestListEndpoints:+ def test_pipelines_unwraps_the_wrapper_object(self, monkeypatch: Any) -> None:+ pipelines = [{"id": "p1", "name": "prod"}]+ rows, _ = _run_endpoint(+ "pipelines", lambda path, params: {"pipelines": pipelines}, _FakeResumableManager(), monkeypatch+ )+ assert rows == pipelines++ def test_users_yields_the_bare_array(self, monkeypatch: Any) -> None:+ users = [{"id": "u1", "email": "[email protected]"}]+ rows, _ = _run_endpoint("users", lambda path, params: users, _FakeResumableManager(), monkeypatch)+ assert rows == users++ @pytest.mark.parametrize(+ "page_sizes,expected_calls",+ [+ # A short final page (< 100) signals the end, so the paginator stops without an extra request.+ ([3], 1),+ ([100, 2], 2),+ # Exactly-full final page forces one more request that returns empty, then stops.+ ([100, 0], 2),+ ],+ )+ def test_data_structures_pagination_terminates(+ self, page_sizes: list[int], expected_calls: int, monkeypatch: Any+ ) -> None:+ pages = [[{"hash": f"h{p}-{i}"} for i in range(size)] for p, size in enumerate(page_sizes)]++ def handler(path: str, params: dict | None) -> Any:+ offset = (params or {})["from"]+ index = offset // 100+ return pages[index] if index < len(pages) else []++ rows, client = _run_endpoint("data_structures", handler, _FakeResumableManager(), monkeypatch)+ assert len(client.calls) == expected_calls+ assert len(rows) == sum(page_sizes)+++class TestClientAuth:+ def _session(self, responses: list[MagicMock]) -> MagicMock:+ session = MagicMock()+ session.get.side_effect = responses+ return session++ def _token_response(self, token: str = "jwt-1") -> MagicMock:+ response = MagicMock(status_code=200, ok=True)+ response.json.return_value = {"accessToken": token}+ return response++ def _data_response(self, payload: Any) -> MagicMock:+ response = MagicMock(status_code=200, ok=True)+ response.json.return_value = payload+ return response++ def test_token_is_minted_once_and_reused(self) -> None:+ session = self._session([self._token_response(), self._data_response([1]), self._data_response([2])])+ with patch.object(snowplow, "make_tracked_session", return_value=session) as mock_session_factory:+ client = SnowplowClient("org-1", "key-id", "key", MagicMock())+ assert client.get("/users") == [1]+ assert client.get("/users") == [2]+ # The session must never follow redirects: the token exchange carries the admin-capable API+ # key in custom X-API-Key headers, which requests would replay to a redirect target.+ assert mock_session_factory.call_args.kwargs["allow_redirects"] is False+ # Exactly one token mint for two data calls; re-minting per request would double API traffic+ # and hammer the credentials endpoint.+ token_calls = [c for c in session.get.call_args_list if "credentials/v3/token" in c.args[0]]+ assert len(token_calls) == 1+ data_call = next(c for c in session.get.call_args_list if "credentials" not in c.args[0])+ assert data_call.kwargs["headers"]["Authorization"] == "Bearer jwt-1"++ def test_expired_token_is_reminted_once_mid_sync(self) -> None:+ # The JWT is only valid ~24h; a long sync must recover from a 401 by re-minting instead of+ # failing the job.+ expired = MagicMock(status_code=401, ok=False)+ session = self._session(+ [self._token_response("jwt-1"), expired, self._token_response("jwt-2"), self._data_response([1])]+ )+ with patch.object(snowplow, "make_tracked_session", return_value=session):+ client = SnowplowClient("org-1", "key-id", "key", MagicMock())+ assert client.get("/users") == [1]+ last_data_call = session.get.call_args_list[-1]+ assert last_data_call.kwargs["headers"]["Authorization"] == "Bearer jwt-2"++ def test_persistent_401_raises(self) -> None:+ unauthorized = requests.Response()+ unauthorized.status_code = 401++ def raise_401() -> None:+ raise requests.HTTPError(+ "401 Client Error: Unauthorized for url: https://console.snowplowanalytics.com",+ response=unauthorized,+ )++ expired = MagicMock(status_code=401, ok=False)+ expired.raise_for_status.side_effect = raise_401+ session = self._session([self._token_response("jwt-1"), expired, self._token_response("jwt-2"), expired])+ with patch.object(snowplow, "make_tracked_session", return_value=session):+ client = SnowplowClient("org-1", "key-id", "key", MagicMock())+ with pytest.raises(requests.HTTPError):+ client.get("/users")++ @parameterized.expand([("unauthorized", 401), ("forbidden", 403), ("org_not_found", 404)])+ def test_mint_token_raises_auth_error(self, _name: str, status: int) -> None:+ response = MagicMock(status_code=status, ok=False)+ session = self._session([response])+ with patch.object(snowplow, "make_tracked_session", return_value=session):+ client = SnowplowClient("org-1", "key-id", "key", MagicMock())+ with pytest.raises(SnowplowAuthError):+ client._mint_token()++ def test_retryable_status_is_retried(self) -> None:+ bad = MagicMock(status_code=503, ok=False)+ session = self._session([self._token_response(), bad, self._data_response([1])])+ with (+ patch.object(snowplow, "make_tracked_session", return_value=session),+ patch.object(SnowplowClient._request.retry, "sleep", lambda *_: None), # type: ignore[attr-defined]+ ):+ client = SnowplowClient("org-1", "key-id", "key", MagicMock())+ assert client.get("/users") == [1]+ assert session.get.call_count == 3+++class TestValidateCredentials:+ def test_valid_credentials(self) -> None:+ with patch.object(SnowplowClient, "_mint_token", return_value="jwt"):+ assert validate_credentials("org-1", "key-id", "key", MagicMock()) == (True, None)++ def test_auth_error_surfaces_its_message(self) -> None:+ with patch.object(SnowplowClient, "_mint_token", side_effect=SnowplowAuthError("bad key")):+ ok, error = validate_credentials("org-1", "key-id", "key", MagicMock())+ assert ok is False+ assert error == "bad key"++ def test_network_error_is_invalid_with_generic_message(self) -> None:+ with patch.object(SnowplowClient, "_mint_token", side_effect=requests.ConnectionError("boom")):+ ok, error = validate_credentials("org-1", "key-id", "key", MagicMock())+ assert ok is False+ assert error is not None+++class TestSourceResponse:+ @parameterized.expand(+ [+ ("pipelines", "asc", None, ["id"]),+ ("users", "asc", None, ["id"]),+ ("data_models", "asc", None, ["name"]),+ ("data_structures", "asc", None, ["hash"]),+ ("job_runs", "desc", "startTime", ["runId"]),+ ("job_run_steps", "desc", "runStartTime", ["runId", "name"]),+ ("failed_event_metrics", "desc", "window", ["pipelineId", "errorId", "window"]),+ ]+ )+ def test_sort_mode_partition_and_primary_keys(+ self, endpoint: str, expected_sort: str, partition_key: str | None, primary_keys: list[str]+ ) -> None:+ # Incremental endpoints must report "desc" so the watermark persists only at successful job+ # end; "asc" per-batch persistence would let a crashed run advance past rows it still owes.+ response = snowplow_source(+ organization_id="org-1",+ api_key_id="key-id",+ api_key="key",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=MagicMock(),+ )+ assert response.sort_mode == expected_sort+ assert response.partition_keys == ([partition_key] if partition_key else None)+ assert response.primary_keys == SNOWPLOW_ENDPOINTS[endpoint].primary_keys == primary_keysdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/snowplow/tests/test_snowplow_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/snowplow/tests/test_snowplow_source.pynew file mode 100644index 000000000000..ff0885449d1d--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/snowplow/tests/test_snowplow_source.py@@ -0,0 +1,161 @@+from typing import Optional++from unittest.mock import MagicMock, patch++from parameterized import parameterized++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceInputs+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import SnowplowSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.snowplow import source as source_module+from products.warehouse_sources.backend.temporal.data_imports.sources.snowplow.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.snowplow.snowplow import SnowplowResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.snowplow.source import SnowplowSource+from products.warehouse_sources.backend.types import ExternalDataSourceType+++def _source_inputs(+ schema_name: str, last_value: Optional[object] = None, use_incremental: bool = False+) -> SourceInputs:+ return SourceInputs(+ schema_name=schema_name,+ schema_id="schema-1",+ source_id="source-1",+ team_id=1,+ should_use_incremental_field=use_incremental,+ db_incremental_field_last_value=last_value,+ db_incremental_field_earliest_value=None,+ incremental_field="startTime" if use_incremental else None,+ incremental_field_type=None,+ job_id="job-1",+ logger=MagicMock(),+ reset_pipeline=False,+ )+++class TestSnowplowSource:+ def setup_method(self) -> None:+ self.source = SnowplowSource()++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.SNOWPLOW++ def test_source_config_fields(self) -> None:+ config = self.source.get_source_config+ fields = {f.name: f for f in config.fields if isinstance(f, SourceFieldInputConfig)}+ assert set(fields.keys()) == {"organization_id", "api_key_id", "api_key"}+ # Only the API key is confidential; the org ID and key ID must stay editable/visible.+ assert fields["api_key"].type == SourceFieldInputConfigType.PASSWORD+ assert fields["api_key"].secret is True+ assert fields["organization_id"].secret is False+ assert fields["api_key_id"].secret is False+ assert all(f.required for f in fields.values())++ def test_source_is_released_as_alpha(self) -> None:+ config = self.source.get_source_config+ assert config.releaseStatus == ReleaseStatus.ALPHA+ # unreleasedSource hides the connector from every user; a finished source must not carry it.+ assert not config.unreleasedSource+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/snowplow"++ def test_connection_host_fields_cover_organization(self) -> None:+ # organization_id decides which org the stored API key reaches, so the update serializer+ # must force the key to be re-entered when it changes.+ assert self.source.connection_host_fields == ["organization_id"]++ def test_lists_tables_without_credentials(self) -> None:+ # get_schemas is a static, no-I/O catalog, so the public docs table list must render.+ assert self.source.lists_tables_without_credentials is True++ def test_get_schemas_returns_every_endpoint(self) -> None:+ schemas = self.source.get_schemas(MagicMock(), team_id=1)+ assert {s.name for s in schemas} == set(ENDPOINTS)++ def test_get_schemas_filters_by_names(self) -> None:+ schemas = self.source.get_schemas(MagicMock(), team_id=1, names=["job_runs"])+ assert [s.name for s in schemas] == ["job_runs"]++ @parameterized.expand(+ [+ # Only the time-windowed endpoints have a genuine server-side filter; the small+ # current-state catalogs are full refresh.+ ("job_runs", True, ["startTime"]),+ ("job_run_steps", True, ["runStartTime"]),+ ("failed_event_metrics", True, ["window"]),+ ("pipelines", False, []),+ ("users", False, []),+ ("data_models", False, []),+ ("data_structures", False, []),+ ]+ )+ def test_incremental_support_per_endpoint(+ self, endpoint: str, supports_incremental: bool, incremental_fields: list[str]+ ) -> None:+ schema = next(s for s in self.source.get_schemas(MagicMock(), team_id=1) if s.name == endpoint)+ assert schema.supports_incremental is supports_incremental+ # Rows are revised upstream (run states transition, buckets accumulate) and incremental+ # re-pulls a lookback window that merge dedupes, so append is never offered.+ assert schema.supports_append is False+ assert [f["field"] for f in schema.incremental_fields] == incremental_fields++ @parameterized.expand([("valid", (True, None)), ("invalid", (False, "bad credentials"))])+ def test_validate_credentials(self, _name: str, probe_result: tuple[bool, str | None]) -> None:+ config = SnowplowSourceConfig(organization_id="org-1", api_key_id="key-id", api_key="key")+ with patch.object(source_module, "validate_snowplow_credentials", return_value=probe_result) as mock_probe:+ ok, error = self.source.validate_credentials(config, team_id=1)+ assert (ok, error) == probe_result+ assert mock_probe.call_args.args[:3] == ("org-1", "key-id", "key")++ @parameterized.expand(+ [+ (+ "token_mint_auth_failure",+ "Snowplow API authentication failed: the API key or API key ID is invalid or has been revoked.",+ ),+ (+ "unauthorized",+ "401 Client Error: Unauthorized for url: https://console.snowplowanalytics.com/api/msc/v1/organizations/org/jobs/v1/runs",+ ),+ (+ "forbidden",+ "403 Client Error: Forbidden for url: https://console.snowplowanalytics.com/api/msc/v1/organizations/org/users",+ ),+ ]+ )+ def test_credential_errors_are_non_retryable(self, _name: str, observed_error: str) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable)++ def test_get_resumable_source_manager_is_bound_to_resume_config(self) -> None:+ manager = self.source.get_resumable_source_manager(_source_inputs("job_runs"))+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is SnowplowResumeConfig++ def test_source_for_pipeline_plumbs_credentials_and_endpoint(self) -> None:+ config = SnowplowSourceConfig(organization_id="org-1", api_key_id="key-id", api_key="key")+ inputs = _source_inputs("job_runs", last_value="2026-07-10T00:00:00Z", use_incremental=True)+ with patch.object(source_module, "snowplow_source") as mock_source:+ self.source.source_for_pipeline(config, MagicMock(), inputs)+ kwargs = mock_source.call_args.kwargs+ assert kwargs["organization_id"] == "org-1"+ assert kwargs["api_key_id"] == "key-id"+ assert kwargs["api_key"] == "key"+ assert kwargs["endpoint"] == "job_runs"+ assert kwargs["should_use_incremental_field"] is True+ assert kwargs["db_incremental_field_last_value"] == "2026-07-10T00:00:00Z"++ def test_source_for_pipeline_omits_last_value_when_not_incremental(self) -> None:+ # Passing a stale watermark on a full-refresh run would wrongly narrow the time window.+ config = SnowplowSourceConfig(organization_id="org-1", api_key_id="key-id", api_key="key")+ inputs = _source_inputs("job_runs", last_value="2026-07-10T00:00:00Z", use_incremental=False)+ with patch.object(source_module, "snowplow_source") as mock_source:+ self.source.source_for_pipeline(config, MagicMock(), inputs)+ assert mock_source.call_args.kwargs["db_incremental_field_last_value"] is None++ def test_canonical_descriptions_cover_every_endpoint(self) -> None:+ # Drift here (an endpoint renamed in settings but not here) silently drops the curated docs+ # and falls back to LLM enrichment, so keep the two in lockstep.+ descriptions = self.source.get_canonical_descriptions()+ assert set(descriptions.keys()) == set(ENDPOINTS)