Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(data-warehouse): point source authoring at the shared REST framework + add missing helpers (#71477)

Tom Owersdbcc387b23f9
diff --git a/.agents/skills/implementing-warehouse-sources/SKILL.md b/.agents/skills/implementing-warehouse-sources/SKILL.md
index 1826108ad3a8..9bd6f1d99601 100644
--- a/.agents/skills/implementing-warehouse-sources/SKILL.md
+++ b/.agents/skills/implementing-warehouse-sources/SKILL.md
@@ -11,13 +11,13 @@ Use this skill when building or updating Data warehouse sources in `products/war
Before coding, read:
-- `products/warehouse_sources/backend/temporal/data_imports/sources/source.template` (use the top-of-file TODOs as a starting reference, but verify target files against the current source implementations — the template can drift, e.g. it currently still points at the old `posthog/warehouse/types.py` path instead of `products/warehouse_sources/backend/types.py`)
+- `products/warehouse_sources/backend/temporal/data_imports/sources/source.template` (the top-of-file TODOs are the bootstrap checklist; still verify target files against current source implementations, since the template can drift)
- `products/warehouse_sources/backend/temporal/data_imports/sources/README.md`
- `products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md` — inventory of every registered source with its communication method (HTTP / vendor SDK / gRPC / DB protocol / webhook) and tracked-transport state. Skim this first to see how similar sources are wired and what state today's source you're touching is in. **Keep it in sync** — see "Updating SOURCES.md" below.
- `products/warehouse_sources/backend/temporal/data_imports/sources/common/base.py` — base classes (`SimpleSource`, `ResumableSource`, `WebhookSource`) and the `FieldType` union
- `products/warehouse_sources/backend/temporal/data_imports/sources/common/resumable.py` — `ResumableSourceManager`
- `products/warehouse_sources/backend/temporal/data_imports/sources/common/webhook_s3.py` — `WebhookSourceManager`
-- 1 API source with `settings.py` + transport logic (e.g. klaviyo, github). For dependent-resource fan-out (parent→child with `type: "resolve"`), also read `products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/__init__.py` and `config_setup.py` (e.g. `process_parent_data_item`, `make_parent_key_name`).
+- **`chargebee/` — the canonical reference for a new REST source.** It uses the shared `rest_source` framework (declarative `RESTAPIConfig` + `rest_api_resource`, framework auth + paginators, tracked+retrying transport) and is resumable — proof the framework covers the dominant "paginate a list endpoint and yield, resumably" shape. Read it first, alongside "Prefer the shared REST framework" below. Read `klaviyo/` or `github/` only as a _bespoke-transport_ fallback: they hand-roll their client for edge cases (custom query-string encoding, multi-level fan-out, JSON:API reshaping) that most sources don't have — don't copy that boilerplate into a source that doesn't need it. For dependent-resource fan-out (parent→child with `type: "resolve"`), also read `products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/__init__.py` and `config_setup.py` (e.g. `process_parent_data_item`, `make_parent_key_name`).
- For webhook-capable sources, read `products/warehouse_sources/backend/temporal/data_imports/sources/stripe/source.py` as the reference implementation.
## Picking the right base class
@@ -47,6 +47,30 @@ Rule of thumb:
Databases and file-transfer sources (SFTP, S3) stay on `SimpleSource` unless there's a clear reason otherwise.
+## Prefer the shared REST framework
+
+Most REST sources should be built on the shared `rest_source` framework
+(`common/rest_source/`), not a hand-rolled client. It already provides — so you write **none** of it:
+
+- **Tracked, retrying transport** — `RESTClient` defaults to `make_tracked_session()` and retries
+ `429` + transient `5xx` honoring `Retry-After`. No `tenacity`, no `RetryableError`, no fetch loop.
+- **Paginators** (`rest_source/paginators.py`, chosen by string/dict in the config, not hand-written):
+ `single_page`, `header_link`, `json_response` (next-URL in body), `cursor`, `offset`, `page_number`.
+- **Auth** (`rest_source/auth.py`): `bearer`, `api_key` (header/query/cookie), `http_basic`, `oauth2`
+ (customer-owned client-credentials/refresh). Each redacts its own secrets — no `_get_headers` builder.
+- **Incremental params, `data_selector`, response actions, resume** (`resume_hook` /
+ `initial_paginator_state`), and **parent/child fan-out** (`fanout.build_dependent_resource`).
+
+`chargebee/` is the canonical example (declarative endpoints + framework auth + resume). `zendesk/`
+shows multi-endpoint + `data_selector`; `attio/` shows cursor pagination.
+
+**When hand-rolling is justified** (read `klaviyo/` then): the API needs query strings the framework
+can't produce (literal brackets/operators, e.g. `filter=greater-than(...)`, `page[size]`);
+multi-level (2+ deep) fan-out; or per-item reshaping the `data_selector` can't express (e.g.
+flattening JSON:API `attributes` into the row root). Single-level fan-out and per-item maps are
+supported declaratively — don't hand-roll for those. If you must hand-roll, still ride
+`make_tracked_session()` and do **not** add a second status-code retry layer (see "Retry and throttling").
+
## End-to-end workflow for a new API source
Follow this order. Each step maps to TODOs in `source.template`.
@@ -65,7 +89,7 @@ Follow this order. Each step maps to TODOs in `source.template`.
Then update the two hand-edited files (the template still lists `posthog/schema.py` too, but that file is regenerated by `pnpm run schema:build` in step 12 — don't maintain it by hand):
- `ExternalDataSourceType` at `products/warehouse_sources/backend/types.py` — follow the existing convention in that file: `ALL_CAPS` with **no underscores** between words (e.g. `ACTIVECAMPAIGN`, `APPLESEARCHADS`), value is `PascalCase`
- - `externalDataSources` at `frontend/src/queries/schema/schema-general.ts` (`lower-kebab-case`)
+ - `externalDataSources` at `frontend/src/queries/schema/schema-general.ts` — **PascalCase, identical to the `ExternalDataSourceType` value** (e.g. `'ActiveCampaign'`, `'GoogleAds'`, `'CustomerIO'`). NOT kebab-case. (The only kebab-case identifier in the flow is the optional `featureFlag="dwh-{source_name}"`.)
3. **Pick the base class** (see above) and rename the class / `source_type` return.
4. **Define `get_source_config`** — name, **category** (required — see "Source category & keywords"), label, caption, docsUrl, iconPath, fields, and optional `keywords`. Use appropriate field types (see below). Also set the vendor API version metadata class attributes — see "Vendor API version metadata".
@@ -74,7 +98,7 @@ Follow this order. Each step maps to TODOs in `source.template`.
7. **Swap the generic `Config` type** in `source.py` for the generated `{Source}SourceConfig` class.
8. **Implement**: `validate_credentials`, `get_schemas`, `source_for_pipeline` (plus `get_resumable_source_manager` / `get_webhook_source_manager` as needed).
9. **Split transport logic.** Put API client, paginator, row normalization, and `SourceResponse` assembly in `{source}.py`. Keep endpoint catalog/incremental fields/primary keys/partition defaults in `settings.py`.
-10. **Add icon.** Place at `frontend/public/services/{source}.svg` (prefer SVG). If the logo isn't already committed, fetch from [Logo.dev](https://docs.logo.dev/introduction) — **ask the user for the Logo.dev API key**; do not hardcode one. Keep file size reasonable.
+10. **Add icon.** Place at `frontend/public/services/{source}.png` — **PNG is the repo convention** (~800 png vs ~58 svg, and `source.template` defaults to `.png`). SVG is accepted but not the norm; set `iconPath` to match whichever extension you commit. If the logo isn't already committed, fetch from [Logo.dev](https://docs.logo.dev/introduction) — **ask the user for the Logo.dev API key**; do not hardcode one. Logo.dev's image API returns PNG (not SVG). Keep file size reasonable.
11. **Run migrations.** `DEBUG=1 python manage.py makemigrations && DEBUG=1 ./bin/migrate` (only needed if a new enum value triggers a Django migration).
12. **Rebuild schema types**: `pnpm run schema:build`. This updates `posthog/schema.py` from `schema-general.ts` and makes the source appear in frontend dropdowns. Re-run whenever `schema-general.ts` changes.
13. **Release status — a finished source has no `unreleasedSource` flag.** The default for the deliverable this skill produces is **no `unreleasedSource`** — a completed, working source ships visible and connectable. You don't need anyone's sign-off to ship it released; that's just the finished state. The scaffolded stub ships with `unreleasedSource=True` pre-set, so deleting that line is part of finishing the source — go ahead and remove it. (Why it matters: `unreleasedSource=True` **hides the connector from users entirely** — the frontend filters out every source where it's truthy; see `DataWarehouseQueryVariant.tsx`, `InlineSourceSetup.tsx`, and the "coming soon / Notify me" path in `nonHogFunctionTemplatesLogic.tsx`.)
@@ -299,7 +323,7 @@ Return a `SourceResponse` directly. **Do not** use `dlt_source_to_source_respons
Prefer yielding data in the shape the API returns it. No custom dataclasses, no heavy parsing. Yield either `dict`, `list[dict]` (preferred when possible), or a `pyarrow.Table`. The pipeline buffers and batches for you.
-**Don't import or instantiate `Batcher` at the source layer.** The pipeline already runs one (`pipelines/pipeline/pipeline.py`) at the same 5000-row / 200 MiB thresholds. Yielding raw `dict` / `list[dict]` from your generator is the canonical path — reach for `pyarrow.Table` only when you already have arrow-shaped data (e.g., a ClickHouse adapter). Source-level batching results in double-buffering with no behavioral win.
+**Default to yielding raw `dict` / `list[dict]` and let the pipeline batch for you.** The pipeline already runs a `Batcher` (`pipelines/pipeline/pipeline.py`) at 5000-row / 200 MiB thresholds, so the common case needs no batcher of its own. Reach for `pyarrow.Table` only when you already have arrow-shaped data (e.g. a ClickHouse adapter). A source _may_ instantiate its own `Batcher` with **smaller** thresholds (e.g. `chunk_size=2000, chunk_size_bytes=100 * 1024 * 1024`, as klaviyo and ~70 other sources do) when it deliberately wants a tighter memory footprint for large/wide rows — that's a valid choice, not the default. What to avoid is a second _full-size_ batcher, which just double-buffers with no win.
For pyarrow tables, cap in-memory rows at ~200 MiB or ~5000 rows. Use helpers like `table_from_iterator()` / `table_from_py_list()` from `products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/utils.py`.
@@ -382,6 +406,11 @@ log line and OTel metric, and participates in opt-in sample capture.
- For raw `requests` usage: `make_tracked_session(headers=..., retry=...)` returns a `requests.Session`. Use
`session.get/post/...` instead of the module-level `requests.get/...` shortcuts.
+- **Redact secrets from the captured samples.** Pass `redact_values=(api_key, token, ...)` to
+ `make_tracked_session(...)` so the tracked transport masks those literal values in logged URLs, headers,
+ and sampled bodies — important for keys that ride in a query param or an odd header name. `rest_source`
+ auth classes do this automatically (each implements `secret_values()`); only raw-session sources need to
+ pass `redact_values` themselves.
- For sources that already go through `rest_source.RESTClient`: it defaults to a tracked session
automatically; no change needed.
- For vendor SDKs that accept a session/HTTP-client hook (Stripe `RequestsClient(session=...)`,
@@ -435,6 +464,25 @@ concurrent PRs — don't collapse it back into a comma-separated paragraph. If y
source, also append a short "Notes on partially-tracked sources" entry explaining what blocks tracking
(e.g. a vendor SDK with no session/interceptor seam).
+## Base-class capability flags & API versioning
+
+`common/base.py` exposes class-level flags most API sources leave at their defaults, but which matter
+when they apply:
+
+- `supports_column_selection` (default `False`; `SQLSource` sets `True`) — whether the source honors
+ `enabled_columns` via SELECT projection.
+- `supports_row_filters` (default `False`) — must be `True` for a source to apply saved `row_filters`;
+ otherwise filters are ignored.
+- `has_managed_hogql_schema` (default `False`; `True` for revenue-analytics sources like Stripe,
+ Paddle, Zendesk) — a fixed field set powers a managed HogQL schema, which disables column selection.
+ A new billing/revenue source that ignores this can break revenue analytics.
+- `cleanup_cdc_resources_on_deletion` — best-effort teardown hook for sources that provision CDC
+ resources; override only if your source creates such resources.
+
+For vendor **API versioning** (`supported_versions`, `default_version`, `api_docs_url`,
+`deprecated_versions`, `resolve_api_version()`), use the dedicated **`warehouse-source-new-version`**
+skill — don't hand-roll version handling.
+
## Required coding conventions
- Register with `@SourceRegistry.register`.
@@ -500,10 +548,9 @@ If undocumented, keep parsing/merge logic conservative and add a short code comm
## Retry and throttling strategy
-- Use `tenacity` instead of manual retry loops.
-- Retry transport failures and retryable status codes (`429`, transient `5xx`).
-- Prefer server-provided rate-limit reset headers on `429`; fall back to exponential backoff.
-- Bound and make deterministic (`stop_after_attempt`). Preserve clear terminal behavior.
+- **`make_tracked_session()` and `rest_source.RESTClient` already retry `429` + transient `5xx` at the transport layer**, honoring `Retry-After`. Do NOT wrap a second `tenacity` `@retry` around your fetch for status codes — it compounds (e.g. 3 transport attempts × 5 tenacity attempts) and is the single most-copied mistake across existing sources. If you use the framework or the tracked session, status-code retries are already handled; write none.
+- Only add `tenacity` for a condition the transport does **not** cover — e.g. an app-level "still processing" body that isn't a retryable HTTP status. If you do, disable transport retries so they don't compound: `make_tracked_session(retry=Retry(total=0))`.
+- Prefer server-provided rate-limit reset headers on `429` — the transport already honors `Retry-After`. Keep any custom retry bounded and deterministic (`stop_after_attempt`), with clear terminal behavior.
- Keep timeout/retry settings near the top of the module for easy tuning.
The backoff above is the right control when the **customer owns the credential** — their own PAT / API key / OAuth token on their own third-party account, which is nearly every source.
@@ -602,7 +649,7 @@ preserved (omitted) secret is reused — exfiltrating the credential. `host` and
already handled separately, so only sources whose connection target lives in a differently named field (e.g.
Okta's `okta_domain`) need to override this. The default is `[]` (no extra fields).
-Pair this with `_is_host_safe` (see `## Outbound HTTP must go through the tracked transport`) at both
+Pair this with `_is_host_safe` (`common/mixins.py`) at both
source-create and sync time to block hosts resolving to internal/private IPs.
## Mixins
@@ -615,8 +662,8 @@ From `products/warehouse_sources/backend/temporal/data_imports/sources/common/mi
## Icons
-- Prefer SVG over PNG. Keep file size reasonable.
-- Place in `frontend/public/services/` and reference as `/static/services/{name}.svg` in `iconPath`.
+- PNG is the repo convention (`source.template` defaults to `.png`; ~800 png vs ~58 svg). SVG is accepted but not the norm. Keep file size reasonable.
+- Place in `frontend/public/services/` and reference as `/static/services/{name}.png` (or `.svg`) in `iconPath` — match the extension you commit.
- If the source logo isn't already in the project, pull via [Logo.dev](https://docs.logo.dev/introduction). **Ask the user for the API key** — do not hardcode one. If the user hasn't provided one, surface that as a blocker rather than committing a placeholder.
## Testing expectations
@@ -652,7 +699,7 @@ Use parameterized tests for status codes and edge cases. Lean toward over-coveri
```text
Bootstrapping:
- [ ] Enum added to products/warehouse_sources/backend/types.py (ALL_CAPS, no underscores between words)
-- [ ] Entry added to frontend/src/queries/schema/schema-general.ts (kebab-case) — `pnpm run schema:build` regenerates posthog/schema.py from this; don't hand-edit posthog/schema.py
+- [ ] Entry added to frontend/src/queries/schema/schema-general.ts (PascalCase, matching the ExternalDataSourceType value — NOT kebab-case) — `pnpm run schema:build` regenerates posthog/schema.py from this; don't hand-edit posthog/schema.py
- [ ] Source imported in products/warehouse_sources/backend/temporal/data_imports/sources/__init__.py + __all__
- [ ] Class inherits from SimpleSource / ResumableSource / WebhookSource (or combo) — see "Picking the right base class"
@@ -676,7 +723,7 @@ Source implementation:
- [ ] (Fixed-schema sources, static get_schemas only) Set lists_tables_without_credentials = True so public docs render the table catalog
Tooling & assets:
-- [ ] Icon in frontend/public/services/ (SVG preferred — ask user for Logo.dev key if needed)
+- [ ] Icon in frontend/public/services/ (PNG is the convention; ask user for Logo.dev key if needed)
- [ ] Run `pnpm run generate:source-configs`
- [ ] Swap generic Config for generated {Source}SourceConfig in source.py
- [ ] Run `pnpm run schema:build`
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/chargebee/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/chargebee/source.py
index b01c1a728b10..17d05d841474 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/chargebee/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/chargebee/source.py
@@ -28,7 +28,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.can
)
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 SourceSchema
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import (
+ SourceSchema,
+ build_endpoint_schemas,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import ChargebeeSourceConfig
from products.warehouse_sources.backend.types import ExternalDataSourceType
@@ -65,21 +68,7 @@ class ChargebeeSource(ResumableSource[ChargebeeSourceConfig, ChargebeeResumeConf
names: list[str] | None = None,
force_refresh: bool = False,
) -> list[SourceSchema]:
- schemas = [
- SourceSchema(
- name=endpoint,
- supports_incremental=INCREMENTAL_FIELDS.get(endpoint, None) is not None,
- supports_append=INCREMENTAL_FIELDS.get(endpoint, None) is not None,
- incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
- )
- for endpoint in list(ENDPOINTS)
- ]
-
- if names is not None:
- names_set = set(names)
- schemas = [s for s in schemas if s.name in names_set]
-
- return schemas
+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)
def validate_credentials(
self, config: ChargebeeSourceConfig, team_id: int, schema_name: Optional[str] = None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/errors.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/errors.py
new file mode 100644
index 000000000000..3989c9d835dc
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/errors.py
@@ -0,0 +1,34 @@
+"""Shared non-retryable-error helpers for warehouse sources.
+
+`get_non_retryable_errors()` returns a dict mapping a substring of the stringified exception to a
+friendly message; the pipeline fails the job (instead of retrying) when a raised error contains one
+of these substrings. Nearly every source hand-writes the same 401/403 pair, so centralize it here.
+"""
+
+
+def auth_non_retryable_errors(host: str | None = None, *, service: str | None = None) -> dict[str, str | None]:
+ """Standard 401/403 -> friendly-message map for `get_non_retryable_errors()`.
+
+ A bad or unscoped credential is permanent, not transient, so the job should fail fast rather than
+ retry. Keys match the stable ``requests`` ``raise_for_status()`` text as a substring.
+
+ Pass ``host`` (the source's base URL) to scope the match to this source's requests — e.g.
+ ``"401 Client Error: Unauthorized for url: https://api.example.com"`` — so an unrelated 401 from a
+ different host in the same job can't match. Omit it for a host-agnostic match. ``service`` names
+ the vendor in the message. Sources with provider-specific copy should still hand-write their own.
+ """
+ svc = f"{service} " if service else ""
+ unauthorized = f"Your {svc}API key or token is invalid or expired. Please reconnect with valid credentials."
+ forbidden = (
+ f"Your {svc}credentials don't have permission to access this resource. Check the key's scopes and reconnect."
+ )
+ if host:
+ return {
+ f"401 Client Error: Unauthorized for url: {host}": unauthorized,
+ f"403 Client Error: Forbidden for url: {host}": forbidden,
+ }
+ return {"401 Client Error": unauthorized, "403 Client Error": forbidden}
+
+
+# Host-agnostic default, for sources that just want the common pair with no service name.
+AUTH_401_403_ERRORS: dict[str, str | None] = auth_non_retryable_errors()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/schema.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/schema.py
index 5f671dd88027..1a579c9babbf 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/schema.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/schema.py
@@ -1,7 +1,8 @@
+from collections.abc import Collection, Iterable, Mapping
from dataclasses import dataclass, field
from typing import Any
-from products.warehouse_sources.backend.types import IncrementalField
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
# Preference order (lowercased) for auto-selecting an incremental field. Columns that
# advance on every write (`updated_at`) catch late-arriving updates that creation-only
@@ -107,3 +108,67 @@ def build_default_schemas(source_schemas: list[SourceSchema]) -> list[dict]:
entry["primary_key_columns"] = source_schema.detected_primary_keys
schemas.append(entry)
return schemas
+
+
+def incremental_field(
+ field: str,
+ field_type: IncrementalFieldType = IncrementalFieldType.DateTime,
+ label: str | None = None,
+) -> IncrementalField:
+ """Build an ``IncrementalField`` for a settings.py endpoint catalog.
+
+ Replaces the hand-written 4-key dict (``label``/``type``/``field``/``field_type``) that most
+ sources repeat per endpoint, where ``type`` and ``field_type`` are almost always the same value
+ and ``label`` defaults to the field name — a frequent copy-paste bug source.
+ """
+ return {"label": label or field, "type": field_type, "field": field, "field_type": field_type}
+
+
+def build_endpoint_schemas(
+ endpoints: Iterable[str],
+ incremental_fields: Mapping[str, list[IncrementalField]],
+ names: list[str] | None = None,
+ *,
+ append_only: Collection[str] = (),
+ merge_only: Collection[str] = (),
+ descriptions: Mapping[str, str] | None = None,
+ should_sync_default: Mapping[str, bool] | None = None,
+ supports_webhooks: Collection[str] = (),
+) -> list[SourceSchema]:
+ """Build the ``SourceSchema`` list for a static endpoint-catalog source's ``get_schemas``.
+
+ Collapses the near-universal ``for endpoint in ENDPOINTS: SourceSchema(...)`` loop plus the
+ identical ``names`` filter tail. An endpoint with incremental fields defaults to
+ ``supports_incremental=True`` and ``supports_append=True`` (the dominant pattern). Overrides:
+
+ - ``append_only``: endpoints that support append but not incremental merge.
+ - ``merge_only``: endpoints that support incremental merge but not append.
+ - ``descriptions`` / ``should_sync_default`` / ``supports_webhooks``: per-endpoint metadata.
+
+ ``names`` (the schema-picker filter) keeps only the requested endpoints when set.
+ """
+ descriptions = descriptions or {}
+ should_sync_default = should_sync_default or {}
+ schemas = []
+ for name in endpoints:
+ fields = incremental_fields.get(name)
+ # Match the hand-written loop's `.get(name) is not None`: a mapping entry (even an
+ # explicit `[]`) counts as incremental, a missing one doesn't.
+ has_incremental = fields is not None
+ schemas.append(
+ SourceSchema(
+ name=name,
+ supports_incremental=has_incremental and name not in append_only,
+ supports_append=has_incremental and name not in merge_only,
+ incremental_fields=fields or [],
+ description=descriptions.get(name),
+ should_sync_default=should_sync_default.get(name, True),
+ supports_webhooks=name in supports_webhooks,
+ )
+ )
+
+ if names is not None:
+ names_set = set(names)
+ schemas = [s for s in schemas if s.name in names_set]
+
+ return schemas
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/source_helpers.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/source_helpers.py
new file mode 100644
index 000000000000..a17b3100c952
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/source_helpers.py
@@ -0,0 +1,40 @@
+"""Shared helpers for source credential validation.
+
+Most API sources implement `validate_credentials` by probing one cheap endpoint and mapping the HTTP
+status to a bool. Centralize that probe so sources don't each re-implement the try/except + status
+check (and so the 401-vs-403 distinction the skill describes is handled consistently).
+"""
+
+from collections.abc import Callable, Mapping
+
+import requests
+from requests.auth import AuthBase
+
+
+def validate_via_probe(
+ session_factory: Callable[[], requests.Session],
+ url: str,
+ *,
+ headers: Mapping[str, str] | None = None,
+ auth: AuthBase | None = None,
+ ok_statuses: tuple[int, ...] = (200,),
+ timeout: float = 10.0,
+) -> tuple[bool, int | None]:
+ """Probe ``url`` with a GET and report ``(is_valid, status_code)``.
+
+ ``session_factory`` should return a tracked session (``make_tracked_session``). ANY failure
+ building the session or making the request (transport error, and defensively anything else) maps
+ to ``(False, None)`` — a credential probe should never raise out of ``validate_credentials`` and
+ fail source creation; an unreachable/erroring probe just means "not validated". This matches the
+ broad ``except Exception`` the hand-rolled probes across ~all sources use, so it's a drop-in.
+ Any HTTP response maps to ``(status in ok_statuses, status)`` so the caller can distinguish 401
+ (bad token) from 403 (valid token, missing scope) — accept 403 at source-create when
+ ``schema_name`` is None, per the skill. The caller wraps the result into the ``(bool, message)``
+ its ``validate_credentials`` returns.
+ """
+ try:
+ session = session_factory()
+ response = session.get(url, headers=dict(headers) if headers else None, auth=auth, timeout=timeout)
+ except Exception: # noqa: BLE001 — a credential probe must never raise; any failure means "not validated"
+ return False, None
+ return response.status_code in ok_statuses, response.status_code
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_source_helpers.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_source_helpers.py
new file mode 100644
index 000000000000..ccd039a0d31a
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_source_helpers.py
@@ -0,0 +1,143 @@
+from unittest.mock import Mock
+
+import requests
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.errors import auth_non_retryable_errors
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import (
+ SourceSchema,
+ build_endpoint_schemas,
+ incremental_field,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probe
+from products.warehouse_sources.backend.types import IncrementalFieldType
+
+ENDPOINTS = ("charges", "invoices", "events")
+INCREMENTAL_FIELDS = {
+ "charges": [incremental_field("updated_at")],
+ "invoices": [incremental_field("created", IncrementalFieldType.Date)],
+ # "events" intentionally has no incremental fields (full-refresh only)
+}
+
+
+class TestIncrementalField:
+ def test_defaults_type_and_label_from_field(self) -> None:
+ assert incremental_field("updated_at") == {
+ "label": "updated_at",
+ "type": IncrementalFieldType.DateTime,
+ "field": "updated_at",
+ "field_type": IncrementalFieldType.DateTime,
+ }
+
+ def test_type_and_field_type_stay_in_sync(self) -> None:
+ # The whole point of the helper: type == field_type, so they can't drift apart.
+ f = incremental_field("created", IncrementalFieldType.Date, label="Created")
+ assert f["label"] == "Created"
+ assert f["type"] == f["field_type"] == IncrementalFieldType.Date
+
+
+class TestBuildEndpointSchemas:
+ def test_matches_the_hand_written_loop(self) -> None:
+ # Equivalent to the loop copy-pasted across ~421 sources — output must be identical.
+ expected = [
+ SourceSchema(
+ name=e,
+ supports_incremental=INCREMENTAL_FIELDS.get(e) is not None,
+ supports_append=INCREMENTAL_FIELDS.get(e) is not None,
+ incremental_fields=INCREMENTAL_FIELDS.get(e, []),
+ )
+ for e in ENDPOINTS
+ ]
+ assert build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS) == expected
+
+ def test_endpoint_without_incremental_fields_is_full_refresh(self) -> None:
+ events = next(s for s in build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS) if s.name == "events")
+ assert events.supports_incremental is False
+ assert events.supports_append is False
+ assert events.incremental_fields == []
+
+ def test_names_filter_keeps_only_requested(self) -> None:
+ schemas = build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names=["invoices"])
+ assert [s.name for s in schemas] == ["invoices"]
+
+ def test_names_none_returns_all(self) -> None:
+ assert len(build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names=None)) == len(ENDPOINTS)
+
+ def test_append_only_disables_incremental_but_keeps_append(self) -> None:
+ charges = next(
+ s
+ for s in build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, append_only={"charges"})
+ if s.name == "charges"
+ )
+ assert charges.supports_incremental is False
+ assert charges.supports_append is True
+
+ def test_merge_only_disables_append_but_keeps_incremental(self) -> None:
+ charges = next(
+ s
+ for s in build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, merge_only={"charges"})
+ if s.name == "charges"
+ )
+ assert charges.supports_incremental is True
+ assert charges.supports_append is False
+
+ def test_per_endpoint_metadata_overrides(self) -> None:
+ schemas = build_endpoint_schemas(
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+ descriptions={"charges": "A charge"},
+ should_sync_default={"events": False},
+ supports_webhooks={"invoices"},
+ )
+ by_name = {s.name: s for s in schemas}
+ assert by_name["charges"].description == "A charge"
+ assert by_name["events"].should_sync_default is False
+ assert by_name["invoices"].supports_webhooks is True
+ # unspecified endpoints keep the defaults
+ assert by_name["charges"].should_sync_default is True
+ assert by_name["charges"].supports_webhooks is False
+
+
+class TestAuthNonRetryableErrors:
+ def test_host_scoped_keys_match_requests_error_text(self) -> None:
+ # Keys must be substrings of the real `raise_for_status()` message, or non-retryable
+ # matching silently fails and bad-credential jobs retry forever.
+ host = "https://api.example.com"
+ errors = auth_non_retryable_errors(host, service="Example")
+ assert f"401 Client Error: Unauthorized for url: {host}" in errors
+ assert f"403 Client Error: Forbidden for url: {host}" in errors
+ unauthorized_message = errors[f"401 Client Error: Unauthorized for url: {host}"]
+ assert unauthorized_message is not None and "Example" in unauthorized_message
+
+ def test_host_agnostic_default(self) -> None:
+ errors = auth_non_retryable_errors()
+ assert set(errors) == {"401 Client Error", "403 Client Error"}
+
+
+class TestValidateViaProbe:
+ @parameterized.expand([(200, True), (204, False), (401, False), (403, False), (500, False)])
+ def test_status_mapping(self, status: int, expected_valid: bool) -> None:
+ response = Mock(status_code=status)
+ session = Mock()
+ session.get.return_value = response
+ valid, code = validate_via_probe(lambda: session, "https://api.example.com/ping")
+ assert (valid, code) == (expected_valid, status)
+
+ def test_custom_ok_statuses(self) -> None:
+ session = Mock()
+ session.get.return_value = Mock(status_code=204)
+ valid, code = validate_via_probe(lambda: session, "https://x", ok_statuses=(200, 204))
+ assert (valid, code) == (True, 204)
+
+ def test_transport_error_maps_to_false_none(self) -> None:
+ session = Mock()
+ session.get.side_effect = requests.ConnectionError("boom")
+ assert validate_via_probe(lambda: session, "https://x") == (False, None)
+
+ def test_any_exception_maps_to_false_none(self) -> None:
+ # A credential probe must never raise out of validate_credentials — matches the broad
+ # `except Exception` the hand-rolled source probes use, so the helper is a drop-in.
+ def boom() -> Mock:
+ raise ValueError("session build failed")
+
+ assert validate_via_probe(boom, "https://x") == (False, None)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/source.template b/products/warehouse_sources/backend/temporal/data_imports/sources/source.template
index 2eff72d7e320..4dadf6c4d4cd 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/source.template
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/source.template
@@ -1,17 +1,17 @@
-# 1. TODO: add a new value for your source in the following three places:
-# - ExternalDataSourceType at `posthog/warehouse/types.py`
-# - ExternalDataSourceType at `posthog/schema.py`. this is only needed so type checking doesn't initially fail
+# 1. TODO: add a new value for your source in these TWO hand-edited places:
+# - ExternalDataSourceType at `products/warehouse_sources/backend/types.py`
+# (models.TextChoices: `KEY = "PascalValue", "PascalValue"`, KEY is ALL_CAPS with NO underscores)
# - externalDataSources at `frontend/src/queries/schema/schema-general.ts`
-#
-# following the casing conventions for each file whether ALL_CAPS_WITH_UNDERS, PascalCase, or
-# lower-kebab-case
+# (PascalCase string, identical to the types.py value — NOT kebab-case)
+# Do NOT hand-edit `posthog/schema.py` / `posthog/schema_enums.py` — `pnpm run schema:build`
+# (step 12) regenerates the ExternalDataSourceType enum there from schema-general.ts.
# 2. TODO: run django migrations with `DEBUG=1 python manage.py makemigrations && DEBUG=1 ./bin/migrate`
# 3. TODO: change the name of your source class from TemplateSource
# 4. TODO: update the return value of source_type to match the ExternalDataSourceType you created in step one
-# 5. TODO: update ExternalDataSourceType in `posthog/schema.py` to include your
-# source type as an enum value again, the key should be ALL_CAPS_WITH_UNDERS
-# and the value should be PascalCase
-# 6. TODO: update get_source_config(). update the name to match the SchemaExternalDataSourceType from step 5.
+# 5. NOTE: you do NOT hand-edit posthog/schema.py — `pnpm run schema:build` (step 12) regenerates the
+# SchemaExternalDataSourceType enum from your schema-general.ts entry (step 1). The member key is
+# derived automatically (PascalCase value -> ALL_CAPS_WITH_UNDERS key, e.g. GoogleAds -> GOOGLE_ADS).
+# 6. TODO: update get_source_config(). set the name to SchemaExternalDataSourceType.<YOUR_KEY> (generated in step 12).
# also add any config fields users will need to connect the source. see other sources for examples.
# set `category` to the closest DataWarehouseSourceCategory bucket (required — it groups the source in
# the new-source wizard catalog) and optionally `keywords` (search aliases). see other sources for examples.