Implementing warehouse sources

From PostHog/posthog · View interactive version

Implementing warehouse sources is an AI agent skill from the GitHub repository PostHog/posthog. Implement and extend PostHog Data warehouse import sources. Use when adding a new source under products/warehouse_sources/sources/ (or changing one there or under products/warehouse_sources/backend/temporal/data_imports/sources), adding datasets/endpoints to an existing source, or adding incremental

How to use this skill

Skill file

Implementing Data warehouse sources

Use this skill when building or updating Data warehouse sources. New sources go in the products/warehouse_sources/sources/ tree, one directory per vendor (products/warehouse_sources/sources/AGENTS.md). Shared code (common/) and the vendors that other code imports stay in products/warehouse_sources/backend/temporal/data_imports/sources/.

Read first

Before coding, read:

Picking the right base class

Every new source must inherit from one (or a combination) of these:

Combine by multiple inheritance when both apply, e.g.:

class StripeSource(
    ResumableSource[StripeSourceConfig, StripeResumeConfig],
    WebhookSource[StripeSourceConfig],
    OAuthMixin,
):
    ...

Rule of thumb:

Databases and file-transfer sources (SFTP, S3) stay on SimpleSource unless there's a clear reason otherwise.

Durable source cursors (`CursorSource`)

The incremental field covers the common case: the pipeline takes the max of a column and the next run filters above it.

Some positions are not a column max: a Postgres xmin ceiling captured before the read, or a set of Kafka partition offsets.

For those, add the CursorSource[CursorT] mixin from sources/common/cursor.py instead of new fields on SourceResponse or new keys in sync_type_config.

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:

429 + transient 5xx honoring Retry-After. No tenacity, no RetryableError, no fetch loop.

single_page, header_link, json_response (next-URL in body), cursor, offset, page_number.

(customer-owned client-credentials/refresh). Each redacts its own secrets — no _get_headers builder.

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.

  1. Survey the source. Pick the endpoints a user will actually want. Cross-reference:

Find the official API docs or OpenAPI spec, and work out the vendor's latest generally-available API version before you write any request code — that is the version the source must be built against. Check the vendor's changelog, versioning, or deprecation page, not just whichever page ranked first; docs sites routinely default to an older version, and Airbyte/Fivetran connectors are often years behind. See "Vendor API version metadata" for what counts as latest and what to do when the newest channel isn't GA.

  1. Bootstrap the source. Copy the template and set the source key:

```sh

mkdir -p products/warehouse_sources/sources/{SOURCE_NAME}

cp products/warehouse_sources/sources/source.template products/warehouse_sources/sources/{SOURCE_NAME}/source.py

touch products/warehouse_sources/sources/{SOURCE_NAME}/init.py

```

Then set SOURCE_KEY in source.py. The key is a PascalCase string (e.g. "AcmeCrm") that names the

source everywhere: it is stored on every source row, sent by the API, and used to find the vendor module.

Rules (a catalog invariant test checks them): letters and digits only, at most 128 characters, and

lowercased it equals the directory name without underscores (AcmeCrm -> acme_crm/). Do not add an

ExternalDataSourceType member: a new vendor has none, so the PR needs no migration and no regenerated

API types. Existing vendors keep their members. (The only kebab-case identifier in the flow is the

optional featureFlag="dwh-{source_name}".)

  1. Pick the base class (see above) and rename the class / source_type return.
  2. 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". When the source is released, also set codebase_detection, as described in "Codebase detection".
  3. Register the source — nothing to edit. The loader finds products/warehouse_sources/sources/{SOURCE_NAME}/source.py by its directory, and the @SourceRegistry.register decorator on the class handles runtime registration. Keep the empty __init__.py files in the vendor directory and in tests/.
  4. Run the config generator: pnpm run generate:source-configs. Confirm the new config class appears in products/warehouse_sources/sources/<your_source>/_config.py (one generated module per source; vendors that stay in the product get products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/<your_source>.py, whose package __init__.py is hand-written and never regenerated). Do not edit generated modules by hand. Every time you change get_source_config.fields, re-run the generator. Then regenerate the field classification audit, the credential kinds and the default auth types with hogli build:projections --only warehouse-source-fields. hogli build:projections --check fails in CI when field_classification.csv is out of date. If the CSV conflicts in a rebase, regenerate it. Do not merge it by hand.
  5. Swap the generic Config type in source.py for the generated {Source}SourceConfig class.
  6. Implement: validate_credentials, get_schemas, source_for_pipeline (plus get_resumable_source_manager / get_webhook_source_manager as needed).
  7. 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.
  8. Add icon. Place it at products/warehouse_sources/sources/{SOURCE_NAME}/icon.png and set iconPath="/static/warehouse-sources/{SOURCE_NAME}/icon.png" (see "Icons"). If the logo isn't already committed, fetch from Logo.dev — ask the user for the Logo.dev API key; do not hardcode one. Keep file size reasonable.
  9. Nothing outside the vendor directory. A new vendor needs no migration, no hogli build:openapi run and no SOURCES.md line: the API publishes the source key as a plain string, and the wizard reads the catalog from the registry at runtime. If git status shows a change outside products/warehouse_sources/sources/{SOURCE_NAME}/, find out why before you commit it.
  10. (Only when you change source_config.py itself) run hogli build:openapi to regenerate the frontend and MCP API types from the source-config contract.
  11. 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 InlineSourceSetup.tsx and the "coming soon / Notify me" path in nonHogFunctionTemplatesLogic.tsx.)

Deleting that line is mandatory, and it is not gated on anything you can't do in your environment. In particular, "I couldn't curl the live API" or "I couldn't verify against a real account" is NOT a reason to keep the flag — that is exactly what releaseStatus=ReleaseStatus.BETA is for (a soft "new, still being validated" label on a _visible_ source). The only time unreleasedSource=True legitimately stays is when the source physically cannot sync yet because it is being landed across several PRs and the implementing code isn't all there. A source with working get_schemas / source_for_pipeline and passing tests is finished — the flag comes out. Never write a test that asserts unreleasedSource is True — that locks the bug in and is what kept 166 finished sources hidden until they had to be released in bulk.

So a newly finished, tested source ships with:

Whenever you set releaseStatus, use the ReleaseStatus enum from products.warehouse_sources.backend.facade.source_config — never a bare string literal. Add ReleaseStatus to your existing import block from that module.

  1. Document the source. Write or update the user-facing doc on posthog.com following the

/documenting-warehouse-sources skill (template, shared snippets, <SourceParameters /> +

<SourceTables />). Ensure docsUrl in get_source_config matches the doc filename

(kebab-case), and — if get_schemas is a static endpoint catalog — set

lists_tables_without_credentials = True (see below) so the doc's Supported tables section

renders. A finished source ships with a consistent doc, not a stub.

  1. Delete the template TODO comments before PR.

Source architecture contract

For API-backed sources, use this split:

This keeps endpoint behavior declarative and easy to extend.

Source behaviour goes in the source, never in the API layer

The warehouse_sources presentation layer (products/warehouse_sources/backend/presentation/views/external_data_source.py, external_data_schema.py) must stay source-agnostic.

Do not add if source_type == ExternalDataSourceType.X / source.is_direct_<engine> branches there — a CI guard (.github/scripts/check-dwh-source-agnostic.py) blocks new ones.

When a source needs behaviour the API must invoke, expose it on the source instead:

Keep source-domain semantics (how to talk to the engine, how it names things, whether filters push down) on the source; the warehouse-domain work it drives (DataWarehouseTable rows, managed viewsets, hog functions) stays in data_warehouse, keyed off what the source or adapter returns.

Source capabilities never import data_warehouse types.

See products/data_warehouse/backend/presentation/README.md.

For REST sources that mix top-level and fan-out endpoints, keep endpoint metadata in settings.py and route in {source}.py with this priority:

  1. endpoint-specific custom iterators (only when required),
  2. generic fan-out helper path,
  3. top-level endpoint path.

Canonical descriptions (semantic enrichment)

After a table syncs, a background activity (workflow_activities/enrich_table_semantics.py) writes

WarehouseColumnAnnotation rows describing each table/column, surfaced to the AI agent. For

fixed-schema sources (SaaS APIs) the schema is the same for everyone, so document it once from the

official API docs instead of paying an LLM to re-derive it per team. These curated descriptions are

authoritative — they're applied directly (description_source="canonical") and never sent to the LLM.

Add a canonical_descriptions.py accompanying the source (sibling of source.py / settings.py):

# products/warehouse_sources/sources/{source}/canonical_descriptions.py
from products.warehouse_sources.sources.sdk import CanonicalDescriptions

CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
    "Charge": {  # key = ExternalDataSchema.name (the endpoint name from get_schemas / ENDPOINTS)
        "description": "A single attempt to move money into your account by charging a payment source.",
        "docs_url": "https://stripe.com/docs/api/charges",  # passed to the LLM for columns not covered here
        "columns": {  # column name -> one-line description, taken from the official API docs
            "id": "Unique identifier for the charge.",
            "amount": "Amount intended to be collected, in the smallest currency unit (e.g. cents).",
        },
    },
}

Then override the hook on the source class with a lazy import of the sibling file:

def get_canonical_descriptions(self) -> CanonicalDescriptions:
    from products.warehouse_sources.sources.{source}.canonical_descriptions import CANONICAL_DESCRIPTIONS
    return CANONICAL_DESCRIPTIONS

Rules:

prefixed warehouse table name.

missing endpoint, column, or table-level description falls back to the LLM, which is given the

source name, endpoint, docs_url, and column data types.

nothing — the base hook returns {}.

Publishing the table catalog to public docs

The posthog.com docs render a Supported tables section via a <SourceTables /> component fed by the

public_source_configs API, which calls get_documented_tables() on each source. The base

implementation lists tables from get_schemas (merged with canonical_descriptions) **only when the

source opts in**:

class MySource(SimpleSource[MySourceConfig]):
    lists_tables_without_credentials = True  # static endpoint catalog — safe for public docs

Set this to True only when get_schemas iterates a static endpoint catalog with no I/O — no

network, no DB, no credentials (the common fixed-schema SaaS pattern: for endpoint in ENDPOINTS). The

endpoint builds a placeholder config and calls get_schemas with no real credentials, so a source that

connects to discover schemas (SQL, file storage, MongoDB, ad platforms that list accounts) must leave

this False (the default) — otherwise it would try to connect to an empty host, hang, or close the DB

session. When False, the docs render a generic "discovered from your account" note instead.

The richer the table list, the better the docs — so pair this with canonical_descriptions.py

(table/column descriptions). Verify the rendered output via the API:

GET /api/public_source_configs → your source → tables.

Source category & keywords

Every source must set category on its SourceConfig — it groups the source in the new-source wizard

catalog (a category rail + tile grid). A test (tests/test_source_categories.py) fails if any registered

source has no category, so this is non-optional. A vendor in products/warehouse_sources/sources/ imports SourceConfig,

DataWarehouseSourceCategory from products.warehouse_sources.sources.sdk:

from products.warehouse_sources.sources.sdk import DataWarehouseSourceCategory, SourceConfig
...
return SourceConfig(
    name=self.source_type,
    category=DataWarehouseSourceCategory.PAYMENTS___BILLING,
    keywords=["billing", "subscriptions"],
    ...
)

Pick the single closest bucket. The enum members (note the triple underscore where the label has " & "):

The category list is backend-owned: DataWarehouseSourceCategory in

products/warehouse_sources/backend/facade/source_config.py is the source of truth, and hogli build:openapi

regenerates the frontend type from it. Adding a new category means editing that enum — don't invent

ad-hoc strings.

keywords is an optional list of lowercase search aliases — only add when the source has a common acronym or

alternate spelling a user might type (e.g. ["ga4", "ga"], ["sql server"], ["facebook ads"]). Skip it when

the name already obviously matches; don't add noise.

Codebase detection

A released source (no unreleasedSource=True) must set the codebase_detection class attribute. The PostHog wizard uses it to tell that a customer's codebase uses the vendor, to suggest the source and to spot PostHog alternatives.

Use detect(...) from products/warehouse_sources/backend/facade/codebase_detection.py. List the vendor's official SDK package names per ecosystem, the .env key names the vendor documents as anchored regexes, and any CDN host its script tag loads from.

The wizard creates the source from the terminal unless the source's fields need OAuth, a file upload or an account picker. Set the class attribute setup_requires_ui = True when users should still go to the app, for example because a credential is hard to find.

Use NOT_DETECTABLE when no package, key or script gives the vendor away. tests/test_codebase_detection.py fails for a released source without the attribute, and for an unreleased source with one.

The image build renders the declarations into the catalog the wizard downloads, so there is no generated file to update.

Self-driving Inbox candidacy (issues / tickets / conversations)

Some sources are also candidates for the Self-driving Inbox — the feature that watches a synced

table of _actionable records_ and emits findings into the PostHog Desktop Inbox. Shipped today: GitHub,

Linear, Zendesk, pganalyze, and Jira.

The signal is the table you sync, not the vendor: a source is an inbox candidate when one of its

tables is a stream of records a human (or agent) triages one by one — an issues, tickets, or

conversations table. These live under the support/helpdesk (CUSTOMER_SUPPORT), issue-tracker and

monitoring (ENGINEERING___MONITORING), and some project-tool (PRODUCTIVITY) categories. Analytics,

billing, ad-platform, CRM, and raw database sources are not inbox candidates — they sync facts to

query, not a work queue to act on. If the source you're building has no such table, there's nothing to

do here.

Wiring a source into the inbox is a separate, additive piece of work with its own skill —

/adding-inbox-sources — and it changes nothing in this skill's deliverable. It only becomes possible

once the data-warehouse source exists (which is exactly what this skill produces), so build and ship the

source first. That skill touches three surfaces: a server-side "signals scout" emitter plus a registry

entry and SignalSourceProduct enum in this repo (products/signals/backend/), the inbox UI in the

separate posthog/code repo, and the npx @posthog/wizard self-driving onboarding flow in

PostHog/context-mill. Read /adding-inbox-sources before starting — none of that plumbing belongs in

the source's own products/warehouse_sources/ code.

Vendor API version metadata

Every source declares three class attributes (on the source class body, alongside lists_tables_without_credentials)

describing the vendor's API version.

The framework (common/base.py) records the version each ExternalDataSource runs against so old pins keep working

and deprecations can be surfaced;

sources/tests/test_source_versions.py enforces the invariants below across every registered source, so a new

source that gets these wrong fails CI.

Two cases:

header value (a dated 2022-11-28), a dated query/version param, or a named release. Declare all three:

```python

class MySource(SimpleSource[MySourceConfig]):

supported_versions = ("v3",) # opaque vendor labels — never parsed or ordered

default_version = "v3" # stamped onto newly created sources; must be in supported_versions

api_docs_url = "https://vendor.example/docs/api" # API reference or changelog page (https, not the marketing site)

```

Build the source against the vendor's latest generally-available version, and pin that. A new source starts

on one version and every customer who connects it lands there, so shipping on an older version means shipping a

migration someone has to run later. Two rules, and they must agree:

1. Write the request code against the newest GA version the vendor offers.

2. Declare the version that code actually calls (the base URL path, a version header, or a version constant

in settings.py / {source}.py). Never declare a version the code doesn't send — that pin is a lie the

framework can't detect, and it makes the deprecation warnings and the upgrade path wrong for every customer.

If you can't reach the newest version — it's preview/beta/unstable/RC, it's gated behind an application or a

paid tier, or its response shapes aren't implemented yet — build against the newest GA version you can actually

call, pin that, and say why in a comment on the class. "Latest" means latest stable: don't pin Shopify's

unstable, a vendor's -rc channel, or a version whose docs are still marked preview.

Examples already in the tree: Anthropic ("2023-06-01",) (dated anthropic-version header),

ActiveCampaign ("v3",) (/api/3 path segment), Alguna ("2026-04-01",) (dated version header).

A source that later gains a second version declares them oldest→newest — GitHub ("2022-11-28", "2026-03-10"),

HubSpot ("v3", "2026-03") — but that's the /warehouse-source-new-version skill's job, not this one.

default_version at the framework default (("v1",), the UNVERSIONED_API_VERSION sentinel). A bare /v1/

that has never changed and isn't a documented version choice is this case.

Rules:

source with a deprecated_versions entry covering its only version is a bug — it means the source was written

against the wrong version. test_source_versions.py fails the build if default_version is deprecated.

it's where the next version gets announced, and it's what the next person checks before repinning.

(self.resolve_api_version(inputs.api_version)), which already falls back to default_version.

/warehouse-source-new-version skill — not this one.

Source fields (the form the user fills in)

Defined in get_source_config.fields. All field types live in products/warehouse_sources/backend/facade/source_config.py and are unioned as FieldType in products/warehouse_sources/backend/temporal/data_imports/sources/common/base.py.

Guidelines:

Connection fields vs sync settings

Each top-level key in a source's job_inputs has one kind. The kind decides where the value is stored. products/warehouse_sources/sources/common/job_input_classification.py resolves it. split_job_inputs returns the five parts, and merge_job_inputs joins them again without loss.

Rules:

Credential kind

Each source has a credential kind: the Integration kind that holds its typed-in credentials. It is at most 32 characters. The source gives it with the credential_kind property on its own class. The default on BaseSource is:

  1. The kind of the source's OAuth field (SourceFieldOauthConfig.kind), at any depth.
  2. Else the kebab-case source type (AwsCloudTrail is aws-cloud-trail).

Override credential_kind in your source.py when the default is wrong:

A subclass inherits the override of its parent, so a subclass of an overriding source sets its own kind (NeonSource returns neon, not the postgresql of PostgresSource).

The result is frozen in the generated file facade/credential_kinds.py (CREDENTIAL_KINDS), because a kind is stored data. Never change the kind of a released source. A test fails when the file is out of date, when a kind is longer than 32 characters, or when two source types share a kind.

Each credential kind also has a default auth type: the credential_auth_type property on the source class. The default on BaseSource (derive_credential_auth_type in products/warehouse_sources/sources/common/credential_auth_type.py) reads the connection fields:

Override credential_auth_type in your source.py only when this rule gives the wrong type for the source.

The result is frozen in facade/credential_auth_types.py (CREDENTIAL_AUTH_TYPES), because a row stores its auth type only when it is not the default. The product registers these kinds with the integrations SDK at startup. Read and write their rows with IntegrationManager.source(kind) from posthog.integrations. A kind that is also in the integrations catalogue (stripe, postgresql) keeps the default of the catalogue.

Both generated files are append-only. A new source adds its entry. A removed source keeps its entry, because rows of its kind can exist. When a change to a source would change a committed kind or default auth type, hogli build:projections fails and writes nothing. Keep the old value with an override in the source class. If the change is necessary, write a data migration for the stored rows first, then run DEBUG=1 python manage.py generate_source_field_classification --allow-changed-defaults.

Reading and writing `job_inputs`

Read and write a source's job_inputs only through SourceInputsStore (products/warehouse_sources/backend/logic/source_inputs.py). Code outside the product, and code in its presentation layer, imports it from facade/source_inputs.py. The store lets the connection fields move to their own storage without a change to your code.

The semgrep rule warehouse-source-inputs-go-through-store blocks source.job_inputs and job_inputs= on ExternalDataSource outside the store. Tests and migrations can still set the field directly.

Connection fields in an Integration row

A source's typed-in connection fields go to one Integration row of the source's credential kind (see "Credential kind"). WarehouseSourceCredentialsStore (products/warehouse_sources/backend/logic/source_credentials.py) is the only code that reads or writes these rows. It goes through the integrations SDK: IntegrationManager.source(kind).token or .credentials (posthog/integrations/manager.py). It never uses the Integration model directly.

Stripped sources

The store strips each new source, and each source that it updates, when the inputs hold typed-in connection fields or an OAuth pointer. It removes the connection fields, or the OAuth pointers (also stale ones under options that are not selected), from job_inputs and sets the store key connection_fields_stripped_at.

OAuth pointers

A source's OAuth field (SourceFieldOauthConfig, a *_integration_id input) can sit at the top level or inside an option of a select or a switch group (GitHub auth_method.github_integration_id, BigQuery auth_type.google_cloud_service_account_integration_id).

Implementing `source_for_pipeline`

Return a SourceResponse directly. Do not use dlt_source_to_source_response for new sources — DLT is being removed.

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.

Default to yielding raw dict / list[dict] and let the pipeline batch for you. The pipeline already runs a Batcher (pipelines/pipeline_v3/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/core/arrow_utils.py.

URL construction: use urllib.parse.urlencode for query strings. Don't use requests.Request(...).prepare().url — PreparedRequest.url is typed Optional[str] and the typical workaround (prepared.url or f"...") carries an unreachable fallback. urlencode is shorter, dependency-free, and produces identical output for ASCII-safe params.

Resumable source pattern

@dataclasses.dataclass
class MyResumeConfig:
    next_url: str  # or cursor, offset, time window — whatever the API uses

class MySource(ResumableSource[MySourceConfig, MyResumeConfig]):
    def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[MyResumeConfig]:
        return ResumableSourceManager[MyResumeConfig](inputs, MyResumeConfig)

    def source_for_pipeline(
        self,
        config: MySourceConfig,
        resumable_source_manager: ResumableSourceManager[MyResumeConfig],
        inputs: SourceInputs,
    ) -> SourceResponse:
        return my_source(..., resumable_source_manager=resumable_source_manager)

In the transport function:

resume = manager.load_state() if manager.can_resume() else None
url = resume.next_url if resume else initial_url

while True:
    data = fetch_page(url)
    next_url = data.get("links", {}).get("next")
    if next_url:
        manager.save_state(MyResumeConfig(next_url=next_url))  # stage before the yield it covers
    # yield batch
    if not next_url:
        break
    url = next_url  # advance before the next fetch, otherwise we loop on the same page

Save state before yielding the batch it covers. save_state only stages the cursor; the pipeline commits it to Redis once that batch is written, so a crash resumes exactly after the last written batch. Do not save after the yield. On a worker shutdown the pipeline ends the attempt before control returns to the source, so state saved after the yield is lost for the last batch: the next attempt reads that batch again (merge dedupes on primary key, a resumed full refresh appends it twice), and an attempt that writes one batch or fewer keeps no progress. A source with nothing yielded yet, such as one persisting an export job id before polling it, stages inside with manager.committing():, which commits when the block ends.

A saved cursor can commit only after the pipeline confirms it. The pipeline confirms when the source hands it the next item, ends, or reaches a safe point.

A cursor saved after the last yield therefore does not persist when the source raises, because the source can still hold rows that the cursor skips. The next attempt continues from the cursor of the last yield.

A source that ends its own attempt on a page or time budget calls manager.safe_point() directly before the raise, with its local buffer empty, to keep its last cursor.

Call manager.safe_point() wherever the source can make many requests that return no rows: an empty delta page, a fan-out parent with no children, a page with no comments.

The pipeline checks for a worker shutdown only when an item arrives, so a run of empty responses otherwise holds the worker for the whole graceful shutdown timeout, and its cursor never commits.

At a safe point the pipeline can hand the run to another worker, and it commits the staged cursor when nothing is waiting to be written.

Call it only where resuming from the staged cursor loses no rows: every row the cursor covers is already yielded, and none sits in a local buffer.

References: document_deltas in convex/convex.py, the sparse-sweep checkpoint in stripe/stripe.py, _page_fan_out in notion/notion.py.

The rest_source framework reaches a safe point after each page and before each retry wait on its own, but only when SourceResponse.items returns the framework's Resource directly. A source that wraps it gets no framework safe points, because the wrapper could buffer rows.

The same condition decides when a resume_hook runs. When items returns the Resource directly, the hook runs before the page reaches the pipeline, so a page and its cursor commit together and a hand-off repeats no rows. When a source wraps the Resource, the hook runs when the wrapper asks for the next page, so a hand-off reads the last page again. Return the Resource directly when you can: use data_map, add_map and add_filter for row changes. A wrapper that hands each page on unchanged and holds no rows can keep the framework behavior by returning Resource(wrapper, name=..., hints=resource._hints) (see the usage report in anthropic/anthropic.py).

Do not call safe_point() or commit() in a resume_hook.

The source contract

A worker that shuts down hands each running import to another worker. Every source with extraction code must make that possible:

  1. Bounded calls: each request has a read timeout, and one request with its retries and waits holds the worker for 5 minutes at most, also after a 429 with a large Retry-After.
  2. A safe point for each request: the source makes no more than 3 requests in a row with no yield and no safe point.
  3. Resume state is staged before the yield it covers.

sources/tests/test_source_contract.py runs each source in the registry against a fake HTTP server that stalls, rate-limits and returns empty pages. It compares the result with sources/tests/source_contract_baseline.txt, which lists each source that fails a condition or that the fake server cannot drive. A new source must pass; the baseline may only get shorter.

posthog/test/repo_invariants/test_warehouse_source_static_contract.py and test_resume_state_staged_before_yield.py check the same contract in the source text of every source: no raw time.sleep, no session call without timeout=, no wrapper around a framework Resource without a safe point, and no save_state after the yield.

pytest products/warehouse_sources/backend/temporal/data_imports/sources/tests/test_source_contract.py posthog/test/repo_invariants/test_warehouse_source_static_contract.py posthog/test/repo_invariants/test_resume_state_staged_before_yield.py

When a fix makes an entry wrong, regenerate the baseline and commit it:

SOURCE_CONTRACT_WRITE_BASELINE=1 pytest products/warehouse_sources/backend/temporal/data_imports/sources/tests/test_source_contract.py -p no:xdist
PYTHONPATH=. python posthog/test/repo_invariants/test_warehouse_source_static_contract.py
PYTHONPATH=. python posthog/test/repo_invariants/test_resume_state_staged_before_yield.py
Row order and `sort_mode`

SourceResponse.sort_mode says whether the rows of an incremental or append read are ordered:

It has no meaning for a full refresh. A full refresh can read in any order, and nothing requires it to sort.

The watermark does not depend on the value: it is the largest incremental value the run read, and the loader saves it when the run completes.

"asc" is a promise the pipeline relies on. After a worker shutdown, the next attempt of an "asc" run reads only the rows after the last value the earlier attempt queued. A row below that value that arrives later is never read, and the watermark then moves past it. A false "asc" loses rows silently. With None the interrupted run starts again from the stored watermark, which is always correct.

Before you set "asc", prove all of these:

  1. The order comes from the query or the API contract: an ORDER BY <incremental field> ASC, or an explicit ascending sort parameter on the incremental field. A default order that the vendor does not document is not proof.
  2. The run is one ordered series. Pages by another key (a primary-key keyset, an _id cursor), one request series per parent, account or partition, unsorted time windows, and an ordered query whose stored result is read back with no order do not qualify.
  3. The value is set per run, where the response is built. Say "asc" only on the read path that has the order, not on a keyset, partition, fallback or full refresh path of the same source.
  4. No fallback or retry in the generator drops the order, or starts the read again after rows were yielded.
  5. A test fails when the incremental query or request loses its sort, and a test asserts sort_mode for each read path.

When in doubt, leave None. The only cost is that an interrupted run starts again from the stored watermark.

Webhook source pattern

Multi-schema SQL database sources

SQL DB sources (Postgres, MSSQL, Snowflake, Redshift today) can import tables from every namespace (schema) in one connection: a blank namespace field discovers tables across all non-system namespaces, the wizard groups them by namespace, and sync writes one warehouse table per namespace.table. Reference implementation: postgres/postgres.py + PostgresImplementation; the shared seam lives in common/sql/.

The capability marker is the source's schema field being optional (required=False) in get_source_config — is_multi_schema_capable_sql_source() (products/data_warehouse/backend/sql_warehouse_migration.py) keys off it, so flipping the field optional is what turns on the viewset migration behavior. Treat None / "" / whitespace as "all namespaces" (normalize_namespace in common/sql/location.py) and never emit WHERE table_schema = ''.

Checklist for bringing a SQL source to multi-schema parity:

  1. Namespace field optional — required=False on the schema field, rerun pnpm run generate:source-configs. Keep database required: the database/catalog stays fixed per connection.
  2. Multi-namespace discovery — in get_columns, get_primary_keys, index/row-count/foreign-key helpers: when the namespace is blank, drop the WHERE table_schema = <ns> predicate (excluding system namespaces like information_schema, pg_catalog, sys) and return qualified display names (namespace.table). Keep the single-namespace fast path when the field is set.
  3. Implement get_source_metadata — return SourceMetadata(catalog_by_table, schema_by_table, table_name_by_table) keyed by the qualified display name. SQLSource.get_schemas stamps it onto each SourceSchema, and reconcile_schema_metadata persists it into ExternalDataSchema.sync_type_config["schema_metadata"].
  4. Per-row routing in build_pipeline — resolve (schema, table_name, response_name) with resolve_source_location (common/sql/location.py): per-row metadata → dotted-name self-heal → config namespace. Run SQL against the resolved schema + unqualified table; set SourceResponse.name = response_name (dwh_storage_key or schema.name, normalized) — never the bare table name, or the row's Delta path moves and orphans synced data.
  5. Thread the resolved namespace through every streaming/stats helper — table metadata, row stats, average row size, partition settings, chunk size, primary-key lookup all take (schema, table). Missing one degrades silently (no partitioning / wrong stats).
  6. Never feed a dotted display name to an identifier quoter — quote("a.b") yields one wrong identifier. Split into (schema, table) first and use quote_qualified (common/sql/identifiers.py).
  7. Naming layers are derived, never stored — display name analytics.users; S3/Delta subdir analytics_users (normalized response_name); HogQL table {prefix}_analytics_users. The one stored exception is dwh_storage_key, which pins a migrated legacy row to its original Delta path.
  8. Legacy migration is capability-driven, not source-type-gated — when a user clears the namespace on an existing single-schema source, sql_warehouse_migration.py renames rows to qualified form and stamps dwh_storage_key, preserving synced data with no re-sync. Don't add source_type == "..." branches to the shared layer.
  9. Tests — two namespaces with the same table name stay distinct end to end; blank-namespace discovery excludes system namespaces; per-row routing hits the right namespace; legacy single-namespace sources keep working; migrated rows keep their legacy Delta path.

Discovery cost: validate_credentials and database_schema run discovery with no name filter, so a blank namespace on a catalog with hundreds of schemas must not issue per-table queries per namespace — batch the listing queries or cap enumeration (see Snowflake's SHOW PRIMARY KEYS handling).

Outbound HTTP must go through the tracked transport

Every HTTP call from products/warehouse_sources/backend/temporal/data_imports/sources/** must go through make_tracked_session() (from

products.warehouse_sources.backend.temporal.data_imports.sources.common.http). The tracked session attaches team_id, source_type,

external_data_source_id, external_data_schema_id, and external_data_job_id to every outbound request's

log line and OTel metric, and participates in opt-in sample capture.

session.get/post/... instead of the module-level requests.get/... shortcuts.

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.

automatically; no change needed.

gspread authorize(credentials, session=...), BigQuery via AuthorizedSession + TrackedHTTPAdapter),

inject one. Reference patterns live in stripe/stripe.py, google_sheets/google_sheets.py, and

bigquery/bigquery.py.

# nosemgrep: data-imports-http-transport-... pragma with a one-line reason and record the source as

⚠️ Vendor SDK in SOURCES.md.

CI enforces this via .semgrep/rules/security/data-imports-http-transport.yaml. The rule bans direct requests.Session(),

requests.<verb>(...), and httpx.Client/AsyncClient/<verb> inside sources/**. Type-only imports

(from requests import Response, from requests.exceptions import HTTPError) remain allowed.

Outbound gRPC must go through the tracked gRPC transport

gRPC calls from sources/** ride client interceptors from

products.warehouse_sources.backend.temporal.data_imports.sources.common.grpc, which attach the same JobContext labels to logs and

OTel metrics (data_import_grpc_*) and feed opt-in sample capture (protobuf → scrubbed JSON). Two seams:

interceptors=tracked_interceptors(host) on every get_service call — google-ads rebuilds the channel

per call, so the interceptors must be re-supplied each time. Reference: google_ads/google_ads.py.

channel, wrap it with make_tracked_channel(channel, host=...), then hand it to the transport. Reference:

bigquery/bigquery.py:bigquery_storage_read_client.

CI enforces this via .semgrep/rules/security/data-imports-grpc-transport.yaml, which bans raw grpc.*_channel(...)

and direct BigQueryReadClient(...) / GoogleAdsClient(...) construction inside sources/** (outside the

common/grpc/ package and the two reference source files). Operators arm sample capture with

python manage.py warehouse_sources_capture_grpc_samples enable ....

SOURCES.md

products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md is a hand-kept inventory of

communication methods and tracked-transport state. Nothing reads it in code or CI. A new vendor does not

add a line to it, because a vendor PR touches only its own directory; the registry and the wizard catalog

are the list of sources. Update an existing entry only when you change that source's protocol or

tracked-transport state (for example a vendor SDK migrated to a tracked session).

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:

enabled_columns via SELECT projection.

otherwise filters are ignored.

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.

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

Shaping rows with the shared helpers

Do not write your own _flatten* function for these shapes.

Import the helper from products.warehouse_sources.sources.sdk.

The helpers are in common/row_shaping.py.

| Response shape | Helper |

| -------------------------------------------------------- | --------------------------------------------------------------------------- |

| JSON:API resource (id, type, attributes) | flatten_jsonapi(item, relationships_as_ids=True, on_clash="root") |

| One nested object to lift into the row (metadata) | lift_nested(row, key, on_clash="root") |

| Nested camelCase objects to parent_child columns | flatten_nested(obj, sep="_", key_fn=camel_to_snake, keep_raw=frozenset()) |

| One camelCase key to snake_case (AWS style, SOARecord) | camel_to_snake(name) |

Use the return value.

Keep the default "root" for a new source.

With "nested", a JSON:API attribute named id or type replaces the resource's id (the primary key) or type.

Set it to False to keep relationships as one JSON column.

Their values stay whole, as one JSON column.

Incremental sync guidance

Shared date and incremental-start helpers

Do not write a private _format_datetime, _to_epoch_ms or start-date resolver. Import the shared helpers from products.warehouse_sources.sources.sdk:

Do not test a cursor for truthiness (should_use_incremental_field and db_incremental_field_last_value). A 0 or "" cursor is a real value, so check is not None. resolve_incremental_start does this for you, and it raises ValueError for a cursor it cannot read.

If the API needs a format that no style gives, write a local helper. Do not add a rounding variant: rounding up can skip a row at the lower bound.

API behavior verification checklist

Before finalizing endpoint logic, verify from docs and with curl against the live API (not just docs — APIs frequently silently ignore unknown params or document outdated enums):

If undocumented, keep parsing/merge logic conservative and add a short code comment noting the uncertainty.

Endpoint inventory workflow

Top-level endpoints (org/account level)

Pagination tips

Retry and throttling strategy

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.

PostHog can't overspend a budget it doesn't own, so honoring 429 / Retry-After at the source is enough.

The exception is a credential PostHog owns and shares across processes — today that's the PostHog GitHub App installation token (many PostHog subsystems draw from one per-installation budget at once).

There, reactive backoff isn't enough: without coordination, concurrent PostHog callers collectively blow past the shared limit before any 429 comes back.

Those calls must route through CODE0 — a Redis-backed shared budget plus telemetry, gated by construction — never hand-rolled requests. Invoke /routing-outbound-api-calls before adding such a call.

The GitHub source is the reference: it keys the limiter on the GitHub App installation id (the budget owner in GitHub's own id space, not a PostHog DB row), and the customer-PAT path skips the limiter token-blind.

Raw calls to api.github.com are blocked by the github-api-calls-go-through-egress semgrep rule, so a GitHub-shaped source lands on the egress path by construction.

Deciding question is never "is this a warehouse source?" — it's "who owns the token, and could concurrent PostHog processes trample each other on it?"

Fan-out endpoints

Fan-out = iterate a parent resource, then query child endpoints per parent.

Prefer dependent resources for single-hop fan-out. Use rest_api_resources with a parent and child that declares type: "resolve" for the parent field. Shared infra (rest_source/__init__.py, config_setup.process_parent_data_item) paginates the parent and calls the child per parent row. Use include_from_parent so child rows carry parent fields (injected as _<parent>_<field> via make_parent_key_name).

Make fan-out declarative. Add a fan-out config object in settings.py (e.g. DependentEndpointConfig) with parent_name, resolve_param, resolve_field, include_from_parent, optional parent field renames, and optional parent endpoint params. Route single-hop fan-out through a shared helper (e.g. common/rest_source/fanout.py:build_dependent_resource).

Parent field rename mapping belongs in the helper. Callers should not branch on whether renames exist.

Per-endpoint pagination/selectors — build_dependent_resource supports endpoint overrides (parent_endpoint_extra, child_endpoint_extra for paginator / data_selector, page_size_param for non-limit size params).

Path pre-formatting: process_parent_data_item only does str.format() with the resolved param. Pre-format static placeholders with .replace() before passing to the resource config, so only the resolved placeholder remains.

Custom iterator only when fan-out is 2+ levels deep. Reuse the same pagination/retry helpers as elsewhere.

Reading the fan-out parent from the warehouse (`parent_source="warehouse"`)

[!IMPORTANT]

Not generally available — do not opt new sources in. The flag is limited to dogfood rollouts and the only wired caller is Sentry's issue_tag_values custom iterator, gated on an incremental watermark.

This section is here because the shared fan-out builder carries the machinery either way, so anyone changing fan-out internals needs to know the constraints. Treat the caveats below (windowed parents, ordered parents, non-REST callers) as unproven outside Sentry, and ask the data warehouse team before opting another source in.

By default a fan-out child re-fetches its parent endpoint on every sync — syncing issue_hashes re-pulls all of issues even when the issues schema already synced.

A child endpoint opts into warehouse parent reuse with parent_source="warehouse" on its DependentEndpointConfig:

the child then streams parent rows from the parent schema's already-synced Delta table (iter_parent_pages_from_warehouse in common/rest_source/warehouse_parent.py) instead of hitting the parent API.

Reference implementation: Sentry's issue_tag_values custom iterator calling the reader directly, warehouse-mode only when an incremental watermark bounds the scan.

Requirements and behavior:

Nothing in the API constrains the selection either: a child can be enabled without its parent, and a parent can be disabled or deleted while children sync. _warehouse_parent_reuse_available in import_data_activity_sync decides per run — a parent that is missing, disabled, not yet initially synced, or on any sync type other than merge or full refresh sends that run down the legacy parent-API path, so opting a child in can never break a schema that syncs today. A parent that is merely mid-sync does not force the fallback, because resolve_parent_table_ref pins the read to the parent's last completed snapshot via Delta time travel.

Never enable a parent as a side effect of enabling a child: parent syncs count toward the customer's billed rows.

The effective bound is usually invisible in our code, so classify empirically: run the listing against a real account with and without explicit bounds, compare counts, and check whether items outside the suspected bound still serve their child endpoints.

Such a source also skips the shared fan-out's telemetry, so call log_fanout_parent_rows_consumed (sources/common/fanout_telemetry.py) when its parent sweep ends, with the parent_source the run actually read from. Without that line nothing can compare the warehouse fan-out size against the API path's, which is the only detector for a parent that is missing rows the listing still returns.

OAuth configuration

Before implementing OAuth, check if the integration already exists — search the posthog/models/integration/ package loosely for the service name before concluding it's new.

The kinds live in model.py and the OAuth wiring in oauth.py; a provider only gets its own module when it carries business logic beyond the OAuth config, as Slack, GitHub, and Stripe do.

__init__.py only re-exports the public surface, so keep importing from posthog.models.integration but make edits in the defining module.

If new:

  1. Env vars. Add to posthog/settings/integrations.py:

```python

YOUR_SOURCE_CLIENT_ID = get_from_env("YOUR_SOURCE_CLIENT_ID", "")

YOUR_SOURCE_CLIENT_SECRET = get_from_env("YOUR_SOURCE_CLIENT_SECRET", "")

```

  1. Integration kind.

Read and write its rows through the integrations SDK, for example IntegrationManager.your_source.oauth.get(team_id, integration_id).

See posthog/integrations/README.md.

Raise NotImplementedError("<Source> app not configured") when the env vars are empty — that's the

fail-closed message, so code and charts can ship before the secret values exist.

This settings and oauth_config_for_kind() wiring is still required for the OAuth connect flow in the web app.

Source code that runs during a sync must read PostHog-owned credentials (client ids, client secrets, developer tokens,

service-account keys) with credentials_service.get_secret(s) from products/warehouse_sources/sources/common/credentials_service.py, not settings.X.

Resolve them inside the function that needs them, never at import time.

access-token JWT and set id_path / name_path from a claim (sub), mirroring the reddit/bing

branches in integration_from_oauth_response.

  1. Register the client + deploy the credentials. Registering the OAuth client with the provider,

the redirect URIs (US/EU/dev/localhost), the charts PR (wiring the env vars into both

posthog-django-shared-secrets for the web app and the worker's secret_env_app_specific store),

and writing the values into AWS Secrets Manager via the PostHog/secrets UI or CLI — plus which of these

an agent can vs. must not automate — are all in

references/oauth-app-deployment.md.

Non-retryable errors

Override get_non_retryable_errors() to mark errors that should permanently fail instead of retrying:

def get_non_retryable_errors(self) -> dict[str, str | None]:
    return {
        "401 Client Error: Unauthorized for url: https://api.example.com": "Your API key is invalid or expired. Please generate a new key and reconnect.",
        "403 Client Error: Forbidden for url: https://api.example.com": "Your API key does not have the required permissions. Please check the key permissions and try again.",
    }

Common cases: 401 Unauthorized, 403 Forbidden, invalid/expired tokens, OAuth tokens needing re-auth.

`validate_credentials`

Called with schema_name=None at source-create (one cheap probe to confirm the token is genuine) and with schema_name=<name> from the per-schema incremental_fields action (confirm scope for that specific endpoint).

If the API distinguishes 401 (bad token) from 403 (valid token, missing scope), accept 403 at source-create — users may legitimately only grant scopes for the endpoints they want to sync. Re-raise 403 only when schema_name is set. Sync-time 403s are handled separately by get_non_retryable_errors().

For per-table scope status in the schema picker, override get_endpoint_permissions(config, team_id, endpoints) -> {name: None | reason}: probe each endpoint and return None when reachable or a short reason when not. The database_schema action surfaces it as each table's permission_error, so the user sees which tables need extra scopes and deselects them — it must never block source-create. The base default reports everything reachable.

When you do surface a missing scope, name it — providers usually state it (`Required access: read_x access scope.), so parse that into your own message instead of dumping the raw exception or collapsing it to a bare table list. Probe whatever field the **sync query** needs (not just id`) so the per-table check reflects what syncing that table actually requires. Keep the probe narrow: only a real denial is a missing scope — a throttle, 5xx, or network blip is not, so route those through the retryable path rather than bucketing every exception as "missing permission".

Document required token scopes

If the API issues OAuth scopes or per-resource access tokens, declare every scope the source actually calls so users know what to grant — don't make them grant the full set defensively.

Connection host fields (credential retargeting)

If your source stores a secret (API token, password) and sends it to a host that the user configures in a

non-host field, declare that field on the source class's connection_host_fields property (from the

base source in common/base.py):

@property
def connection_host_fields(self) -> list[str]:
    # `okta_domain` is where the stored API token is sent; retargeting it must re-require the token.
    return ["okta_domain"]

The update serializer reads this list and forces the editor to re-enter the source's secrets whenever one of

these fields changes. Without it, an org member could PATCH the host field to a server they control while the

preserved (omitted) secret is reused — exfiltrating the credential. host and the SSH-tunnel target are

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_database_host_valid (common/mixins.py) at source-create time to block hosts

resolving to internal/private IPs. At connect time, open every direct database connection through

with_ssh_tunnel(), which re-checks the host on each open, and pin the validated addresses in the

client where the driver allows it (see pinned_host_kwargs in common/mixins.py).

Mixins

From products/warehouse_sources/backend/temporal/data_imports/sources/common/mixins.py:

Icons

Testing expectations

Read references/testing.md before you write a source test.

Source tests were about a fifth of the monorepo's test cases.

#113325 deleted most of them after per-test coverage showed they caught nothing.

The gate: before each test, name the runtime failure it catches that no other test catches.

If you cannot, do not write it. See /writing-tests for the general gate.

Do not write:

Write, in tests/test_<source>.py: a multi-page walk to the terminal page, incremental against full-refresh request shaping, the order the source yields when it sorts or windows rows itself, error mapping driven by a real vendor response through the transport, resume from saved state, and row shaping on edge-case inputs.

Add tests/test_<source>_source.py only for branches the source class takes itself.

A typical REST source needs one transport module of 10 to 25 parameterized cases.

Implementation checklist

Bootstrapping:
- [ ] SOURCE_KEY set in source.py (PascalCase, lowercased equals the directory name without underscores); no ExternalDataSourceType member
- [ ] Source directory at products/warehouse_sources/sources/<source>/ with empty __init__.py files (vendor dir and tests/)
- [ ] Class inherits from SimpleSource / ResumableSource / WebhookSource (or combo) — see "Picking the right base class"

Source implementation:
- [ ] Set category on get_source_config (required — DataWarehouseSourceCategory; groups the source in the wizard catalog)
- [ ] Add keywords if the source has a common acronym / alternate spelling (optional, lowercase)
- [ ] Set api_docs_url (https, vendor API docs/changelog); add supported_versions + default_version if the vendor
      exposes a real version token — pin what the code actually calls (see "Vendor API version metadata")
- [ ] Define source fields in get_source_config
- [ ] Implement validate_credentials
- [ ] Implement get_schemas
- [ ] Add endpoint settings (settings.py)
- [ ] Implement transport + paginator ({source}.py)
- [ ] Return SourceResponse with correct primary_keys, partitioning, sort_mode
      (keys unique table-wide — parent id in fan-out child keys; sort_mode verified against actual response order;
      incremental cursor pagination stops at the watermark)
- [ ] Implement get_resumable_source_manager if ResumableSource
- [ ] Implement webhook methods if WebhookSource
- [ ] Add get_non_retryable_errors for auth/permission errors
- [ ] (Fixed-schema sources) Add canonical_descriptions.py from the API docs + override get_canonical_descriptions
- [ ] (Fixed-schema sources, static get_schemas only) Set lists_tables_without_credentials = True so public docs render the table catalog

Tooling & assets:
- [ ] icon.png in the vendor directory, iconPath /static/warehouse-sources/<source>/icon.png (ask user for Logo.dev key if needed)
- [ ] Run `pnpm run generate:source-configs`
- [ ] Swap generic Config for generated {Source}SourceConfig in source.py
- [ ] `git status` shows changes only under products/warehouse_sources/sources/<source>/

Release status (a finished source has NO unreleasedSource flag — it hides the source from users entirely):
- [ ] REQUIRED: delete `unreleasedSource=True` from the finished source (the scaffolded stub ships with it).
      Not being able to curl the live API is NOT a reason to keep it — use releaseStatus=BETA.
      Keep it ONLY when the code genuinely can't sync yet (landed across multiple PRs).
- [ ] No test asserts `unreleasedSource is True` (that anti-pattern locks the source hidden)
- [ ] When set, releaseStatus uses the `ReleaseStatus` enum, never a string literal
- [ ] releaseStatus=ReleaseStatus.BETA for a new source
      (ReleaseStatus.GA or omit once a customer sync has completed and loaded data)
- [ ] featureFlag="dwh-{source_name}" ONLY if you want a controlled rollout instead of releasing to all

Tests & handoff:
- [ ] Tests follow references/testing.md: no declaration read-backs, no re-tested framework code, no duplicate coverage
- [ ] Source tests (test_<source>_source.py) — branches only, no declaration restatements
- [ ] Transport tests (test_<source>.py) — paginators, error mapping, request shaping
- [ ] User-facing doc written/updated per /documenting-warehouse-sources (docsUrl matches filename; `audit_source_docs` passes)
- [ ] `ruff check . --fix` and `ruff format .`
- [ ] List any new env vars (OAuth client IDs/secrets, etc) in the PR / handoff
- [ ] (Only if the source syncs an issues/tickets/conversations table) Note it as a Self-driving Inbox
      candidate — that's a separate follow-up via /adding-inbox-sources, not part of shipping the source

Validation and generation workflow

After changing source fields, re-run pnpm run generate:source-configs, then the targeted tests for the new source. Run ruff check . --fix and ruff format . on modified Python files.

Common pitfalls

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.