Imported from posthog/posthog (
.agents/skills/implementing-warehouse-sources/SKILL.md). Install upstream withnpx skills add posthog/posthog --skill implementing-warehouse-sources. Copyright stays with the author.
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:
products/warehouse_sources/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.mdproducts/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md— a hand-kept inventory of how sources talk to their upstream (HTTP / vendor SDK / gRPC / DB protocol / webhook) and their tracked-transport state. Skim it to see how similar sources are wired. A new vendor does not add a line; see "SOURCES.md" below.products/warehouse_sources/backend/temporal/data_imports/sources/common/base.py— base classes (SimpleSource,ResumableSource,WebhookSource) and theFieldTypeunionproducts/warehouse_sources/backend/temporal/data_imports/sources/common/resumable.py—ResumableSourceManagerproducts/warehouse_sources/backend/temporal/data_imports/sources/common/webhook_s3.py—WebhookSourceManagerproducts/warehouse_sources/sources/chargebee/— the canonical reference for a new REST source. It uses the sharedrest_sourceframework (declarativeRESTAPIConfig+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. Readproducts/warehouse_sources/sources/klaviyo/orproducts/warehouse_sources/backend/temporal/data_imports/sources/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 withtype: "resolve"), also readproducts/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/__init__.pyandconfig_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.pyas the reference implementation.
Picking the right base class
Every new source must inherit from one (or a combination) of these:
SimpleSource[Config]— default for straightforward pull-based APIs where each run fully iterates the endpoint.ResumableSource[Config, ResumableData]— preferred for any new API-backed source whose underlying API supports resumption (cursor/link-header pagination, time windows, offset tokens, or any other deterministic way to pick back up where we left off). If the API gives us a next-page token, aLinkheader, or a stable time filter, useResumableSource. This lets Temporal resume after heartbeat timeouts without restarting from scratch.save_statestages the cursor in memory; the pipeline commits it to Redis (24h TTL) right after it writes the rows yielded so far.WebhookSource[Config]— only when the source can push events to us (e.g. Stripe webhook endpoints). Typically combined withResumableSourceso the initial backfill is resumable and subsequent deltas come via webhook.
Combine by multiple inheritance when both apply, e.g.:
class StripeSource(
ResumableSource[StripeSourceConfig, StripeResumeConfig],
WebhookSource[StripeSourceConfig],
OAuthMixin,
):
...
Rule of thumb:
- Pull-only API, no cursor we can persist →
SimpleSource. - Pull-only API with any cursor/next-page/time-filter we can save between runs →
ResumableSource. - Source can call us back with change events → add
WebhookSourceon top of whichever pull base fits. - Source's next run starts from a position only the source can compute, not the max of a column → add
CursorSource.
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.
- Define the cursor as a
@frozendataclass with acursor_kind: ClassVar[str]. Keep the kind stable, because a changed kind discards every stored cursor. Give fields added later a default, because a stored cursor that lacks a required field is discarded. - Implement
cursor_class(). Overridemerge_cursors(current, candidate)when a run that read less must not move the cursor back (Kafka keeps the per-partition max). Overridecursor_from_legacy()only when migrating state that was stored under other keys. - In
source_for_pipeline, callself.get_cursor_manager(inputs).load()returns the stored cursor, orNoneon a reset or a table rebuild.stage(cursor)hands the next cursor to the pipeline. - The pipeline persists the staged cursor only after the run's rows are durable (on v3, the loader promotes it with the final batch), and a reset clears it.
postgres/xmin_cursor.pyis the reference.
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 —
RESTClientdefaults tomake_tracked_session()and retries429+ transient5xxhonoringRetry-After. Notenacity, noRetryableError, 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_headersbuilder. - 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.
-
Survey the source. Pick the endpoints a user will actually want. Cross-reference:
- Airbyte: https://airbyte.com/connectors (connector pages often link to source code — useful reference)
- Fivetran: https://www.fivetran.com/connectors
- Stitch: https://www.stitchdata.com/docs/integrations/ 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.
-
Bootstrap the source. Copy the template and set the source key:
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__.pyThen set
SOURCE_KEYinsource.py. The key is aPascalCasestring (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 anExternalDataSourceTypemember: 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 optionalfeatureFlag="dwh-{source_name}".) -
Pick the base class (see above) and rename the class /
source_typereturn. -
Define
get_source_config— name, category (required — see "Source category & keywords"), label, caption, docsUrl, iconPath, fields, and optionalkeywords. 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 setcodebase_detection, as described in "Codebase detection". -
Register the source — nothing to edit. The loader finds
products/warehouse_sources/sources/{SOURCE_NAME}/source.pyby its directory, and the@SourceRegistry.registerdecorator on the class handles runtime registration. Keep the empty__init__.pyfiles in the vendor directory and intests/. -
Run the config generator:
pnpm run generate:source-configs. Confirm the new config class appears inproducts/warehouse_sources/sources/<your_source>/_config.py(one generated module per source; vendors that stay in the product getproducts/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/<your_source>.py, whose package__init__.pyis hand-written and never regenerated). Do not edit generated modules by hand. Every time you changeget_source_config.fields, re-run the generator. Then regenerate the field classification audit withDEBUG=1 python manage.py generate_source_field_classification. A test fails whenfield_classification.csvis out of date. If the CSV conflicts in a rebase, regenerate it. Do not merge it by hand. -
Swap the generic
Configtype insource.pyfor the generated{Source}SourceConfigclass. -
Implement:
validate_credentials,get_schemas,source_for_pipeline(plusget_resumable_source_manager/get_webhook_source_manageras needed). -
Split transport logic. Put API client, paginator, row normalization, and
SourceResponseassembly in{source}.py. Keep endpoint catalog/incremental fields/primary keys/partition defaults insettings.py. -
Add icon. Place it at
products/warehouse_sources/sources/{SOURCE_NAME}/icon.pngand seticonPath="/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. -
Nothing outside the vendor directory. A new vendor needs no migration, no
hogli build:openapirun and noSOURCES.mdline: the API publishes the source key as a plain string, and the wizard reads the catalog from the registry at runtime. Ifgit statusshows a change outsideproducts/warehouse_sources/sources/{SOURCE_NAME}/, find out why before you commit it. -
(Only when you change
source_config.pyitself) runhogli build:openapito regenerate the frontend and MCP API types from the source-config contract. -
Release status — a finished source has no
unreleasedSourceflag. The default for the deliverable this skill produces is nounreleasedSource— 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 withunreleasedSource=Truepre-set, so deleting that line is part of finishing the source — go ahead and remove it. (Why it matters:unreleasedSource=Truehides the connector from users entirely — the frontend filters out every source where it's truthy; seeInlineSourceSetup.tsxand the "coming soon / Notify me" path innonHogFunctionTemplatesLogic.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.BETAis for (a soft "new, still being validated" label on a visible source). The only timeunreleasedSource=Truelegitimately 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 workingget_schemas/source_for_pipelineand passing tests is finished — the flag comes out. Never write a test that assertsunreleasedSource 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:
- no
unreleasedSource(visible and connectable), releaseStatus=ReleaseStatus.BETAfor every new source — it is promoted toReleaseStatus.GA(orreleaseStatusomitted) once at least one customer sync completes and loads data — a soft label on a visible source, not a gate,- optional
featureFlag="dwh-{source_name}"(kebab-case) only if you want a controlled rollout to flagged users instead of releasing to everyone.
Whenever you set
releaseStatus, use theReleaseStatusenum fromproducts.warehouse_sources.backend.facade.source_config— never a bare string literal. AddReleaseStatusto your existing import block from that module. - no
-
Document the source. Write or update the user-facing doc on posthog.com following the
/documenting-warehouse-sourcesskill (template, shared snippets,<SourceParameters />+<SourceTables />). EnsuredocsUrlinget_source_configmatches the doc filename (kebab-case), and — ifget_schemasis a static endpoint catalog — setlists_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. -
Delete the template TODO comments before PR.
Source architecture contract
For API-backed sources, use this split:
source.py: source registration, source form fields, schema list, credential validation, resumable/webhook manager wiring, pipeline handoff.settings.py: endpoint catalog, incremental fields, primary key, partition defaults.{source}.py: API client/auth, paginator, request params, row normalization, andSourceResponse.
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:
- A boolean/value the API reads → add a flag on
_BaseSourcewith a safe default (likesupports_column_selection,connection_host_fields,has_managed_hogql_schema), and let the API branch on the flag. - Methods only some sources have (CDC, xmin, webhooks, custom manifests) → a capability mixin the source opts into; the API dispatches with
isinstance(source, <Capability>). - Direct-query engine behaviour (how a SQL engine resolves a table location, builds its
DataWarehouseTable, maps columns) is keyed on the engine, not the source type — dispatch onsource.direct_enginethrough the engine adapter/registry (posthog/hogql/direct_sql/for query concerns, thedata_warehouseengine registry for materialization), neversource_type.
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:
- endpoint-specific custom iterators (only when required),
- generic fan-out helper path,
- 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:
- Key entries by the endpoint/schema name
get_schemasreturns (matchesENDPOINTS), not the prefixed warehouse table name. - Source descriptions from the official API docs, not guesses. Partial coverage is fine — any
missing endpoint, column, or table-level
descriptionfalls back to the LLM, which is given the source name, endpoint,docs_url, and column data types. - Optional and only meaningful for fixed-schema sources. SQL sources (arbitrary user schemas) ship
nothing — the base hook returns
{}. - Don't touch
source.py/settings.pytransport logic — this is purely additive metadata.
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 " & "):
DATABASES— OLTP/OLAP databases, warehouses, data streams (Postgres, Snowflake, BigQuery, Kafka, …)FILE_STORAGE— object/file stores & file transfer (S3, Azure Blob, GCS, Google Drive, SFTP, …)ADVERTISING— ad platforms & mobile attribution (Google Ads, Meta Ads, Reddit Ads, Adjust, …)MARKETING___EMAIL— email/SMS/marketing automation (Klaviyo, Mailchimp, Braze, SendGrid, …)CRM— CRM & sales intelligence (HubSpot, Salesforce, Attio, Pipedrive, ZoomInfo, …)SALES— sales engagement/enablement, contracts (Salesloft, Outreach, Gong, DocuSign, …)CUSTOMER_SUPPORT— helpdesk/support/CX (Zendesk, Intercom, Freshdesk, Front, …)PAYMENTS___BILLING— payment processors & subscription billing (Stripe, Chargebee, PayPal, …)FINANCE___ACCOUNTING— accounting/ERP/expense/spend (QuickBooks, Xero, NetSuite, SAP ERP, …)ANALYTICS— product/web/marketing analytics & experimentation (Amplitude, Mixpanel, GA, …)ENGINEERING___MONITORING— dev tooling, CI, error/uptime monitoring, feature flags, identity/auth (GitHub, Datadog, Sentry, LaunchDarkly, Auth0, …)PRODUCTIVITY— project mgmt, docs, forms, scheduling (Notion, Airtable, Jira, Linear, Typeform, …)HR___RECRUITING— HRIS/ATS/payroll/people (Ashby, Greenhouse, BambooHR, Workday, Gusto, …)COMMUNICATION— messaging/meetings/telephony/social (Slack, Zoom, Microsoft Teams, Twilio, …)E_COMMERCE— online store/commerce (Shopify, WooCommerce, BigCommerce, …)
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:
-
The vendor exposes a real, pinnable API version — a URL path segment (
/v3/,/2/), a required version header value (a dated2022-11-28), a dated query/version param, or a named release. Declare all three: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:
- Write the request code against the newest GA version the vendor offers.
- 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-rcchannel, or a version whose docs are still marked preview.Examples already in the tree: Anthropic
("2023-06-01",)(datedanthropic-versionheader), ActiveCampaign("v3",)(/api/3path 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-versionskill's job, not this one. -
The vendor has no meaningful API versioning — set only
api_docs_url; leavesupported_versions/default_versionat the framework default (("v1",), theUNVERSIONED_API_VERSIONsentinel). A bare/v1/that has never changed and isn't a documented version choice is this case.
Rules:
default_versionmust equal the single entry insupported_versions, andapi_docs_urlmust behttps://.- Use the vendor's exact version string; never invent one.
- Never ship a new source on a version the vendor has already deprecated or given a sunset date. A brand-new
source with a
deprecated_versionsentry covering its only version is a bug — it means the source was written against the wrong version.test_source_versions.pyfails the build ifdefault_versionis deprecated. - Prefer an
api_docs_urlthat points at the vendor's versioning/changelog page over a generic API landing page — it's where the next version gets announced, and it's what the next person checks before repinning. - Don't hardcode a fallback version in the transport/request layer — resolve it from the source class
(
self.resolve_api_version(inputs.api_version)), which already falls back todefault_version. - Adding support for a new vendor version later, or deprecating an old one, is the
/warehouse-source-new-versionskill — 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.
SourceFieldInputConfig— basic input (text,email,number,password,textarea). Rendered as<LemonInput />.SourceFieldSwitchGroupConfig— toggle that reveals a sub-group of fields. Use for optional feature blocks.SourceFieldSelectConfig— dropdown. Options can carry sub-fieldsshown when selected (use for alternative auth methods — e.g. API key vs OAuth).SourceFieldOauthConfig— OAuth viaIntegrationmodel. See OAuth section.SourceFieldFileUploadConfig— file upload (JSON). Usekeys=["..."]allow-list or"*".SourceFieldSSHTunnelConfig— renders SSH tunnel sub-fields; addsssh_tunnel: SSHTunnelto the config with helpers.
Guidelines:
- Multiple auth methods →
SourceFieldSelectConfigwith childfieldsper option. - Optional toggles →
SourceFieldSwitchGroupConfig. - Confidential fields must use
SourceFieldInputConfigType.PASSWORD. The serializer derives sensitive vs nonsensitive keys automatically from the field definitions — you do not need to maintain an allow-list elsewhere.
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.
- Connection (the default): a value needed to authenticate or reach the third party. Examples are API keys, tokens, passwords, credential IDs (
aws_access_key_id,key_id), host, port, user, database name, account, tenant or project ids, region, base URLs, the SSH tunnel, TLS certificates and keys, auth-method selects and OAuth*_integration_idpointers. Connection values move to anIntegrationrow for the source, so do not read them from the model field directly. UseSourceInputsStore(below). - Reference: a pointer to an existing
Integrationrow, such asbing_ads_integration_id. EverySourceFieldOauthConfigfield is a reference, so you set no flag. The value stays injob_inputs. - Selector: an account chosen after the user authenticates, such as
account_id,customer_id,property_idorsite_url. Several sources can share one OAuth row, so the choice belongs to the source and stays injob_inputs. EverySourceFieldOauthAccountSelectConfigfield is a selector. For a plain input, select or switch group, setaccount_selector=True. The flag does not appear in the API payload or the generated types. A field inconnection_host_fieldsmust stay a connection field. - Sync setting: a value that only chooses what or how to sync. Examples are table or schema selection, a table prefix, start dates, file patterns and formats, delimiters,
repositoriesand filters. Setsync_setting=Trueon the field. The flag exists onSourceFieldInputConfig,SourceFieldSelectConfig,SourceFieldSwitchGroupConfigandSourceFieldOauthAccountSelectConfig. It is valid only on top-level fields. It does not appear in the API payload or the generated types. - Select with a reference option: for a select such as
auth_method, the stored value decides. If the chosen option holds only OAuth fields (oauth), the whole value is a reference. If the chosen option holds typed-in fields (api_key,pat), the whole value is a connection field. An option that mixes an OAuth field and a typed-in field is always a connection field. Keys of other options that are stored empty (Noneor"", asserialize_configleaves them) do not count; a populated one makes the whole value a connection field. - Runtime: state the server writes, not the user. Keys that start with
cdc_are runtime for every source. For other server-written keys, setruntime_job_input_keyson the source class (seeFileUploadSource).
Rules:
- When you are not sure, keep the default (connection). A setting stored as a connection field still works. A credential marked as a sync setting stays in plain source config.
- A field in
connection_host_fieldsmust stay a connection field. The invariant test fails otherwise. - Never set
sync_setting=Trueon a field that issecret=True, a password or a file upload. The invariant test fails otherwise. - Every new source and every field change needs the audit CSV regenerated (step 6 of the workflow). The command also rewrites
facade/credential_kinds.pyandfacade/credential_auth_types.py. - A source that has an OAuth field and an account id field must mark the account id field
account_selector=True. A test flags the unmarked ones by name.
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:
- The kind of the source's OAuth field (
SourceFieldOauthConfig.kind), at any depth. - Else the kebab-case source type (
AwsCloudTrailisaws-cloud-trail).
Override credential_kind in your source.py when the default is wrong:
- The source has the credential shape of an existing
Integrationkind (PostgresSourcereturnspostgresql,AmazonS3Sourcereturnsaws-s3). - Kebab-case splits a one-word brand name (
MySQLSourcereturnsmysql, notmy-sql). - The source has no credential kind. Return
None(CustomSourcedoes this).
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 reconcile_warehouse_source_credentials command checks that each *_integration_id field and each credentials_integration_id column points at an Integration row. When your source keeps its OAuth rows in another model, override integration_id_fields_point_at_integrations to return False (CustomSource does this).
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:
oauth: the source has an OAuth field and no typed-in connection field.token: the source has exactly one typed-in field, and it is a secret.credentials: every other source.
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, generate_source_field_classification 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 rerun the command with --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.
SourceInputsStore.load(source)gives all inputs as a new dict. Use it beforeparse_config.SourceInputsStore.load_many(sources)gives the inputs of many sources, keyed by source id. Use it on list paths.SourceInputsStore.load_settings(source)gives only the sync settings and runtime keys. It never gives a connection field. Use it for reads such asschemaorcdc_*keys on hot paths.SourceInputsStore.save(source, inputs)replaces all inputs and saves them. Use it for a credential write, for example a refreshed token. It also saves thecredentials_integration_idcolumn, so a sync that holds its source for a long time usesupdate_runtimeorupdate_oauth_inputsinstead.SourceInputsStore.assign(source, inputs)sets the inputs without a save. Use it when you save the model yourself in the same write.SourceInputsStore.create(inputs=..., **fields)creates a source.SourceInputsStore.update_runtime(source, updates, remove=...)sets or removes runtime keys and saves. It raisesValueErrorfor a key that is not a runtime key.- In async code, use
aloadandasave. loadraisesUnreadableSourceInputsErrorwhen the stored value is not a mapping. Catch it where the old code accepted a bad value.
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.
- The source points at its row with its
credentials_integration_idcolumn, not with a key in its inputs. The column holds the string form ofIntegrationReference(posthog/integrations/references.py): a decimal legacy id, or later a UUID. Never parse or format it yourself. WarehouseSourceCredentialsStore.createandupdateset the column on the source and do not save it. Save the source with its inputs in the same write:SourceInputsStore.saveandcreate, and a full model save, write the column.SourceInputsStore.update_runtimedoes not write it.- An OAuth source keeps its own
*_integration_idkey and gets no new row. Behind the dual-write flag, the column also holds that pointer. Account selectors stay injob_inputs, because several sources can share one OAuth row. - The row has the auth type that
facade/credential_auth_types.pyderives for the kind (tokenorcredentials). An OAuth-only source has no typed-in row. On a catalogue kind with an OAuth default, the row has a second auth type of that kind (stripetoken,githubtoken). The catalogue entry of the kind (posthog/integrations/catalogue.py) must support the derived auth type. If it does not, add the type there and runhogli build:projections --only integration-kinds. The testtest_every_typed_in_source_type_has_an_auth_type_its_kind_supportsfails otherwise. - The row has the marker
config["warehouse_source_type"]. The SDK writes the marker only throughIntegrationManager.source(kind), and the named accessors (IntegrationManager.stripe.token) and kind-limited pickers skip marked rows. Hog functions can never use a marked row as an input. - Rows are visible in the integrations list with their auth type, and several sources can use one row. An edit of a shared row raises
SharedCredentialsErrorunless the caller confirms. An edit of an identifying field of a shared row makes a new row. The source gives these fields with thecredential_identity_fieldsproperty on its class. The default isconnection_host_fieldsplus each generic name inGENERIC_IDENTITY_FIELDS(host,port,instance_url,connection_string,ssh_tunnel,user,username,account,account_id,account_sid) that the source declares, at any depth (Snowflake keepsuserunderauth_type). The compare skips the secrets insideconnection_string(it reads the scheme, user, hosts and database) and insidessh_tunnel(it readsenabled,host,portand the username), so a secret rotation asks for a confirmation and does not make a new row. Override the property in yoursource.pyonly when a different field says where the credentials connect, or as which account. - The store never deletes a row. A soft delete of a source does not read or change its row. A row that nothing uses stays in the integrations list.
products/warehouse_sources/backend/integration_usages.pyreports each source that points at a row, with itscredentials_integration_idcolumn (one indexed query) or a*_integration_idfield in its inputs. A source whose inputs do not decode counts as a user of every OAuth row of its credential kind, with the usage typeunreadable_warehouse_source, but not of a typed-in row, because the column always reads. Such a user blocks a delete only. It does not make an edit of the row shared. The SDK reads the usages forusages, anddeleteraisesIntegrationInUsewhile a source uses the row. The integrations API returns that as a 400.- Never query these rows in source code, and do not call the credentials store from source code. Use
SourceInputsStore, which will use the credentials store internally. The Custom source keeps itsjob_inputsas they are. - When the team has the
warehouse-source-credentials-dual-writeflag,save,asave,assignandcreatekeep thecredentials_integration_idcolumn in step with the inputs they write. The column holds the one row that the source uses:- An OAuth source: the row that its in-use
*_integration_idinput points at. The source class finds it within_use_oauth_pointer(see "OAuth pointers" below). A source whose selected options hold an OAuth field gets no typed-in row, also when it has typed-in fields next to it (Pardotenvironment). - A source with typed-in connection fields: the credentials row. The first copy creates the row and sets the column. Later copies update the row. The copy reads the stored column under the source lock, so a writer that holds an old instance does not make a second row.
- Any other source (for example a select switched away from both): no reference.
- With the flag off, the column keeps its value. Only the API reference pick (below) changes it.
update_runtimeandupdate_oauth_inputsnever write the column. Useupdate_oauth_inputsfor a token that an OAuth source refreshes in its inputs. A caller that saves withupdate_fieldsafterassignlists every field inSourceInputsStore.update_fields.job_inputsstays the source of truth until the team also has thewarehouse-source-credentials-readflag.
- An OAuth source: the row that its in-use
- A copy that would change a secret of a shared row skips the row and counts
shared_skip. A copy that changes an identifying field of a shared row makes a new row for this source instead. The source update API passesSharedCredentialsEdit.REFUSE, so the API returns a 409 with the other users unless the request sendsupdate_shared_credentials=true. The row then differs fromjob_inputs, so a read with the read flag on keepsjob_inputsand countsfallback_mismatch. The confirmed edit changes the shared row. The other sources keep their ownjob_inputscopy until their reads move to the row. A write that changes no stored value never needs a confirmation. - The source update API keeps the stored reference. A client can point the source at another row with
credentials_integration_idin the editedjob_inputs, only when the source can use that row (same team, kind and auth type, and a warehouse source row). Otherwise the API returns a 400. The API moves the value to the column, never intojob_inputs. This check runs also while the dual-write flag is off. When the client sets another row, the source adopts the connection fields of that row. The edit never writes its own connection fields into that row. - In async code, use
asave. A call toassignorsavein an event loop thread skips the copy. - When the team also has the
warehouse-source-credentials-readflag,load,aloadandload_manyreturn the connection fields from the row thatcredentials_integration_idpoints at, and the selectors, settings and runtime keys fromjob_inputs. A missing, unreadable or empty row falls back tojob_inputs. Whilejob_inputsstill holds the connection fields, a row whose values differ from them also falls back tojob_inputsand countsfallback_mismatch. A write that skipped the row (the dual-write flag was off, a shared row) makes such a difference. Always read the inputs withSourceInputsStore. Never readsource.job_inputsdirectly. - An OAuth source reads its pointer from the column with the same rule. While
job_inputsholds the pointer, the column is used only when it holds the same row. Otherwise the read keepsjob_inputsand countsfallback_oauth_mismatchorfallback_oauth_missing. Whenjob_inputsholds no pointer, the read puts the column value at the path of the OAuth field that the selected options use (in_use_oauth_slot). - In async code, use
aload. A call toloadin an event loop thread cannot read the row and returnsjob_inputs. - A loop that calls
loadonce per table of a source adds one row query per call. CallSourceInputsStore.preload(sources)first: it fetches the rows in one query per team and source type, and laterloadcalls on the same instances reuse them until a write through the store.
Stripped sources
An operator command strips each source after its credentials_integration_id column is verified. A source with typed-in credentials needs a column that points at a row with the same connection fields. An OAuth source needs a column that holds its in-use OAuth pointer. The command refuses a source without a reference (run the backfill first). 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. When the team has the warehouse-source-credentials-strip flag and both earlier flags, a new source with typed-in credentials or an OAuth pointer is stripped when it is created.
- On a stripped source,
job_inputson the model holds no connection field and no OAuth pointer. The row and the column are the only copy. Never write a connection field or an OAuth pointer tojob_inputsyourself. load,aloadandload_manymerge the row, the column andjob_inputsfor a stripped source, whatever the flags are. The OAuth pointer goes back at the path of the in-use OAuth field, so the parsed config and the API form do not change. The result never holds the marker key.- If the row is missing or cannot be read, or the column of an OAuth source holds no legacy id,
loadraisesSourceCredentialsMissingError, a subclass ofUnreadableSourceInputsError. It does not fall back tojob_inputs.load_manyleaves the source out of its result. - The sync maps this error to a non-retryable error that tells the user to enter the credentials again or reconnect the account. Do not catch it in source code, and do not retry it.
save,asave,assignandcreatewrite the connection fields of a stripped source only to the row, and its OAuth pointer only to the column. If the row write fails, the call raises beforejob_inputschanges. A change to a shared row raisesSharedCredentialsErrorunless the API request confirms it, because a skipped write would lose the change.update_runtimekeeps the marker. Write runtime keys only withupdate_runtime.- When a typed-in source would read as an OAuth source without its connection fields (Slack: a pasted token wins over its legacy pointer), the strip also sets the store key
connection_fields_stripped_typed_in, so the source stays typed-in. If yourin_use_oauth_slotoverride reads a connection field, it gets this for free; do not read the key in source code. - A stripped source in async code must use
aload. A call toloadin an event loop thread raises, because it cannot read the row andjob_inputshas no copy. list_sources_using_integrationand the integrations SDK usages find a stripped source by its column. The inputs search also sees a stripped OAuth source, becauseload_manyputs its pointer back.
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).
source.in_use_oauth_slot(job_inputs)gives the path of the OAuth field that the sync uses, with or without a value, or None. An OAuth field under an option that is not selected, or under a switch group that is off, is never in use, and a pointer there is stale.source.in_use_oauth_pointer(job_inputs)gives the pointer at that path, as anOAuthPointer(path and integration id), or None. The values parse asstr_to_optional_intdoes, so an int and a string of digits are equal.source.oauth_pointer_pathsgives every path that can hold a pointer, also the stale ones.- The default walks the form (
sources/common/oauth_pointers.py). It reads only the shape thatserialize_configwrites: a select as a mapping withselection, a switch group as a mapping withenabled. Any other shape (a flat legacy key, a select stored as a string) raisesOAuthPointerShapeError. Callers then leave the source alone. They never guess. - Override
in_use_oauth_slotandoauth_pointer_pathson your source class only for a pointer that no form field declares. Slack does this for its legacyslack_integration_id, which a pastedslack_access_tokenoverrides.
Backfill outcomes for legacy OAuth tokens
backfill_warehouse_source_credentials moves legacy OAuth tokens that sit in job_inputs into an OAuth Integration row.
A source opts in with two hooks on its class: has_legacy_oauth_tokens(job_inputs) (no network) and adopt_legacy_oauth(job_inputs) (can call the provider). HubSpot is the only source that uses them.
hubspot_legacy_adopted: the source hashubspot_secret_keyandhubspot_refresh_tokenand nohubspot_integration_id. With--execute, the command exchanges the refresh token, reads the hub id from HubSpot, and reuses thehubspotrow of the team for that hub id or creates one. It then setshubspot_integration_idand the column, and removes the two legacy keys. Preview only counts.reconcile_warehouse_source_credentials --verifyreports it aslegacy_oauth_tokens_in_job_inputs.skipped_legacy_token_unusable: HubSpot rejected the token, returned no hub id, or the inputs changed during the run. The command writes nothing. A later run tries again. Only a confirmed rejection of the refresh token (invalid_grant,BAD_REFRESH_TOKENorBAD_HUB) makes the grant unusable. Any other failure, such as a network error, a 408, a 429, a 5xx, a malformed body or a refusal of PostHog's app credentials (invalid_client), is a retryable error: the backfill counts it asfailed, and the cleanup command counts it asskipped_transient.
Cleanup of dead credentials
cleanup_dead_warehouse_source_credentials clears credentials that no sync can use. Some sources hold legacy OAuth tokens that HubSpot no longer accepts, or an integration pointer whose row is gone. These sources block a clean reconcile_warehouse_source_credentials --verify.
A source is dead only when both rules hold:
- Its credentials are dead. Either it holds legacy OAuth tokens (
has_legacy_oauth_tokens) andadopt_legacy_oauthraisesLegacyOAuthGrantUnusable, or its column or its in-use OAuth pointer names no integration row of the team. A source that still has a live reference is left alone. - No schema with
should_syncsynced in the last--idle-daysdays (default 30), and no schema is running.
Preview is the default and makes no network call. With --execute, the command takes the source lock, writes a backup with the model of the strip command, removes the legacy token keys (legacy_oauth_keys() of the source class) and the dangling pointers at their real paths, clears a dangling column, and sets the marker dead_credentials_cleared_at. It never deletes a source, a schema or a row. Output is counts only. Stripped sources are skipped.
- The backfill skips a marked source (
skipped_cleaned), andreconcile --verifytreats it as clean. restore_warehouse_source_connection_fieldsputs the backed-upjob_inputsback and removes the marker.- Do not write the marker key from source code.
SourceInputsStorehides it from readers and keeps it on save.
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
*Truncated - read the full file at https://github.com/posthog/posthog/blob/HEAD/.agents/skills/implementing-warehouse-sources/SKILL.md.*