Skip to content

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

feat(data-warehouse): sync a table to destinations, starting with postgres (#86986)

Tom Owersc665d10c4248
diff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yaml
index 07c6da18e385..5d76420fd6fb 100644
--- a/.semgrep/rules/security/idor-team-scoped-models.yaml
+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml
@@ -182,10 +182,13 @@ rules:
|ExperimentSavedMetric
|ExportedAsset
|ExportedRecording
+ |ExternalDataDestination
|ExternalDataJob
|ExternalDataSchema
+ |ExternalDataSchemaDestination
|ExternalDataSchemaOOMEvent
|ExternalDataSource
+ |ExternalDataSourceDestination
|FeatureFlag
|FeatureRequest
|FeatureRequestAccountLink
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 159dc00ae8bf..b94b9bef2de6 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -2156,6 +2156,46 @@ snapshots:
hash: v1.k794b7964.a1866d682eb35809e8a9bea08ec0c7af8cb77581e4667745851bd9db5f49918d.mhIpdnK7yIoTFvovSR-wJrEHGV_7_T3eTvSNRv0UbtY
customer-analytics-custom-property-sync-runs--loading--light:
hash: v1.k794b7964.b376cab90219eb5e85b659c1399b40c0d60caf7a91b006c0d168375ed365d2af.61Y57PmrNuzzIfBps59FSyMmFnBf3yzKDcPD6vs5VHI
+ data-warehouse-destinationlist--both-selected--dark:
+ hash: v1.k794b7964.5da0169833ea8b87e6d903cb4fc0f4d629a1b1db09149c5fb7c450ef312641a0.MH4OyaTjM18a4cpxtpCHPVm1QWWajZL5cz4NlzbJag0
+ data-warehouse-destinationlist--both-selected--light:
+ hash: v1.k794b7964.a04d9a8cba7e3e7a4b16d0fd133b56d13252bbfde561fed7f83a1c1250c0fe3a.QLsXpO4tjZq831U9SXfJZXkcyn-XAcB3nbUbTS-1bMk
+ data-warehouse-destinationlist--empty--dark:
+ hash: v1.k794b7964.5b25d5e8ff014a4cb34ffcbfc7568fba8c19aadd692de77f37ec0970151d1eff.GE7T2nmnyyFVA1ZACg7wjJRx7eVZW5Ci4hK_P_iRC_o
+ data-warehouse-destinationlist--empty--light:
+ hash: v1.k794b7964.8241ee0362b2f6e0073de7f30f5c68afa47f4f23e313276d671bbf78ba91ae16.cRck4PSG75RYtojOnzBPN6f9aOLZ83w_l85Ej5iyHts
+ data-warehouse-destinationlist--inherited-from-source--dark:
+ hash: v1.k794b7964.c44f001cbc728edba036e401f6e284d3771a19a953c51a7aae1124096515f739.7BBFxPH7l4SOWD9KSIzfxgZFC_L4DOphrRTO0x-CP3o
+ data-warehouse-destinationlist--inherited-from-source--light:
+ hash: v1.k794b7964.8ea1a2db6498c4a2231dab1588b6aa597ce0ca5397d3d0ed4046992470aba010.EJx53hPzMGFBUAmL36EmpGmdU0DGn4c4sZwOfF-r0FQ
+ data-warehouse-destinationlist--loading--dark:
+ hash: v1.k794b7964.4c547e76477fd7c16c982f60a56ccda8227f3e879a4ca085c219547eb57dd47b.ZUTg5YvL_d_0vftz7fV8wEwsKx6gJKBfEsocNyW_MiE
+ data-warehouse-destinationlist--loading--light:
+ hash: v1.k794b7964.478218b655fde7084770f8fdddc604238523e073c3f55fc1d32082794e4a8b51.U7PeVHVYl24e9YeBMAZq_B6WuJHPqJc2gY9xzjvdpI0
+ data-warehouse-destinationlist--only-one-left--dark:
+ hash: v1.k794b7964.9b522de92c0ec0977626e3e694a64ceceda80fa691f50c490c906a06b012d0dd.ai1KpccNrHIv4qosfkQoeeTHQ1hkIw2rvoNF7Q3Yriw
+ data-warehouse-destinationlist--only-one-left--light:
+ hash: v1.k794b7964.e73d80636fa8aec2163ca81b6615ab5ae432296f391a74623cda19d1ab34f542.RCgSTjXC1oN6_ir0V3CST_szMCiJdf6beKhAr2rg4wA
+ data-warehouse-jobdestinations--destination-since-deleted--dark:
+ hash: v1.k794b7964.7850b437d0b757b20409473a16858b9ef875f35021e592521bdf94b2876e85c5.ix5aXJkl2sMIrSYeEmiT_OgH7Eb94qxUEEAt_DvutJk
+ data-warehouse-jobdestinations--destination-since-deleted--light:
+ hash: v1.k794b7964.1006a4fb83ff9f0134af7e919f30ca873aac4f04b8dfd068eb631717a884d43d.tkCjdAFZpkv34Y6e9vv--B5P7ZPcYHIGZJl6wb26oVc
+ data-warehouse-jobdestinations--none-recorded--dark:
+ hash: v1.k794b7964.dea76b53ba18d6bfe40ecb75b1a64fab690266a082624956d99f67a6e0b6ebf8.HDCVy9kwOdoEb5dCIc-6oAUhUJvUKTAjmtL4eVgm3_g
+ data-warehouse-jobdestinations--none-recorded--light:
+ hash: v1.k794b7964.08667ab1c9265093c965360b142e49375d4d501fb118aee7685c52400615a6f1.Cm1L_qMrAlW3V_unPXRb8OAryI5Fbw0cbxhxRQBrYSA
+ data-warehouse-jobdestinations--still-loading--dark:
+ hash: v1.k794b7964.dea76b53ba18d6bfe40ecb75b1a64fab690266a082624956d99f67a6e0b6ebf8.xA22JNcrso3fgiZdWGiwIW94beEQN4ka7hHIwybKxSo
+ data-warehouse-jobdestinations--still-loading--light:
+ hash: v1.k794b7964.08667ab1c9265093c965360b142e49375d4d501fb118aee7685c52400615a6f1.bxjUqKhDKWMtrbza8OwXaQIXuBIhI143eo-gxpQMGwY
+ data-warehouse-jobdestinations--two-destinations--dark:
+ hash: v1.k794b7964.0a813176ca0b1322fde4f0dc75b7b61e4b0a662caada85f5e13fb29aeeba79a6.BKy4UyuXgDzGGeKZUr630fJLrXSLelURHWq_2t1G3mU
+ data-warehouse-jobdestinations--two-destinations--light:
+ hash: v1.k794b7964.a59e6d22b31f379e6bbc6dc24d274293efc93df82f73d8c736df90af608f7e74.d1Gued6xNLNHXAJVTNJSBifeJY_VuoKvBjHVWDBe9aY
+ data-warehouse-jobdestinations--warehouse-only--dark:
+ hash: v1.k794b7964.d399de8f69dbd7b97698c047c094b96d9fd6e01656b231b2cf8180c04485cb03.t3DT8wXet-xFzPBD7EFBpn2_d3IoptfOQSMokIXtp_o
+ data-warehouse-jobdestinations--warehouse-only--light:
+ hash: v1.k794b7964.b5ce51491fcae6e2e4658221c1f8c48a34fe6d0582c90740d3e035606c6e3d6c.240aibJqTX7Ongo2jSSbRnagxCkDDa3O1OjYsT5ibME
data-warehouse-query-history-modal--empty--dark:
hash: v1.k794b7964.4c38283dea0ebc9b3e3e0aa03a05f6e4153bfe3550336ead008a187a43ddab4c.4ArpfVpkJGTdOVoU2PbGNjGH1Kzbq84osask8eFk-BA
data-warehouse-query-history-modal--empty--light:
@@ -6529,13 +6569,13 @@ snapshots:
scenes-app-data-warehouse-settings-api-version-deprecation-banner--without-sunset-date--light:
hash: v1.k794b7964.5538a3b913cdaf075ffa11b124181028792db175d494b4ddfc464b7c136abad1.lRLOGn7WM05iOpm8oCLLc5FkYge6teK_L_hm0JgjlLE
scenes-app-data-warehouse-settings-schemas--default--dark:
- hash: v1.k794b7964.e5106868c53498f94d35610999934e3af78ebc1470762c9cc5c3b59b78be5b97.N9Dz37JkAOg2wSfXUNmoaGWbCeqoiPwh4U5S0UZM1cs
+ hash: v1.k794b7964.e7a413df9cb3388523740737801eb45647588b41aa26b1af2591f1027bd7b111.q8e8BaNl6LJbRusi5AFHOEjEux6ITpXReNUkJAdaNFY
scenes-app-data-warehouse-settings-schemas--default--light:
- hash: v1.k794b7964.94544006edc718224777abda790cf5d6340c040b69aa3855e6cd5117de4c0fab.Rlu_iGXXV-vpljXOH6GfNsc_qALJMT3zBMRiTrOWfmE
+ hash: v1.k794b7964.62abbaebed2e50cc731d2816d8ff2ffd75665676c1d448039b77697b11cfda3d.yhKMeKZR4Sv4nIaEdQNjBtd1fGZhog5pIDHUUPJZlaU
scenes-app-data-warehouse-settings-schemas--multi-schema--dark:
- hash: v1.k794b7964.77017514db35e3e357c05f6fa22aa864ae0bd2bb0053228c76ff022048fd1e3e.cHJ3Ov8xzBvR7HOK-RjCpjW1SbNP-ZKdOneMjgvo1_U
+ hash: v1.k794b7964.a1f856f6850f014c67d316b6b991f7d22c6926162d98821b08381551ebb0210a.LckDFFHZtedM5hRnsCZUyHAPWA4_QRjE0RGlh39_65M
scenes-app-data-warehouse-settings-schemas--multi-schema--light:
- hash: v1.k794b7964.5ffdf524ce0fccb08b6337e373019c4f8601698dbd2ed67c236128731535cce0.dCP7dQzs_qdpEswIIblxlI6tpTWrpUNYGke67f_ZzHc
+ hash: v1.k794b7964.e5d678194a8e191fdf4f8a92cd7328f1e3cb162a81d3c4d05ef608f3c61537da.ZshlecoDn8CpsaVHaONi7UiXq8r-Xi4zJSWKeg7nAP0
scenes-app-data-warehouse-sql-editor--managed-warehouse-connection--dark:
hash: v1.k794b7964.4d87a8398ed4a62e9e18ef60f2e907fc8f1585d178833c8eacc34eb5b49cd7cf.jIj6nVJk8Wp1LwkjVO3t4AsK_U0iWUqtUVC6HzXz12g
scenes-app-data-warehouse-sql-editor--managed-warehouse-connection--light:
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index a6d49f8027a4..4da289a0ed1a 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -542,6 +542,7 @@ export const FEATURE_FLAGS = {
VISION_GOAL_BASED_CREATION_FLOW: 'vision-goal-based-creation-flow', // owner: #team-replay multivariate=control,test — gate on === 'test'; a truthy check turns on for control too
VISUAL_REVIEW: 'visual-review', // owner: #team-devex
WAREHOUSE_PERSON_PROPERTIES: 'warehouse-person-properties', // owner: @tomowers #team-warehouse-sources, gates warehouse -> person properties (person-target custom property sources)
+ WAREHOUSE_MULTI_DESTINATION: 'warehouse-multi-destination', // owner: #team-warehouse-sources
WEB_ANALYTICS_ACHIEVEMENTS: 'web-analytics-achievements', // owner: @jordanm-posthog #team-web-analytics
WEB_ANALYTICS_AGENT_ANALYTICS: 'web-analytics-agent-analytics', // owner: @jordanm-posthog #team-web-analytics
WEB_ANALYTICS_BACK_NAVIGATION_RESET: 'web-analytics-back-navigation-reset', // owner: @jordanm-posthog #team-web-analytics
diff --git a/frontend/src/scenes/integrations/postgresql/PostgreSQLSetupModal.tsx b/frontend/src/scenes/integrations/postgresql/PostgreSQLSetupModal.tsx
index 7efe980b044b..28d9c6b6891f 100644
--- a/frontend/src/scenes/integrations/postgresql/PostgreSQLSetupModal.tsx
+++ b/frontend/src/scenes/integrations/postgresql/PostgreSQLSetupModal.tsx
@@ -27,6 +27,14 @@ export const PostgreSQLSetupModal = (props: PostgreSQLSetupModalLogicProps): JSX
>
<Form logic={postgreSQLSetupModalLogic} props={props} formKey="postgreSQLIntegration">
<div className="gap-4 flex flex-col">
+ <LemonField
+ name="name"
+ label="Name"
+ info="What this connection is called wherever PostHog lists it. Optional — without one it shows the user and host."
+ >
+ <LemonInput placeholder="Customer database" />
+ </LemonField>
+
<LemonField name="host" label="Host">
<LemonInput placeholder="my-host" />
</LemonField>
diff --git a/frontend/src/scenes/integrations/postgresql/postgreSQLSetupModalLogic.ts b/frontend/src/scenes/integrations/postgresql/postgreSQLSetupModalLogic.ts
index e2a8a87a8221..a4f81f1b3176 100644
--- a/frontend/src/scenes/integrations/postgresql/postgreSQLSetupModalLogic.ts
+++ b/frontend/src/scenes/integrations/postgresql/postgreSQLSetupModalLogic.ts
@@ -20,6 +20,7 @@ export interface postgreSQLSetupModalLogicValues {
isPostgreSQLIntegrationValid: boolean
postgreSQLIntegration: {
host: string | null
+ name: string
password: string | null
port: number
ssl_mode: string
@@ -32,6 +33,7 @@ export interface postgreSQLSetupModalLogicValues {
postgreSQLIntegrationErrors: DeepPartialMap<
{
host: string | null
+ name: string
password: string | null
port: number
ssl_mode: string
@@ -48,6 +50,7 @@ export interface postgreSQLSetupModalLogicValues {
postgreSQLIntegrationValidationErrors: DeepPartialMap<
{
host: string | null
+ name: string
password: string | null
port: number
ssl_mode: string
@@ -65,6 +68,7 @@ export interface postgreSQLSetupModalLogicActions {
loadIntegrations: () => any // integrationsLogic
resetPostgreSQLIntegration: (values?: {
host: string | null
+ name: string
password: string | null
port: number
ssl_mode: string
@@ -74,6 +78,7 @@ export interface postgreSQLSetupModalLogicActions {
}) => {
values?: {
host: string | null
+ name: string
password: string | null
port: number
ssl_mode: string
@@ -95,6 +100,7 @@ export interface postgreSQLSetupModalLogicActions {
setPostgreSQLIntegrationValues: (
values: DeepPartial<{
host: string | null
+ name: string
password: string | null
port: number
ssl_mode: string
@@ -105,6 +111,7 @@ export interface postgreSQLSetupModalLogicActions {
) => {
values: DeepPartial<{
host: string | null
+ name: string
password: string | null
port: number
ssl_mode: string
@@ -125,6 +132,7 @@ export interface postgreSQLSetupModalLogicActions {
}
submitPostgreSQLIntegrationRequest: (postgreSQLIntegration: {
host: string | null
+ name: string
password: string | null
port: number
ssl_mode: string
@@ -134,6 +142,7 @@ export interface postgreSQLSetupModalLogicActions {
}) => {
postgreSQLIntegration: {
host: string | null
+ name: string
password: string | null
port: number
ssl_mode: string
@@ -144,6 +153,7 @@ export interface postgreSQLSetupModalLogicActions {
}
submitPostgreSQLIntegrationSuccess: (postgreSQLIntegration: {
host: string | null
+ name: string
password: string | null
port: number
ssl_mode: string
@@ -153,6 +163,7 @@ export interface postgreSQLSetupModalLogicActions {
}) => {
postgreSQLIntegration: {
host: string | null
+ name: string
password: string | null
port: number
ssl_mode: string
@@ -181,6 +192,7 @@ export const postgreSQLSetupModalLogic = kea<postgreSQLSetupModalLogicType>([
forms(({ props, actions, values }) => ({
postgreSQLIntegration: {
defaults: {
+ name: '' as string,
host: null as string | null,
port: 5432,
user: null as string | null,
@@ -201,11 +213,12 @@ export const postgreSQLSetupModalLogic = kea<postgreSQLSetupModalLogicType>([
}),
submit: async () => {
try {
- const { host, port, user, password, ssl_mode, use_system_ca, ssl_root_cert } =
+ const { name, host, port, user, password, ssl_mode, use_system_ca, ssl_root_cert } =
values.postgreSQLIntegration
const integration = await api.integrations.create({
kind: 'postgresql',
config: {
+ ...(name?.trim() ? { name: name.trim() } : {}),
host: host,
port: port,
user: user,
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index 1aa151541350..e73993596b9f 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -6445,6 +6445,8 @@ export interface ExternalDataSourceCreatePayload {
direct_query_enabled?: boolean
created_via: 'web' | 'api' | 'mcp'
payload: Record<string, any>
+ /** Destinations every table on the source writes to. Set at creation so the opening sync carries them. */
+ destination_ids?: string[]
}
/** Response of `POST warehouse_tables/upload_file` — the stored file a self-managed table is built from. */
@@ -6745,6 +6747,12 @@ export interface ExternalDataJob {
* runs the customer isn't charged for. `null` on legacy rows and means billable.
*/
billable?: boolean | null
+ /**
+ * Destinations this run delivered to, snapshotted when it started. Empty on runs that predate
+ * destinations, which wrote to the PostHog warehouse alone. `rows_synced` counts the rows read
+ * from the source once, not once per destination.
+ */
+ destination_ids?: string[]
}
export interface SimpleDataWarehouseTable {
diff --git a/posthog/models/activity_logging/activity_log.py b/posthog/models/activity_logging/activity_log.py
index 65b239a49d54..869050cb3abd 100644
--- a/posthog/models/activity_logging/activity_log.py
+++ b/posthog/models/activity_logging/activity_log.py
@@ -827,12 +827,17 @@ field_exclusions: dict[AuditableScope, list[str]] = {
# Reverse relation to a fail-closed model: reading through it in `changes_between` raises
# TeamScopeError when a source is saved outside request scope, and it isn't source-config intent.
"custom_oauth2_integrations",
+ # Same hazard: the destination set is edited through its own endpoint, not by saving a source.
+ "destination_links",
],
"ExternalDataSchema": [
"status",
"sync_type_config",
"latest_error",
"last_synced_at",
+ # Reverse relation to a fail-closed model — same hazard as the source's `destination_links`.
+ # Every sync saves the schema from a Temporal activity, where diffing it would raise.
+ "destination_links",
# Pipeline-assigned, not user intent. Diffing it resolves the FK through
# DataWarehouseTable.objects, whose manager adds two joins and a prefetch on every
# schema save (even ones that don't touch this field) — the extra queries have
diff --git a/posthog/models/integration/model.py b/posthog/models/integration/model.py
index 19bfc7623cd1..71d52c660575 100644
--- a/posthog/models/integration/model.py
+++ b/posthog/models/integration/model.py
@@ -281,6 +281,14 @@ class Integration(models.Model):
return self.config.get("email", self.integration_id)
if self.kind == "apns":
return self.config.get("bundle_id", self.integration_id)
+ if self.kind == Integration.IntegrationKind.POSTGRESQL:
+ # The derived id reads as "1-db.example.com-5432-postgres", so prefer a name the
+ # user chose. Falls back to host and user, which still beats the raw id.
+ if name := self.config.get("name"):
+ return name
+ host = self.config.get("host")
+ user = self.config.get("user")
+ return f"{user}@{host}" if user and host else f"ID: {self.integration_id}"
return f"ID: {self.integration_id}"
diff --git a/posthog/models/integration/postgres.py b/posthog/models/integration/postgres.py
index 8ff5222decbd..301b7b5ebdcf 100644
--- a/posthog/models/integration/postgres.py
+++ b/posthog/models/integration/postgres.py
@@ -109,6 +109,14 @@ class PostgreSQLServerIntegration:
if ssl_mode not in ("require", "verify-ca", "verify-full"):
raise common.IntegrationError("SSL mode must be one of: require, verify-ca, verify-full")
+ # Optional, and display only. It stays out of `integration_id` so that two connections to
+ # the same server under different names stay one integration.
+ name = config.get("name", None)
+ if name is not None:
+ if not isinstance(name, str):
+ raise common.IntegrationError("Name must be a string")
+ name = name.strip() or None
+
ssl_root_cert = config.get("ssl_root_cert", None)
if ssl_mode in ("verify-ca", "verify-full"):
if not ssl_root_cert:
@@ -118,10 +126,23 @@ class PostgreSQLServerIntegration:
if not isinstance(ssl_root_cert, str):
raise common.IntegrationError("SSL root certificate must be a string")
+ integration_id = f"{team_id}-{host}-{port}-{user}"
+
+ if name is None:
+ # `update_or_create` replaces the whole config, so a reconnect that omits the name
+ # would otherwise drop the one the user already chose.
+ name = (
+ model.Integration.objects.filter(
+ team_id=team_id, kind=cls.integration_kind, integration_id=integration_id
+ )
+ .values_list("config__name", flat=True)
+ .first()
+ )
+
integration, _ = model.Integration.objects.update_or_create(
team_id=team_id,
kind=cls.integration_kind,
- integration_id=f"{team_id}-{host}-{port}-{user}",
+ integration_id=integration_id,
defaults={
"config": {
"host": host,
@@ -129,6 +150,7 @@ class PostgreSQLServerIntegration:
"user": user,
"ssl_mode": ssl_mode,
"ssl_root_cert": ssl_root_cert,
+ **({"name": name} if name else {}),
},
"sensitive_config": {
"password": password,
diff --git a/posthog/tasks/usage_report.py b/posthog/tasks/usage_report.py
index eed781c7491d..b17b426cbf18 100644
--- a/posthog/tasks/usage_report.py
+++ b/posthog/tasks/usage_report.py
@@ -75,7 +75,8 @@ from products.tasks.backend.facade.billing import (
get_task_sandbox_usage_by_team,
)
from products.warehouse_sources.backend.facade.models import DataWarehouseTable, ExternalDataJob, ExternalDataSchema
-from products.warehouse_sources.backend.facade.types import ExternalDataJobStatus, ExternalDataSchemaStatus
+from products.warehouse_sources.backend.facade.types import ExternalDataSchemaStatus
+from products.warehouse_sources.backend.models.external_data_job import billable_destination_multiplier
logger = structlog.get_logger(__name__)
logging.getLogger(__name__).setLevel(logging.INFO)
@@ -2046,6 +2047,38 @@ def combine_posthog_code_credits(token_credits: int, compute_credits: int) -> in
dwh_pricing_free_period_start = datetime(2025, 10, 29, 0, 0, 0, tzinfo=UTC)
dwh_pricing_free_period_end = datetime(2025, 11, 6, 0, 0, 0, tzinfo=UTC)
+# A source's first week of syncing is free.
+NEW_SOURCE_FREE_WINDOW = timedelta(days=7)
+
+
+def _rows_synced_totals(
+ begin: datetime,
+ end: datetime,
+ source_age: Literal["any", "new_only", "established_only"],
+) -> list:
+ """Rows synced per team, counted once per destination the run delivered to.
+
+ A run is complete only once every destination has taken every batch, so multiplying by
+ the destination count snapshotted on the run is exact. Runs that predate destinations
+ carry a count of 1 and bill exactly as they did before.
+ """
+ filters = Q(
+ finished_at__gte=begin,
+ finished_at__lte=end,
+ billable=True,
+ status=ExternalDataJob.Status.COMPLETED,
+ )
+
+ if source_age != "any":
+ is_new = Q(pipeline__created_at__gte=end - NEW_SOURCE_FREE_WINDOW)
+ filters &= is_new if source_age == "new_only" else ~is_new
+
+ return list(
+ ExternalDataJob.objects.filter(filters)
+ .values("team_id")
+ .annotate(total=Sum(F("rows_synced") * billable_destination_multiplier()))
+ )
+
@timed_log()
@retry(tries=QUERY_RETRIES, delay=QUERY_RETRY_DELAY, backoff=QUERY_RETRY_BACKOFF)
@@ -2056,28 +2089,9 @@ def get_teams_with_rows_synced_in_period(begin: datetime, end: datetime) -> list
if begin >= dwh_pricing_free_period_end:
# after the free period, don't include rows reported in the free historical period
- return list(
- ExternalDataJob.objects.filter(
- ~Q(pipeline__created_at__gte=end - timedelta(days=7)),
- finished_at__gte=begin,
- finished_at__lte=end,
- billable=True,
- status=ExternalDataJobStatus.COMPLETED,
- )
- .values("team_id")
- .annotate(total=Sum("rows_synced"))
- )
+ return _rows_synced_totals(begin, end, source_age="established_only")
- return list(
- ExternalDataJob.objects.filter(
- finished_at__gte=begin,
- finished_at__lte=end,
- billable=True,
- status=ExternalDataJobStatus.COMPLETED,
- )
- .values("team_id")
- .annotate(total=Sum("rows_synced"))
- )
+ return _rows_synced_totals(begin, end, source_age="any")
@timed_log()
@@ -2085,28 +2099,9 @@ def get_teams_with_rows_synced_in_period(begin: datetime, end: datetime) -> list
def get_teams_with_free_historical_rows_synced_in_period(begin: datetime, end: datetime) -> list:
if begin >= dwh_pricing_free_period_start and begin < dwh_pricing_free_period_end:
# during the free period, all rows get reported as free historical rows synced
- return list(
- ExternalDataJob.objects.filter(
- finished_at__gte=begin,
- finished_at__lte=end,
- billable=True,
- status=ExternalDataJobStatus.COMPLETED,
- )
- .values("team_id")
- .annotate(total=Sum("rows_synced"))
- )
+ return _rows_synced_totals(begin, end, source_age="any")
- return list(
- ExternalDataJob.objects.filter(
- finished_at__gte=begin,
- finished_at__lte=end,
- billable=True,
- status=ExternalDataJobStatus.COMPLETED,
- pipeline__created_at__gte=end - timedelta(days=7),
- )
- .values("team_id")
- .annotate(total=Sum("rows_synced"))
- )
+ return _rows_synced_totals(begin, end, source_age="new_only")
@timed_log()
diff --git a/posthog/test/activity_logging/test_external_data_schema_activity_logging.py b/posthog/test/activity_logging/test_external_data_schema_activity_logging.py
index be90ea94c95f..832f33739436 100644
--- a/posthog/test/activity_logging/test_external_data_schema_activity_logging.py
+++ b/posthog/test/activity_logging/test_external_data_schema_activity_logging.py
@@ -19,7 +19,8 @@ class TestExternalDataSchemaActivityLogging(ActivityLogTestHelper):
self.assertIn("last_synced_at", external_data_schema_exclusions)
self.assertIn("status", external_data_schema_exclusions)
self.assertIn("table", external_data_schema_exclusions)
- self.assertEqual(len(external_data_schema_exclusions), 5)
+ self.assertIn("destination_links", external_data_schema_exclusions)
+ self.assertEqual(len(external_data_schema_exclusions), 6)
def test_external_data_schema_scope_in_activity_log_types(self):
self.assertIn("ExternalDataSchema", get_args(ActivityScope))
diff --git a/products/architecture.md b/products/architecture.md
index 07ba5f42416b..622718a8656c 100644
--- a/products/architecture.md
+++ b/products/architecture.md
@@ -120,6 +120,7 @@ There the class crosses for registration only, core drives only the registry's m
**The watched-models allowance** is the one further, deliberately temporary exception, for products whose models are load-bearing substrate that core and sibling products consume and cannot yet stop consuming.
Two products hold entries.
`warehouse_sources`: core HogQL reads its warehouse table/schema/source models to build queryable tables.
+`ExternalDataDestination`, `ExternalDataSourceDestination` and `ExternalDataSchemaDestination` cross for the same reason as the rest of the product's models — the destination CRUD `ModelViewSet` and the source-/schema-level link-table editors need the classes themselves for `Meta.model`, querysets, and edits to the link rows, not a read-only shape.
`product_analytics`: `Insight` and `InsightVariable`.
Core and seven products (alerts, dashboards, surveys, annotations, exports, customer_analytics, pulse) hold ForeignKeys or M2Ms into `Insight` — dashboard tiles, subscriptions and exported assets, sharing configurations, tagged items — and rely on cascade deletes, relation traversal, reverse relations, and queryset-typed access-control filtering that a frozen contract cannot express.
`InsightVariable` has no consumer left outside the product; its entry survives only because the SQL-variables `ModelViewSet` in `presentation/` needs the class and presentation may reach internals only through the facade, so retiring the entry means converting that viewset off `ModelSerializer` first.
diff --git a/products/data_warehouse/frontend/scenes/NewSourceScene/NewSourceScene.tsx b/products/data_warehouse/frontend/scenes/NewSourceScene/NewSourceScene.tsx
index dc65158058f7..9af307823943 100644
--- a/products/data_warehouse/frontend/scenes/NewSourceScene/NewSourceScene.tsx
+++ b/products/data_warehouse/frontend/scenes/NewSourceScene/NewSourceScene.tsx
@@ -39,12 +39,13 @@ import { FreeHistoricalSyncsBanner } from '../../shared/components/FreeHistorica
import { SourceIcon } from '../../shared/components/SourceIcon'
import { availableSourcesLogic } from './availableSourcesLogic'
import { BillingLimitNotice } from './components/BillingLimitNotice'
+import { DestinationStep } from './components/DestinationStep'
import { FileUploadSourceForm } from './components/FileUploadSourceForm'
import { SelfManagedSourceForm } from './components/SelfManagedSourceForm'
import { FILE_UPLOAD_SOURCE_NAME } from './fileUploadSource'
import { selfManagedSourceLogic } from './selfManagedSourceLogic'
import { SourceCatalog } from './SourceCatalog'
-import { type SourceWizardLogicProps, sourceWizardLogic } from './sourceWizardLogic'
+import { WIZARD_DESTINATION_STEP, type SourceWizardLogicProps, sourceWizardLogic } from './sourceWizardLogic'
export const getEffectiveAccessMethod = (
currentStep: number,
@@ -377,6 +378,8 @@ function InternalSourcesWizard(props: NewSourcesWizardProps): JSX.Element {
<WebhookSetupStep sourceWizardLogicProps={props.sourceWizardLogicProps} />
) : currentStep === 5 ? (
<ProgressStep />
+ ) : currentStep === WIZARD_DESTINATION_STEP ? (
+ <DestinationStep />
) : (
<UnknownWizardStepFallback currentStep={currentStep} onRestart={onClear} />
)}
diff --git a/products/data_warehouse/frontend/scenes/NewSourceScene/components/DestinationStep.tsx b/products/data_warehouse/frontend/scenes/NewSourceScene/components/DestinationStep.tsx
new file mode 100644
index 000000000000..77359800b003
--- /dev/null
+++ b/products/data_warehouse/frontend/scenes/NewSourceScene/components/DestinationStep.tsx
@@ -0,0 +1,80 @@
+import { useActions, useValues } from 'kea'
+import { useEffect } from 'react'
+
+import { IconPlusSmall } from '@posthog/icons'
+import { LemonButton } from '@posthog/lemon-ui'
+
+import { LemonBanner } from 'lib/lemon-ui/LemonBanner'
+
+import { DestinationList } from 'products/data_warehouse/frontend/shared/components/DestinationList'
+import { DestinationModal } from 'products/data_warehouse/frontend/shared/components/DestinationModal'
+import { destinationModalLogic } from 'products/data_warehouse/frontend/shared/logics/destinationModalLogic'
+
+import { destinationStepLogic } from './destinationStepLogic'
+
+export function DestinationStep(): JSX.Element {
+ const { destinations, destinationsLoading, selectedIds, hasLoaded } = useValues(destinationStepLogic)
+ const { loadDestinations, toggleDestination, selectDefault } = useActions(destinationStepLogic)
+
+ useEffect(() => {
+ // The warehouse is preselected once the list resolves, so a person who ignores this step
+ // gets what they would have got before destinations existed.
+ if (hasLoaded) {
+ selectDefault()
+ }
+ }, [hasLoaded]) // oxlint-disable-line react-hooks/exhaustive-deps
+
+ const modalProps = {
+ modalKey: 'wizard',
+ onSaved: (destination: { id: string }) => {
+ loadDestinations()
+ if (!selectedIds.includes(destination.id)) {
+ toggleDestination(destination.id)
+ }
+ },
+ onDeleted: (destinationId: string) => {
+ loadDestinations()
+ if (selectedIds.includes(destinationId)) {
+ toggleDestination(destinationId)
+ }
+ },
+ }
+ const { openForCreate, openForEdit } = useActions(destinationModalLogic(modalProps))
+
+ return (
+ <div className="deprecated-space-y-4">
+ <div className="flex gap-2 items-start justify-between">
+ <p className="max-w-prose">
+ Choose where this source writes its tables. Picking them now means the first sync already lands
+ there. Adding one later re-reads every table from the source to fill in the history.
+ </p>
+ <LemonButton
+ type="secondary"
+ icon={<IconPlusSmall />}
+ onClick={openForCreate}
+ data-attr="wizard-destination-new"
+ >
+ New destination
+ </LemonButton>
+ </div>
+
+ <DestinationList
+ destinations={destinations}
+ loading={destinationsLoading}
+ selectedIds={selectedIds}
+ onToggle={toggleDestination}
+ onEdit={openForEdit}
+ />
+
+ {!destinationsLoading &&
+ !selectedIds.some((id) => destinations.find((d) => d.id === id)?.type !== 'PostHogWarehouse') && (
+ <LemonBanner type="info">
+ This source will sync into PostHog only. Turn on another destination to also send its tables to
+ your own database.
+ </LemonBanner>
+ )}
+
+ <DestinationModal {...modalProps} />
+ </div>
+ )
+}
diff --git a/products/data_warehouse/frontend/scenes/NewSourceScene/components/destinationStepLogic.ts b/products/data_warehouse/frontend/scenes/NewSourceScene/components/destinationStepLogic.ts
new file mode 100644
index 000000000000..3272944178f1
--- /dev/null
+++ b/products/data_warehouse/frontend/scenes/NewSourceScene/components/destinationStepLogic.ts
@@ -0,0 +1,109 @@
+import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'
+import { loaders } from 'kea-loaders'
+
+import { teamLogic } from 'scenes/teamLogic'
+
+import { externalDataDestinationsList } from 'products/warehouse_sources/frontend/generated/api'
+import { ExternalDataDestinationApi } from 'products/warehouse_sources/frontend/generated/api.schemas'
+
+import { sourceWizardLogic } from '../sourceWizardLogic'
+import { defaultDestinationIds, toggleDestinationId } from './destinationStepUtils'
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface destinationStepLogicValues {
+ wizardDestinationIds: string[] // sourceWizardLogic
+ currentTeamId: number | null // teamLogic
+ destinations: ExternalDataDestinationApi[]
+ destinationsLoading: boolean
+ hasLoaded: boolean
+ selectedIds: string[]
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface destinationStepLogicActions {
+ setWizardDestinationIds: (destinationIds: string[]) => {
+ destinationIds: string[]
+ } // sourceWizardLogic
+ loadDestinations: () => any
+ loadDestinationsFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadDestinationsSuccess: (
+ destinations: ExternalDataDestinationApi[],
+ payload?: any
+ ) => {
+ destinations: ExternalDataDestinationApi[]
+ payload?: any
+ }
+ selectDefault: () => {
+ value: true
+ }
+ toggleDestination: (destinationId: string) => {
+ destinationId: string
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface destinationStepLogicMeta {
+ __keaTypeGenInternalSelectorTypes: {
+ selectedIds: (wizardDestinationIds: any) => string[]
+ }
+}
+
+export type destinationStepLogicType = MakeLogicType<
+ destinationStepLogicValues,
+ destinationStepLogicActions,
+ Record<string, any>,
+ destinationStepLogicMeta
+>
+
+export const destinationStepLogic = kea<destinationStepLogicType>([
+ path(['products', 'data_warehouse', 'frontend', 'scenes', 'NewSourceScene', 'destinationStepLogic']),
+ connect(() => ({
+ values: [teamLogic, ['currentTeamId'], sourceWizardLogic, ['wizardDestinationIds']],
+ actions: [sourceWizardLogic, ['setWizardDestinationIds']],
+ })),
+ actions({
+ toggleDestination: (destinationId: string) => ({ destinationId }),
+ selectDefault: true,
+ }),
+ loaders(({ values }: any) => ({
+ destinations: [
+ [] as ExternalDataDestinationApi[],
+ {
+ loadDestinations: async () => {
+ const response = await externalDataDestinationsList(String(values.currentTeamId))
+ return response.results ?? []
+ },
+ },
+ ],
+ })),
+ reducers({
+ hasLoaded: [
+ false,
+ {
+ loadDestinationsSuccess: () => true,
+ },
+ ],
+ }),
+ selectors({
+ // The wizard owns the picked set, so it survives stepping back and forth and is still
+ // there when the source is created.
+ selectedIds: [(s: any) => [s.wizardDestinationIds], (ids: string[]) => ids],
+ }),
+ listeners(({ values, actions }: any) => ({
+ toggleDestination: ({ destinationId }: { destinationId: string }) => {
+ actions.setWizardDestinationIds(toggleDestinationId(values.wizardDestinationIds, destinationId))
+ },
+ selectDefault: () => {
+ actions.setWizardDestinationIds(defaultDestinationIds(values.destinations, values.wizardDestinationIds))
+ },
+ })),
+ afterMount(({ actions }: any) => {
+ actions.loadDestinations()
+ }),
+])
diff --git a/products/data_warehouse/frontend/scenes/NewSourceScene/components/destinationStepUtils.test.ts b/products/data_warehouse/frontend/scenes/NewSourceScene/components/destinationStepUtils.test.ts
new file mode 100644
index 000000000000..33fe30d70362
--- /dev/null
+++ b/products/data_warehouse/frontend/scenes/NewSourceScene/components/destinationStepUtils.test.ts
@@ -0,0 +1,72 @@
+import { defaultDestinationIds, shouldShowDestinationStep, toggleDestinationId } from './destinationStepUtils'
+
+const WAREHOUSE = { id: 'wh', is_posthog_warehouse: true }
+const POSTGRES = { id: 'pg', is_posthog_warehouse: false }
+
+const visible = {
+ flagEnabled: true,
+ isDirectQueryMode: false,
+ schemas: [{ should_sync: true, sync_type: 'full_refresh' }],
+ requiredTables: undefined,
+} as Parameters<typeof shouldShowDestinationStep>[0]
+
+describe('destination step', () => {
+ describe('shouldShowDestinationStep', () => {
+ it('asks for destinations on an ordinary import', () => {
+ expect(shouldShowDestinationStep(visible)).toBe(true)
+ })
+
+ it.each([
+ ['the flag is off', { flagEnabled: false }],
+ ['the source is queried directly rather than imported', { isDirectQueryMode: true }],
+ ['a caller drives the wizard to a fixed table list', { requiredTables: ['charges'] }],
+ ])('does not ask when %s', (_label, override) => {
+ expect(shouldShowDestinationStep({ ...visible, ...override })).toBe(false)
+ })
+
+ it('does not ask when a table syncs by CDC, which stays warehouse-only', () => {
+ expect(
+ shouldShowDestinationStep({
+ ...visible,
+ schemas: [
+ { should_sync: true, sync_type: 'full_refresh' },
+ { should_sync: true, sync_type: 'cdc' },
+ ],
+ })
+ ).toBe(false)
+ })
+
+ it('still asks when a CDC table is present but not being synced', () => {
+ expect(
+ shouldShowDestinationStep({
+ ...visible,
+ schemas: [{ should_sync: false, sync_type: 'cdc' }],
+ })
+ ).toBe(true)
+ })
+ })
+
+ describe('defaultDestinationIds', () => {
+ it('starts on the PostHog warehouse, so skipping the step changes nothing', () => {
+ expect(defaultDestinationIds([POSTGRES, WAREHOUSE], [])).toEqual(['wh'])
+ })
+
+ it('keeps an existing choice, so stepping back and forth does not reset it', () => {
+ expect(defaultDestinationIds([POSTGRES, WAREHOUSE], ['pg'])).toEqual(['pg'])
+ })
+
+ it('selects nothing when the team has no warehouse destination row yet', () => {
+ expect(defaultDestinationIds([POSTGRES], [])).toEqual([])
+ })
+ })
+
+ describe('toggleDestinationId', () => {
+ it('adds one that is off', () => {
+ expect(toggleDestinationId(['wh'], 'pg')).toEqual(['wh', 'pg'])
+ })
+
+ it('removes one that is on', () => {
+ expect(toggleDestinationId(['wh', 'pg'], 'pg')).toEqual(['wh'])
+ })
+ })
+})
diff --git a/products/data_warehouse/frontend/scenes/NewSourceScene/components/destinationStepUtils.ts b/products/data_warehouse/frontend/scenes/NewSourceScene/components/destinationStepUtils.ts
new file mode 100644
index 000000000000..940d1019adc0
--- /dev/null
+++ b/products/data_warehouse/frontend/scenes/NewSourceScene/components/destinationStepUtils.ts
@@ -0,0 +1,48 @@
+import type { ExternalDataSourceSyncSchema } from '~/types'
+
+import { ExternalDataDestinationApi } from 'products/warehouse_sources/frontend/generated/api.schemas'
+
+export interface DestinationStepVisibility {
+ flagEnabled: boolean
+ isDirectQueryMode: boolean
+ schemas: Pick<ExternalDataSourceSyncSchema, 'should_sync' | 'sync_type'>[]
+ /** Set when a caller (e.g. signals setup) drives the wizard to a fixed table list. */
+ requiredTables: unknown
+}
+
+/** Whether the wizard should ask for destinations before creating the source. */
+export function shouldShowDestinationStep({
+ flagEnabled,
+ isDirectQueryMode,
+ schemas,
+ requiredTables,
+}: DestinationStepVisibility): boolean {
+ if (!flagEnabled || isDirectQueryMode || requiredTables) {
+ return false
+ }
+ // CDC ticks a final batch continuously, so it has no run-scoped commit for a destination to
+ // publish, and stays warehouse-only.
+ return !schemas.some((schema) => schema.should_sync && schema.sync_type === 'cdc')
+}
+
+/**
+ * What the step starts with selected.
+ *
+ * The PostHog warehouse, so a person who steps past this gets what they would have got before
+ * destinations existed. An existing choice is left alone, so stepping back and forth keeps it.
+ */
+export function defaultDestinationIds(
+ destinations: Pick<ExternalDataDestinationApi, 'id' | 'is_posthog_warehouse'>[],
+ current: string[]
+): string[] {
+ if (current.length > 0) {
+ return current
+ }
+ const warehouse = destinations.find((destination) => destination.is_posthog_warehouse)
+ return warehouse ? [warehouse.id] : []
+}
+
+/** Adding or removing one destination from the picked set. */
+export function toggleDestinationId(current: string[], destinationId: string): string[] {
+ return current.includes(destinationId) ? current.filter((id) => id !== destinationId) : [...current, destinationId]
+}
diff --git a/products/data_warehouse/frontend/scenes/NewSourceScene/sourceWizardLogic.tsx b/products/data_warehouse/frontend/scenes/NewSourceScene/sourceWizardLogic.tsx
index 1affa435e786..5d376c13c4e3 100644
--- a/products/data_warehouse/frontend/scenes/NewSourceScene/sourceWizardLogic.tsx
+++ b/products/data_warehouse/frontend/scenes/NewSourceScene/sourceWizardLogic.tsx
@@ -10,6 +10,7 @@ import { LemonDialog, lemonToast } from '@posthog/lemon-ui'
import api from 'lib/api'
import { tryShowMCPHint } from 'lib/components/MCPHint/mcpHintLogic'
import { SetupTaskId, globalSetupLogic } from 'lib/components/ProductSetup'
+import { FEATURE_FLAGS } from 'lib/constants'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'
import { Scene } from 'scenes/sceneTypes'
@@ -54,6 +55,7 @@ import {
} from '../../shared/components/forms/schemaGroupingUtils'
import type { WebhookCreateResult } from '../../shared/components/forms/WebhookSetupForm'
import { sourceManagementLogic } from '../../shared/logics/sourceManagementLogic'
+import { shouldShowDestinationStep } from './components/destinationStepUtils'
import { FILE_UPLOAD_SOURCE_CONFIG, FILE_UPLOAD_SOURCE_NAME } from './fileUploadSource'
import { selfManagedSourceLogic } from './selfManagedSourceLogic'
import { restoreSourceFormState, saveSourceFormState } from './wizardFormStorage'
@@ -421,6 +423,7 @@ export interface sourceWizardLogicValues {
manualLinkingProvider: ManualLinkSourceType | null
modalTitle:
| ''
+ | 'Choose destinations'
| 'Importing your data...'
| 'Link your data source'
| 'Select tables to import'
@@ -438,6 +441,7 @@ export interface sourceWizardLogicValues {
schemaGroupKeysFingerprint: string
schemaNameFilter: string
selectedConnector: SourceConfig | null
+ showDestinationStep: boolean
showFooter: boolean | SourceConfig
showSkipButton: boolean
showSourceConnectionDetailsErrors: boolean
@@ -474,6 +478,7 @@ export interface sourceWizardLogicValues {
webhookFieldInputsValidationErrors: DeepPartialMap<Record<string, any>, ValidationErrorType>
webhookResult: WebhookCreateResult | null
webhookStepComplete: boolean
+ wizardDestinationIds: string[]
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
@@ -2028,6 +2033,9 @@ export interface sourceWizardLogicActions {
setWebhookResult: (result: WebhookCreateResult | null) => {
result: WebhookCreateResult | null
}
+ setWizardDestinationIds: (destinationIds: string[]) => {
+ destinationIds: string[]
+ }
submitSourceConnectionDetails: () => {
value: boolean
}
@@ -2198,6 +2206,7 @@ export interface sourceWizardLogicMeta {
isManualLinkingSelected: boolean,
isDirectQueryMode: boolean,
hasWebhookSchemas: boolean,
+ showDestinationStep: boolean,
arg: any,
returnConfig: {
returnLabel: string
@@ -2238,11 +2247,18 @@ export interface sourceWizardLogicMeta {
tables: ExternalDataSourceSyncSchema[]
}[]
) => string[]
+ showDestinationStep: (
+ featureFlags: FeatureFlagsSet,
+ isDirectQueryMode: boolean,
+ databaseSchema: ExternalDataSourceSyncSchema[],
+ arg: any
+ ) => boolean
modalTitle: (
currentStep: number,
isDirectQueryMode: boolean
) =>
| ''
+ | 'Choose destinations'
| 'Importing your data...'
| 'Link your data source'
| 'Select tables to import'
@@ -2260,6 +2276,11 @@ export type sourceWizardLogicType = MakeLogicType<
sourceWizardLogicMeta
>
+// Numbered after the existing steps rather than slotted between them. Several scenes embed this
+// wizard and pin steps 1-5 (webhook, progress), so renumbering would move the ground under them
+// for a flag most projects do not have on. Order comes from the explicit jumps below, not the number.
+export const WIZARD_DESTINATION_STEP = 6
+
export const sourceWizardLogic = kea<sourceWizardLogicType>([
path(['products', 'dataWarehouse', 'sourceWizardLogic']),
props({} as SourceWizardLogicProps),
@@ -2280,6 +2301,7 @@ export const sourceWizardLogic = kea<sourceWizardLogicType>([
onBack: true,
onNext: true,
onSubmit: true,
+ setWizardDestinationIds: (destinationIds: string[]) => ({ destinationIds }),
resetSourceForm: (accessMethod?: 'warehouse' | 'direct') => ({ accessMethod }),
setDatabaseSchemas: (schemas: ExternalDataSourceSyncSchema[]) => ({
schemas,
@@ -2398,11 +2420,20 @@ export const sourceWizardLogic = kea<sourceWizardLogicType>([
toggleManualLinkFormVisible: (_, { visible }) => visible,
},
],
+ wizardDestinationIds: [
+ [] as string[],
+ {
+ setWizardDestinationIds: (_, { destinationIds }) => destinationIds,
+ onClear: () => [],
+ },
+ ],
currentStep: [
1,
{
onNext: (state) => state + 1,
- onBack: (state) => state - 1,
+ // The destination step sits after the numbered ones, so stepping back from it
+ // returns to table selection rather than decrementing into the progress step.
+ onBack: (state) => (state === WIZARD_DESTINATION_STEP ? 3 : state - 1),
onClear: () => 1,
setStep: (_, { step }) => step,
setInitialConnector: () => 2,
@@ -2866,6 +2897,7 @@ export const sourceWizardLogic = kea<sourceWizardLogicType>([
s.isManualLinkingSelected,
s.isDirectQueryMode,
s.hasWebhookSchemas,
+ s.showDestinationStep,
(_, props) => props.onComplete,
s.returnConfig,
s.sourceId,
@@ -2875,6 +2907,7 @@ export const sourceWizardLogic = kea<sourceWizardLogicType>([
isManualLinkingSelected: boolean,
isDirectQueryMode: boolean,
hasWebhookSchemas: boolean,
+ showDestinationStep: boolean,
onComplete,
returnConfig: {
returnLabel: string
@@ -2895,13 +2928,18 @@ export const sourceWizardLogic = kea<sourceWizardLogicType>([
return 'Set up webhook'
}
- return 'Import'
+ // The destination step follows, so this one no longer creates the source.
+ return showDestinationStep ? 'Next' : 'Import'
}
if (currentStep === 4) {
return 'Next'
}
+ if (currentStep === WIZARD_DESTINATION_STEP) {
+ return 'Import'
+ }
+
if (currentStep === 5) {
if (onComplete) {
return 'Next'
@@ -3004,6 +3042,23 @@ export const sourceWizardLogic = kea<sourceWizardLogicType>([
}[]
) => getDefaultExpandedSchemaKeys(groupedDatabaseSchema),
],
+ // Destinations are picked before the source is created, so the first sync already lands
+ // where the user wants it. Choosing them afterwards costs a full resync of every table.
+ showDestinationStep: [
+ (s) => [s.featureFlags, s.isDirectQueryMode, s.databaseSchema, (_, props) => props.requiredTables],
+ (
+ featureFlags: FeatureFlagsSet,
+ isDirectQueryMode: boolean,
+ databaseSchema: ExternalDataSourceSyncSchema[],
+ requiredTables: unknown
+ ): boolean =>
+ shouldShowDestinationStep({
+ flagEnabled: !!featureFlags[FEATURE_FLAGS.WAREHOUSE_MULTI_DESTINATION],
+ isDirectQueryMode,
+ schemas: databaseSchema,
+ requiredTables,
+ }),
+ ],
modalTitle: [
(s) => [s.currentStep, s.isDirectQueryMode],
(currentStep: number, isDirectQueryMode: boolean) => {
@@ -3022,6 +3077,10 @@ export const sourceWizardLogic = kea<sourceWizardLogicType>([
return 'Set up webhook'
}
+ if (currentStep === WIZARD_DESTINATION_STEP) {
+ return 'Choose destinations'
+ }
+
if (currentStep === 5) {
return isDirectQueryMode ? 'Tables ready to query' : 'Importing your data...'
}
@@ -3301,6 +3360,12 @@ export const sourceWizardLogic = kea<sourceWizardLogicType>([
actions.openCdcSelfManagedSetupDialog()
return
}
+ if (values.showDestinationStep) {
+ // Pick destinations before the source exists, so its first sync
+ // already lands where the user wants it.
+ actions.setStep(WIZARD_DESTINATION_STEP)
+ return
+ }
actions.setIsLoading(true)
actions.createSource()
if (values.selectedConnector) {
@@ -3319,7 +3384,15 @@ export const sourceWizardLogic = kea<sourceWizardLogicType>([
})
}
- if (step === 4) {
+ if (step === WIZARD_DESTINATION_STEP) {
+ actions.setIsLoading(true)
+ actions.createSource()
+ if (values.selectedConnector) {
+ posthog.capture('source created', {
+ sourceType: values.selectedConnector.name,
+ })
+ }
+ } else if (step === 4) {
if (webhookResultHasNoPendingInputs(values.webhookResult)) {
actions.onNext()
} else {
@@ -3402,9 +3475,15 @@ export const sourceWizardLogic = kea<sourceWizardLogicType>([
...values.source,
source_type: values.selectedConnector.name,
created_via: 'web',
+ // Sent with creation, not after it. Creation schedules the first sync before
+ // it returns, and extraction snapshots the destinations onto that run, so a
+ // follow-up request lands too late and the opening run goes to the warehouse
+ // alone.
+ ...(values.wizardDestinationIds.length > 0 ? { destination_ids: values.wizardDestinationIds } : {}),
})
actions.setSourceId(id)
+
actions.resetSourceConnectionDetails()
actions.loadSources()
actions.markTaskAsCompleted(SetupTaskId.ConnectSource)
diff --git a/products/data_warehouse/frontend/scenes/SchemaScene/ConfigurationTab.tsx b/products/data_warehouse/frontend/scenes/SchemaScene/ConfigurationTab.tsx
index 74eee4cb428e..50e348449ed4 100644
--- a/products/data_warehouse/frontend/scenes/SchemaScene/ConfigurationTab.tsx
+++ b/products/data_warehouse/frontend/scenes/SchemaScene/ConfigurationTab.tsx
@@ -55,6 +55,7 @@ import { ColumnSelectionPicker } from '../SourceScene/tabs/ColumnSelectionModal'
import { RowFilterEditor } from '../SourceScene/tabs/RowFilterEditor'
import { validateRowFilters } from '../SourceScene/tabs/rowFilterUtils'
import { columnAnnotationsLogic } from './columnAnnotationsLogic'
+import { DestinationsSection } from './DestinationsSection'
import { SchemaConfigurationSection, schemaSceneLogic } from './schemaSceneLogic'
// null means "all columns" on either side, so switching to null after a partial list flags
@@ -120,6 +121,8 @@ export function ConfigurationTab({
<ApiVersionSection sourceId={sourceId} source={source} schema={schema} />
</div>
)
+ case 'destinations':
+ return <DestinationsSection schemaId={schema.id} />
case 'columns':
return (
<ColumnsAndRowFiltersSection
@@ -274,7 +277,7 @@ function DetailsSection({
)}
</div>
<div className="flex items-center justify-between">
- <span className="text-muted">Rows synced</span>
+ <span className="text-muted">Row count</span>
<span>{schema.table?.row_count?.toLocaleString() ?? '—'}</span>
</div>
<div className="flex items-center justify-between">
diff --git a/products/data_warehouse/frontend/scenes/SchemaScene/DestinationsSection.tsx b/products/data_warehouse/frontend/scenes/SchemaScene/DestinationsSection.tsx
new file mode 100644
index 000000000000..200410c85292
--- /dev/null
+++ b/products/data_warehouse/frontend/scenes/SchemaScene/DestinationsSection.tsx
@@ -0,0 +1,104 @@
+import { useActions, useValues } from 'kea'
+
+import { IconPlusSmall } from '@posthog/icons'
+import { LemonButton, LemonSwitch } from '@posthog/lemon-ui'
+
+import { LemonBanner } from 'lib/lemon-ui/LemonBanner'
+
+import { DestinationList } from 'products/data_warehouse/frontend/shared/components/DestinationList'
+import { DestinationModal } from 'products/data_warehouse/frontend/shared/components/DestinationModal'
+import { destinationModalLogic } from 'products/data_warehouse/frontend/shared/logics/destinationModalLogic'
+
+import { schemaDestinationsLogic } from './schemaDestinationsLogic'
+
+export interface DestinationsSectionProps {
+ schemaId: string
+}
+
+export function DestinationsSection({ schemaId }: DestinationsSectionProps): JSX.Element {
+ const logic = schemaDestinationsLogic({ schemaId })
+ const { destinations, destinationsLoading, draftDestinationIds, isOverriding, overrideLoading, canSave } =
+ useValues(logic)
+ const { toggleDestination, setOverriding, save, clearOverride, loadDestinations } = useActions(logic)
+
+ const modalProps = {
+ modalKey: `schema-${schemaId}`,
+ onSaved: (destination: { id: string }) => {
+ loadDestinations()
+ if (isOverriding && !draftDestinationIds.includes(destination.id)) {
+ toggleDestination(destination.id)
+ }
+ },
+ onDeleted: (destinationId: string) => {
+ loadDestinations()
+ if (draftDestinationIds.includes(destinationId)) {
+ toggleDestination(destinationId)
+ }
+ },
+ }
+ const { openForCreate, openForEdit } = useActions(destinationModalLogic(modalProps))
+
+ return (
+ <div className="deprecated-space-y-4">
+ <div className="flex gap-2 items-start justify-between">
+ <LemonSwitch
+ bordered
+ checked={isOverriding}
+ onChange={setOverriding}
+ label="Override source destinations"
+ data-attr="warehouse-schema-destinations-override"
+ />
+ <LemonButton
+ type="secondary"
+ icon={<IconPlusSmall />}
+ onClick={openForCreate}
+ data-attr="warehouse-destination-new"
+ >
+ New destination
+ </LemonButton>
+ </div>
+
+ {!isOverriding && (
+ <LemonBanner type="info">
+ This table syncs to whatever its source is set to. Turn on the override to choose destinations just
+ for this table.
+ </LemonBanner>
+ )}
+
+ <DestinationList
+ destinations={destinations}
+ loading={destinationsLoading}
+ selectedIds={draftDestinationIds}
+ onToggle={toggleDestination}
+ onEdit={openForEdit}
+ toggleDisabledReason={
+ isOverriding ? undefined : 'This table follows its source. Turn on the override to change it.'
+ }
+ />
+
+ {isOverriding && (
+ <div className="flex gap-2">
+ <LemonButton
+ type="primary"
+ onClick={save}
+ loading={overrideLoading}
+ disabledReason={canSave ? undefined : 'Pick at least one destination'}
+ data-attr="warehouse-schema-destinations-save"
+ >
+ Save
+ </LemonButton>
+ <LemonButton
+ type="secondary"
+ onClick={clearOverride}
+ loading={overrideLoading}
+ data-attr="warehouse-schema-destinations-reset"
+ >
+ Reset to source destinations
+ </LemonButton>
+ </div>
+ )}
+
+ <DestinationModal {...modalProps} />
+ </div>
+ )
+}
diff --git a/products/data_warehouse/frontend/scenes/SchemaScene/SchemaScene.tsx b/products/data_warehouse/frontend/scenes/SchemaScene/SchemaScene.tsx
index 13714dc20d30..62f49087a6cd 100644
--- a/products/data_warehouse/frontend/scenes/SchemaScene/SchemaScene.tsx
+++ b/products/data_warehouse/frontend/scenes/SchemaScene/SchemaScene.tsx
@@ -45,6 +45,7 @@ const SECTION_LABELS: Record<SchemaConfigurationSection, string> = {
'sync-method': 'Sync method',
columns: 'Columns and filters',
descriptions: 'Descriptions',
+ destinations: 'Destinations',
schedule: 'Schedule',
'danger-zone': 'Danger zone',
}
@@ -71,8 +72,14 @@ function SchemaSceneContent({ sourceId, schemaId }: SchemaSceneProps): JSX.Eleme
// The warehouse table only exists once the schema has synced, and checks hang off that table.
const showDataQuality = !!featureFlags[FEATURE_FLAGS.DATA_QUALITY_CHECKS] && !!schema?.table?.id
const showColumnsSection = supportsColumnSelection
+ // Same gate as the source's Destinations tab. Without it a table offers a destination set that
+ // the sync ignores, because a run only snapshots destinations when the flag is on.
+ const showDestinations = !!featureFlags[FEATURE_FLAGS.WAREHOUSE_MULTI_DESTINATION]
const visibleSections = SCHEMA_CONFIGURATION_SECTIONS.filter(
- (key) => (key !== 'columns' || showColumnsSection) && (key !== 'descriptions' || showDescriptions)
+ (key) =>
+ (key !== 'columns' || showColumnsSection) &&
+ (key !== 'descriptions' || showDescriptions) &&
+ (key !== 'destinations' || showDestinations)
)
useEffect(() => {
diff --git a/products/data_warehouse/frontend/scenes/SchemaScene/schemaDestinationsLogic.ts b/products/data_warehouse/frontend/scenes/SchemaScene/schemaDestinationsLogic.ts
new file mode 100644
index 000000000000..0ca907c7423b
--- /dev/null
+++ b/products/data_warehouse/frontend/scenes/SchemaScene/schemaDestinationsLogic.ts
@@ -0,0 +1,261 @@
+import { MakeLogicType, actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
+import { loaders } from 'kea-loaders'
+
+import { LemonDialog } from 'lib/lemon-ui/LemonDialog'
+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
+import { teamLogic } from 'scenes/teamLogic'
+
+import {
+ externalDataDestinationsList,
+ externalDataSchemasDestinationsPartialUpdate,
+ externalDataSchemasDestinationsRetrieve,
+ externalDataSchemasResyncCreate,
+} from 'products/warehouse_sources/frontend/generated/api'
+import {
+ ExternalDataDestinationApi,
+ SchemaDestinationsApi,
+} from 'products/warehouse_sources/frontend/generated/api.schemas'
+
+export interface SchemaDestinationsLogicProps {
+ schemaId: string
+}
+
+type SchemaDestinationsResponse = SchemaDestinationsApi
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface schemaDestinationsLogicValues {
+ currentTeamId: number | null // teamLogic
+ addedDestinationIds: string[]
+ canSave: boolean
+ destinations: ExternalDataDestinationApi[]
+ destinationsLoading: boolean
+ draftDestinationIds: string[]
+ inheritsFromSource: boolean
+ isOverriding: boolean
+ override: SchemaDestinationsResponse
+ overrideLoading: boolean
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface schemaDestinationsLogicActions {
+ clearOverride: () => {
+ value: true
+ }
+ loadDestinations: () => any
+ loadDestinationsFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadDestinationsSuccess: (
+ destinations: ExternalDataDestinationApi[],
+ payload?: any
+ ) => {
+ destinations: ExternalDataDestinationApi[]
+ payload?: any
+ }
+ loadOverride: () => any
+ loadOverrideFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadOverrideSuccess: (
+ override: SchemaDestinationsApi,
+ payload?: any
+ ) => {
+ override: SchemaDestinationsApi
+ payload?: any
+ }
+ resyncAfterAdding: () => {
+ value: true
+ }
+ save: () => {
+ value: true
+ }
+ saveOverride: (destinationIds: string[] | null) => string[] | null
+ saveOverrideFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ saveOverrideSuccess: (
+ override: SchemaDestinationsApi,
+ payload?: string[] | null
+ ) => {
+ override: SchemaDestinationsApi
+ payload?: string[] | null
+ }
+ setOverriding: (overriding: boolean) => {
+ overriding: boolean
+ }
+ toggleDestination: (destinationId: string) => {
+ destinationId: string
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface schemaDestinationsLogicMeta {
+ key: string
+ __keaTypeGenInternalSelectorTypes: {
+ inheritsFromSource: (override: any) => boolean
+ canSave: (draftDestinationIds: any, isOverriding: any) => boolean
+ addedDestinationIds: (draftDestinationIds: any, override: any) => string[]
+ }
+}
+
+export type schemaDestinationsLogicType = MakeLogicType<
+ schemaDestinationsLogicValues,
+ schemaDestinationsLogicActions,
+ SchemaDestinationsLogicProps,
+ schemaDestinationsLogicMeta
+>
+
+export const schemaDestinationsLogic = kea<schemaDestinationsLogicType>([
+ path(['products', 'data_warehouse', 'frontend', 'scenes', 'SchemaScene', 'schemaDestinationsLogic']),
+ props({} as SchemaDestinationsLogicProps),
+ key((props: SchemaDestinationsLogicProps) => props.schemaId),
+ connect(() => ({
+ values: [teamLogic, ['currentTeamId']],
+ })),
+ actions({
+ toggleDestination: (destinationId: string) => ({ destinationId }),
+ setOverriding: (overriding: boolean) => ({ overriding }),
+ save: true,
+ clearOverride: true,
+ resyncAfterAdding: true,
+ }),
+ loaders(({ values, props }: any) => ({
+ destinations: [
+ [] as ExternalDataDestinationApi[],
+ {
+ loadDestinations: async () => {
+ const response = await externalDataDestinationsList(String(values.currentTeamId))
+ return response.results ?? []
+ },
+ },
+ ],
+ override: [
+ {
+ destination_ids: null,
+ inherits_from_source: true,
+ effective_destination_ids: [],
+ } as SchemaDestinationsResponse,
+ {
+ loadOverride: async () =>
+ (await externalDataSchemasDestinationsRetrieve(
+ String(values.currentTeamId),
+ props.schemaId
+ )) as SchemaDestinationsResponse,
+ saveOverride: async (destinationIds: string[] | null) =>
+ (await externalDataSchemasDestinationsPartialUpdate(String(values.currentTeamId), props.schemaId, {
+ destination_ids: destinationIds,
+ })) as SchemaDestinationsResponse,
+ },
+ ],
+ })),
+ reducers({
+ // Starts as whatever the table effectively syncs to, so switching from inheriting to
+ // overriding does not silently change where data goes.
+ draftDestinationIds: [
+ [] as string[],
+ {
+ toggleDestination: (state: string[], { destinationId }: { destinationId: string }) =>
+ state.includes(destinationId)
+ ? state.filter((id) => id !== destinationId)
+ : [...state, destinationId],
+ loadOverrideSuccess: (_: string[], { override }: { override: SchemaDestinationsResponse }) =>
+ override.effective_destination_ids ?? [],
+ saveOverrideSuccess: (_: string[], { override }: { override: SchemaDestinationsResponse }) =>
+ override.destination_ids ?? override.effective_destination_ids ?? [],
+ },
+ ],
+ isOverriding: [
+ false,
+ {
+ setOverriding: (_: boolean, { overriding }: { overriding: boolean }) => overriding,
+ loadOverrideSuccess: (_: boolean, { override }: { override: SchemaDestinationsResponse }) =>
+ !override.inherits_from_source,
+ saveOverrideSuccess: (_: boolean, { override }: { override: SchemaDestinationsResponse }) =>
+ !override.inherits_from_source,
+ },
+ ],
+ }),
+ selectors({
+ inheritsFromSource: [
+ (s: any) => [s.override],
+ (override: SchemaDestinationsResponse) => override.inherits_from_source !== false,
+ ],
+ // The API rejects an empty set, because with no rows there is nothing to tell it apart
+ // from having no override at all, so the table would quietly follow its source again.
+ canSave: [
+ (s: any) => [s.draftDestinationIds, s.isOverriding],
+ (draft: string[], isOverriding: boolean) => isOverriding && draft.length > 0,
+ ],
+ // Measured against where the table syncs today, inherited or not: either way a destination
+ // that is not already receiving this table holds none of its history.
+ addedDestinationIds: [
+ (s: any) => [s.draftDestinationIds, s.override],
+ (draft: string[], override: SchemaDestinationsResponse): string[] => {
+ const current = override.destination_ids ?? override.effective_destination_ids ?? []
+ return draft.filter((id) => !current.includes(id))
+ },
+ ],
+ }),
+ listeners(({ values, actions, props, asyncActions }: any) => ({
+ save: () => {
+ const added = values.addedDestinationIds
+ if (added.length === 0) {
+ actions.saveOverride(values.draftDestinationIds)
+ return
+ }
+
+ const addedNames = values.destinations
+ .filter((destination: ExternalDataDestinationApi) => added.includes(destination.id))
+ .map((destination: ExternalDataDestinationApi) => destination.name)
+ .join(', ')
+
+ LemonDialog.open({
+ title: 'Resync to fill in the history?',
+ description: `${addedNames} holds none of the data this table has already synced. Saving resyncs the table from scratch so it gets the full history. Every row is read again from the source, and rows bill once per destination, so this bills for every destination this table syncs to.`,
+ primaryButton: {
+ children: 'Save and resync',
+ onClick: () => actions.resyncAfterAdding(),
+ },
+ secondaryButton: { children: 'Cancel' },
+ })
+ },
+ // Saved before the resync: a resync against the old set would re-import the table without
+ // the destination the user just agreed to pay for.
+ resyncAfterAdding: async () => {
+ await asyncActions.saveOverride(values.draftDestinationIds)
+ try {
+ await externalDataSchemasResyncCreate(String(values.currentTeamId), props.schemaId, {})
+ lemonToast.success('Resyncing this table')
+ } catch {
+ lemonToast.error('Could not start a resync for this table')
+ }
+ },
+ clearOverride: () => actions.saveOverride(null),
+ saveOverrideSuccess: ({ override }: { override: SchemaDestinationsResponse }) => {
+ lemonToast.success(
+ override.inherits_from_source
+ ? 'This table follows its source again'
+ : 'Destinations updated for this table'
+ )
+ },
+ saveOverrideFailure: ({ error }: { error: string }) => {
+ lemonToast.error(error || 'Could not update destinations')
+ },
+ })),
+ afterMount(({ actions }: any) => {
+ actions.loadDestinations()
+ actions.loadOverride()
+ }),
+])
diff --git a/products/data_warehouse/frontend/scenes/SchemaScene/schemaSceneLogic.ts b/products/data_warehouse/frontend/scenes/SchemaScene/schemaSceneLogic.ts
index d57b23756ef6..b2074ebbdb97 100644
--- a/products/data_warehouse/frontend/scenes/SchemaScene/schemaSceneLogic.ts
+++ b/products/data_warehouse/frontend/scenes/SchemaScene/schemaSceneLogic.ts
@@ -31,6 +31,7 @@ export const SCHEMA_CONFIGURATION_SECTIONS = [
'sync-method',
'columns',
'descriptions',
+ 'destinations',
'schedule',
'danger-zone',
] as const
@@ -81,7 +82,7 @@ export interface schemaSceneLogicValues {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface schemaSceneLogicActions {
_setCurrentSection: (section: SchemaConfigurationSection) => {
- section: 'columns' | 'danger-zone' | 'descriptions' | 'details' | 'schedule' | 'sync-method'
+ section: 'columns' | 'danger-zone' | 'descriptions' | 'destinations' | 'details' | 'schedule' | 'sync-method'
}
_setCurrentTab: (tab: SchemaSceneTab) => {
tab: 'configuration' | 'data-quality' | 'history' | 'metrics' | 'syncs'
@@ -132,7 +133,7 @@ export interface schemaSceneLogicActions {
schema: ExternalDataSourceSchema
}
setCurrentSection: (section: SchemaConfigurationSection) => {
- section: 'columns' | 'danger-zone' | 'descriptions' | 'details' | 'schedule' | 'sync-method'
+ section: 'columns' | 'danger-zone' | 'descriptions' | 'destinations' | 'details' | 'schedule' | 'sync-method'
}
setCurrentTab: (tab: SchemaSceneTab) => {
tab: 'configuration' | 'data-quality' | 'history' | 'metrics' | 'syncs'
diff --git a/products/data_warehouse/frontend/scenes/SourceScene/SourceScene.tsx b/products/data_warehouse/frontend/scenes/SourceScene/SourceScene.tsx
index cbce3d0e9cd6..916dc37659dd 100644
--- a/products/data_warehouse/frontend/scenes/SourceScene/SourceScene.tsx
+++ b/products/data_warehouse/frontend/scenes/SourceScene/SourceScene.tsx
@@ -45,13 +45,22 @@ import {
import { cleanSourceId, isSelfManagedSourceId } from 'products/data_warehouse/frontend/utils'
import { ConfigurationTab } from './tabs/ConfigurationTab'
+import { DestinationsTab } from './tabs/DestinationsTab'
import { MetricsTab } from './tabs/MetricsTab'
import { SchemasTab } from './tabs/SchemasTab'
import { sourceSettingsLogic } from './tabs/sourceSettingsLogic'
import { SyncsTab } from './tabs/SyncsTab'
import { WebhookTab } from './tabs/WebhookTab'
-const SOURCE_SCENE_TABS = ['schemas', 'syncs', 'metrics', 'configuration', 'webhook', 'history'] as const
+const SOURCE_SCENE_TABS = [
+ 'schemas',
+ 'syncs',
+ 'destinations',
+ 'metrics',
+ 'configuration',
+ 'webhook',
+ 'history',
+] as const
export type SourceSceneTab = (typeof SOURCE_SCENE_TABS)[number]
export interface SourceSceneProps {
@@ -93,13 +102,13 @@ export interface sourceSceneLogicValues {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface sourceSceneLogicActions {
_setCurrentTab: (tab: SourceSceneTab) => {
- tab: 'configuration' | 'history' | 'metrics' | 'schemas' | 'syncs' | 'webhook'
+ tab: 'configuration' | 'destinations' | 'history' | 'metrics' | 'schemas' | 'syncs' | 'webhook'
}
setBreadcrumbName: (name: string) => {
name: string
}
setCurrentTab: (tab: SourceSceneTab) => {
- tab: 'configuration' | 'history' | 'metrics' | 'schemas' | 'syncs' | 'webhook'
+ tab: 'configuration' | 'destinations' | 'history' | 'metrics' | 'schemas' | 'syncs' | 'webhook'
}
}
@@ -280,6 +289,7 @@ function ManagedSourceTabs({
const showSyncsTab = shouldShowManagedSourceSyncsTab(source)
const showWebhookTab = !!source?.supports_webhooks
+ const showDestinationsTab = !!featureFlags[FEATURE_FLAGS.WAREHOUSE_MULTI_DESTINATION]
const showMetricsTab = shouldShowManagedSourceMetricsTab(source, !!featureFlags[FEATURE_FLAGS.DWH_SOURCE_METRICS])
useEffect(() => {
@@ -320,6 +330,10 @@ function ManagedSourceTabs({
tabs.push({ label: 'Metrics', key: 'metrics', content: <MetricsTab id={sourceId} /> })
}
+ if (showDestinationsTab) {
+ tabs.push({ label: 'Destinations', key: 'destinations', content: <DestinationsTab id={sourceId} /> })
+ }
+
tabs.push({ label: 'Configuration', key: 'configuration', content: <ConfigurationTab id={sourceId} /> })
if (showWebhookTab) {
diff --git a/products/data_warehouse/frontend/scenes/SourceScene/tabs/DestinationsTab.tsx b/products/data_warehouse/frontend/scenes/SourceScene/tabs/DestinationsTab.tsx
new file mode 100644
index 000000000000..4d72e95143d7
--- /dev/null
+++ b/products/data_warehouse/frontend/scenes/SourceScene/tabs/DestinationsTab.tsx
@@ -0,0 +1,78 @@
+import { useActions, useValues } from 'kea'
+
+import { IconPlusSmall } from '@posthog/icons'
+import { LemonButton } from '@posthog/lemon-ui'
+
+import { DestinationList } from 'products/data_warehouse/frontend/shared/components/DestinationList'
+import { DestinationModal } from 'products/data_warehouse/frontend/shared/components/DestinationModal'
+import { destinationModalLogic } from 'products/data_warehouse/frontend/shared/logics/destinationModalLogic'
+
+import { destinationsLogic } from './destinationsLogic'
+
+export interface DestinationsTabProps {
+ id: string
+}
+
+export function DestinationsTab({ id }: DestinationsTabProps): JSX.Element {
+ const logic = destinationsLogic({ sourceId: id })
+ const { destinations, destinationsLoading, attachedDestinationIds, savedDestinationIdsLoading, canSave } =
+ useValues(logic)
+ const { toggleDestination, save, loadDestinations, setAttached } = useActions(logic)
+
+ const modalProps = {
+ modalKey: `source-${id}`,
+ // A destination you just added is one you meant to use, so select it and let the same Save
+ // (and its resync confirmation) apply.
+ onSaved: (destination: { id: string }) => {
+ loadDestinations()
+ if (!attachedDestinationIds.includes(destination.id)) {
+ setAttached([...attachedDestinationIds, destination.id])
+ }
+ },
+ onDeleted: (destinationId: string) => {
+ loadDestinations()
+ setAttached(attachedDestinationIds.filter((id) => id !== destinationId))
+ },
+ }
+ const { openForCreate, openForEdit } = useActions(destinationModalLogic(modalProps))
+
+ return (
+ <div className="deprecated-space-y-4">
+ <div className="flex gap-2 items-start justify-between">
+ <p className="max-w-prose">
+ Every table on this source syncs to the destinations turned on here. A table with its own
+ destinations ignores this list.
+ </p>
+ <LemonButton
+ type="secondary"
+ icon={<IconPlusSmall />}
+ onClick={openForCreate}
+ data-attr="warehouse-destination-new"
+ >
+ New destination
+ </LemonButton>
+ </div>
+
+ <DestinationList
+ destinations={destinations}
+ loading={destinationsLoading}
+ selectedIds={attachedDestinationIds}
+ onToggle={toggleDestination}
+ onEdit={openForEdit}
+ metricsSourceId={id}
+ />
+
+ <LemonButton
+ type="primary"
+ onClick={save}
+ loading={savedDestinationIdsLoading}
+ disabledReason={canSave ? undefined : 'No changes to save'}
+ data-attr="warehouse-destinations-save"
+ >
+ Save destinations
+ </LemonButton>
+
+ <DestinationModal {...modalProps} />
+ </div>
+ )
+}
diff --git a/products/data_warehouse/frontend/scenes/SourceScene/tabs/SchemasTab.tsx b/products/data_warehouse/frontend/scenes/SourceScene/tabs/SchemasTab.tsx
index e6271c5ddf5a..f4666ca0d8cf 100644
--- a/products/data_warehouse/frontend/scenes/SourceScene/tabs/SchemasTab.tsx
+++ b/products/data_warehouse/frontend/scenes/SourceScene/tabs/SchemasTab.tsx
@@ -128,7 +128,7 @@ function ManagedSchemasTab({ id }: { id: string }): JSX.Element {
} = useActions(sourceSettingsLogic)
const { featureFlags } = useValues(featureFlagLogic)
- // Load (and poll) jobs so the Rows synced column can show live progress for in-progress
+ // Load (and poll) jobs so the Row count column can show live progress for in-progress
// syncs, before the warehouse table exists. loadJobsSuccess reschedules itself.
useEffect(() => {
if (source && source.access_method !== 'direct') {
@@ -480,7 +480,7 @@ function ManagedSchemaTable({
),
},
{
- title: 'Rows synced',
+ title: 'Row count',
key: 'rows_synced',
align: 'right',
sorter: (a, b) => (a.table?.row_count ?? 0) - (b.table?.row_count ?? 0),
diff --git a/products/data_warehouse/frontend/scenes/SourceScene/tabs/SyncsTab.tsx b/products/data_warehouse/frontend/scenes/SourceScene/tabs/SyncsTab.tsx
index 511c59d85661..7c9bd393f0f7 100644
--- a/products/data_warehouse/frontend/scenes/SourceScene/tabs/SyncsTab.tsx
+++ b/products/data_warehouse/frontend/scenes/SourceScene/tabs/SyncsTab.tsx
@@ -5,15 +5,20 @@ import { useEffect } from 'react'
import { LemonButton, LemonDivider, LemonTable, LemonTag, LemonTagType, Tooltip } from '@posthog/lemon-ui'
import { TZLabel } from 'lib/components/TZLabel'
+import { FEATURE_FLAGS } from 'lib/constants'
import { dayjsUtcToTimezone } from 'lib/dayjs'
import { LemonInputSelect } from 'lib/lemon-ui/LemonInputSelect/LemonInputSelect'
import { LemonLabel } from 'lib/lemon-ui/LemonLabel'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { LogsViewer } from 'scenes/hog-functions/logs/LogsViewer'
import { teamLogic } from 'scenes/teamLogic'
import { userLogic } from 'scenes/userLogic'
import { ExternalDataJob, ExternalDataJobStatus, LogEntryLevel } from '~/types'
+import { JobDestinations } from 'products/data_warehouse/frontend/shared/components/JobDestinations'
+import { destinationLookupLogic } from 'products/data_warehouse/frontend/shared/logics/destinationLookupLogic'
+
import { sourceSettingsLogic } from './sourceSettingsLogic'
const StatusTagSetting: Record<ExternalDataJob['status'], LemonTagType> = {
@@ -39,7 +44,19 @@ export const SyncsTab = ({ id, lockedSchema }: SyncsTabProps): JSX.Element => {
const { user } = useValues(userLogic)
const { source, jobs, jobsLoading, canLoadMoreJobs, selectedSchemas } = useValues(logic)
const { loadJobs, loadMoreJobs, setSelectedSchemas } = useActions(logic)
+ const { featureFlags } = useValues(featureFlagLogic)
+ const { loadDestinations } = useActions(destinationLookupLogic)
+ const { destinationsById, destinationsLoading } = useValues(destinationLookupLogic)
const showDebugLogs = user?.is_staff || user?.is_impersonated
+ // Without the flag every run goes to the warehouse alone, so a column of identical logos
+ // would be noise.
+ const showDestinations = !!featureFlags[FEATURE_FLAGS.WAREHOUSE_MULTI_DESTINATION]
+
+ useEffect(() => {
+ if (showDestinations) {
+ loadDestinations()
+ }
+ }, [showDestinations, loadDestinations])
// Lock to a single schema when asked, otherwise apply a `?schema=<name>` deep link once on
// mount so links from the schemas list and the schema configuration page land here filtered.
@@ -163,11 +180,27 @@ export const SyncsTab = ({ id, lockedSchema }: SyncsTabProps): JSX.Element => {
},
},
{
- title: 'Rows synced',
+ title: 'Row count',
+ tooltip:
+ 'Rows read from the source. A run reads them once however many destinations it writes to.',
render: (_, job) => {
return job.rows_synced.toLocaleString()
},
},
+ ...(showDestinations
+ ? [
+ {
+ title: 'Destinations',
+ render: (_: any, job: ExternalDataJob) => (
+ <JobDestinations
+ destinationIds={job.destination_ids ?? []}
+ destinationsById={destinationsById}
+ loading={destinationsLoading}
+ />
+ ),
+ },
+ ]
+ : []),
{
title: 'Synced at',
render: (_, job) => {
diff --git a/products/data_warehouse/frontend/scenes/SourceScene/tabs/destinationsLogic.ts b/products/data_warehouse/frontend/scenes/SourceScene/tabs/destinationsLogic.ts
new file mode 100644
index 000000000000..c967263bb257
--- /dev/null
+++ b/products/data_warehouse/frontend/scenes/SourceScene/tabs/destinationsLogic.ts
@@ -0,0 +1,282 @@
+import { MakeLogicType, actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
+import { loaders } from 'kea-loaders'
+
+import { LemonDialog } from 'lib/lemon-ui/LemonDialog'
+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
+import { pluralize } from 'lib/utils/strings'
+import { teamLogic } from 'scenes/teamLogic'
+
+import { ExternalDataSourceSchema } from '~/types'
+
+import {
+ externalDataDestinationsList,
+ externalDataSchemasResyncCreate,
+ externalDataSourcesDestinationsPartialUpdate,
+ externalDataSourcesDestinationsRetrieve,
+ externalDataSourcesRetrieve,
+} from 'products/warehouse_sources/frontend/generated/api'
+import { ExternalDataDestinationApi } from 'products/warehouse_sources/frontend/generated/api.schemas'
+
+export interface DestinationsLogicProps {
+ sourceId: string
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface destinationsLogicValues {
+ currentTeamId: number | null // teamLogic
+ addedDestinationIds: string[]
+ attachedDestinationIds: string[]
+ canSave: boolean
+ destinations: ExternalDataDestinationApi[]
+ destinationsLoading: boolean
+ hasUnsavedChanges: boolean
+ savedDestinationIds: string[]
+ savedDestinationIdsLoading: boolean
+ sourceSchemas: ExternalDataSourceSchema[]
+ sourceSchemasLoading: boolean
+ syncedSchemas: ExternalDataSourceSchema[]
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface destinationsLogicActions {
+ loadAttached: () => any
+ loadAttachedFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadAttachedSuccess: (
+ savedDestinationIds: string[],
+ payload?: any
+ ) => {
+ savedDestinationIds: string[]
+ payload?: any
+ }
+ loadDestinations: () => any
+ loadDestinationsFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadDestinationsSuccess: (
+ destinations: ExternalDataDestinationApi[],
+ payload?: any
+ ) => {
+ destinations: ExternalDataDestinationApi[]
+ payload?: any
+ }
+ loadSourceSchemas: () => any
+ loadSourceSchemasFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadSourceSchemasSuccess: (
+ sourceSchemas: ExternalDataSourceSchema[],
+ payload?: any
+ ) => {
+ sourceSchemas: ExternalDataSourceSchema[]
+ payload?: any
+ }
+ resyncAfterAdding: () => {
+ value: true
+ }
+ save: () => {
+ value: true
+ }
+ saveAttached: (destinationIds: string[]) => string[]
+ saveAttachedFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ saveAttachedSuccess: (
+ savedDestinationIds: string[],
+ payload?: string[]
+ ) => {
+ savedDestinationIds: string[]
+ payload?: string[]
+ }
+ setAttached: (destinationIds: string[]) => {
+ destinationIds: string[]
+ }
+ toggleDestination: (destinationId: string) => {
+ destinationId: string
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface destinationsLogicMeta {
+ key: string
+ __keaTypeGenInternalSelectorTypes: {
+ hasUnsavedChanges: (attachedDestinationIds: string[], savedDestinationIds: string[]) => boolean
+ canSave: (attachedDestinationIds: string[], hasUnsavedChanges: boolean) => boolean
+ addedDestinationIds: (attachedDestinationIds: string[], savedDestinationIds: string[]) => string[]
+ syncedSchemas: (sourceSchemas: ExternalDataSourceSchema[]) => ExternalDataSourceSchema[]
+ }
+}
+
+export type destinationsLogicType = MakeLogicType<
+ destinationsLogicValues,
+ destinationsLogicActions,
+ DestinationsLogicProps,
+ destinationsLogicMeta
+>
+
+export const destinationsLogic = kea<destinationsLogicType>([
+ path(['products', 'data_warehouse', 'frontend', 'scenes', 'SourceScene', 'tabs', 'destinationsLogic']),
+ props({} as DestinationsLogicProps),
+ key((props) => props.sourceId),
+ connect(() => ({
+ values: [teamLogic, ['currentTeamId']],
+ })),
+ actions({
+ setAttached: (destinationIds: string[]) => ({ destinationIds }),
+ toggleDestination: (destinationId: string) => ({ destinationId }),
+ save: true,
+ resyncAfterAdding: true,
+ }),
+ loaders(({ values, props }) => ({
+ destinations: [
+ [] as ExternalDataDestinationApi[],
+ {
+ loadDestinations: async () => {
+ const response = await externalDataDestinationsList(String(values.currentTeamId))
+ return response.results ?? []
+ },
+ },
+ ],
+ sourceSchemas: [
+ [] as ExternalDataSourceSchema[],
+ {
+ loadSourceSchemas: async () => {
+ const source = await externalDataSourcesRetrieve(String(values.currentTeamId), props.sourceId)
+ // The generated shape for an embedded schema is an untyped map; the app-level
+ // type is what every other warehouse surface reads it as.
+ return (source.schemas ?? []) as unknown as ExternalDataSourceSchema[]
+ },
+ },
+ ],
+ savedDestinationIds: [
+ [] as string[],
+ {
+ loadAttached: async () => {
+ const response = await externalDataSourcesDestinationsRetrieve(
+ String(values.currentTeamId),
+ props.sourceId
+ )
+ return response.destination_ids ?? []
+ },
+ saveAttached: async (destinationIds: string[]) => {
+ const response = await externalDataSourcesDestinationsPartialUpdate(
+ String(values.currentTeamId),
+ props.sourceId,
+ { destination_ids: destinationIds }
+ )
+ return response.destination_ids ?? []
+ },
+ },
+ ],
+ })),
+ reducers({
+ attachedDestinationIds: [
+ [] as string[],
+ {
+ setAttached: (_, { destinationIds }) => destinationIds,
+ toggleDestination: (state, { destinationId }) =>
+ state.includes(destinationId)
+ ? state.filter((id) => id !== destinationId)
+ : [...state, destinationId],
+ loadAttachedSuccess: (_, { savedDestinationIds }) => savedDestinationIds,
+ saveAttachedSuccess: (_, { savedDestinationIds }) => savedDestinationIds,
+ },
+ ],
+ }),
+ selectors({
+ hasUnsavedChanges: [
+ (s) => [s.attachedDestinationIds, s.savedDestinationIds],
+ (attached: string[], saved: string[]): boolean =>
+ attached.length !== saved.length || attached.some((id: string) => !saved.includes(id)),
+ ],
+ canSave: [
+ (s) => [s.attachedDestinationIds, s.hasUnsavedChanges],
+ (attached: string[], hasUnsavedChanges: boolean): boolean => hasUnsavedChanges && attached.length > 0,
+ ],
+ // A destination added now holds none of the history already synced, so these are the ones
+ // that make a resync necessary. Removing one never does.
+ addedDestinationIds: [
+ (s) => [s.attachedDestinationIds, s.savedDestinationIds],
+ (attached: string[], saved: string[]): string[] => attached.filter((id) => !saved.includes(id)),
+ ],
+ syncedSchemas: [
+ (s) => [s.sourceSchemas],
+ (schemas: ExternalDataSourceSchema[]): ExternalDataSourceSchema[] =>
+ schemas.filter((schema) => schema.should_sync && !!schema.sync_type),
+ ],
+ }),
+ listeners(({ values, actions, asyncActions }) => ({
+ save: async () => {
+ const added = values.addedDestinationIds
+ const tables = values.syncedSchemas
+
+ if (added.length === 0 || tables.length === 0) {
+ actions.saveAttached(values.attachedDestinationIds)
+ return
+ }
+
+ const addedNames = values.destinations
+ .filter((destination) => added.includes(destination.id))
+ .map((destination) => destination.name)
+ .join(', ')
+
+ LemonDialog.open({
+ title: 'Resync to fill in the history?',
+ description: `${addedNames} holds none of the data you have already synced. Saving resyncs ${pluralize(
+ tables.length,
+ 'table',
+ 'tables'
+ )} from scratch so it gets the full history. Every table is read again from the source, and rows bill once per destination, so this bills for every destination on this source, not just the new one.`,
+ primaryButton: {
+ children: 'Save and resync',
+ onClick: () => actions.resyncAfterAdding(),
+ },
+ secondaryButton: { children: 'Cancel' },
+ })
+ },
+ // The save has to land before the resync: a resync against the old destination set would
+ // re-import every table without the destination the user just agreed to pay for.
+ resyncAfterAdding: async () => {
+ const tables = values.syncedSchemas
+ await asyncActions.saveAttached(values.attachedDestinationIds)
+
+ const results = await Promise.allSettled(
+ tables.map((schema) => externalDataSchemasResyncCreate(String(values.currentTeamId), schema.id, {}))
+ )
+ const failed = results.filter((result) => result.status === 'rejected').length
+ if (failed > 0) {
+ lemonToast.error(`Could not start a resync for ${pluralize(failed, 'table', 'tables')}`)
+ return
+ }
+ lemonToast.success(`Resyncing ${pluralize(tables.length, 'table', 'tables')}`)
+ },
+ saveAttachedSuccess: () => {
+ lemonToast.success('Destinations updated')
+ },
+ saveAttachedFailure: ({ error }) => {
+ lemonToast.error(error || 'Could not update destinations')
+ },
+ })),
+ afterMount(({ actions }) => {
+ actions.loadDestinations()
+ actions.loadAttached()
+ actions.loadSourceSchemas()
+ }),
+])
diff --git a/products/data_warehouse/frontend/shared/components/DestinationIcon.tsx b/products/data_warehouse/frontend/shared/components/DestinationIcon.tsx
new file mode 100644
index 000000000000..5657e88378e2
--- /dev/null
+++ b/products/data_warehouse/frontend/shared/components/DestinationIcon.tsx
@@ -0,0 +1,61 @@
+import { Tooltip } from 'lib/lemon-ui/Tooltip'
+
+import IconPostHog from 'public/posthog-icon.svg'
+import IconS3 from 'public/services/aws-s3.png'
+import IconAzureBlob from 'public/services/azure-blob-storage.png'
+import IconBigQuery from 'public/services/bigquery.png'
+import IconDatabricks from 'public/services/databricks.png'
+import IconPostgres from 'public/services/postgres.png'
+import IconRedshift from 'public/services/redshift.png'
+import IconSnowflake from 'public/services/snowflake.png'
+
+import { ExternalDataDestinationTypeEnumApi } from 'products/warehouse_sources/frontend/generated/api.schemas'
+
+// The same artwork batch exports uses for its destinations, so one warehouse shows the same logo
+// wherever a PostHog surface names it. Keyed off this product's own enum rather than shared with
+// `BATCH_EXPORT_ICON_MAP`, because the two enums spell S3 differently.
+export const DESTINATION_ICON_MAP: Record<ExternalDataDestinationTypeEnumApi, string> = {
+ PostHogWarehouse: IconPostHog,
+ Postgres: IconPostgres,
+ Redshift: IconRedshift,
+ Snowflake: IconSnowflake,
+ BigQuery: IconBigQuery,
+ Databricks: IconDatabricks,
+ AzureBlob: IconAzureBlob,
+ S3: IconS3,
+}
+
+const DESTINATION_TYPE_LABELS: Record<ExternalDataDestinationTypeEnumApi, string> = {
+ PostHogWarehouse: 'PostHog warehouse',
+ Postgres: 'Postgres',
+ Redshift: 'Redshift',
+ Snowflake: 'Snowflake',
+ BigQuery: 'BigQuery',
+ Databricks: 'Databricks',
+ AzureBlob: 'Azure Blob',
+ S3: 'S3',
+}
+
+/** The label a person should see for a destination type. The API serializes the raw enum value. */
+export function destinationTypeLabel(type: ExternalDataDestinationTypeEnumApi): string {
+ return DESTINATION_TYPE_LABELS[type] ?? type
+}
+
+export interface DestinationIconProps {
+ type: ExternalDataDestinationTypeEnumApi
+ size?: 'small' | 'medium'
+}
+
+export function DestinationIcon({ type, size = 'small' }: DestinationIconProps): JSX.Element {
+ const label = destinationTypeLabel(type)
+
+ return (
+ <Tooltip title={label}>
+ {/* Fixed box, natural aspect: the service marks are square but PostHog's is a wide
+ wordmark, and forcing it square squashes it. */}
+ <span className={`flex items-center justify-center ${size === 'small' ? 'size-8' : 'size-11'}`}>
+ <img src={DESTINATION_ICON_MAP[type]} alt={label} className="max-w-full max-h-full" />
+ </span>
+ </Tooltip>
+ )
+}
diff --git a/products/data_warehouse/frontend/shared/components/DestinationList.stories.tsx b/products/data_warehouse/frontend/shared/components/DestinationList.stories.tsx
new file mode 100644
index 000000000000..422b786fabd8
--- /dev/null
+++ b/products/data_warehouse/frontend/shared/components/DestinationList.stories.tsx
@@ -0,0 +1,79 @@
+import { Meta, StoryFn } from '@storybook/react'
+
+import { ExternalDataDestinationApi } from 'products/warehouse_sources/frontend/generated/api.schemas'
+
+import { DestinationList, DestinationListProps } from './DestinationList'
+
+const WAREHOUSE: ExternalDataDestinationApi = {
+ id: '01a03e9c-1b76-0000-9079-2a0ee2186dea',
+ type: 'PostHogWarehouse',
+ name: 'PostHog warehouse',
+ config: {},
+ integration: null,
+ is_posthog_warehouse: true,
+ created_at: '2026-08-20T10:00:00Z',
+ updated_at: '2026-08-25T10:00:00Z',
+ created_by: null,
+} as ExternalDataDestinationApi
+
+const POSTGRES: ExternalDataDestinationApi = {
+ id: '01a03e9c-1b7c-0000-71ce-5e5d7b04df8f',
+ type: 'Postgres',
+ name: 'Customer Postgres',
+ config: { database: 'analytics', schema: 'customer_sync' },
+ integration: 1,
+ is_posthog_warehouse: false,
+ created_at: '2026-08-24T10:00:00Z',
+ updated_at: '2026-08-26T14:00:00Z',
+ created_by: null,
+} as ExternalDataDestinationApi
+
+const meta: Meta<typeof DestinationList> = {
+ title: 'Data Warehouse/DestinationList',
+ component: DestinationList,
+ tags: ['autodocs'],
+}
+export default meta
+
+const Template: StoryFn<typeof DestinationList> = (props: DestinationListProps) => <DestinationList {...props} />
+
+export const BothSelected = Template.bind({})
+BothSelected.args = {
+ destinations: [POSTGRES, WAREHOUSE],
+ loading: false,
+ selectedIds: [POSTGRES.id, WAREHOUSE.id],
+ onToggle: () => {},
+ onEdit: () => {},
+}
+
+// The last one on cannot be turned off, so a source can never end up syncing nowhere.
+export const OnlyOneLeft = Template.bind({})
+OnlyOneLeft.args = {
+ ...BothSelected.args,
+ selectedIds: [WAREHOUSE.id],
+}
+
+export const InheritedFromSource = Template.bind({})
+InheritedFromSource.args = {
+ ...BothSelected.args,
+ toggleDisabledReason: 'This table follows its source. Turn on the override to change it.',
+}
+
+export const Loading = Template.bind({})
+Loading.args = {
+ ...BothSelected.args,
+ destinations: [],
+ loading: true,
+}
+Loading.parameters = {
+ // This story shows a permanent loading state by design, so the test runner must not
+ // wait for the loader to disappear before taking its snapshot.
+ testOptions: { waitForLoadersToDisappear: false },
+}
+
+export const Empty = Template.bind({})
+Empty.args = {
+ ...BothSelected.args,
+ destinations: [],
+ selectedIds: [],
+}
diff --git a/products/data_warehouse/frontend/shared/components/DestinationList.tsx b/products/data_warehouse/frontend/shared/components/DestinationList.tsx
new file mode 100644
index 000000000000..c3c5d3d86eee
--- /dev/null
+++ b/products/data_warehouse/frontend/shared/components/DestinationList.tsx
@@ -0,0 +1,155 @@
+import { IconPencil } from '@posthog/icons'
+import { LemonButton, LemonSwitch, LemonTable, LemonTableColumn, LemonTag } from '@posthog/lemon-ui'
+
+import { AppMetricsSparkline } from 'lib/components/AppMetrics/AppMetricsSparkline'
+
+import { DATA_WAREHOUSE_APP_SOURCE } from 'products/data_warehouse/frontend/shared/components/metrics/DataWarehouseMetrics'
+import { ExternalDataDestinationApi } from 'products/warehouse_sources/frontend/generated/api.schemas'
+
+import { DestinationIcon, destinationTypeLabel } from './DestinationIcon'
+
+/** Where a destination writes, as far as its non-secret config says. Null when there is nothing to add. */
+export function destinationTarget(destination: ExternalDataDestinationApi): string | null {
+ if (destination.is_posthog_warehouse) {
+ return 'Managed by PostHog'
+ }
+ const config = (destination.config ?? {}) as Record<string, unknown>
+ const parts = [config.database, config.schema, config.dataset, config.bucket].filter(
+ (part): part is string => typeof part === 'string' && part.length > 0
+ )
+ return parts.length > 0 ? parts.join('.') : null
+}
+
+export interface DestinationListProps {
+ destinations: ExternalDataDestinationApi[]
+ loading: boolean
+ /** Destinations currently syncing. Rows not listed here render as off. */
+ selectedIds: string[]
+ onToggle: (destinationId: string) => void
+ onEdit: (destination: ExternalDataDestinationApi) => void
+ /** Set to make every toggle read-only, e.g. while a table inherits its source's set. */
+ toggleDisabledReason?: string
+ /**
+ * The source these destinations belong to. Set it to show what each one has been receiving.
+ * Left unset before the source exists, as in the creation wizard, where there is nothing yet.
+ */
+ metricsSourceId?: string
+}
+
+export function DestinationList({
+ destinations,
+ loading,
+ selectedIds,
+ onToggle,
+ onEdit,
+ toggleDisabledReason,
+ metricsSourceId,
+}: DestinationListProps): JSX.Element {
+ // Turning the last one off would leave the source syncing nowhere, which is what disabling a
+ // table is for. Pin it on rather than letting the save fail.
+ const isLastSelected = (id: string): boolean => selectedIds.length === 1 && selectedIds[0] === id
+
+ const columns: LemonTableColumn<ExternalDataDestinationApi, any>[] = [
+ {
+ title: '',
+ key: 'icon',
+ width: 0,
+ render: (_, destination) => <DestinationIcon type={destination.type} />,
+ },
+ {
+ title: 'Name',
+ key: 'name',
+ sorter: (a, b) => a.name.localeCompare(b.name, undefined, { sensitivity: 'base', numeric: true }),
+ render: (_, destination) => (
+ <div className="flex flex-col">
+ <span className="font-semibold">{destination.name}</span>
+ {destinationTarget(destination) ? (
+ <span className="text-muted text-xs">{destinationTarget(destination)}</span>
+ ) : null}
+ </div>
+ ),
+ },
+ {
+ title: 'Type',
+ key: 'type',
+ render: (_, destination) => (
+ <LemonTag type={destination.is_posthog_warehouse ? 'highlight' : 'default'}>
+ {destinationTypeLabel(destination.type)}
+ </LemonTag>
+ ),
+ },
+ ...(metricsSourceId
+ ? [
+ {
+ title: 'Rows synced (7d)',
+ key: 'rows_synced_sparkline',
+ render: function RenderSparkline(_: unknown, destination: ExternalDataDestinationApi) {
+ return (
+ <AppMetricsSparkline
+ logicKey={`dwh-destination-sparkline-${destination.id}`}
+ loadOnChanges
+ successMetricNames={['rows_synced']}
+ metricLabels={{ rows_synced: 'Rows synced' }}
+ forceParams={{
+ appSource: DATA_WAREHOUSE_APP_SOURCE,
+ appSourceId: metricsSourceId,
+ // Runs record each destination on its own, without a schema,
+ // so one series covers every table on the source.
+ instanceId: destination.id,
+ metricName: ['rows_synced'],
+ breakdownBy: 'metric_name',
+ interval: 'day',
+ dateFrom: '-7d',
+ }}
+ />
+ )
+ },
+ },
+ ]
+ : []),
+ {
+ title: '',
+ key: 'actions',
+ width: 0,
+ render: (_, destination) => (
+ <div className="flex gap-2 items-center justify-end">
+ <LemonButton
+ size="small"
+ icon={<IconPencil />}
+ onClick={() => onEdit(destination)}
+ data-attr="warehouse-destination-edit"
+ tooltip={
+ destination.is_posthog_warehouse
+ ? 'The PostHog warehouse is managed for you'
+ : 'Edit this destination'
+ }
+ disabledReason={
+ destination.is_posthog_warehouse ? 'The PostHog warehouse is managed for you' : undefined
+ }
+ />
+ <LemonSwitch
+ checked={selectedIds.includes(destination.id)}
+ onChange={() => onToggle(destination.id)}
+ data-attr="warehouse-destination-toggle"
+ disabledReason={
+ toggleDisabledReason ??
+ (isLastSelected(destination.id)
+ ? 'Pick at least one destination. To stop syncing, turn off syncing instead.'
+ : undefined)
+ }
+ />
+ </div>
+ ),
+ },
+ ]
+
+ return (
+ <LemonTable
+ dataSource={destinations}
+ loading={loading}
+ rowKey={(destination) => destination.id}
+ columns={columns}
+ emptyState="No destinations yet. Add one to sync these tables somewhere besides PostHog."
+ />
+ )
+}
diff --git a/products/data_warehouse/frontend/shared/components/DestinationModal.tsx b/products/data_warehouse/frontend/shared/components/DestinationModal.tsx
new file mode 100644
index 000000000000..cea9ca85e5d5
--- /dev/null
+++ b/products/data_warehouse/frontend/shared/components/DestinationModal.tsx
@@ -0,0 +1,116 @@
+import { useActions, useValues } from 'kea'
+import { Form } from 'kea-forms'
+
+import { LemonButton, LemonInput, LemonModal } from '@posthog/lemon-ui'
+
+import { IntegrationChoice } from 'lib/components/CyclotronJob/integrations/IntegrationChoice'
+import { IntegrationView } from 'lib/integrations/IntegrationView'
+import { LemonBanner } from 'lib/lemon-ui/LemonBanner'
+import { LemonField } from 'lib/lemon-ui/LemonField'
+
+import {
+ DestinationModalLogicProps,
+ destinationModalLogic,
+} from 'products/data_warehouse/frontend/shared/logics/destinationModalLogic'
+
+import { DestinationIcon } from './DestinationIcon'
+
+export function DestinationModal(props: DestinationModalLogicProps): JSX.Element {
+ const logic = destinationModalLogic(props)
+ const { isOpen, editing, editingIntegration, isDestinationFormSubmitting } = useValues(logic)
+ const { closeModal, submitDestinationForm, deleteDestination } = useActions(logic)
+
+ return (
+ <>
+ <LemonModal
+ isOpen={isOpen}
+ onClose={closeModal}
+ title={
+ <div className="flex gap-2 items-center">
+ <DestinationIcon type="Postgres" />
+ <span>{editing ? 'Edit destination' : 'New destination'}</span>
+ </div>
+ }
+ footer={
+ <>
+ {editing && !editing.is_posthog_warehouse ? (
+ <LemonButton
+ type="secondary"
+ status="danger"
+ onClick={() => deleteDestination(editing)}
+ data-attr="warehouse-destination-delete"
+ // Sits apart from Cancel and Save so it is not reached by accident.
+ className="mr-auto"
+ >
+ Delete
+ </LemonButton>
+ ) : null}
+ <LemonButton type="secondary" onClick={closeModal}>
+ Cancel
+ </LemonButton>
+ <LemonButton
+ type="primary"
+ onClick={submitDestinationForm}
+ loading={isDestinationFormSubmitting}
+ data-attr="warehouse-destination-save"
+ >
+ {editing ? 'Save' : 'Add destination'}
+ </LemonButton>
+ </>
+ }
+ >
+ <Form
+ logic={destinationModalLogic}
+ props={props}
+ formKey="destinationForm"
+ className="deprecated-space-y-4"
+ >
+ <LemonField name="name" label="Name">
+ <LemonInput placeholder="Customer Postgres" data-attr="warehouse-destination-name" />
+ </LemonField>
+
+ <LemonField
+ name="integrationId"
+ label="Connection"
+ info="Credentials live on the connection, so one connection can back several destinations and batch exports."
+ >
+ {({ value, onChange }) =>
+ editing ? (
+ editingIntegration ? (
+ <IntegrationView integration={editingIntegration} suffix={<></>} />
+ ) : (
+ <span className="text-muted">
+ This destination's connection is no longer available.
+ </span>
+ )
+ ) : (
+ <IntegrationChoice
+ integration="postgresql"
+ value={value ?? undefined}
+ onChange={onChange}
+ />
+ )
+ }
+ </LemonField>
+
+ <div className="flex gap-2">
+ <LemonField name="database" label="Database" className="flex-1">
+ <LemonInput data-attr="warehouse-destination-database" disabled={!!editing} />
+ </LemonField>
+ <LemonField name="schema" label="Schema" className="flex-1">
+ <LemonInput data-attr="warehouse-destination-schema" disabled={!!editing} />
+ </LemonField>
+ </div>
+
+ {editing ? (
+ <LemonBanner type="info">
+ The connection, database and schema are fixed once a destination exists. Everything already
+ synced sits where it is now, so pointing this somewhere else would leave that behind and
+ need a full resync. Add a second destination instead.
+ </LemonBanner>
+ ) : null}
+ </Form>
+ </LemonModal>
+ </>
+ )
+}
diff --git a/products/data_warehouse/frontend/shared/components/JobDestinations.stories.tsx b/products/data_warehouse/frontend/shared/components/JobDestinations.stories.tsx
new file mode 100644
index 000000000000..da4cbebebeb4
--- /dev/null
+++ b/products/data_warehouse/frontend/shared/components/JobDestinations.stories.tsx
@@ -0,0 +1,68 @@
+import { Meta, StoryFn } from '@storybook/react'
+
+import { ExternalDataDestinationApi } from 'products/warehouse_sources/frontend/generated/api.schemas'
+
+import { JobDestinations, JobDestinationsProps } from './JobDestinations'
+
+const WAREHOUSE = {
+ id: '01a03e9c-1b76-0000-9079-2a0ee2186dea',
+ type: 'PostHogWarehouse',
+ name: 'PostHog warehouse',
+ config: {},
+ integration: null,
+ is_posthog_warehouse: true,
+} as ExternalDataDestinationApi
+
+const POSTGRES = {
+ id: '01a03e9c-1b7c-0000-71ce-5e5d7b04df8f',
+ type: 'Postgres',
+ name: 'Customer Postgres',
+ config: { database: 'analytics', schema: 'customer_sync' },
+ integration: 1,
+ is_posthog_warehouse: false,
+} as ExternalDataDestinationApi
+
+const BY_ID = { [WAREHOUSE.id]: WAREHOUSE, [POSTGRES.id]: POSTGRES }
+
+const meta: Meta<typeof JobDestinations> = {
+ title: 'Data Warehouse/JobDestinations',
+ component: JobDestinations,
+ tags: ['autodocs'],
+}
+export default meta
+
+const Template: StoryFn<typeof JobDestinations> = (props: JobDestinationsProps) => <JobDestinations {...props} />
+
+export const TwoDestinations = Template.bind({})
+TwoDestinations.args = {
+ destinationIds: [WAREHOUSE.id, POSTGRES.id],
+ destinationsById: BY_ID,
+}
+
+export const WarehouseOnly = Template.bind({})
+WarehouseOnly.args = {
+ destinationIds: [WAREHOUSE.id],
+ destinationsById: BY_ID,
+}
+
+// A run from before destinations existed recorded none, so there is nothing to show.
+export const NoneRecorded = Template.bind({})
+NoneRecorded.args = {
+ destinationIds: [],
+ destinationsById: BY_ID,
+}
+
+// Deleting a destination leaves the runs that used it pointing at nothing.
+export const DestinationSinceDeleted = Template.bind({})
+DestinationSinceDeleted.args = {
+ destinationIds: ['01a03e9c-0000-0000-0000-000000000000'],
+ destinationsById: BY_ID,
+}
+
+// Mid-fetch an unknown id is not yet a deleted one, so it stays quiet.
+export const StillLoading = Template.bind({})
+StillLoading.args = {
+ destinationIds: [POSTGRES.id],
+ destinationsById: {},
+ loading: true,
+}
diff --git a/products/data_warehouse/frontend/shared/components/JobDestinations.tsx b/products/data_warehouse/frontend/shared/components/JobDestinations.tsx
new file mode 100644
index 000000000000..1299d3284763
--- /dev/null
+++ b/products/data_warehouse/frontend/shared/components/JobDestinations.tsx
@@ -0,0 +1,60 @@
+import { Tooltip } from 'lib/lemon-ui/Tooltip'
+
+import { ExternalDataDestinationApi } from 'products/warehouse_sources/frontend/generated/api.schemas'
+
+import { DESTINATION_ICON_MAP, destinationTypeLabel } from './DestinationIcon'
+import { destinationTarget } from './DestinationList'
+
+export interface JobDestinationsProps {
+ /** Snapshotted on the run when it started. Empty on runs that predate destinations. */
+ destinationIds: readonly string[]
+ /** Every destination the project has, so ids can be named. Absent until the lookup mounts. */
+ destinationsById?: Record<string, ExternalDataDestinationApi>
+ /** True while `destinationsById` is still being fetched, so an id is not yet unknown. */
+ loading?: boolean
+}
+
+function tooltipFor(destination: ExternalDataDestinationApi): string {
+ const target = destinationTarget(destination)
+ return target ? `${destination.name} — ${target}` : destination.name
+}
+
+/** Where one run delivered, as a logo each. */
+export function JobDestinations({ destinationIds, destinationsById = {}, loading }: JobDestinationsProps): JSX.Element {
+ // A run from before destinations existed wrote to the warehouse and recorded nothing, so it
+ // has nothing to show rather than nothing to say.
+ if (destinationIds.length === 0) {
+ return <span className="text-muted">—</span>
+ }
+
+ const known = destinationIds.map((id) => destinationsById[id]).filter(Boolean)
+
+ if (known.length === 0) {
+ // A table renders rows before the lookup logic has mounted, so an id that is not in the
+ // map yet is not the same as one that will never be there.
+ return loading || Object.keys(destinationsById).length === 0 ? (
+ <span className="text-muted">—</span>
+ ) : (
+ // Deleting a destination leaves the runs that used it pointing at nothing.
+ <Tooltip title="This run delivered to a destination that no longer exists">
+ <span className="text-muted">{destinationIds.length} removed</span>
+ </Tooltip>
+ )
+ }
+
+ return (
+ <div className="flex items-center gap-1">
+ {known.map((destination) => (
+ <Tooltip key={destination.id} title={tooltipFor(destination)}>
+ <span className="flex items-center justify-center size-5">
+ <img
+ src={DESTINATION_ICON_MAP[destination.type]}
+ alt={destinationTypeLabel(destination.type)}
+ className="max-w-full max-h-full"
+ />
+ </span>
+ </Tooltip>
+ ))}
+ </div>
+ )
+}
diff --git a/products/data_warehouse/frontend/shared/components/metrics/DataWarehouseMetrics.tsx b/products/data_warehouse/frontend/shared/components/metrics/DataWarehouseMetrics.tsx
index 3054b4dac9dc..8c5890233ac6 100644
--- a/products/data_warehouse/frontend/shared/components/metrics/DataWarehouseMetrics.tsx
+++ b/products/data_warehouse/frontend/shared/components/metrics/DataWarehouseMetrics.tsx
@@ -1,10 +1,19 @@
-import { useValues } from 'kea'
+import { useActions, useValues } from 'kea'
+import { useEffect, useState } from 'react'
import { getColorVar } from 'lib/colors'
import { AppMetricsFilters } from 'lib/components/AppMetrics/AppMetricsFilters'
import { appMetricsLogic } from 'lib/components/AppMetrics/appMetricsLogic'
import { AppMetricsTrends } from 'lib/components/AppMetrics/AppMetricsTrends'
import { AppMetricSummary } from 'lib/components/AppMetrics/AppMetricSummary'
+import { FEATURE_FLAGS } from 'lib/constants'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import { teamLogic } from 'scenes/teamLogic'
+
+import { destinationLookupLogic } from 'products/data_warehouse/frontend/shared/logics/destinationLookupLogic'
+import { externalDataSourcesDestinationsRetrieve } from 'products/warehouse_sources/frontend/generated/api'
+
+import { DestinationMetricSummary } from './DestinationMetricSummary'
export const DATA_WAREHOUSE_APP_SOURCE = 'warehouse_source_sync'
@@ -28,7 +37,7 @@ const DATA_WAREHOUSE_METRICS_INFO: Record<string, { name: string; description: s
},
rows_synced: {
name: 'Rows synced',
- description: 'Total number of rows imported from the source',
+ description: 'Rows read from the source. A run reads them once however many destinations it writes to.',
color: getColorVar('success'),
},
}
@@ -57,6 +66,30 @@ export function DataWarehouseMetrics({ logicKey, sourceId, schemaId }: DataWareh
})
const { appMetricsTrends, appMetricsTrendsLoading, getSingleTrendSeries } = useValues(logic)
+ const { featureFlags } = useValues(featureFlagLogic)
+ const { currentTeamId } = useValues(teamLogic)
+ const { destinations } = useValues(destinationLookupLogic)
+ const { loadDestinations } = useActions(destinationLookupLogic)
+ const [attachedIds, setAttachedIds] = useState<string[] | null>(null)
+
+ const showDestinations = !!featureFlags[FEATURE_FLAGS.WAREHOUSE_MULTI_DESTINATION] && !schemaId
+
+ useEffect(() => {
+ if (!showDestinations) {
+ return
+ }
+ loadDestinations()
+ // Only the destinations this source actually writes to. The lookup holds every destination
+ // the project has, and one the source does not use has nothing to chart.
+ externalDataSourcesDestinationsRetrieve(String(currentTeamId), sourceId)
+ .then((response) => setAttachedIds(response.destination_ids ?? []))
+ .catch(() => setAttachedIds([]))
+ }, [showDestinations, loadDestinations, currentTeamId, sourceId])
+
+ const attached = destinations.filter((destination) => attachedIds?.includes(destination.id))
+ // With a single destination every row already went there, so a breakdown would repeat the
+ // totals above it.
+ const destinationBreakdown = showDestinations && attached.length > 1 ? attached : []
const metricLabels = Object.fromEntries(
DATA_WAREHOUSE_METRIC_KEYS.map((key) => [key, DATA_WAREHOUSE_METRICS_INFO[key].name])
@@ -88,6 +121,21 @@ export function DataWarehouseMetrics({ logicKey, sourceId, schemaId }: DataWareh
loading={appMetricsTrendsLoading}
metricLabels={metricLabels}
/>
+
+ {destinationBreakdown.length > 0 && (
+ <>
+ <h3 className="mb-0 mt-2">By destination</h3>
+ <div className="flex flex-row gap-2 flex-wrap justify-center">
+ {destinationBreakdown.map((destination) => (
+ <DestinationMetricSummary
+ key={destination.id}
+ sourceId={sourceId}
+ destination={destination}
+ />
+ ))}
+ </div>
+ </>
+ )}
</div>
)
}
diff --git a/products/data_warehouse/frontend/shared/components/metrics/DestinationMetricSummary.tsx b/products/data_warehouse/frontend/shared/components/metrics/DestinationMetricSummary.tsx
new file mode 100644
index 000000000000..14037455453b
--- /dev/null
+++ b/products/data_warehouse/frontend/shared/components/metrics/DestinationMetricSummary.tsx
@@ -0,0 +1,48 @@
+import { useValues } from 'kea'
+
+import { getColorVar } from 'lib/colors'
+import { appMetricsLogic } from 'lib/components/AppMetrics/appMetricsLogic'
+import { AppMetricSummary } from 'lib/components/AppMetrics/AppMetricSummary'
+
+import { destinationTarget } from 'products/data_warehouse/frontend/shared/components/DestinationList'
+import { ExternalDataDestinationApi } from 'products/warehouse_sources/frontend/generated/api.schemas'
+
+import { DATA_WAREHOUSE_APP_SOURCE } from './DataWarehouseMetrics'
+
+export interface DestinationMetricSummaryProps {
+ sourceId: string
+ destination: ExternalDataDestinationApi
+}
+
+/** What one destination has received from this source, across all of its tables. */
+export function DestinationMetricSummary({ sourceId, destination }: DestinationMetricSummaryProps): JSX.Element {
+ const logic = appMetricsLogic({
+ logicKey: `dwh-destination-metrics-${sourceId}-${destination.id}`,
+ loadOnMount: true,
+ loadOnChanges: true,
+ forceParams: {
+ appSource: DATA_WAREHOUSE_APP_SOURCE,
+ appSourceId: sourceId,
+ // Runs record each destination on its own, without a schema, so this covers every
+ // table on the source rather than needing one request per table.
+ instanceId: destination.id,
+ metricName: ['rows_synced'],
+ breakdownBy: 'metric_name',
+ },
+ })
+
+ const { appMetricsTrendsLoading, getSingleTrendSeries } = useValues(logic)
+ const target = destinationTarget(destination)
+
+ return (
+ <AppMetricSummary
+ name={destination.name}
+ description={target ? `Rows written to ${target}` : `Rows written to ${destination.name}`}
+ loading={appMetricsTrendsLoading}
+ timeSeries={getSingleTrendSeries('rows_synced')}
+ previousPeriodTimeSeries={getSingleTrendSeries('rows_synced', true)}
+ color={getColorVar('success')}
+ colorIfZero={getColorVar('muted')}
+ />
+ )
+}
diff --git a/products/data_warehouse/frontend/shared/logics/destinationLookupLogic.ts b/products/data_warehouse/frontend/shared/logics/destinationLookupLogic.ts
new file mode 100644
index 000000000000..7bf9253140a3
--- /dev/null
+++ b/products/data_warehouse/frontend/shared/logics/destinationLookupLogic.ts
@@ -0,0 +1,80 @@
+import { connect, kea, path, selectors } from 'kea'
+import { MakeLogicType } from 'kea'
+import { loaders } from 'kea-loaders'
+
+import { teamLogic } from 'scenes/teamLogic'
+
+import { externalDataDestinationsList } from 'products/warehouse_sources/frontend/generated/api'
+import { ExternalDataDestinationApi } from 'products/warehouse_sources/frontend/generated/api.schemas'
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface destinationLookupLogicValues {
+ currentTeamId: number | null // teamLogic
+ destinations: ExternalDataDestinationApi[]
+ destinationsById: Record<string, ExternalDataDestinationApi>
+ destinationsLoading: boolean
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface destinationLookupLogicActions {
+ loadDestinations: () => any
+ loadDestinationsFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadDestinationsSuccess: (
+ destinations: ExternalDataDestinationApi[],
+ payload?: any
+ ) => {
+ destinations: ExternalDataDestinationApi[]
+ payload?: any
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface destinationLookupLogicMeta {
+ __keaTypeGenInternalSelectorTypes: {
+ destinationsById: (destinations: any) => Record<string, ExternalDataDestinationApi>
+ }
+}
+
+export type destinationLookupLogicType = MakeLogicType<
+ destinationLookupLogicValues,
+ destinationLookupLogicActions,
+ Record<string, any>,
+ destinationLookupLogicMeta
+>
+
+/**
+ * Every destination the project has, keyed by id.
+ *
+ * A run records only destination ids, so any surface naming a run's destinations needs the rows
+ * to go with them. One mounted logic serves them all rather than each list fetching its own.
+ */
+export const destinationLookupLogic = kea<destinationLookupLogicType>([
+ path(['products', 'data_warehouse', 'shared', 'destinationLookupLogic']),
+ connect(() => ({
+ values: [teamLogic, ['currentTeamId']],
+ })),
+ loaders(({ values }) => ({
+ destinations: [
+ [] as ExternalDataDestinationApi[],
+ {
+ loadDestinations: async () => {
+ const response = await externalDataDestinationsList(String(values.currentTeamId))
+ return response.results ?? []
+ },
+ },
+ ],
+ })),
+ selectors({
+ destinationsById: [
+ (s: any) => [s.destinations],
+ (destinations: ExternalDataDestinationApi[]): Record<string, ExternalDataDestinationApi> =>
+ Object.fromEntries(destinations.map((destination) => [destination.id, destination])),
+ ],
+ }),
+])
diff --git a/products/data_warehouse/frontend/shared/logics/destinationModalLogic.ts b/products/data_warehouse/frontend/shared/logics/destinationModalLogic.ts
new file mode 100644
index 000000000000..e370a2de5e28
--- /dev/null
+++ b/products/data_warehouse/frontend/shared/logics/destinationModalLogic.ts
@@ -0,0 +1,250 @@
+import { MakeLogicType, actions, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
+import { forms } from 'kea-forms'
+import type { DeepPartialMap, ValidationErrorType } from 'kea-forms'
+import type { DeepPartial, FieldName } from 'kea-forms'
+
+import { integrationsLogic } from 'lib/integrations/integrationsLogic'
+import { LemonDialog } from 'lib/lemon-ui/LemonDialog'
+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
+import { teamLogic } from 'scenes/teamLogic'
+
+import type { IntegrationType } from '~/types'
+
+import {
+ externalDataDestinationsCreate,
+ externalDataDestinationsDestroy,
+ externalDataDestinationsPartialUpdate,
+} from 'products/warehouse_sources/frontend/generated/api'
+import { ExternalDataDestinationApi } from 'products/warehouse_sources/frontend/generated/api.schemas'
+
+export interface DestinationModalLogicProps {
+ /** Distinguishes the source-level modal from the schema-level one so they keep separate form state. */
+ modalKey: string
+ onSaved: (destination: ExternalDataDestinationApi) => void
+ /** Called after a destination is deleted, so the caller can drop it from its list. */
+ onDeleted?: (destinationId: string) => void
+}
+
+export interface DestinationFormValues {
+ name: string
+ integrationId: number | null
+ database: string
+ schema: string
+}
+
+const NEW_DESTINATION_FORM: DestinationFormValues = {
+ name: '',
+ integrationId: null,
+ database: 'postgres',
+ schema: 'public',
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface destinationModalLogicValues {
+ integrations: IntegrationType[] | null // integrationsLogic
+ currentTeamId: number | null // teamLogic
+ destinationForm: DestinationFormValues
+ destinationFormAllErrors: Record<string, any>
+ destinationFormChanged: boolean
+ destinationFormErrors: DeepPartialMap<DestinationFormValues, ValidationErrorType>
+ destinationFormHasErrors: boolean
+ destinationFormManualErrors: Record<string, any>
+ destinationFormTouched: boolean
+ destinationFormTouches: Record<string, boolean>
+ destinationFormValidationErrors: DeepPartialMap<DestinationFormValues, ValidationErrorType>
+ editing: ExternalDataDestinationApi | null
+ editingIntegration: IntegrationType | null
+ isDestinationFormSubmitting: boolean
+ isDestinationFormValid: boolean
+ isOpen: boolean
+ postgresIntegrations: IntegrationType[]
+ showDestinationFormErrors: boolean
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface destinationModalLogicActions {
+ loadIntegrations: () => any // integrationsLogic
+ closeModal: () => {
+ value: true
+ }
+ deleteDestination: (destination: ExternalDataDestinationApi) => {
+ destination: ExternalDataDestinationApi
+ }
+ openForCreate: () => {
+ value: true
+ }
+ openForEdit: (destination: ExternalDataDestinationApi) => {
+ destination: ExternalDataDestinationApi
+ }
+ resetDestinationForm: (values?: DestinationFormValues) => {
+ values?: DestinationFormValues
+ }
+ setDestinationFormManualErrors: (errors: Record<string, any>) => {
+ errors: Record<string, any>
+ }
+ setDestinationFormValue: (
+ key: FieldName,
+ value: any
+ ) => {
+ name: FieldName
+ value: any
+ }
+ setDestinationFormValues: (values: DeepPartial<DestinationFormValues>) => {
+ values: DeepPartial<DestinationFormValues>
+ }
+ submitDestinationForm: () => {
+ value: boolean
+ }
+ submitDestinationFormFailure: (
+ error: Error,
+ errors: Record<string, any>
+ ) => {
+ error: Error
+ errors: Record<string, any>
+ }
+ submitDestinationFormRequest: (destinationForm: DestinationFormValues) => {
+ destinationForm: DestinationFormValues
+ }
+ submitDestinationFormSuccess: (destinationForm: DestinationFormValues) => {
+ destinationForm: DestinationFormValues
+ }
+ touchDestinationFormField: (key: string) => {
+ key: string
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface destinationModalLogicMeta {
+ key: string
+ __keaTypeGenInternalSelectorTypes: {
+ postgresIntegrations: (integrations: any) => IntegrationType[]
+ editingIntegration: (editing: any, integrations: any) => IntegrationType | null
+ }
+}
+
+export type destinationModalLogicType = MakeLogicType<
+ destinationModalLogicValues,
+ destinationModalLogicActions,
+ DestinationModalLogicProps,
+ destinationModalLogicMeta
+>
+
+export const destinationModalLogic = kea<destinationModalLogicType>([
+ path(['products', 'data_warehouse', 'frontend', 'shared', 'logics', 'destinationModalLogic']),
+ props({} as DestinationModalLogicProps),
+ key((props: DestinationModalLogicProps) => props.modalKey),
+ connect(() => ({
+ values: [teamLogic, ['currentTeamId'], integrationsLogic, ['integrations']],
+ actions: [integrationsLogic, ['loadIntegrations']],
+ })),
+ actions({
+ openForCreate: true,
+ openForEdit: (destination: ExternalDataDestinationApi) => ({ destination }),
+ closeModal: true,
+ deleteDestination: (destination: ExternalDataDestinationApi) => ({ destination }),
+ }),
+ reducers({
+ isOpen: [
+ false,
+ {
+ openForCreate: () => true,
+ openForEdit: () => true,
+ closeModal: () => false,
+ },
+ ],
+ editing: [
+ null as ExternalDataDestinationApi | null,
+ {
+ openForCreate: () => null,
+ openForEdit: (_, { destination }) => destination,
+ closeModal: () => null,
+ },
+ ],
+ }),
+ selectors({
+ postgresIntegrations: [
+ (s: any) => [s.integrations],
+ (integrations: IntegrationType[] | null): IntegrationType[] =>
+ (integrations ?? []).filter((integration) => integration.kind === 'postgresql'),
+ ],
+ // The connection a destination already has, so editing can show it without offering to
+ // change it. Null while integrations load, or if the integration was deleted.
+ editingIntegration: [
+ (s: any) => [s.editing, s.integrations],
+ (
+ editing: ExternalDataDestinationApi | null,
+ integrations: IntegrationType[] | null
+ ): IntegrationType | null =>
+ (editing?.integration && integrations?.find((one) => one.id === editing.integration)) || null,
+ ],
+ }),
+ forms(({ values, props, actions }: any) => ({
+ destinationForm: {
+ defaults: NEW_DESTINATION_FORM,
+ errors: ({ name, integrationId }: DestinationFormValues) => ({
+ name: !name?.trim() ? 'Give this destination a name' : undefined,
+ integrationId: integrationId ? undefined : 'Pick a connection',
+ }),
+ submit: async (formValues: DestinationFormValues) => {
+ const payload = {
+ type: 'Postgres' as const,
+ name: formValues.name.trim(),
+ integration: formValues.integrationId,
+ config: { database: formValues.database, schema: formValues.schema },
+ }
+ const teamId = String(values.currentTeamId)
+ const saved = values.editing
+ ? await externalDataDestinationsPartialUpdate(teamId, values.editing.id, payload)
+ : await externalDataDestinationsCreate(teamId, payload)
+
+ lemonToast.success(values.editing ? 'Destination updated' : 'Destination added')
+ actions.closeModal()
+ props.onSaved(saved)
+ },
+ },
+ })),
+ listeners(({ actions, values, props }: any) => ({
+ deleteDestination: ({ destination }: { destination: ExternalDataDestinationApi }) => {
+ LemonDialog.open({
+ title: `Delete ${destination.name}?`,
+ description:
+ 'Every source and table that syncs here stops doing so. Tables already written ' +
+ 'to it are left where they are, and runs already under way finish first. ' +
+ 'This cannot be undone.',
+ primaryButton: {
+ children: 'Delete destination',
+ status: 'danger',
+ onClick: async () => {
+ try {
+ await externalDataDestinationsDestroy(String(values.currentTeamId), destination.id)
+ lemonToast.success(`Deleted ${destination.name}`)
+ actions.closeModal()
+ props.onDeleted?.(destination.id)
+ } catch (e: any) {
+ lemonToast.error(e.detail ?? `Could not delete ${destination.name}`)
+ }
+ },
+ },
+ secondaryButton: { children: 'Cancel' },
+ })
+ },
+ openForCreate: () => {
+ actions.loadIntegrations()
+ actions.setDestinationFormValues({
+ ...NEW_DESTINATION_FORM,
+ // One connection usually means one obvious answer; preselect it.
+ integrationId: values.postgresIntegrations.length === 1 ? values.postgresIntegrations[0].id : null,
+ })
+ },
+ openForEdit: ({ destination }: { destination: ExternalDataDestinationApi }) => {
+ actions.loadIntegrations()
+ const config = (destination.config ?? {}) as Record<string, unknown>
+ actions.setDestinationFormValues({
+ name: destination.name,
+ integrationId: destination.integration ?? null,
+ database: typeof config.database === 'string' ? config.database : 'postgres',
+ schema: typeof config.schema === 'string' ? config.schema : 'public',
+ })
+ },
+ })),
+])
diff --git a/products/model_crossing_uses_baseline.txt b/products/model_crossing_uses_baseline.txt
index 245dce8191e8..91b95d8f222f 100644
--- a/products/model_crossing_uses_baseline.txt
+++ b/products/model_crossing_uses_baseline.txt
@@ -115,6 +115,7 @@ posthog.Integration slack_app.SlackThreadTaskMapping.integration reverse-accesso
posthog.Integration slack_app.SlackUserProfileCache.integration reverse-accessor(slack_user_profile_cache) 1
posthog.Integration tasks.SandboxSnapshot.integration reverse-accessor(snapshots) 1
posthog.Integration tasks.Task.github_integration reverse-accessor(task_set) 1
+posthog.Integration warehouse_sources.ExternalDataDestination.integration reverse-accessor(externaldatadestination_set) 1
posthog.Organization access_control.OrganizationResourceAccess.organization reverse-accessor(resource_access) 1
posthog.Organization access_control.Role.organization reverse-accessor(roles) 1
posthog.Organization access_control.RoleExternalReference.organization reverse-accessor(role_external_references) 1
@@ -390,10 +391,13 @@ posthog.Team user_interviews.UserInterviewTopic.team reverse-accessor(userinterv
posthog.Team warehouse_sources.CustomOAuth2Integration.team reverse-accessor(customoauth2integration_set) 1
posthog.Team warehouse_sources.DataWarehouseCredential.team reverse-accessor(datawarehousecredential_set) 1
posthog.Team warehouse_sources.DataWarehouseTable.team reverse-accessor(datawarehousetable_set) 1
+posthog.Team warehouse_sources.ExternalDataDestination.team reverse-accessor(externaldatadestination_set) 1
posthog.Team warehouse_sources.ExternalDataJob.team reverse-accessor(externaldatajob_set) 1
posthog.Team warehouse_sources.ExternalDataSchema.team reverse-accessor(externaldataschema_set) 1
+posthog.Team warehouse_sources.ExternalDataSchemaDestination.team reverse-accessor(externaldataschemadestination_set) 1
posthog.Team warehouse_sources.ExternalDataSchemaOOMEvent.team reverse-accessor(externaldataschemaoomevent_set) 1
posthog.Team warehouse_sources.ExternalDataSource.team reverse-accessor(externaldatasource_set) 1
+posthog.Team warehouse_sources.ExternalDataSourceDestination.team reverse-accessor(externaldatasourcedestination_set) 1
posthog.Team warehouse_sources.PendingSourceCredential.team reverse-accessor(pendingsourcecredential_set) 1
posthog.Team warehouse_sources.WarehouseColumnAnnotation.team reverse-accessor(warehousecolumnannotation_set) 1
posthog.Team warehouse_sources.WarehouseColumnStatistics.team reverse-accessor(warehousecolumnstatistics_set) 1
@@ -574,6 +578,7 @@ posthog.User user_interviews.UserInterviewTopic.created_by reverse-accessor(user
posthog.User warehouse_sources.CustomOAuth2Integration.created_by reverse-accessor(customoauth2integration_set) 1
posthog.User warehouse_sources.DataWarehouseCredential.created_by reverse-accessor(datawarehousecredential_set) 1
posthog.User warehouse_sources.DataWarehouseTable.created_by reverse-accessor(datawarehousetable_set) 1
+posthog.User warehouse_sources.ExternalDataDestination.created_by reverse-accessor(externaldatadestination_set) 1
posthog.User warehouse_sources.ExternalDataJob.created_by reverse-accessor(externaldatajob_set) 1
posthog.User warehouse_sources.ExternalDataSchema.created_by reverse-accessor(externaldataschema_set) 1
posthog.User warehouse_sources.ExternalDataSource.created_by reverse-accessor(externaldatasource_set) 1
@@ -739,7 +744,7 @@ warehouse_sources.DataWarehouseTable products.marketing_analytics.backend.manage
warehouse_sources.DataWarehouseTable products.posthog_ai.evals.data_warehouse.seeder construct 1
warehouse_sources.DataWarehouseTable products.posthog_ai.evals.data_warehouse.seeder write(bulk_create) 1
warehouse_sources.DataWarehouseTable products.posthog_ai.evals.data_warehouse.seeder write(create) 1
-warehouse_sources.ExternalDataJob posthog.tasks.usage_report instance-many(annotate) 4
+warehouse_sources.ExternalDataJob posthog.tasks.usage_report instance-many(annotate) 1
warehouse_sources.ExternalDataJob products.data_warehouse.backend.logic.data_load.source_templates instance-single 2
warehouse_sources.ExternalDataJob products.data_warehouse.backend.logic.external_data_source.jobs lock 1
warehouse_sources.ExternalDataJob products.data_warehouse.backend.logic.external_data_source.notifications instance-many(filter) 2
diff --git a/products/warehouse_sources/backend/facade/models.py b/products/warehouse_sources/backend/facade/models.py
index 287f95e0dc35..3549002a0751 100644
--- a/products/warehouse_sources/backend/facade/models.py
+++ b/products/warehouse_sources/backend/facade/models.py
@@ -18,6 +18,12 @@ from products.warehouse_sources.backend.models.credential import (
DataWarehouseCredential,
get_or_create_datawarehouse_credential,
)
+from products.warehouse_sources.backend.models.external_data_destination import (
+ ExternalDataDestination,
+ ExternalDataSchemaDestination,
+ ExternalDataSourceDestination,
+ resolve_destinations,
+)
from products.warehouse_sources.backend.models.external_data_job import (
ExternalDataJob,
get_latest_run_if_exists,
@@ -74,9 +80,12 @@ __all__ = [
"DataWarehouseCredential",
"DataWarehouseTable",
"DataWarehouseTableColumns",
+ "ExternalDataDestination",
"ExternalDataJob",
"ExternalDataSchema",
+ "ExternalDataSchemaDestination",
"ExternalDataSource",
+ "ExternalDataSourceDestination",
"MANAGED_WAREHOUSE_LEGACY_CREDENTIAL_KINDS",
"MANAGED_WAREHOUSE_PROJECT_READER_CREDENTIAL_KIND",
"MANAGED_WAREHOUSE_SERVICE_CREDENTIAL_KIND",
@@ -107,6 +116,7 @@ __all__ = [
"postgres_column_to_dwh_column",
"postgres_columns_to_dwh_columns",
"remove_named_tuples",
+ "resolve_destinations",
"snowflake_column_to_dwh_column",
"snowflake_columns_to_dwh_columns",
"sync_frequency_interval_to_sync_frequency",
diff --git a/products/warehouse_sources/backend/migrations/0159_externaldatajob_destination_ids_and_more.py b/products/warehouse_sources/backend/migrations/0159_externaldatajob_destination_ids_and_more.py
new file mode 100644
index 000000000000..f7552d58e139
--- /dev/null
+++ b/products/warehouse_sources/backend/migrations/0159_externaldatajob_destination_ids_and_more.py
@@ -0,0 +1,217 @@
+# Generated by Django 5.2.17 on 2026-08-24 16:50
+
+import django.db.models.deletion
+from django.conf import settings
+from django.db import migrations, models
+
+import posthog.uuidt
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("posthog", "1315_githubinstallrequest_account"),
+ ("warehouse_sources", "0158_migrate_shopify_job_inputs_to_auth_method"),
+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="externaldatajob",
+ name="destination_ids",
+ field=models.JSONField(blank=True, db_default=[], default=list),
+ ),
+ migrations.CreateModel(
+ name="ExternalDataDestination",
+ fields=[
+ ("updated_at", models.DateTimeField(auto_now=True, null=True)),
+ ("deleted", models.BooleanField(blank=True, default=False, null=True)),
+ ("deleted_at", models.DateTimeField(blank=True, null=True)),
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.uuidt.UUIDT,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ (
+ "type",
+ models.CharField(
+ choices=[
+ ("PostHogWarehouse", "PostHog warehouse"),
+ ("Redshift", "Redshift"),
+ ("Snowflake", "Snowflake"),
+ ("BigQuery", "BigQuery"),
+ ("Postgres", "Postgres"),
+ ("Databricks", "Databricks"),
+ ("AzureBlob", "Azure Blob"),
+ ("S3", "S3"),
+ ],
+ max_length=64,
+ ),
+ ),
+ ("name", models.CharField(max_length=400)),
+ (
+ "config",
+ models.JSONField(
+ blank=True,
+ default=dict,
+ help_text="Non-secret shape config: target database/schema/dataset, bucket and prefix, file format.",
+ ),
+ ),
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ (
+ "created_by",
+ models.ForeignKey(
+ blank=True,
+ db_constraint=False,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ to=settings.AUTH_USER_MODEL,
+ ),
+ ),
+ (
+ "integration",
+ models.ForeignKey(
+ blank=True,
+ help_text="Credentials for this destination. Null for the PostHog warehouse.",
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ to="posthog.integration",
+ ),
+ ),
+ (
+ "team",
+ models.ForeignKey(
+ db_constraint=False,
+ on_delete=django.db.models.deletion.CASCADE,
+ to="posthog.team",
+ ),
+ ),
+ ],
+ options={
+ "db_table": "posthog_externaldatadestination",
+ },
+ ),
+ migrations.CreateModel(
+ name="ExternalDataSchemaDestination",
+ fields=[
+ ("updated_at", models.DateTimeField(auto_now=True, null=True)),
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.uuidt.UUIDT,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ ("enabled", models.BooleanField(db_default=True, default=True)),
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ (
+ "destination",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="schema_links",
+ to="warehouse_sources.externaldatadestination",
+ ),
+ ),
+ (
+ "schema",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="destination_links",
+ to="warehouse_sources.externaldataschema",
+ ),
+ ),
+ (
+ "team",
+ models.ForeignKey(
+ db_constraint=False,
+ on_delete=django.db.models.deletion.CASCADE,
+ to="posthog.team",
+ ),
+ ),
+ ],
+ options={
+ "db_table": "posthog_externaldataschemadestination",
+ },
+ ),
+ migrations.CreateModel(
+ name="ExternalDataSourceDestination",
+ fields=[
+ ("updated_at", models.DateTimeField(auto_now=True, null=True)),
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.uuidt.UUIDT,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ ("enabled", models.BooleanField(db_default=True, default=True)),
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ (
+ "destination",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="source_links",
+ to="warehouse_sources.externaldatadestination",
+ ),
+ ),
+ (
+ "source",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="destination_links",
+ to="warehouse_sources.externaldatasource",
+ ),
+ ),
+ (
+ "team",
+ models.ForeignKey(
+ db_constraint=False,
+ on_delete=django.db.models.deletion.CASCADE,
+ to="posthog.team",
+ ),
+ ),
+ ],
+ options={
+ "db_table": "posthog_externaldatasourcedestination",
+ },
+ ),
+ migrations.AddIndex(
+ model_name="externaldatadestination",
+ index=models.Index(fields=["team", "type"], name="wsd_team_type_idx"),
+ ),
+ migrations.AddIndex(
+ model_name="externaldatadestination",
+ index=models.Index(fields=["updated_at"], name="wsd_dest_updated_idx"),
+ ),
+ migrations.AddConstraint(
+ model_name="externaldatadestination",
+ constraint=models.UniqueConstraint(
+ condition=models.Q(("deleted", False), ("type", "PostHogWarehouse")),
+ fields=("team",),
+ name="wsd_one_warehouse_dest_per_team",
+ ),
+ ),
+ migrations.AddIndex(
+ model_name="externaldataschemadestination",
+ index=models.Index(fields=["updated_at"], name="wsd_schema_link_upd_idx"),
+ ),
+ migrations.AddConstraint(
+ model_name="externaldataschemadestination",
+ constraint=models.UniqueConstraint(fields=("schema", "destination"), name="wsd_schema_dest_uniq"),
+ ),
+ migrations.AddIndex(
+ model_name="externaldatasourcedestination",
+ index=models.Index(fields=["updated_at"], name="wsd_src_link_updated_idx"),
+ ),
+ migrations.AddConstraint(
+ model_name="externaldatasourcedestination",
+ constraint=models.UniqueConstraint(fields=("source", "destination"), name="wsd_source_dest_uniq"),
+ ),
+ ]
diff --git a/products/warehouse_sources/backend/migrations/max_migration.txt b/products/warehouse_sources/backend/migrations/max_migration.txt
index 3b0e145cbfcb..0f316a890750 100644
--- a/products/warehouse_sources/backend/migrations/max_migration.txt
+++ b/products/warehouse_sources/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0158_migrate_shopify_job_inputs_to_auth_method
+0159_externaldatajob_destination_ids_and_more
diff --git a/products/warehouse_sources/backend/models/__init__.py b/products/warehouse_sources/backend/models/__init__.py
index c622c1e6036c..b389a73c846a 100644
--- a/products/warehouse_sources/backend/models/__init__.py
+++ b/products/warehouse_sources/backend/models/__init__.py
@@ -2,6 +2,11 @@ from .column_annotation import WarehouseColumnAnnotation
from .column_statistics import WarehouseColumnStatistics
from .credential import DataWarehouseCredential
from .custom_oauth2_integration import CustomOAuth2Integration
+from .external_data_destination import (
+ ExternalDataDestination,
+ ExternalDataSchemaDestination,
+ ExternalDataSourceDestination,
+)
from .external_data_job import ExternalDataJob
from .external_data_schema import ExternalDataSchema
from .external_data_source import ExternalDataSource
@@ -13,8 +18,11 @@ __all__ = [
"CustomOAuth2Integration",
"DataWarehouseCredential",
"DataWarehouseTable",
+ "ExternalDataDestination",
"ExternalDataJob",
"ExternalDataSchema",
+ "ExternalDataSchemaDestination",
+ "ExternalDataSourceDestination",
"ExternalDataSchemaOOMEvent",
"ExternalDataSource",
"PendingSourceCredential",
diff --git a/products/warehouse_sources/backend/models/external_data_destination.py b/products/warehouse_sources/backend/models/external_data_destination.py
new file mode 100644
index 000000000000..8bd0f8441609
--- /dev/null
+++ b/products/warehouse_sources/backend/models/external_data_destination.py
@@ -0,0 +1,172 @@
+from django.db import models
+
+from posthog.models.scoping.root_mixin import TeamScopedRootMixin
+from posthog.models.utils import DeletedMetaFields, UpdatedMetaFields, UUIDTModel, sane_repr
+
+
+class ExternalDataDestination(TeamScopedRootMixin, UpdatedMetaFields, DeletedMetaFields, UUIDTModel):
+ """Somewhere a warehouse source writes its synced rows.
+
+ The PostHog warehouse is one of these, not a special case: a schema's destination set
+ decides where its rows land, and an empty set resolves to the team's warehouse row so
+ sources configured before this feature keep their existing behavior.
+
+ Credentials live on the linked `Integration`, never in `config` — the same split batch
+ exports use, so both products share the integration setup UI and connection tests.
+ """
+
+ class Type(models.TextChoices):
+ POSTHOG_WAREHOUSE = "PostHogWarehouse", "PostHog warehouse"
+ # Values match `BatchExportDestination.Destination` so a destination type resolves to
+ # the same writer vocabulary in both products. Spelled out rather than imported to
+ # keep a model migration from depending on another product's enum.
+ REDSHIFT = "Redshift", "Redshift"
+ SNOWFLAKE = "Snowflake", "Snowflake"
+ BIGQUERY = "BigQuery", "BigQuery"
+ POSTGRES = "Postgres", "Postgres"
+ DATABRICKS = "Databricks", "Databricks"
+ AZURE_BLOB = "AzureBlob", "Azure Blob"
+ S3 = "S3", "S3"
+
+ # `db_constraint=False`: a real FK constraint to the hot `posthog_team` table would
+ # take a lock on it while being created. Team scoping is enforced at the app level
+ # via `TeamScopedRootMixin`. See products/README.md "Adding or moving backend models
+ # and migrations".
+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, db_constraint=False)
+ type = models.CharField(max_length=64, choices=Type)
+ name = models.CharField(max_length=400)
+ config = models.JSONField(
+ default=dict,
+ blank=True,
+ help_text="Non-secret shape config: target database/schema/dataset, bucket and prefix, file format.",
+ )
+ integration = models.ForeignKey(
+ "posthog.Integration",
+ on_delete=models.SET_NULL,
+ null=True,
+ blank=True,
+ help_text="Credentials for this destination. Null for the PostHog warehouse.",
+ )
+ # `db_constraint=False`: `posthog_user` is a hot table, same reasoning as `team`.
+ created_by = models.ForeignKey(
+ "posthog.User", on_delete=models.SET_NULL, null=True, blank=True, db_constraint=False
+ )
+ created_at = models.DateTimeField(auto_now_add=True)
+
+ __repr__ = sane_repr("id", "team_id", "type", "name")
+
+ class Meta:
+ db_table = "posthog_externaldatadestination"
+ constraints = [
+ models.UniqueConstraint(
+ fields=["team"],
+ condition=models.Q(type="PostHogWarehouse", deleted=False),
+ name="wsd_one_warehouse_dest_per_team",
+ ),
+ ]
+ indexes = [
+ models.Index(fields=["team", "type"], name="wsd_team_type_idx"),
+ models.Index(fields=["updated_at"], name="wsd_dest_updated_idx"),
+ ]
+
+ @property
+ def is_posthog_warehouse(self) -> bool:
+ return self.type == self.Type.POSTHOG_WAREHOUSE
+
+
+class ExternalDataSourceDestination(TeamScopedRootMixin, UpdatedMetaFields, UUIDTModel):
+ """Source-level default destination set, inherited by every schema that does not override it."""
+
+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, db_constraint=False)
+ source = models.ForeignKey(
+ "warehouse_sources.ExternalDataSource", on_delete=models.CASCADE, related_name="destination_links"
+ )
+ destination = models.ForeignKey(ExternalDataDestination, on_delete=models.CASCADE, related_name="source_links")
+ enabled = models.BooleanField(default=True, db_default=True)
+ created_at = models.DateTimeField(auto_now_add=True)
+
+ __repr__ = sane_repr("id", "source_id", "destination_id", "enabled")
+
+ class Meta:
+ db_table = "posthog_externaldatasourcedestination"
+ constraints = [
+ models.UniqueConstraint(fields=["source", "destination"], name="wsd_source_dest_uniq"),
+ ]
+ indexes = [
+ models.Index(fields=["updated_at"], name="wsd_src_link_updated_idx"),
+ ]
+
+
+class ExternalDataSchemaDestination(TeamScopedRootMixin, UpdatedMetaFields, UUIDTModel):
+ """Schema-level destination override.
+
+ Any row here — even a fully disabled set — replaces the source-level set for that schema,
+ mirroring how `ExternalDataSchema.api_version` overrides the source pin.
+ """
+
+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, db_constraint=False)
+ schema = models.ForeignKey(
+ "warehouse_sources.ExternalDataSchema", on_delete=models.CASCADE, related_name="destination_links"
+ )
+ destination = models.ForeignKey(ExternalDataDestination, on_delete=models.CASCADE, related_name="schema_links")
+ enabled = models.BooleanField(default=True, db_default=True)
+ created_at = models.DateTimeField(auto_now_add=True)
+
+ __repr__ = sane_repr("id", "schema_id", "destination_id", "enabled")
+
+ class Meta:
+ db_table = "posthog_externaldataschemadestination"
+ constraints = [
+ models.UniqueConstraint(fields=["schema", "destination"], name="wsd_schema_dest_uniq"),
+ ]
+ indexes = [
+ models.Index(fields=["updated_at"], name="wsd_schema_link_upd_idx"),
+ ]
+
+
+DEFAULT_WAREHOUSE_DESTINATION_NAME = "PostHog warehouse"
+
+
+def get_or_create_warehouse_destination(team_id: int) -> ExternalDataDestination:
+ """Return the team's PostHog warehouse destination, creating it on first use.
+
+ Rows are created lazily rather than backfilled: a team that never opts into extra
+ destinations never needs one, and `resolve_destinations` only reaches here when a
+ schema has no destination configured at all.
+ """
+ destination, _ = ExternalDataDestination.objects.for_team(team_id).get_or_create(
+ team_id=team_id,
+ type=ExternalDataDestination.Type.POSTHOG_WAREHOUSE,
+ deleted=False,
+ defaults={"name": DEFAULT_WAREHOUSE_DESTINATION_NAME, "config": {}},
+ )
+ return destination
+
+
+def resolve_destinations(schema: "ExternalDataSchema") -> list[ExternalDataDestination]: # type: ignore[name-defined] # noqa: F821
+ """Resolve where one schema's rows should be written.
+
+ Schema-level links win over source-level links whenever any exist, so clearing a
+ schema's override is what restores inheritance — the same precedence
+ `ExternalDataSchema.api_version` uses against the source pin.
+
+ No links at either level means the source predates destinations, which must keep
+ syncing to the PostHog warehouse exactly as it did before.
+
+ Queried through `for_team` rather than `schema.destination_links`: the related manager
+ is the fail-closed one, so traversing it raises `TeamScopeError` in the Temporal
+ activities and management commands that resolve destinations outside a request.
+ """
+ team_id = schema.team_id
+ links: list = list(
+ ExternalDataSchemaDestination.objects.for_team(team_id)
+ .filter(schema_id=schema.id)
+ .select_related("destination")
+ ) or list(
+ ExternalDataSourceDestination.objects.for_team(team_id)
+ .filter(source_id=schema.source_id)
+ .select_related("destination")
+ )
+ if links:
+ return [link.destination for link in links if link.enabled and not link.destination.deleted]
+ return [get_or_create_warehouse_destination(team_id)]
diff --git a/products/warehouse_sources/backend/models/external_data_job.py b/products/warehouse_sources/backend/models/external_data_job.py
index acd9a7b4963a..39e838bd75bd 100644
--- a/products/warehouse_sources/backend/models/external_data_job.py
+++ b/products/warehouse_sources/backend/models/external_data_job.py
@@ -3,7 +3,8 @@ from uuid import UUID
from django.conf import settings
from django.db import models
-from django.db.models import OuterRef, Prefetch, Subquery
+from django.db.models import F, Func, IntegerField, OuterRef, Prefetch, Subquery, Value
+from django.db.models.functions import Greatest
from posthog.models.utils import CreatedMetaFields, UpdatedMetaFields, UUIDTModel, sane_repr
from posthog.sync import database_sync_to_async
@@ -29,6 +30,10 @@ class ExternalDataJob(CreatedMetaFields, UpdatedMetaFields, UUIDTModel):
pipeline_version = models.CharField(max_length=400, choices=PipelineVersion, null=True, blank=True)
billable = models.BooleanField(default=True, null=True, blank=True)
+ # The destinations this run delivers to, snapshotted when the run started so a config
+ # change mid-run cannot alter where an in-flight run lands or what it bills. Empty means
+ # the PostHog warehouse alone, which is every run that predates destinations.
+ destination_ids = models.JSONField(default=list, blank=True, db_default=[])
finished_at = models.DateTimeField(null=True, blank=True)
storage_delta_mib = models.FloatField(null=True, blank=True, default=0)
# Also stores `cdc_write_mode` (`incremental_merge` | `scd2_append`) so the Syncs UI can
@@ -128,3 +133,16 @@ def get_latest_run_if_exists(team_id: int, pipeline_id: UUID) -> ExternalDataJob
)
return job
+
+
+def billable_destination_multiplier() -> Greatest:
+ """How many destinations a run billed for, derived from the ids it snapshotted.
+
+ An empty list means the PostHog warehouse alone, so the floor is one. Derived rather than
+ stored beside the ids: the count is exactly `len(destination_ids)`, and a second column
+ holding the same fact can drift from it without anything noticing.
+ """
+ return Greatest(
+ Func(F("destination_ids"), function="jsonb_array_length", output_field=IntegerField()),
+ Value(1),
+ )
diff --git a/products/warehouse_sources/backend/presentation/views/destination_links.py b/products/warehouse_sources/backend/presentation/views/destination_links.py
new file mode 100644
index 000000000000..210f071864b2
--- /dev/null
+++ b/products/warehouse_sources/backend/presentation/views/destination_links.py
@@ -0,0 +1,125 @@
+"""Setting which destinations a source or one of its tables syncs to.
+
+Kept out of the source and schema viewsets so the destination set is edited through one
+shared, tested path rather than two near-copies.
+"""
+
+from typing import Any
+
+from django.db import transaction
+
+from rest_framework import serializers
+from rest_framework.exceptions import ValidationError
+
+from products.warehouse_sources.backend.facade.models import (
+ ExternalDataDestination,
+ ExternalDataSchemaDestination,
+ ExternalDataSourceDestination,
+)
+
+EMPTY_SET_MESSAGE = (
+ "Pick at least one destination. To stop syncing this data, turn off syncing instead of removing every destination."
+)
+
+# The delivery loop writes a batch to every selected destination in turn, so an unbounded set
+# would let one source or table tie up a consumer for as long as it takes to reach every one of
+# them. A source realistically syncs to a small number of downstream warehouses.
+MAX_DESTINATIONS_PER_LINK = 10
+TOO_MANY_DESTINATIONS_MESSAGE = f"Pick at most {MAX_DESTINATIONS_PER_LINK} destinations."
+
+
+class SourceDestinationsSerializer(serializers.Serializer):
+ """Response shape for a source's destination set."""
+
+ destination_ids = serializers.ListField(
+ child=serializers.UUIDField(), help_text="Destinations every table on this source syncs to."
+ )
+
+
+class SchemaDestinationsSerializer(serializers.Serializer):
+ """Response shape for a table's destination override."""
+
+ destination_ids = serializers.ListField(
+ child=serializers.UUIDField(),
+ allow_null=True,
+ help_text="The table's own destinations, or null when it follows its source.",
+ )
+ inherits_from_source = serializers.BooleanField(
+ help_text="Whether this table follows its source rather than having its own destinations."
+ )
+ effective_destination_ids = serializers.ListField(
+ child=serializers.UUIDField(),
+ required=False,
+ help_text="Where the table actually syncs, after inheritance is resolved.",
+ )
+
+
+class DestinationLinkSerializer(serializers.Serializer):
+ destination_ids = serializers.ListField(
+ child=serializers.UUIDField(),
+ allow_empty=True,
+ allow_null=True,
+ help_text=(
+ "Destinations to sync to. On a table, null clears the override so the table follows its source again."
+ ),
+ )
+
+
+def _resolve_destinations(team_id: int, destination_ids: list) -> list[ExternalDataDestination]:
+ if len(destination_ids) > MAX_DESTINATIONS_PER_LINK:
+ raise ValidationError({"destination_ids": TOO_MANY_DESTINATIONS_MESSAGE})
+
+ destinations = list(
+ ExternalDataDestination.objects.for_team(team_id).filter(id__in=destination_ids).exclude(deleted=True)
+ )
+ missing = {str(i) for i in destination_ids} - {str(d.id) for d in destinations}
+ if missing:
+ raise ValidationError({"destination_ids": f"Unknown destinations: {', '.join(sorted(missing))}"})
+ return destinations
+
+
+def set_source_destinations(*, team_id: int, source_id: Any, destination_ids: list | None) -> list[str]:
+ """Replace a source's destination set. Returns the ids now attached."""
+ if not destination_ids:
+ raise ValidationError({"destination_ids": EMPTY_SET_MESSAGE})
+
+ destinations = _resolve_destinations(team_id, destination_ids)
+
+ # Atomic because the delete and the creates are one edit: a failure between them would leave
+ # the source with a partial set, and every table without an override would sync to it.
+ with transaction.atomic():
+ ExternalDataSourceDestination.objects.for_team(team_id).filter(source_id=source_id).delete()
+ for destination in destinations:
+ ExternalDataSourceDestination.objects.for_team(team_id).create(
+ team_id=team_id, source_id=source_id, destination=destination
+ )
+ return [str(d.id) for d in destinations]
+
+
+def set_schema_destinations(*, team_id: int, schema_id: Any, destination_ids: list | None) -> list[str] | None:
+ """Replace a table's destination override, or clear it so the table follows its source.
+
+ Null clears the override. An empty list is rejected rather than treated as "sync nowhere":
+ with no rows left there is nothing to distinguish it from having no override, so the table
+ would quietly fall back to its source's destinations. Turning syncing off is the supported
+ way to stop a table.
+ """
+ if destination_ids is not None and not destination_ids:
+ raise ValidationError({"destination_ids": EMPTY_SET_MESSAGE})
+
+ # Resolved before anything is deleted. There are no `ATOMIC_REQUESTS` here, so a rejection
+ # after the delete would commit it, and the table would silently fall back to its source's
+ # destinations on a request that returned 400.
+ destinations = [] if destination_ids is None else _resolve_destinations(team_id, destination_ids)
+
+ with transaction.atomic():
+ ExternalDataSchemaDestination.objects.for_team(team_id).filter(schema_id=schema_id).delete()
+
+ if destination_ids is None:
+ return None
+
+ for destination in destinations:
+ ExternalDataSchemaDestination.objects.for_team(team_id).create(
+ team_id=team_id, schema_id=schema_id, destination=destination
+ )
+ return [str(d.id) for d in destinations]
diff --git a/products/warehouse_sources/backend/presentation/views/external_data_destination.py b/products/warehouse_sources/backend/presentation/views/external_data_destination.py
new file mode 100644
index 000000000000..790f1f59c0bd
--- /dev/null
+++ b/products/warehouse_sources/backend/presentation/views/external_data_destination.py
@@ -0,0 +1,224 @@
+from typing import Any, cast
+
+from django.db import transaction
+from django.db.models import Q
+
+from rest_framework import serializers, status, viewsets
+from rest_framework.exceptions import PermissionDenied, ValidationError
+from rest_framework.request import Request
+from rest_framework.response import Response
+
+from posthog.api.routing import TeamAndOrgViewSetMixin
+from posthog.api.scoped_related_fields import TeamScopedPrimaryKeyRelatedField
+from posthog.models.integration import Integration
+from posthog.permissions import is_service_auth
+
+from products.access_control.backend.facade.user_access_control import access_level_satisfied_for_resource
+from products.warehouse_sources.backend.facade.models import ExternalDataDestination, ExternalDataSchema
+
+# Which Integration kind holds the credentials for each destination type. A type absent from
+# this map needs no integration; the PostHog warehouse is the only such type today.
+#
+# Only the types with a writer that has actually run against that warehouse appear here. The
+# `Type` enum carries the rest so the column and its data do not change as each one lands, but
+# a user cannot select one until its writer ships.
+DESTINATION_INTEGRATION_KINDS: dict[str, tuple[str, ...]] = {
+ str(ExternalDataDestination.Type.POSTGRES): (str(Integration.IntegrationKind.POSTGRESQL),),
+}
+
+# Types a user may create. The PostHog warehouse row is created by the sync itself the first
+# time a schema resolves to it, and every team has exactly one, so it is not user-managed.
+USER_CREATABLE_TYPES = frozenset(DESTINATION_INTEGRATION_KINDS)
+
+
+class ExternalDataDestinationSerializer(serializers.ModelSerializer):
+ type = serializers.ChoiceField(
+ choices=ExternalDataDestination.Type.choices,
+ help_text="Where synced rows are written. The PostHog warehouse is managed for you, so you cannot create one here.",
+ )
+ name = serializers.CharField(
+ max_length=400, help_text="Human-readable name shown when picking destinations for a source or table."
+ )
+ config = serializers.JSONField(
+ required=False,
+ help_text=(
+ "Settings for this destination: target database, schema or dataset, bucket and prefix, file "
+ "format. Credentials are not stored here. They live on the linked integration."
+ ),
+ )
+ integration = TeamScopedPrimaryKeyRelatedField(
+ queryset=Integration.objects.all(),
+ required=False,
+ allow_null=True,
+ help_text="Integration holding this destination's credentials. Required for every type except the PostHog warehouse.",
+ )
+ is_posthog_warehouse = serializers.BooleanField(
+ read_only=True, help_text="Whether this is the managed PostHog warehouse destination."
+ )
+
+ class Meta:
+ model = ExternalDataDestination
+ fields = [
+ "id",
+ "type",
+ "name",
+ "config",
+ "integration",
+ "is_posthog_warehouse",
+ "created_at",
+ "created_by",
+ "updated_at",
+ ]
+ read_only_fields = ["id", "is_posthog_warehouse", "created_at", "created_by", "updated_at"]
+
+ def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:
+ destination_type = attrs.get("type", getattr(self.instance, "type", None))
+
+ if destination_type not in USER_CREATABLE_TYPES:
+ raise ValidationError(
+ {"type": "PostHog warehouse destinations are managed for you. Pick a different type."}
+ )
+
+ integration = attrs.get("integration", getattr(self.instance, "integration", None))
+ if integration is None:
+ raise ValidationError(
+ {
+ "integration": (
+ f"{destination_type} destinations need an integration. Add one with your "
+ f"{destination_type} credentials, then try again."
+ )
+ }
+ )
+
+ allowed_kinds = DESTINATION_INTEGRATION_KINDS[destination_type]
+ if integration.kind not in allowed_kinds:
+ expected = " or ".join(f"'{kind}'" for kind in allowed_kinds)
+ raise ValidationError({"integration": f"A {destination_type} destination needs a {expected} integration."})
+
+ if self.instance is not None:
+ self._reject_retargeting(attrs)
+
+ return attrs
+
+ # Where a destination points is fixed once it exists. Everything already synced sits at the
+ # current server and schema, so repointing one strands that data and needs a full resync of
+ # every table that syncs there. A second destination is the supported way to write elsewhere.
+ RETARGETING_FIELDS = ("database", "schema")
+
+ def _reject_retargeting(self, attrs: dict[str, Any]) -> None:
+ assert self.instance is not None
+ if "integration" in attrs and attrs["integration"] != self.instance.integration:
+ raise ValidationError(
+ {
+ "integration": (
+ "A destination keeps the connection it was created with. Add a second "
+ "destination for the other server."
+ )
+ }
+ )
+
+ if "config" not in attrs:
+ return
+
+ current = self.instance.config or {}
+ incoming = attrs["config"] or {}
+ for field in self.RETARGETING_FIELDS:
+ if field in incoming and incoming[field] != current.get(field):
+ raise ValidationError(
+ {
+ "config": (
+ f"A destination keeps the {field} it was created with. Add a second "
+ f"destination for the other {field}."
+ )
+ }
+ )
+
+ def create(self, validated_data: dict[str, Any]) -> ExternalDataDestination:
+ request = self.context["request"]
+ return ExternalDataDestination.objects.for_team(self.context["get_team"]().pk).create(
+ team_id=self.context["get_team"]().pk,
+ created_by=request.user,
+ **validated_data,
+ )
+
+
+class ExternalDataDestinationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
+ """Manage where warehouse sources write their synced rows.
+
+ A destination can be attached to several sources, or to a single table on a source.
+ Credentials come from an integration, so one connection can be reused across syncs.
+ """
+
+ scope_object = "external_data_source"
+ # `ExternalDataDestination` has no `model_to_resource` mapping, so object-level RBAC
+ # (`check_access_level_for_object`) is a no-op for it and every request would otherwise
+ # fall through to "has specific access to *any* external_data_source object", letting a
+ # user with narrow write access to one source manage every destination on the team. A
+ # destination is shared across sources and tables rather than owned by one of them, so
+ # there is no single object to check specific access against here; require resource-level
+ # access to `external_data_source` instead.
+ requires_resource_level_access = True
+ # `.unscoped()` is import-safe (the fail-closed manager raises on `.all()` without team
+ # context); the mixin scopes every request by team_id.
+ queryset = ExternalDataDestination.objects.unscoped().exclude(deleted=True)
+ serializer_class = ExternalDataDestinationSerializer
+ ordering = "name"
+
+ def safely_get_queryset(self, queryset: Any) -> Any:
+ return queryset.filter(team_id=self.team_id).order_by(self.ordering)
+
+ def _assert_can_mutate(self, instance: ExternalDataDestination) -> None:
+ """Per-table gate for changing or deleting a shared destination.
+
+ `requires_resource_level_access` only proves editor access to *some* source; a
+ destination is wired to every table on each source it's linked to (directly, or
+ through a schema-level override), and a table can be locked below that resource-level
+ grant. Changing the destination's integration/config, or deleting it outright, reroutes
+ every one of those tables' next sync, so this mirrors
+ `ExternalDataSourceViewSet._assert_can_write_schemas` — the same gate a source-level
+ destination change goes through — rather than trusting the coarser resource check alone.
+ """
+ if is_service_auth(self.request):
+ return
+
+ source_ids = {link.source_id for link in instance.source_links.filter(enabled=True)}
+ direct_schema_ids = {link.schema_id for link in instance.schema_links.filter(enabled=True)}
+ schemas = list(
+ ExternalDataSchema.objects.exclude(deleted=True)
+ .filter(team_id=self.team_id)
+ .filter(Q(source_id__in=source_ids) | Q(id__in=direct_schema_ids))
+ .select_related("table")
+ )
+
+ uac = self.user_access_control
+ for schema in schemas:
+ level = uac.get_user_access_level(schema.table or schema.source)
+ if level is None or not access_level_satisfied_for_resource("warehouse_table", level, "editor"):
+ raise PermissionDenied("You do not have editor access to every table wired to this destination.")
+
+ def perform_update(self, serializer: serializers.BaseSerializer) -> None:
+ # `.instance` is `Any | None` on the base serializer type, but `update`/`partial_update`
+ # always construct this viewset's serializer with the existing instance to update.
+ self._assert_can_mutate(cast(ExternalDataDestination, serializer.instance))
+ super().perform_update(serializer)
+
+ def destroy(self, request: Request, *args: Any, **kwargs: Any) -> Response:
+ """Soft-delete, and detach it from everything that syncs to it.
+
+ Runs already in flight keep their own snapshot of the destination, so deleting one
+ never strands a run part-way through. The next run of each affected table resolves
+ without it.
+ """
+ instance = self.get_object()
+ if instance.is_posthog_warehouse:
+ raise ValidationError({"type": "The PostHog warehouse destination cannot be deleted."})
+ self._assert_can_mutate(instance)
+
+ # One edit, so one transaction: detaching without the soft delete leaves a live
+ # destination nothing points at, and the reverse leaves links to a deleted one.
+ with transaction.atomic():
+ instance.source_links.all().delete()
+ instance.schema_links.all().delete()
+ instance.deleted = True
+ instance.save(update_fields=["deleted", "updated_at"])
+ return Response(status=status.HTTP_204_NO_CONTENT)
diff --git a/products/warehouse_sources/backend/presentation/views/external_data_schema.py b/products/warehouse_sources/backend/presentation/views/external_data_schema.py
index eaeee2c77b26..ec029a9152d2 100644
--- a/products/warehouse_sources/backend/presentation/views/external_data_schema.py
+++ b/products/warehouse_sources/backend/presentation/views/external_data_schema.py
@@ -45,7 +45,9 @@ from products.data_warehouse.backend.facade.api import (
from products.warehouse_sources.backend.facade.models import (
ExternalDataJob,
ExternalDataSchema,
+ ExternalDataSchemaDestination,
ExternalDataSource,
+ resolve_destinations,
sync_frequency_interval_to_sync_frequency,
sync_frequency_to_sync_frequency_interval,
update_sync_type_config_keys,
@@ -63,6 +65,11 @@ from products.warehouse_sources.backend.facade.source_management import (
validate_and_coerce_row_filters,
)
from products.warehouse_sources.backend.facade.types import ExternalDataSourceType, IncrementalFieldType
+from products.warehouse_sources.backend.presentation.views.destination_links import (
+ DestinationLinkSerializer,
+ SchemaDestinationsSerializer,
+ set_schema_destinations,
+)
from products.warehouse_sources.backend.presentation.views.source_api_versions import (
ExternalDataSourceApiVersionDeprecationSerializer,
api_version_deprecation_payload,
@@ -1474,6 +1481,7 @@ class ExternalDataSchemaViewset(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
"cancel",
"incremental_fields",
"delete_data",
+ "destinations",
]
scope_object_read_actions = ["list", "retrieve", "logs"]
queryset = ExternalDataSchema.objects.all()
@@ -1561,6 +1569,52 @@ class ExternalDataSchemaViewset(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
return Response(status=status.HTTP_204_NO_CONTENT)
+ @extend_schema(
+ request=DestinationLinkSerializer,
+ responses={200: SchemaDestinationsSerializer},
+ )
+ @action(methods=["GET", "PATCH"], detail=True, filter_backends=[])
+ def destinations(self, request: Request, *args: Any, **kwargs: Any) -> Response:
+ """Read or replace this table's destination override.
+
+ Send `destination_ids: null` to clear the override so the table follows its source again.
+ """
+ schema = self.get_object()
+
+ if request.method == "GET":
+ links = list(
+ ExternalDataSchemaDestination.objects.for_team(self.team_id)
+ .filter(schema_id=schema.id, enabled=True)
+ .exclude(destination__deleted=True)
+ )
+ overridden = (
+ ExternalDataSchemaDestination.objects.for_team(self.team_id).filter(schema_id=schema.id).exists()
+ )
+ return Response(
+ status=status.HTTP_200_OK,
+ data=SchemaDestinationsSerializer(
+ {
+ "destination_ids": [str(link.destination_id) for link in links] if overridden else None,
+ "inherits_from_source": not overridden,
+ "effective_destination_ids": [str(d.id) for d in resolve_destinations(schema)],
+ }
+ ).data,
+ )
+
+ serializer = DestinationLinkSerializer(data=request.data)
+ serializer.is_valid(raise_exception=True)
+ attached = set_schema_destinations(
+ team_id=self.team_id,
+ schema_id=schema.id,
+ destination_ids=serializer.validated_data["destination_ids"],
+ )
+ return Response(
+ status=status.HTTP_200_OK,
+ data=SchemaDestinationsSerializer(
+ {"destination_ids": attached, "inherits_from_source": attached is None}
+ ).data,
+ )
+
@extend_schema(parameters=[LogEntryRequestSerializer])
@action(methods=["GET"], detail=True, filter_backends=[])
def logs(self, request: Request, *args: Any, **kwargs: Any) -> Response:
diff --git a/products/warehouse_sources/backend/presentation/views/external_data_source.py b/products/warehouse_sources/backend/presentation/views/external_data_source.py
index 7feb8e374a04..c81902e875d6 100644
--- a/products/warehouse_sources/backend/presentation/views/external_data_source.py
+++ b/products/warehouse_sources/backend/presentation/views/external_data_source.py
@@ -108,9 +108,11 @@ from products.warehouse_sources.backend.facade.api import validate_source_prefix
from products.warehouse_sources.backend.facade.models import (
MANAGED_WAREHOUSE_SOURCE_PREFIX,
DataWarehouseTable,
+ ExternalDataDestination,
ExternalDataJob,
ExternalDataSchema,
ExternalDataSource,
+ ExternalDataSourceDestination,
PendingSourceCredential,
auto_enable_new_schemas,
latest_completed_job_prefetch,
@@ -164,6 +166,11 @@ from products.warehouse_sources.backend.facade.types import (
ExternalDataSourceType,
ManagedWarehouseSQLMode,
)
+from products.warehouse_sources.backend.presentation.views.destination_links import (
+ DestinationLinkSerializer,
+ SourceDestinationsSerializer,
+ set_source_destinations,
+)
from products.warehouse_sources.backend.presentation.views.external_data_schema import (
ExternalDataSchemaListSerializer,
ExternalDataSchemaSerializer,
@@ -909,6 +916,15 @@ class ExternalDataJobSerializers(serializers.ModelSerializer):
"`null` on legacy rows and means billable."
),
)
+ destination_ids = serializers.ListField(
+ child=serializers.CharField(),
+ read_only=True,
+ help_text=(
+ "Destinations this run delivered to, snapshotted when it started. Empty on runs that "
+ "predate destinations, which wrote to the PostHog warehouse alone. `rows_synced` counts "
+ "the rows read from the source once, not once per destination."
+ ),
+ )
class Meta:
model = ExternalDataJob
@@ -924,6 +940,7 @@ class ExternalDataJobSerializers(serializers.ModelSerializer):
"workflow_run_id",
"cdc_write_mode",
"billable",
+ "destination_ids",
]
read_only_fields = [
"id",
@@ -937,6 +954,7 @@ class ExternalDataJobSerializers(serializers.ModelSerializer):
"workflow_run_id",
"cdc_write_mode",
"billable",
+ "destination_ids",
]
def get_cdc_write_mode(self, instance: ExternalDataJob) -> str | None:
@@ -1618,6 +1636,14 @@ class ExternalDataSourceCreateSerializer(serializers.Serializer):
"Defaults to false; ignored for pure direct-query sources."
),
)
+ destination_ids = serializers.ListField(
+ child=serializers.UUIDField(),
+ required=False,
+ help_text=(
+ "Destinations every table on this source writes to. Set here rather than afterwards, "
+ "so the opening sync already carries them. Omit to write to the PostHog warehouse only."
+ ),
+ )
class SourceSetupSerializer(serializers.Serializer):
@@ -1990,6 +2016,7 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi
"store_credentials",
"source_prefix",
"revenue_analytics_config",
+ "destinations",
"create_webhook",
"update_webhook_inputs",
"delete_webhook",
@@ -2233,6 +2260,7 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi
access_method=serializer.validated_data.get("access_method", ExternalDataSource.AccessMethod.WAREHOUSE),
created_via=serializer.validated_data.get("created_via", ExternalDataSource.CreatedVia.API),
direct_query_enabled=serializer.validated_data.get("direct_query_enabled", False),
+ destination_ids=serializer.validated_data.get("destination_ids"),
)
# Stored credentials are single-use: once the source owns them (in job_inputs), drop the stash.
if resolved.credential is not None and response.status_code == status.HTTP_201_CREATED:
@@ -2360,6 +2388,7 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi
created_via: str,
direct_query_enabled: bool = False,
skip_credential_validation: bool = False,
+ destination_ids: list | None = None,
) -> Response:
# `skip_credential_validation` is set only by the `setup` action, which has already run the
# full config + credential gate (including the SSRF host check) before discovering schemas.
@@ -2915,6 +2944,25 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi
if should_sync and new_source_model.supports_scheduled_sync:
active_schemas.append(schema_model)
+ # Attach destinations before any schedule starts. Extraction snapshots the set onto the
+ # run, so a source whose destinations arrive after its first sync began writes that run
+ # to the warehouse alone, and reaching the others costs a full resync.
+ if destination_ids:
+ try:
+ set_source_destinations(
+ team_id=self.team_id,
+ source_id=new_source_model.pk,
+ destination_ids=destination_ids,
+ )
+ except Exception as e:
+ # The source is already created and its tables are configured. Losing that over a
+ # destination set the user can still fix on the Destinations tab is the worse trade.
+ logger.exception(
+ "Could not attach destinations to a new source",
+ exc_info=e,
+ source_id=new_source_model.pk,
+ )
+
# Create all sync schedules over a single shared Temporal connection. Creating them
# one call at a time reconnects to Temporal on every iteration, which does not scale
# to sources with thousands of schemas (e.g. a Slack workspace with thousands of
@@ -4947,6 +4995,64 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi
serializer = DirectConnectionSourceOptionSerializer(options, many=True)
return Response(status=status.HTTP_200_OK, data=serializer.data)
+ @extend_schema(
+ request=DestinationLinkSerializer,
+ responses={200: SourceDestinationsSerializer},
+ )
+ @action(methods=["GET", "PATCH"], detail=True)
+ def destinations(self, request: Request, *args: Any, **kwargs: Any) -> Response:
+ """Read or replace the destinations every table on this source syncs to.
+
+ A table with its own override ignores this set until the override is cleared.
+ """
+ source = self.get_object()
+
+ if request.method == "GET":
+ attached = [
+ str(link.destination_id)
+ for link in ExternalDataSourceDestination.objects.for_team(self.team_id)
+ .filter(source_id=source.id, enabled=True)
+ .exclude(destination__deleted=True)
+ ]
+ # A source nobody configured has no links but is not syncing nowhere: it syncs to the
+ # PostHog warehouse. Report where it actually goes, or the picker shows every
+ # destination off and saving from that state silently drops the warehouse.
+ # Looked up rather than resolved, because `resolve_destinations` creates the
+ # warehouse row on demand and a GET must not write.
+ if not attached:
+ warehouse = (
+ ExternalDataDestination.objects.for_team(self.team_id)
+ .filter(type=ExternalDataDestination.Type.POSTHOG_WAREHOUSE, deleted=False)
+ .first()
+ )
+ attached = [str(warehouse.id)] if warehouse else []
+ return Response(
+ status=status.HTTP_200_OK, data=SourceDestinationsSerializer({"destination_ids": attached}).data
+ )
+
+ serializer = DestinationLinkSerializer(data=request.data)
+ serializer.is_valid(raise_exception=True)
+
+ # Editor on the source isn't enough on its own: this replaces the destination set every
+ # table without its own override inherits, and (like `destroy`) never resolves a schema
+ # through DRF's object permissions, so a table locked below the source would otherwise be
+ # rerouted to a destination its editor never had access to.
+ schemas = list(
+ ExternalDataSchema.objects.exclude(deleted=True)
+ .filter(team_id=self.team_id, source_id=source.id)
+ .select_related("table")
+ )
+ self._assert_can_write_schemas(schemas)
+
+ attached = set_source_destinations(
+ team_id=self.team_id,
+ source_id=source.id,
+ destination_ids=serializer.validated_data["destination_ids"],
+ )
+ return Response(
+ status=status.HTTP_200_OK, data=SourceDestinationsSerializer({"destination_ids": attached}).data
+ )
+
@action(methods=["PATCH"], detail=True)
def revenue_analytics_config(self, request: Request, *args: Any, **kwargs: Any) -> Response:
"""Update the revenue analytics configuration and return the full external data source."""
diff --git a/products/warehouse_sources/backend/routes.py b/products/warehouse_sources/backend/routes.py
index 5176c62654ad..526e601889cb 100644
--- a/products/warehouse_sources/backend/routes.py
+++ b/products/warehouse_sources/backend/routes.py
@@ -2,6 +2,7 @@ from posthog.api.routing import RouterRegistry
from products.warehouse_sources.backend.presentation.views import (
column_statistics,
+ external_data_destination,
external_data_schema,
external_data_source,
)
@@ -14,6 +15,12 @@ def register_routes(routers: RouterRegistry) -> None:
"project_external_data_sources",
["team_id"],
)
+ routers.projects.register(
+ r"external_data_destinations",
+ external_data_destination.ExternalDataDestinationViewSet,
+ "project_external_data_destinations",
+ ["team_id"],
+ )
routers.projects.register(
r"external_data_schemas",
external_data_schema.ExternalDataSchemaViewset,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/destinations/__init__.py b/products/warehouse_sources/backend/temporal/data_imports/destinations/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/warehouse_sources/backend/temporal/data_imports/destinations/contracts.py b/products/warehouse_sources/backend/temporal/data_imports/destinations/contracts.py
new file mode 100644
index 000000000000..f5ca0ea67588
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/destinations/contracts.py
@@ -0,0 +1,114 @@
+"""The contract every sync destination implements, PostHog's own warehouse included.
+
+A run's staged parquet batches are delivered by one writer per destination. The consumer
+engine is destination-agnostic: it claims a (batch, destination) work item, opens the staged
+file, and hands the record batches to the writer resolved for that destination's type. The
+few places the warehouse genuinely differs from an external destination are declared as
+capabilities on the writer rather than branched on by the engine.
+"""
+
+from __future__ import annotations
+
+from collections.abc import AsyncIterator
+from dataclasses import field
+from typing import TYPE_CHECKING, ClassVar, Protocol, runtime_checkable
+
+from posthog.dataclasses import frozen
+
+if TYPE_CHECKING:
+ import pyarrow as pa
+
+
+@frozen
+class DestinationRunContext:
+ """Everything a writer needs that is fixed for the whole run.
+
+ `config` and `integration_id` come from the destination snapshot taken when the run
+ started, so a destination edited mid-run does not change where the run's remaining
+ batches land.
+ """
+
+ team_id: int
+ schema_id: str
+ source_id: str
+ job_id: str
+ run_uuid: str
+ destination_id: str
+ destination_type: str
+ destination_name: str
+ # Fully qualified target name as the user's warehouse prefix resolves it.
+ table_name: str
+ sync_type: str
+ primary_keys: tuple[str, ...] = ()
+ config: dict = field(default_factory=dict)
+ integration_id: int | None = None
+
+ @property
+ def is_full_refresh(self) -> bool:
+ return self.sync_type == "full_refresh"
+
+ @property
+ def is_incremental(self) -> bool:
+ return self.sync_type in ("incremental", "cdc")
+
+
+@frozen
+class DestinationBatchContext:
+ """One batch's coordinates within its run."""
+
+ run: DestinationRunContext
+ batch_index: int
+ is_final_batch: bool
+ is_resume: bool = False
+ # Rows the extractor recorded for this batch. Advisory: the writer reports what it wrote.
+ expected_row_count: int | None = None
+
+ @property
+ def is_first_batch(self) -> bool:
+ return self.batch_index == 0
+
+
+@frozen
+class BatchWriteOutcome:
+ """What a writer actually delivered for one batch."""
+
+ rows_written: int
+ bytes_written: int = 0
+
+
+@runtime_checkable
+class DestinationWriter(Protocol):
+ """Delivers a run's batches to one destination.
+
+ Every method must be safe to call again after a crash or a lease loss: the engine
+ re-claims a batch whose state it could not confirm, so `write_batch` in particular has
+ to be idempotent per `batch_index` (merge on primary keys, delete-then-insert by batch
+ index, or a deterministic object key).
+ """
+
+ # The v3 Redis sync lock is released when this writer's child job goes terminal. Only the
+ # PostHog warehouse sets it: Delta table maintenance runs pre-extraction under that lock
+ # and must not race in-flight writes. External destinations drain outside the lock so an
+ # outage at one of them cannot block the schema's next scheduled sync.
+ holds_sync_lock: ClassVar[bool] = False
+ # This writer owns the post-load steps (table registration, queryable folder, post-import
+ # workflow). Only the PostHog warehouse sets it — those steps describe a warehouse table.
+ runs_post_load: ClassVar[bool] = False
+
+ async def prepare_run(self, ctx: DestinationRunContext) -> None:
+ """Create whatever the run writes into. Called before the run's first batch."""
+ ...
+
+ async def write_batch(
+ self, batches: AsyncIterator[pa.RecordBatch], ctx: DestinationBatchContext
+ ) -> BatchWriteOutcome:
+ """Apply one staged batch. Must be idempotent for a given `ctx.batch_index`."""
+ ...
+
+ async def finalize_run(self, ctx: DestinationRunContext) -> None:
+ """Commit the run. Called once, after the final batch is applied."""
+ ...
+
+ async def abort_run(self, ctx: DestinationRunContext) -> None:
+ """Drop anything staged for a run that will not complete. Best effort."""
+ ...
diff --git a/products/warehouse_sources/backend/temporal/data_imports/destinations/enablement.py b/products/warehouse_sources/backend/temporal/data_imports/destinations/enablement.py
new file mode 100644
index 000000000000..2ea06593d4c1
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/destinations/enablement.py
@@ -0,0 +1,68 @@
+"""Deciding which destinations a run delivers to.
+
+Resolution happens once, when the run's job is created, and the resulting ids travel with
+every batch. A destination added or removed mid-run therefore cannot change where an
+in-flight run's remaining batches land, and cannot change what the run bills.
+"""
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+
+import posthoganalytics
+
+from posthog.exceptions_capture import capture_exception
+from posthog.models.team.team import Team
+
+from products.warehouse_sources.backend.models.external_data_destination import resolve_destinations
+
+if TYPE_CHECKING:
+ from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
+
+WAREHOUSE_MULTI_DESTINATION_FLAG = "warehouse-multi-destination"
+
+
+def is_multi_destination_enabled(team_id: int, source_type: str) -> bool:
+ """Whether this team's syncs of this source type deliver to configured destinations.
+
+ Evaluated in an activity and carried into the workflow as recorded history, the same way
+ the v3 rollout flag is — a workflow must never read a flag directly.
+ """
+ try:
+ team = Team.objects.only("uuid", "organization_id").get(id=team_id)
+ except Team.DoesNotExist:
+ return False
+
+ try:
+ return bool(
+ posthoganalytics.feature_enabled(
+ WAREHOUSE_MULTI_DESTINATION_FLAG,
+ str(team.uuid),
+ groups={
+ "organization": str(team.organization_id),
+ "project": str(team.id),
+ },
+ group_properties={
+ "organization": {"id": str(team.organization_id), "source_type": source_type},
+ "project": {"id": str(team.id), "source_type": source_type},
+ },
+ only_evaluate_locally=False,
+ send_feature_flag_events=False,
+ )
+ )
+ except Exception as e:
+ capture_exception(e)
+ return False
+
+
+def destination_ids_for_run(schema: ExternalDataSchema) -> list[str]:
+ """The destination ids this run delivers to, in a stable order.
+
+ Empty when the schema resolves to the PostHog warehouse alone, which keeps a run that
+ nobody configured destinations for byte-for-byte on the path it took before.
+ """
+ destinations = resolve_destinations(schema)
+ if len(destinations) == 1 and destinations[0].is_posthog_warehouse:
+ return []
+
+ return sorted(str(destination.id) for destination in destinations)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/destinations/registry.py b/products/warehouse_sources/backend/temporal/data_imports/destinations/registry.py
new file mode 100644
index 000000000000..27f520572bf3
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/destinations/registry.py
@@ -0,0 +1,69 @@
+"""Where destination writers are looked up by type.
+
+The external destinations (Redshift, Snowflake, BigQuery, ...) are implemented on top of
+batch exports' destination clients and transformers, which warehouse_sources depends on
+directly (see tach.toml). Writers are still resolved by type string rather than imported at
+the call site, so the processor never names a destination type and a driver only loads when
+a destination of that type is actually written to.
+
+An unregistered type raises rather than degrading to a no-op: silently writing nothing to a
+destination a customer configured, and billing it, is worse than failing the batch.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Callable
+from typing import Any
+
+from products.warehouse_sources.backend.temporal.data_imports.destinations.contracts import (
+ DestinationRunContext,
+ DestinationWriter,
+)
+
+# A writer class is the usual factory: calling it with the run context builds the writer.
+DestinationWriterFactory = Callable[[DestinationRunContext], Any]
+
+_writer_factories: dict[str, DestinationWriterFactory] = {}
+
+
+class UnsupportedDestinationError(Exception):
+ def __init__(self, destination_type: str) -> None:
+ super().__init__(
+ f"No writer registered for destination type '{destination_type}'. "
+ f"Registered types: {sorted(_writer_factories) or 'none'}"
+ )
+ self.destination_type = destination_type
+
+
+def register_destination_writer(destination_type: str, factory: DestinationWriterFactory) -> None:
+ _writer_factories[destination_type] = factory
+
+
+def resolve_destination_writer(ctx: DestinationRunContext) -> DestinationWriter:
+ try:
+ factory = _writer_factories[ctx.destination_type]
+ except KeyError:
+ raise UnsupportedDestinationError(ctx.destination_type)
+ return factory(ctx)
+
+
+def snapshot_registered_writers() -> dict[str, DestinationWriterFactory]:
+ """A copy of the registry, for a caller that will put it back.
+
+ The registry is process-global, so a test that registers a fake writer leaks it into every
+ test that runs after it. Pair with `restore_registered_writers`.
+ """
+ return dict(_writer_factories)
+
+
+def restore_registered_writers(snapshot: dict[str, DestinationWriterFactory]) -> None:
+ _writer_factories.clear()
+ _writer_factories.update(snapshot)
+
+
+def supported_destination_types() -> frozenset[str]:
+ return frozenset(_writer_factories)
+
+
+def is_destination_supported(destination_type: str) -> bool:
+ return destination_type in _writer_factories
diff --git a/products/warehouse_sources/backend/temporal/data_imports/metrics.py b/products/warehouse_sources/backend/temporal/data_imports/metrics.py
index afe42f4c7cb8..2c98048b8cb0 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/metrics.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/metrics.py
@@ -88,33 +88,37 @@ def emit_data_import_app_metrics(job: "ExternalDataJob") -> None:
metric_kind, metric_name = kind_name
finished_at = job.finished_at or dt.datetime.now(dt.UTC)
timestamp = format_clickhouse_timestamp(finished_at)
-
- common_fields = {
- "team_id": job.team_id,
- "app_source": DATA_IMPORT_APP_SOURCE,
- "app_source_id": str(job.pipeline_id),
- "instance_id": str(job.schema_id) if job.schema_id else "",
- "timestamp": timestamp,
- }
-
- payloads: list[dict] = [
- {
- **common_fields,
- "metric_kind": metric_kind,
- "metric_name": metric_name,
- "count": 1,
+ schema_instance_id = str(job.schema_id) if job.schema_id else ""
+
+ def rows_for(instance_id: str) -> list[dict]:
+ common = {
+ "team_id": job.team_id,
+ "app_source": DATA_IMPORT_APP_SOURCE,
+ "app_source_id": str(job.pipeline_id),
+ "instance_id": instance_id,
+ "timestamp": timestamp,
}
- ]
-
- if job.rows_synced and job.rows_synced > 0:
- payloads.append(
- {
- **common_fields,
- "metric_kind": "rows",
- "metric_name": "rows_synced",
- "count": job.rows_synced,
- }
- )
+ emitted = [{**common, "metric_kind": metric_kind, "metric_name": metric_name, "count": 1}]
+ if job.rows_synced and job.rows_synced > 0:
+ emitted.append({**common, "metric_kind": "rows", "metric_name": "rows_synced", "count": job.rows_synced})
+ return emitted
+
+ payloads: list[dict] = rows_for(schema_instance_id)
+
+ # The same metrics again per destination, keyed by "<schema>/<destination>". The metric names
+ # stay as they are: they are LowCardinality on a table several products share, so a destination
+ # id cannot go in them. `instance_id` is a plain String and already means "which instance of
+ # this app source", which is what a destination is here.
+ #
+ # These are extra rows, not replacements. Everything that filters `instance_id` by a bare
+ # schema id matches exactly what it did before and never sees them.
+ #
+ # Each destination is also keyed on its own, without a schema. A source-level surface wants one
+ # series per destination across every table, and the API filters `instance_id` by equality, so
+ # without this row it would have to ask once per schema per destination.
+ for destination_id in job.destination_ids or []:
+ payloads.extend(rows_for(f"{schema_instance_id}/{destination_id}"))
+ payloads.extend(rows_for(str(destination_id)))
try:
producer = get_producer(topic=KAFKA_APP_METRICS2)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/README.md b/products/warehouse_sources/backend/temporal/data_imports/pipelines/README.md
index 30b5b49d67cd..65b71aa9c7ad 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/README.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/README.md
@@ -13,20 +13,41 @@ This page is the map; each package's own docstrings and READMEs carry the detail
5. Post-load (`common/load.py::run_post_load_operations`): delta maintenance, publish queryable files, register the table, CDC companion handling, `POST_LOAD_STEPS`.
6. Finalization (terminal job status, v3 lock release, post-import start) is owned per run: the workflow, or the v3 load consumer once it loads the final batch.
The contract lives on the `PipelineResult` docstring (`core/typings.py`).
+ A run that fans out to several destinations finalizes differently - see [Destinations](#destinations).
7. The post-import workflow (`../post_import_job.py`, `data-import-post-import`) runs the load-dependent step list (table size, DuckLake copy, signals, enrichment, statistics).
+## Destinations
+
+A schema syncs to a set of destinations, of which the PostHog warehouse is one rather than a special case.
+Absence of configuration resolves to the warehouse alone, so a source set up before destinations existed behaves exactly as it did.
+Gated by the `warehouse-multi-destination` flag, evaluated once in `create_external_data_job_model_activity` and carried into the workflow as recorded history.
+
+- **Configuration.** `ExternalDataDestination` is team-scoped and reusable; credentials live on a linked `Integration`, not in its config.
+ Source-level links are the default set, schema-level links override them, and clearing the override restores inheritance (`models/external_data_destination.py::resolve_destinations`).
+- **One job, one run.** The resolved destination ids are snapshotted onto `ExternalDataJob.destination_ids` when the run starts and travel with every batch, so a config change mid-run cannot alter where an in-flight run lands or what it bills.
+- **One consumer.** There is no second deployment. `run_warehouse_sources_load` writes the batch to Delta as it always has, then `destinations_load/delivery.py` writes the same batch to every other destination in turn.
+- **All destinations share one lifecycle.** A batch is done only when every destination has taken it, and a destination that fails fails the batch, which is retried in full. Each destination has its own idempotency key, so a retry skips the ones that already took the batch. The failing destination's name is prefixed onto the job's `latest_error`.
+- **A run that lists destinations but not the warehouse** never touches Delta: no table registration, no post-import.
+- **The cursor** is unchanged from before destinations existed. A batch is either delivered everywhere or retried, so it advances exactly as it always has.
+- **Billing** multiplies the run's rows by the number of destinations it snapshotted (`billable_destination_multiplier`). Runs that predate destinations carry an empty list and bill as one.
+- **Falling behind** is bounded by queue retention, not by patience: past that the staged parquet is gone and the run must be re-extracted. Alert on `oldest_eligible_age_seconds`.
+
+Writers live in `destinations_load/writers/` and are resolved by type from a registry, so the consumer never names a destination type. Only Postgres ships today; it runs on batch exports' `PostgreSQLClient`.
+
+CDC is excluded for now: it ticks a final batch continuously, which has no run-scoped commit for a destination to swap into.
+
## The pipelines
-| Pipeline | Lives in | Attaches at |
-| ------------------------------------ | ------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| v2 extract+load (`PipelineNonDLT`) | `pipeline_v2/` | Step 4 when `pipeline_version == V2`; writes Delta inline per chunk, so extract and load are one activity. The workflow finalizes. |
-| v3 extract (`PipelineV3`) | `pipeline_v3/pipeline.py`, `pipeline_v3/s3/`, `pipeline_v3/postgres_queue/producer.py` | Step 4 when `pipeline_version == V3`, under the sync lock; writes parquet batches to S3 and enqueues them (`ExportSignalMessage`, `pipeline_v3/messages.py`) on the Postgres load queue. |
-| v3 load | `pipeline_v3/postgres_queue/`, `pipeline_v3/batch_consumer.py`, `pipeline_v3/load/` | Its own deployment (`run_warehouse_sources_load`), not the workflow: claims queued batches, writes Delta via `core/delta/`, finalizes the job, releases the lock, starts post-import. |
-| CDC | `../cdc/` | Outside the scheduled flow: the `cdc-extraction` Temporal workflow tails the source WAL and enqueues to the same Postgres queue (jobs are created as V3). The load consumer writes the snapshot table and the `_cdc` SCD2 companion (`core/delta/scd2.py`). |
-| Webhooks | `run_webhook_s3_sink` command; sink behind the `data_warehouse` facade | Buffered ingress: deliveries are buffered to S3 continuously, and the next scheduled sync drains them as ordinary source items (webhook-only schemas skip table resets, `common/extract.py`). |
-| Chunk sinks (CDP, person properties) | `core/sinks.py`, `core/cdp_producer.py`, `core/person_property_row_sink.py` | Gated taps on both write loops, one `stage_chunk` call per chunk (see `ChunkSink`). Downstream: `dwh-cdp-producer-job` produces staged chunks to Kafka for HogFunctions/HogFlows; `sync-warehouse-person-properties` plus `run_person_property_update_consumer` upsert person properties. |
-| Post-import steps | `../post_import_job.py`, children under `../workflow_activities/` | Step 7. Started by whoever finalizes the run (step 6); gates are resolved once in its resolve activity, then the workflow is a loop over recorded step keys. |
-| Repartition | `core/repartition.py`, `core/repartition_controller.py`, `../workflow_activities/repartition_table.py` | Detection is a `POST_LOAD_STEPS` entry (flags oversized partitions); execution is `maybe_repartition_table_activity`, pre-extraction on the next run while the lock is held. |
+| Pipeline | Lives in | Attaches at |
+| ------------------------------------ | ------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| v2 extract+load (`PipelineNonDLT`) | `pipeline_v2/` | Step 4 when `pipeline_version == V2`; writes Delta inline per chunk, so extract and load are one activity. The workflow finalizes. |
+| v3 extract (`PipelineV3`) | `pipeline_v3/pipeline.py`, `pipeline_v3/s3/`, `pipeline_v3/postgres_queue/producer.py` | Step 4 when `pipeline_version == V3`, under the sync lock; writes parquet batches to S3 and enqueues them (`ExportSignalMessage`, `pipeline_v3/messages.py`) on the Postgres load queue. |
+| v3 load | `pipeline_v3/postgres_queue/`, `pipeline_v3/batch_consumer.py`, `pipeline_v3/load/` | Its own deployment (`run_warehouse_sources_load`), not the workflow: claims queued batches, writes Delta via `core/delta/`, finalizes the job, releases the lock, starts post-import. When the run has destinations it also hands each batch to `destinations_load/delivery.py` before finalizing. |
+| CDC | `../cdc/` | Outside the scheduled flow: the `cdc-extraction` Temporal workflow tails the source WAL and enqueues to the same Postgres queue (jobs are created as V3). The load consumer writes the snapshot table and the `_cdc` SCD2 companion (`core/delta/scd2.py`). |
+| Webhooks | `run_webhook_s3_sink` command; sink behind the `data_warehouse` facade | Buffered ingress: deliveries are buffered to S3 continuously, and the next scheduled sync drains them as ordinary source items (webhook-only schemas skip table resets, `common/extract.py`). |
+| Chunk sinks (CDP, person properties) | `core/sinks.py`, `core/cdp_producer.py`, `core/person_property_row_sink.py` | Gated taps on both write loops, one `stage_chunk` call per chunk (see `ChunkSink`). Downstream: `dwh-cdp-producer-job` produces staged chunks to Kafka for HogFunctions/HogFlows; `sync-warehouse-person-properties` plus `run_person_property_update_consumer` upsert person properties. |
+| Post-import steps | `../post_import_job.py`, children under `../workflow_activities/` | Step 7. Started by whoever finalizes the run (step 6); gates are resolved once in its resolve activity, then the workflow is a loop over recorded step keys. |
+| Repartition | `core/repartition.py`, `core/repartition_controller.py`, `../workflow_activities/repartition_table.py` | Detection is a `POST_LOAD_STEPS` entry (flags oversized partitions); execution is `maybe_repartition_table_activity`, pre-extraction on the next run while the lock is held. |
## The shared kernel
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/__init__.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/builtin_writers.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/builtin_writers.py
new file mode 100644
index 000000000000..bc144a039e47
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/builtin_writers.py
@@ -0,0 +1,46 @@
+"""Registering the writers that ship with warehouse sources.
+
+Only Postgres ships here. The other destination types have writers built on batch exports'
+clients, parked on `tom/dwh-destination-writers-parked`, and each one lands in its own change
+once it has been run against that warehouse. Registering a type whose writer has never
+executed is how a customer discovers it does not work.
+
+Registration happens on first use rather than at a bootstrap step, so any entry point into
+delivery resolves a writer. Each writer pulls in its vendor driver, so the imports stay inside
+the function and a deployment only loads what it writes to.
+"""
+
+from __future__ import annotations
+
+from products.warehouse_sources.backend.models.external_data_destination import ExternalDataDestination
+from products.warehouse_sources.backend.temporal.data_imports.destinations.registry import register_destination_writer
+
+# Every destination type this deployment can write. Used as the default claim scope, because
+# claiming a type with no writer would lease the group and then fail every batch in it.
+SUPPORTED_DESTINATION_TYPES: list[str] = [
+ str(ExternalDataDestination.Type.POSTGRES),
+]
+
+
+_registered = False
+
+
+def ensure_builtin_destination_writers_registered() -> None:
+ """Register the built-in writers once, on first use."""
+ global _registered
+ if _registered:
+ return
+ register_builtin_destination_writers()
+ _registered = True
+
+
+def register_builtin_destination_writers() -> None:
+ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.destinations_load.writers.postgres import ( # noqa: PLC0415
+ PostgresDestinationWriter,
+ )
+
+ register_destination_writer(ExternalDataDestination.Type.POSTGRES, PostgresDestinationWriter)
+
+
+def builtin_destination_types() -> list[str]:
+ return list(SUPPORTED_DESTINATION_TYPES)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/delivery.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/delivery.py
new file mode 100644
index 000000000000..d41e3e96e437
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/delivery.py
@@ -0,0 +1,342 @@
+"""Delivering one batch to every destination configured for the run.
+
+The load consumer calls this after it has written the batch to the PostHog warehouse. All
+destinations share one lifecycle: the batch is done only when every one of them has taken it,
+and a destination that fails fails the batch, which is then retried in full.
+
+Retrying in full does not mean writing everything again. Each destination has its own
+idempotency key, so a retry after Redshift was briefly unreachable skips Snowflake and the
+warehouse and writes only what is missing.
+
+The PostHog warehouse is not delivered here. It is written by the delta path in the processor
+before this runs, and it carries the unsuffixed idempotency key it has always had.
+"""
+
+from __future__ import annotations
+
+import time
+from collections.abc import Iterable
+
+import structlog
+from asgiref.sync import async_to_sync
+
+from products.warehouse_sources.backend.models.external_data_destination import ExternalDataDestination
+from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
+from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
+from products.warehouse_sources.backend.temporal.data_imports.destinations.contracts import (
+ BatchWriteOutcome,
+ DestinationBatchContext,
+ DestinationRunContext,
+)
+from products.warehouse_sources.backend.temporal.data_imports.destinations.registry import resolve_destination_writer
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.destinations_load.builtin_writers import (
+ ensure_builtin_destination_writers_registered,
+)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.destinations_load.parquet_source import (
+ aiter_record_batches,
+)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.load.idempotency import (
+ is_batch_already_processed,
+ mark_batch_as_processed,
+)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.messages import ExportSignalMessage
+
+logger = structlog.get_logger(__name__)
+
+
+class DestinationDeliveryError(Exception):
+ """One destination could not take the batch, so the batch is not done.
+
+ Carries the destination's name so a single job's `latest_error` still says which
+ destination stopped the sync.
+ """
+
+ def __init__(self, destination_name: str, cause: Exception) -> None:
+ self.destination_name = destination_name
+ self.cause = cause
+ super().__init__(f"{destination_name}: {cause}")
+
+
+def external_destinations_for(export_signal: ExportSignalMessage) -> list[ExternalDataDestination]:
+ """The run's destinations, minus the PostHog warehouse, in a stable order.
+
+ Ordered by id so every batch visits them the same way, which keeps the logs readable
+ when a run partially fails and retries.
+ """
+ if not export_signal.destination_ids:
+ return []
+
+ destinations = ExternalDataDestination.objects.for_team(export_signal.team_id, canonical=True).filter(
+ id__in=export_signal.destination_ids
+ )
+ return sorted(
+ (d for d in destinations if d.type != ExternalDataDestination.Type.POSTHOG_WAREHOUSE and not d.deleted),
+ key=lambda d: str(d.id),
+ )
+
+
+def warehouse_is_a_destination(export_signal: ExportSignalMessage) -> bool:
+ """Whether this run writes to the PostHog warehouse at all.
+
+ An empty list means the warehouse only, which is every run that predates destinations.
+ A run that lists destinations but not the warehouse never touches delta: the customer
+ asked us to move their data somewhere else, not to keep a copy here.
+ """
+ if not export_signal.destination_ids:
+ return True
+
+ return (
+ ExternalDataDestination.objects.for_team(export_signal.team_id, canonical=True)
+ .filter(
+ id__in=export_signal.destination_ids,
+ type=ExternalDataDestination.Type.POSTHOG_WAREHOUSE,
+ deleted=False,
+ )
+ .exists()
+ )
+
+
+def _source_scoped_table_name(source: ExternalDataSource, schema_name: str) -> str:
+ """Source type, then the source's prefix, then the schema name, each separated.
+
+ The warehouse builds the same three parts but glues the prefix to the source type
+ (`build_table_name` gives `testpostgres_auth_group`), which reads as one word in a customer's
+ own database. Here they stay separated, so `postgres_test_auth_group` says which source type,
+ which source, and which table.
+
+ The sanitizing matches the warehouse: dots parse as `<table>.<column>` in HogQL, and slashes
+ are not identifier characters at all.
+ """
+ safe_schema_name = schema_name.replace("/", "_").replace(".", "__")
+ prefix = (source.prefix or "").strip("_")
+ parts = [source.source_type, prefix, safe_schema_name] if prefix else [source.source_type, safe_schema_name]
+ return "_".join(parts).lower()
+
+
+def destination_table_name(export_signal: ExportSignalMessage, config: dict) -> str:
+ """What a destination calls the table for this schema.
+
+ Carries the source type and prefix so two sources with a same-named resource do not resolve to
+ one table. Falls back to the raw resource name only if the schema has gone, which is a run that
+ is failing anyway. `table_prefix` stays supported as an escape hatch for a name a customer needs
+ to control; nothing sets it today.
+ """
+ schema = (
+ ExternalDataSchema.objects.filter(id=export_signal.schema_id, team_id=export_signal.team_id)
+ .select_related("source")
+ .first()
+ )
+ base = (
+ _source_scoped_table_name(schema.source, schema.name)
+ if schema and schema.source
+ else export_signal.resource_name
+ )
+ return f"{config.get('table_prefix', '')}{base}"
+
+
+def _run_context(export_signal: ExportSignalMessage, destination: ExternalDataDestination) -> DestinationRunContext:
+ config = destination.config or {}
+ return DestinationRunContext(
+ team_id=export_signal.team_id,
+ schema_id=export_signal.schema_id,
+ source_id=export_signal.source_id,
+ job_id=export_signal.job_id,
+ run_uuid=export_signal.run_uuid,
+ destination_id=str(destination.id),
+ destination_type=destination.type,
+ destination_name=destination.name,
+ # Derived from the schema, never configured on the destination: a destination is shared
+ # by every schema of every source pointed at it, so one configured name would collapse
+ # them all into a single table.
+ table_name=destination_table_name(export_signal, config),
+ sync_type=export_signal.sync_type,
+ primary_keys=tuple(export_signal.primary_keys or ()),
+ config=config,
+ integration_id=destination.integration_id,
+ )
+
+
+def _fail_for_unresolved_destinations(
+ export_signal: ExportSignalMessage, resolved: list[ExternalDataDestination]
+) -> None:
+ """Raise if a destination from the run's snapshot no longer delivers here.
+
+ The only reason a snapshotted id can be absent from `resolved` is that it is the PostHog
+ warehouse (delivered elsewhere, exempt here) or that it was deleted after the run started.
+ The warehouse case is fine; the deletion case is not — the run's snapshot promised this
+ destination the batch, and `external_destinations_for` silently dropping it would let the
+ final batch mark the run completed while that destination never received its data. Fail
+ the batch instead, the same as any other destination that could not take it.
+ """
+ resolved_ids = {str(d.id) for d in resolved}
+ missing_ids = [
+ destination_id for destination_id in export_signal.destination_ids if destination_id not in resolved_ids
+ ]
+ if not missing_ids:
+ return
+
+ missing = ExternalDataDestination.objects.for_team(export_signal.team_id, canonical=True).filter(id__in=missing_ids)
+ unresolved = [d for d in missing if d.type != ExternalDataDestination.Type.POSTHOG_WAREHOUSE]
+ if not unresolved:
+ return
+
+ names = ", ".join(sorted(d.name for d in unresolved))
+ raise DestinationDeliveryError(names, LookupError("destination deleted after the run started"))
+
+
+def deliver_batch_to_destinations(
+ export_signal: ExportSignalMessage,
+ destinations: Iterable[ExternalDataDestination] | None = None,
+) -> int:
+ """Write this batch to every external destination that has not already taken it.
+
+ Returns the number of destinations written. Raises `DestinationDeliveryError` on the
+ first failure, which fails the batch and leaves it to be retried. That includes a
+ destination from the run's snapshot that was deleted mid-run: it is reported as failed
+ rather than silently skipped, so the run cannot complete while owing it data.
+
+ Connection hygiene belongs to the caller: `close_old_connections` here would drop the
+ connection a caller's transaction is running in, which is what the load consumer already
+ does once per message before it gets this far.
+ """
+ if destinations is not None:
+ pending = list(destinations)
+ else:
+ pending = external_destinations_for(export_signal)
+ _fail_for_unresolved_destinations(export_signal, pending)
+
+ if not pending:
+ return 0
+
+ written = 0
+ for destination in pending:
+ destination_id = str(destination.id)
+
+ already_written = is_batch_already_processed(
+ export_signal.team_id,
+ export_signal.schema_id,
+ export_signal.run_uuid,
+ export_signal.batch_index,
+ destination_id=destination_id,
+ )
+
+ # Writing and publishing are separate. The extraction side sends the last batch twice,
+ # once while processing and once flagged final, so skipping the whole batch because it
+ # was already written would leave a full refresh staged and never swapped in.
+ if already_written and not export_signal.is_final_batch:
+ logger.info(
+ "destination_batch_already_delivered",
+ destination_name=destination.name,
+ destination_type=destination.type,
+ batch_index=export_signal.batch_index,
+ msg=(f"Batch {export_signal.batch_index} already delivered to {destination.name}, skipping"),
+ )
+ continue
+
+ run_ctx = _run_context(export_signal, destination)
+ batch_ctx = DestinationBatchContext(
+ run=run_ctx,
+ batch_index=export_signal.batch_index,
+ is_final_batch=export_signal.is_final_batch,
+ expected_row_count=export_signal.row_count,
+ )
+
+ started_at = time.monotonic()
+ logger.info(
+ "destination_batch_started",
+ destination_name=destination.name,
+ destination_type=destination.type,
+ table_name=run_ctx.table_name,
+ sync_type=run_ctx.sync_type,
+ batch_index=export_signal.batch_index,
+ expected_rows=export_signal.row_count,
+ msg=(
+ f"Writing {export_signal.row_count:,} rows to {destination.name} "
+ f"({run_ctx.table_name}), batch {export_signal.batch_index}"
+ ),
+ )
+
+ outcome = None
+ try:
+ ensure_builtin_destination_writers_registered()
+ writer = resolve_destination_writer(run_ctx)
+ if not already_written:
+ async_to_sync(writer.prepare_run)(run_ctx)
+ outcome = async_to_sync(_write)(writer, export_signal, batch_ctx)
+ # Marked before publication, not after. `finalize_run` is a no-op the second
+ # time, but `write_batch` is not: on a full refresh it rebuilds the staging
+ # table out of this one batch, so a replay that ran both again would publish
+ # that batch over the complete table the first pass swapped in. Marking first
+ # makes a replay skip the write and re-run only the idempotent publish.
+ mark_batch_as_processed(
+ export_signal.team_id,
+ export_signal.schema_id,
+ export_signal.run_uuid,
+ export_signal.batch_index,
+ destination_id=destination_id,
+ )
+ written += 1
+ if export_signal.is_final_batch:
+ async_to_sync(writer.finalize_run)(run_ctx)
+ logger.info(
+ "destination_run_published",
+ destination_name=destination.name,
+ destination_type=destination.type,
+ table_name=run_ctx.table_name,
+ total_rows=export_signal.total_rows,
+ msg=(
+ f"Published {run_ctx.table_name} on {destination.name}"
+ f"{f' ({export_signal.total_rows:,} rows)' if export_signal.total_rows else ''}"
+ ),
+ )
+ except Exception as e:
+ logger.warning(
+ "destination_batch_failed",
+ destination_name=destination.name,
+ destination_type=destination.type,
+ table_name=run_ctx.table_name,
+ batch_index=export_signal.batch_index,
+ error=str(e),
+ msg=f"Failed writing to {destination.name} ({run_ctx.table_name}): {e}",
+ )
+ raise DestinationDeliveryError(destination.name, e) from e
+
+ rows_written = outcome.rows_written if outcome else 0
+ duration_seconds = round(time.monotonic() - started_at, 3)
+ logger.info(
+ "destination_batch_delivered",
+ destination_name=destination.name,
+ destination_type=destination.type,
+ table_name=run_ctx.table_name,
+ batch_index=export_signal.batch_index,
+ rows_written=rows_written,
+ duration_seconds=duration_seconds,
+ msg=(f"Wrote {rows_written:,} rows to {destination.name} ({run_ctx.table_name}) in {duration_seconds}s"),
+ )
+
+ return written
+
+
+async def _write(
+ writer, export_signal: ExportSignalMessage, batch_ctx: DestinationBatchContext
+) -> BatchWriteOutcome | None:
+ """Stream the staged parquet into the writer a row group at a time.
+
+ Re-read per destination rather than held once: a staged batch targets around 200 MiB of
+ Arrow, and holding it for the whole loop would multiply that by the destination count.
+ """
+ return await writer.write_batch(aiter_record_batches(export_signal.s3_path), batch_ctx)
+
+
+def abort_destinations(export_signal: ExportSignalMessage) -> None:
+ """Let each writer drop what a run that will not finish left staged."""
+ for destination in external_destinations_for(export_signal):
+ run_ctx = _run_context(export_signal, destination)
+ try:
+ ensure_builtin_destination_writers_registered()
+ writer = resolve_destination_writer(run_ctx)
+ async_to_sync(writer.abort_run)(run_ctx)
+ except Exception as e:
+ # Best effort: the next run stages under its own id, so a leftover staging
+ # table costs storage rather than correctness.
+ logger.warning("destination_abort_failed", destination_type=destination.type, error=str(e))
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/parquet_source.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/parquet_source.py
new file mode 100644
index 000000000000..5af70a9caf10
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/parquet_source.py
@@ -0,0 +1,54 @@
+"""Reading a staged parquet batch as a stream of record batches.
+
+Row groups are read one at a time rather than the whole file at once. A staged batch targets
+around 200 MiB of Arrow payload, so materializing it per destination would multiply that by
+the number of destinations a run fans out to.
+"""
+
+from __future__ import annotations
+
+from collections.abc import AsyncIterator, Iterator
+
+import pyarrow as pa
+import pyarrow.parquet as pq
+from asgiref.sync import sync_to_async
+
+from products.data_warehouse.backend.facade.api import get_s3_client
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.s3.common import strip_s3_protocol
+
+# Rows per record batch handed to a writer. Small enough that a writer buffering one batch
+# stays bounded, large enough that per-batch overhead stays negligible.
+DEFAULT_BATCH_ROWS = 50_000
+
+
+def read_parquet_schema(s3_path: str) -> pa.Schema:
+ """The Arrow schema of a staged file, read from its footer without scanning any rows."""
+ s3 = get_s3_client()
+ with s3.open(strip_s3_protocol(s3_path), "rb") as f:
+ return pq.ParquetFile(f).schema_arrow
+
+
+def iter_record_batches(s3_path: str, batch_rows: int = DEFAULT_BATCH_ROWS) -> Iterator[pa.RecordBatch]:
+ s3 = get_s3_client()
+ with s3.open(strip_s3_protocol(s3_path), "rb") as f:
+ parquet_file = pq.ParquetFile(f)
+ yield from parquet_file.iter_batches(batch_size=batch_rows)
+
+
+async def aiter_record_batches(s3_path: str, batch_rows: int = DEFAULT_BATCH_ROWS) -> AsyncIterator[pa.RecordBatch]:
+ """Async view of the same stream, for writers that talk to their destination with asyncio.
+
+ The read itself is blocking, so each pull is handed to a thread rather than run on the
+ event loop.
+ """
+ iterator = iter_record_batches(s3_path, batch_rows)
+ sentinel = object()
+
+ def next_batch():
+ return next(iterator, sentinel)
+
+ while True:
+ batch = await sync_to_async(next_batch, thread_sensitive=False)()
+ if batch is sentinel:
+ return
+ yield batch
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/tests/__init__.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/tests/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/tests/test_builtin_writers.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/tests/test_builtin_writers.py
new file mode 100644
index 000000000000..d4af848e6550
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/tests/test_builtin_writers.py
@@ -0,0 +1,76 @@
+import pytest
+
+from products.warehouse_sources.backend.models.external_data_destination import ExternalDataDestination
+from products.warehouse_sources.backend.presentation.views.external_data_destination import (
+ DESTINATION_INTEGRATION_KINDS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.destinations.contracts import (
+ DestinationRunContext,
+ DestinationWriter,
+)
+from products.warehouse_sources.backend.temporal.data_imports.destinations.registry import (
+ resolve_destination_writer,
+ supported_destination_types,
+)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.destinations_load.builtin_writers import (
+ builtin_destination_types,
+ register_builtin_destination_writers,
+)
+
+# Azure Blob and S3 validate their config eagerly at construction time (a missing container or
+# bucket would otherwise write to a nonsense name hundreds of MiB into a batch), so those two
+# need enough config to pass that check. Every other builtin writer accepts an empty config here.
+_MINIMAL_CONFIG: dict[str, dict] = {
+ str(ExternalDataDestination.Type.AZURE_BLOB): {"container_name": "container"},
+ str(ExternalDataDestination.Type.S3): {"bucket": "bucket", "region": "us-east-1"},
+}
+
+
+def _ctx(destination_type: str) -> DestinationRunContext:
+ return DestinationRunContext(
+ team_id=1,
+ schema_id="schema",
+ source_id="source",
+ job_id="job",
+ run_uuid="run-a1",
+ destination_id="destination",
+ destination_type=destination_type,
+ destination_name=destination_type,
+ table_name="charges",
+ sync_type="incremental",
+ primary_keys=("id",),
+ config=_MINIMAL_CONFIG.get(destination_type, {}),
+ )
+
+
[email protected](autouse=True)
+def _registered():
+ register_builtin_destination_writers()
+
+
[email protected]("destination_type", sorted(DESTINATION_INTEGRATION_KINDS))
+def test_every_type_a_user_can_configure_has_a_writer(destination_type: str) -> None:
+ # Without this, a user could create a destination the consumer leases work for and then
+ # fails every batch of, because nothing knows how to write it.
+ writer = resolve_destination_writer(_ctx(destination_type))
+
+ assert isinstance(writer, DestinationWriter)
+
+
+def test_the_default_claim_scope_matches_what_can_be_written() -> None:
+ # Claiming a type with no writer would lease the group and fail its every batch.
+ assert sorted(builtin_destination_types()) == sorted(supported_destination_types())
+
+
+def test_only_the_warehouse_holds_the_sync_lock_and_runs_post_load() -> None:
+ # Both are warehouse-only capabilities. An external writer claiming either would either
+ # block the schema's next sync or try to register a warehouse table that does not exist.
+ for destination_type in DESTINATION_INTEGRATION_KINDS:
+ writer = resolve_destination_writer(_ctx(destination_type))
+ assert writer.holds_sync_lock is False, destination_type
+ assert writer.runs_post_load is False, destination_type
+
+
+def test_the_warehouse_is_not_written_by_the_external_consumer() -> None:
+ # The warehouse is delivered by the Delta loader, so the external consumer must not claim it.
+ assert ExternalDataDestination.Type.POSTHOG_WAREHOUSE not in builtin_destination_types()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/tests/test_delivery.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/tests/test_delivery.py
new file mode 100644
index 000000000000..9742d7def0be
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/tests/test_delivery.py
@@ -0,0 +1,322 @@
+import uuid
+
+from posthog.test.base import BaseTest
+from unittest import mock
+
+import structlog.testing
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.models.external_data_destination import (
+ ExternalDataDestination,
+ get_or_create_warehouse_destination,
+)
+from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
+from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
+from products.warehouse_sources.backend.temporal.data_imports.destinations.contracts import BatchWriteOutcome
+from products.warehouse_sources.backend.temporal.data_imports.destinations.registry import (
+ register_destination_writer,
+ restore_registered_writers,
+ snapshot_registered_writers,
+)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.destinations_load import delivery
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.destinations_load.delivery import (
+ destination_table_name,
+)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.messages import ExportSignalMessage
+
+
+class RecordingWriter:
+ holds_sync_lock = False
+ runs_post_load = False
+ calls: list[tuple[str, str, int]] = []
+ fail_for: set[str] = set()
+
+ def __init__(self, ctx) -> None:
+ self._ctx = ctx
+
+ async def prepare_run(self, ctx) -> None:
+ return None
+
+ async def write_batch(self, batches, batch_ctx) -> BatchWriteOutcome:
+ if self._ctx.destination_name in RecordingWriter.fail_for:
+ raise RuntimeError("destination unreachable")
+ RecordingWriter.calls.append(("write", self._ctx.destination_name, batch_ctx.batch_index))
+ return BatchWriteOutcome(rows_written=1)
+
+ async def finalize_run(self, ctx) -> None:
+ RecordingWriter.calls.append(("finalize", self._ctx.destination_name, -1))
+
+ async def abort_run(self, ctx) -> None:
+ RecordingWriter.calls.append(("abort", self._ctx.destination_name, -1))
+
+
+class DeliveryTestCase(BaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ RecordingWriter.calls = []
+ RecordingWriter.fail_for = set()
+
+ # The registry is process-global, so these fakes have to come back out or every later
+ # test sees destination types this deployment cannot really write.
+ self.addCleanup(restore_registered_writers, snapshot_registered_writers())
+ for destination_type in (ExternalDataDestination.Type.REDSHIFT, ExternalDataDestination.Type.SNOWFLAKE):
+ register_destination_writer(destination_type, RecordingWriter)
+
+ # Idempotency markers live in memory, so every test starts with none and the writers
+ # never touch Redis. The staged parquet is never read, since no batch reaches a writer.
+ self._seen: set[str] = set()
+ patches = [
+ mock.patch.object(delivery, "aiter_record_batches", return_value=iter(())),
+ mock.patch.object(delivery, "is_batch_already_processed", side_effect=self._already),
+ mock.patch.object(delivery, "mark_batch_as_processed", side_effect=self._mark),
+ ]
+ for patch in patches:
+ patch.start()
+ self.addCleanup(patch.stop)
+
+ def _already(self, team_id, schema_id, run_uuid, batch_index, delta_table_ref=None, destination_id=None) -> bool:
+ return f"{run_uuid}:{batch_index}:{destination_id}" in self._seen
+
+ def _mark(self, team_id, schema_id, run_uuid, batch_index, destination_id=None) -> None:
+ self._seen.add(f"{run_uuid}:{batch_index}:{destination_id}")
+
+ def _destination(
+ self, name: str, type_: str = str(ExternalDataDestination.Type.REDSHIFT)
+ ) -> ExternalDataDestination:
+ return ExternalDataDestination.objects.for_team(self.team.pk).create(
+ team_id=self.team.pk, type=type_, name=name, config={"table_name": "charges"}
+ )
+
+ def _signal(
+ self,
+ destination_ids: list[str],
+ *,
+ batch_index: int = 0,
+ is_final: bool = False,
+ schema_id: str | None = None,
+ ) -> ExportSignalMessage:
+ return ExportSignalMessage(
+ team_id=self.team.pk,
+ job_id=str(uuid.uuid4()),
+ schema_id=schema_id or str(uuid.uuid4()),
+ source_id=str(uuid.uuid4()),
+ resource_name="charges",
+ run_uuid="run-a1",
+ batch_index=batch_index,
+ s3_path="s3://bucket/part-0.parquet",
+ row_count=1,
+ byte_size=1,
+ is_final_batch=is_final,
+ total_batches=1,
+ total_rows=1,
+ sync_type="incremental",
+ data_folder=None,
+ schema_path=None,
+ primary_keys=["id"],
+ destination_ids=destination_ids,
+ )
+
+ @staticmethod
+ def _writes() -> list[str]:
+ return [name for kind, name, _ in RecordingWriter.calls if kind == "write"]
+
+
+class TestDelivery(DeliveryTestCase):
+ def test_every_destination_receives_the_batch(self) -> None:
+ a = self._destination("warehouse a")
+ b = self._destination("warehouse b", ExternalDataDestination.Type.SNOWFLAKE)
+
+ written = delivery.deliver_batch_to_destinations(self._signal([str(a.id), str(b.id)]))
+
+ assert written == 2
+ assert sorted(self._writes()) == ["warehouse a", "warehouse b"]
+
+ def test_the_logs_say_where_the_rows_went(self) -> None:
+ # A run writing to several destinations is otherwise indistinguishable in the logs from
+ # one writing to the warehouse alone, which is what makes a partial failure hard to read.
+ a = self._destination("customer postgres")
+
+ with structlog.testing.capture_logs() as logs:
+ delivery.deliver_batch_to_destinations(self._signal([str(a.id)]))
+
+ by_event = {entry["event"]: entry for entry in logs}
+
+ assert "destination_batch_started" in by_event
+ assert by_event["destination_batch_started"]["destination_name"] == "customer postgres"
+ assert by_event["destination_batch_started"]["table_name"]
+
+ delivered = by_event["destination_batch_delivered"]
+ assert delivered["destination_name"] == "customer postgres"
+ assert delivered["rows_written"] == 1
+ assert delivered["table_name"]
+ assert delivered["duration_seconds"] >= 0
+
+ def test_a_failed_destination_names_itself_and_its_table_in_the_logs(self) -> None:
+ a = self._destination("customer postgres")
+ RecordingWriter.fail_for = {"customer postgres"}
+
+ with structlog.testing.capture_logs() as logs:
+ with self.assertRaises(delivery.DestinationDeliveryError):
+ delivery.deliver_batch_to_destinations(self._signal([str(a.id)]))
+
+ failed = next(entry for entry in logs if entry["event"] == "destination_batch_failed")
+ assert failed["destination_name"] == "customer postgres"
+ assert failed["table_name"]
+ assert "destination unreachable" in failed["error"]
+
+ def test_a_destination_that_already_took_the_batch_is_not_written_again(self) -> None:
+ a = self._destination("warehouse a")
+ signal = self._signal([str(a.id)])
+
+ delivery.deliver_batch_to_destinations(signal)
+ delivery.deliver_batch_to_destinations(signal)
+
+ assert self._writes() == ["warehouse a"]
+
+ def test_a_retry_writes_only_the_destination_that_failed(self) -> None:
+ a = self._destination("warehouse a")
+ b = self._destination("warehouse b", ExternalDataDestination.Type.SNOWFLAKE)
+ signal = self._signal([str(a.id), str(b.id)])
+
+ # Destinations are visited in id order, so fail the one visited last. Picking by name
+ # would make the test depend on which uuid happened to sort first.
+ last = max((a, b), key=lambda d: str(d.id))
+ first = min((a, b), key=lambda d: str(d.id))
+ RecordingWriter.fail_for = {str(last.name)}
+
+ with self.assertRaises(delivery.DestinationDeliveryError):
+ delivery.deliver_batch_to_destinations(signal)
+ assert self._writes() == [first.name]
+
+ RecordingWriter.calls = []
+ RecordingWriter.fail_for = set()
+ delivery.deliver_batch_to_destinations(signal)
+
+ assert self._writes() == [last.name]
+
+ def test_the_error_names_the_destination_that_stopped_the_sync(self) -> None:
+ a = self._destination("customer redshift")
+ RecordingWriter.fail_for = {"customer redshift"}
+
+ with self.assertRaises(delivery.DestinationDeliveryError) as caught:
+ delivery.deliver_batch_to_destinations(self._signal([str(a.id)]))
+
+ assert "customer redshift" in str(caught.exception)
+
+ def test_the_final_batch_publishes_each_destination(self) -> None:
+ a = self._destination("warehouse a")
+
+ delivery.deliver_batch_to_destinations(self._signal([str(a.id)], batch_index=3, is_final=True))
+
+ assert ("finalize", "warehouse a", -1) in RecordingWriter.calls
+
+ def test_a_batch_that_is_not_final_publishes_nothing(self) -> None:
+ a = self._destination("warehouse a")
+
+ delivery.deliver_batch_to_destinations(self._signal([str(a.id)]))
+
+ assert not [c for c in RecordingWriter.calls if c[0] == "finalize"]
+
+ def test_the_posthog_warehouse_is_not_delivered_here(self) -> None:
+ warehouse = get_or_create_warehouse_destination(self.team.pk)
+ a = self._destination("warehouse a")
+
+ written = delivery.deliver_batch_to_destinations(self._signal([str(warehouse.id), str(a.id)]))
+
+ assert written == 1
+ assert self._writes() == ["warehouse a"]
+
+ def test_a_deleted_destination_fails_the_batch(self) -> None:
+ a = self._destination("warehouse a")
+ a.deleted = True
+ a.save(update_fields=["deleted"])
+
+ with self.assertRaises(delivery.DestinationDeliveryError) as caught:
+ delivery.deliver_batch_to_destinations(self._signal([str(a.id)]))
+
+ assert "warehouse a" in str(caught.exception)
+ assert not RecordingWriter.calls
+
+ def test_a_deleted_destination_stops_the_others_from_being_delivered_to_too(self) -> None:
+ a = self._destination("warehouse a")
+ b = self._destination("warehouse b", ExternalDataDestination.Type.SNOWFLAKE)
+ a.deleted = True
+ a.save(update_fields=["deleted"])
+
+ # The batch is not done until every destination in the snapshot has taken it, so a
+ # deleted one blocks the whole batch rather than letting the survivors finish and the
+ # run complete short of what it promised.
+ with self.assertRaises(delivery.DestinationDeliveryError):
+ delivery.deliver_batch_to_destinations(self._signal([str(a.id), str(b.id)]))
+
+ assert not self._writes()
+
+
+class TestDestinationTableName(DeliveryTestCase):
+ """The name a destination writes under, which a customer sees in their own database."""
+
+ def _schema_for(self, source_type: str, prefix: str, name: str) -> ExternalDataSchema:
+ source = ExternalDataSource.objects.create(
+ team=self.team,
+ source_id=f"src-{prefix}{name}",
+ connection_id=f"conn-{prefix}{name}",
+ status="Running",
+ source_type=source_type,
+ prefix=prefix,
+ )
+ return ExternalDataSchema.objects.create(team=self.team, source=source, name=name)
+
+ def test_it_leads_with_the_source_type(self) -> None:
+ schema = self._schema_for("Stripe", "", "Charge")
+
+ signal = self._signal([], schema_id=str(schema.id))
+
+ assert destination_table_name(signal, {}) == "stripe_charge"
+
+ @parameterized.expand([("no trailing underscore", "eu"), ("trailing underscore", "eu_")])
+ def test_a_source_prefix_sits_between_the_type_and_the_table(self, _name: str, prefix: str) -> None:
+ # Two Stripe accounts are told apart by prefix in PostHog, so they must be told apart in
+ # the customer's database too rather than both landing on `stripe_charge`. The warehouse
+ # would glue this into `eu_stripe_charge`; separated, it reads as type, source, table.
+ schema = self._schema_for("Stripe", prefix, "Charge")
+
+ assert destination_table_name(self._signal([], schema_id=str(schema.id)), {}) == "stripe_eu_charge"
+
+ def test_two_sources_sharing_a_resource_name_do_not_collide(self) -> None:
+ postgres = self._schema_for("Postgres", "", "users")
+ mysql = self._schema_for("MySQL", "", "users")
+
+ assert destination_table_name(self._signal([], schema_id=str(postgres.id)), {}) != destination_table_name(
+ self._signal([], schema_id=str(mysql.id)), {}
+ )
+
+ def test_a_dotted_schema_name_is_flattened(self) -> None:
+ # A dot would read as `<table>.<column>`, so the warehouse rewrites it and so must this.
+ schema = self._schema_for("Postgres", "", "public.auth_group")
+
+ assert destination_table_name(self._signal([], schema_id=str(schema.id)), {}) == "postgres_public__auth_group"
+
+ def test_a_configured_prefix_still_applies(self) -> None:
+ schema = self._schema_for("Stripe", "", "Charge")
+
+ name = destination_table_name(self._signal([], schema_id=str(schema.id)), {"table_prefix": "raw_"})
+
+ assert name == "raw_stripe_charge"
+
+ def test_it_falls_back_to_the_resource_name_when_the_schema_is_gone(self) -> None:
+ assert destination_table_name(self._signal([]), {}) == "charges"
+
+
+class TestWarehousePresence(DeliveryTestCase):
+ def test_no_destination_ids_means_the_warehouse(self) -> None:
+ assert delivery.warehouse_is_a_destination(self._signal([])) is True
+
+ def test_the_warehouse_is_recognized_when_listed(self) -> None:
+ warehouse = get_or_create_warehouse_destination(self.team.pk)
+
+ assert delivery.warehouse_is_a_destination(self._signal([str(warehouse.id)])) is True
+
+ def test_external_only_runs_do_not_write_the_warehouse(self) -> None:
+ a = self._destination("warehouse a")
+
+ assert delivery.warehouse_is_a_destination(self._signal([str(a.id)])) is False
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/tests/test_postgres_writer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/tests/test_postgres_writer.py
new file mode 100644
index 000000000000..891ec56a8421
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/tests/test_postgres_writer.py
@@ -0,0 +1,737 @@
+import uuid
+from collections.abc import AsyncIterator
+
+import pytest
+
+from django.conf import settings
+
+import psycopg
+import pyarrow as pa
+import psycopg.conninfo
+
+from products.batch_exports.backend.temporal.destinations.postgres_batch_export import PostgreSQLClient
+from products.warehouse_sources.backend.temporal.data_imports.destinations.contracts import (
+ DestinationBatchContext,
+ DestinationRunContext,
+)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.destinations_load.writers.postgres import (
+ PostgresDestinationWriter,
+ UnrelatedTableExistsError,
+ _owned_marker,
+ _scoped_identifier,
+ merge_stage_name,
+ staging_table_name,
+)
+
+pytestmark = pytest.mark.asyncio
+
+
+async def _batches(*record_batches: pa.RecordBatch) -> AsyncIterator[pa.RecordBatch]:
+ for batch in record_batches:
+ yield batch
+
+
+def _rows(name: list[str], ids: list[int]) -> pa.RecordBatch:
+ return pa.RecordBatch.from_pydict({"id": ids, "name": name})
+
+
+class LocalPostgresWriter(PostgresDestinationWriter):
+ """Points the writer at the local test database instead of a customer's integration."""
+
+ def __init__(self, ctx: DestinationRunContext, dsn: str) -> None:
+ super().__init__(ctx)
+ self._dsn = dsn
+
+ async def _make_client(self) -> PostgreSQLClient:
+ parsed = psycopg.conninfo.conninfo_to_dict(self._dsn)
+ return PostgreSQLClient(
+ user=str(parsed.get("user", "posthog")),
+ password=str(parsed.get("password", "posthog")),
+ host=str(parsed.get("host", "localhost")),
+ port=int(parsed.get("port") or 5432),
+ database=str(parsed.get("dbname", "posthog")),
+ ssl_mode="prefer",
+ )
+
+
+def dsn() -> str:
+ return settings.WAREHOUSE_SOURCES_DATABASE_URL
+
+
+def table_name() -> str:
+ return f"dest_test_{uuid.uuid4().hex[:10]}"
+
+
+def _ctx(
+ table_name: str, sync_type: str, primary_keys: tuple[str, ...] = (), schema_id: str = "schema"
+) -> DestinationRunContext:
+ return DestinationRunContext(
+ team_id=1,
+ schema_id=schema_id,
+ source_id="source",
+ job_id="job",
+ run_uuid=str(uuid.uuid4()),
+ destination_id="destination",
+ destination_type="Postgres",
+ destination_name="test postgres",
+ table_name=table_name,
+ sync_type=sync_type,
+ primary_keys=primary_keys,
+ config={"schema": "public"},
+ )
+
+
+def _read(dsn: str, table: str) -> list[tuple]:
+ with psycopg.connect(dsn, autocommit=True) as conn:
+ return conn.execute(f'SELECT id, name FROM public."{table}" ORDER BY id').fetchall()
+
+
+def _table_exists(dsn: str, table: str) -> bool:
+ with psycopg.connect(dsn, autocommit=True) as conn:
+ return (
+ conn.execute(
+ "SELECT 1 FROM information_schema.tables WHERE table_schema='public' AND table_name=%s",
+ (table,),
+ ).fetchone()
+ is not None
+ )
+
+
+def _row_count(dsn: str, table: str) -> int:
+ with psycopg.connect(dsn, autocommit=True) as conn:
+ row = conn.execute(f'SELECT count(*) FROM public."{table}"').fetchone()
+ assert row is not None
+ return row[0]
+
+
+def _drop(dsn: str, *tables: str) -> None:
+ with psycopg.connect(dsn, autocommit=True) as conn:
+ for table in tables:
+ conn.execute(f'DROP TABLE IF EXISTS public."{table}" CASCADE')
+
+
+class TestStagingTableNameTruncation:
+ """Postgres silently truncates any identifier past 63 bytes. The run-scoped suffix has to
+ survive that truncation itself, or a long enough `table_name` collapses the staging name
+ back onto a name Postgres would treat identically to the live table's own (also
+ truncated) name.
+ """
+
+ async def test_a_short_table_name_is_untouched(self) -> None:
+ ctx = _ctx("orders", "full_refresh")
+ name = staging_table_name(ctx)
+
+ assert name.startswith("orders__ph_stage_")
+ assert len(name.encode()) <= 63
+
+ async def test_a_long_table_name_still_ends_with_its_full_run_suffix(self) -> None:
+ ctx = _ctx("r" * 100, "full_refresh")
+ name = staging_table_name(ctx)
+ suffix = f"__ph_stage_{ctx.run_uuid.replace('-', '')[:12]}"
+
+ # The whole point: Postgres's own truncation drops the *end* of an over-length
+ # identifier first, which is exactly this suffix. Truncating the base ourselves means
+ # the suffix is always what's left, not what's cut.
+ assert name.endswith(suffix)
+ assert len(name.encode()) <= 63
+
+ async def test_two_long_table_names_sharing_a_63_byte_prefix_still_differ(self) -> None:
+ # What an attacker actually needs for the identifier-truncation attack: two
+ # `table_name`s identical for the first 63 bytes (what Postgres alone would leave
+ # standing) but different beyond it.
+ first = _ctx("r" * 100 + "-one", "full_refresh")
+ second = _ctx("r" * 100 + "-two", "full_refresh")
+
+ assert staging_table_name(first) != staging_table_name(second)
+
+ async def test_a_multibyte_table_name_does_not_raise(self) -> None:
+ ctx = _ctx("é" * 60, "full_refresh")
+ name = staging_table_name(ctx)
+
+ assert len(name.encode()) <= 63
+
+
+class TestScopedIdentifierTruncation:
+ """`_scoped_identifier` is what `staging_table_name` above is built on, and also what an
+ incremental merge's per-batch stage table and unique index names are built on. Unlike a
+ full refresh's staging name, an incremental `target` is never itself truncated by this
+ writer, so it can already sit at Postgres's 63-byte limit before a suffix is even added.
+ """
+
+ def test_a_short_base_is_untouched(self) -> None:
+ name = _scoped_identifier("orders", "__ph_merge_abcd1234")
+
+ assert name == "orders__ph_merge_abcd1234"
+
+ def test_a_63_byte_base_still_gets_a_distinct_suffixed_name(self) -> None:
+ # The exact shape of the bug: `target` is already at the limit a merge stage or index
+ # name would otherwise collapse onto if its suffix were left for Postgres to truncate.
+ base = "t" * 63
+ stage = _scoped_identifier(base, "__ph_merge_abcd1234")
+ index = _scoped_identifier(base, "__ph_pk")
+
+ assert stage != base
+ assert index != base
+ assert stage != index
+ assert len(stage.encode()) <= 63
+ assert len(index.encode()) <= 63
+ assert stage.endswith("__ph_merge_abcd1234")
+ assert index.endswith("__ph_pk")
+
+ def test_a_far_longer_base_still_yields_a_distinct_suffixed_name(self) -> None:
+ base = "t" * 200
+ stage = _scoped_identifier(base, "__ph_merge_abcd1234")
+
+ assert stage != base.encode()[:63].decode()
+ assert stage.endswith("__ph_merge_abcd1234")
+ assert len(stage.encode()) <= 63
+
+
+class TestFullRefresh:
+ async def test_the_live_table_only_changes_once_the_run_completes(self, dsn, table_name) -> None:
+ ctx = _ctx(table_name, "full_refresh")
+ writer = LocalPostgresWriter(ctx, dsn)
+ try:
+ await writer.write_batch(
+ _batches(_rows(["a"], [1])),
+ DestinationBatchContext(run=ctx, batch_index=0, is_final_batch=False),
+ )
+
+ # Mid-run the destination table does not exist yet; only the staging table does.
+ with psycopg.connect(dsn, autocommit=True) as conn:
+ live_exists = conn.execute(
+ "SELECT 1 FROM information_schema.tables WHERE table_schema='public' AND table_name=%s",
+ (table_name,),
+ ).fetchone()
+ assert live_exists is None
+
+ await writer.write_batch(
+ _batches(_rows(["b"], [2])),
+ DestinationBatchContext(run=ctx, batch_index=1, is_final_batch=True),
+ )
+ await writer.finalize_run(ctx)
+
+ assert _read(dsn, table_name) == [(1, "a"), (2, "b")]
+ finally:
+ _drop(dsn, table_name, staging_table_name(ctx))
+
+ async def test_reapplying_a_batch_does_not_duplicate_its_rows(self, dsn, table_name) -> None:
+ ctx = _ctx(table_name, "full_refresh")
+ writer = LocalPostgresWriter(ctx, dsn)
+ try:
+ batch_ctx = DestinationBatchContext(run=ctx, batch_index=0, is_final_batch=True)
+ await writer.write_batch(_batches(_rows(["a", "b"], [1, 2])), batch_ctx)
+ # A crash after the write but before the state was recorded re-claims this batch.
+ await writer.write_batch(_batches(_rows(["a", "b"], [1, 2])), batch_ctx)
+ await writer.finalize_run(ctx)
+
+ assert _read(dsn, table_name) == [(1, "a"), (2, "b")]
+ finally:
+ _drop(dsn, table_name, staging_table_name(ctx))
+
+ async def test_replaying_the_published_final_batch_keeps_the_earlier_batches(self, dsn, table_name) -> None:
+ # Without the publish stamp this replays as "write one batch into a fresh staging
+ # table, then swap it over the finished table", leaving only the final batch's rows.
+ # Reachable whenever the write marker is missing: Redis down, or a crash between the
+ # swap and the marker.
+ ctx = _ctx(table_name, "full_refresh")
+ writer = LocalPostgresWriter(ctx, dsn)
+ try:
+ await writer.write_batch(
+ _batches(_rows(["a", "b"], [1, 2])),
+ DestinationBatchContext(run=ctx, batch_index=0, is_final_batch=False),
+ )
+ final_ctx = DestinationBatchContext(run=ctx, batch_index=1, is_final_batch=True)
+ await writer.write_batch(_batches(_rows(["c"], [3])), final_ctx)
+ await writer.finalize_run(ctx)
+ assert _read(dsn, table_name) == [(1, "a"), (2, "b"), (3, "c")]
+
+ await writer.write_batch(_batches(_rows(["c"], [3])), final_ctx)
+ await writer.finalize_run(ctx)
+
+ assert _read(dsn, table_name) == [(1, "a"), (2, "b"), (3, "c")]
+ finally:
+ _drop(dsn, table_name, staging_table_name(ctx))
+
+ async def test_finalizing_twice_leaves_the_swapped_table_alone(self, dsn, table_name) -> None:
+ # The consumer re-claims a final batch whose outcome it could not confirm, so the swap
+ # has to survive being asked for again.
+ ctx = _ctx(table_name, "full_refresh")
+ writer = LocalPostgresWriter(ctx, dsn)
+ try:
+ await writer.write_batch(
+ _batches(_rows(["a"], [1])),
+ DestinationBatchContext(run=ctx, batch_index=0, is_final_batch=True),
+ )
+ await writer.finalize_run(ctx)
+ await writer.finalize_run(ctx)
+
+ assert _read(dsn, table_name) == [(1, "a")]
+ finally:
+ _drop(dsn, table_name, staging_table_name(ctx))
+
+ async def test_a_run_that_never_finishes_leaves_the_previous_data_in_place(self, dsn, table_name) -> None:
+ first = _ctx(table_name, "full_refresh")
+ first_writer = LocalPostgresWriter(first, dsn)
+ second = _ctx(table_name, "full_refresh")
+ second_writer = LocalPostgresWriter(second, dsn)
+ try:
+ await first_writer.write_batch(
+ _batches(_rows(["old"], [1])),
+ DestinationBatchContext(run=first, batch_index=0, is_final_batch=True),
+ )
+ await first_writer.finalize_run(first)
+
+ # A second run writes a batch and then dies before finalizing.
+ await second_writer.write_batch(
+ _batches(_rows(["new"], [2])),
+ DestinationBatchContext(run=second, batch_index=0, is_final_batch=False),
+ )
+ await second_writer.abort_run(second)
+
+ assert _read(dsn, table_name) == [(1, "old")]
+ finally:
+ _drop(dsn, table_name, staging_table_name(first), staging_table_name(second))
+
+
+class TestFullRefreshTableOwnership:
+ """`table_name` is derived from the source's resource name, which a custom-source
+ manifest controls. A full refresh must never take over a table it did not create just
+ because a resource happens to be named after it.
+ """
+
+ async def test_a_full_refresh_refuses_to_replace_a_table_it_did_not_create(self, dsn, table_name) -> None:
+ with psycopg.connect(dsn, autocommit=True) as conn:
+ conn.execute(f'CREATE TABLE public."{table_name}" (id BIGINT, name TEXT)')
+ conn.execute(f"INSERT INTO public.\"{table_name}\" VALUES (99, 'untouched')")
+
+ ctx = _ctx(table_name, "full_refresh")
+ writer = LocalPostgresWriter(ctx, dsn)
+ try:
+ await writer.write_batch(
+ _batches(_rows(["a"], [1])),
+ DestinationBatchContext(run=ctx, batch_index=0, is_final_batch=True),
+ )
+
+ with pytest.raises(UnrelatedTableExistsError):
+ await writer.finalize_run(ctx)
+
+ # The pre-existing table was never touched, and the staging table is still there
+ # for a retry to pick up once the name collision is resolved.
+ assert _read(dsn, table_name) == [(99, "untouched")]
+ finally:
+ _drop(dsn, table_name, staging_table_name(ctx))
+
+ async def test_a_full_refresh_refuses_to_reuse_an_existing_table_as_staging(self, dsn, table_name) -> None:
+ """Guards the staging table itself, not just the final swap target.
+
+ Before the ownership check on `write_batch`'s first batch existed, an identifier
+ collision (see `TestStagingTableNameTruncation`) or any other reason a table already
+ sat at the generated staging name would have this writer adopt it silently: evolve
+ its schema, delete rows matching this run's batch index, and stamp its own ownership
+ marker over whatever was there — all before `finalize_run` ever got a chance to check
+ anything.
+ """
+ ctx = _ctx(table_name, "full_refresh")
+ with psycopg.connect(dsn, autocommit=True) as conn:
+ conn.execute(f'CREATE TABLE public."{staging_table_name(ctx)}" (id BIGINT, name TEXT)')
+ conn.execute(f"INSERT INTO public.\"{staging_table_name(ctx)}\" VALUES (99, 'untouched')")
+
+ writer = LocalPostgresWriter(ctx, dsn)
+ try:
+ with pytest.raises(UnrelatedTableExistsError):
+ await writer.write_batch(
+ _batches(_rows(["a"], [1])),
+ DestinationBatchContext(run=ctx, batch_index=0, is_final_batch=True),
+ )
+
+ # Neither the pre-existing table's schema nor its rows were touched.
+ with psycopg.connect(dsn, autocommit=True) as conn:
+ rows = conn.execute(f'SELECT id, name FROM public."{staging_table_name(ctx)}" ORDER BY id').fetchall()
+ assert rows == [(99, "untouched")]
+ finally:
+ _drop(dsn, table_name, staging_table_name(ctx))
+
+ async def test_a_second_full_refresh_may_replace_a_table_the_first_one_created(self, dsn, table_name) -> None:
+ first = _ctx(table_name, "full_refresh")
+ first_writer = LocalPostgresWriter(first, dsn)
+ second = _ctx(table_name, "full_refresh")
+ second_writer = LocalPostgresWriter(second, dsn)
+ try:
+ await first_writer.write_batch(
+ _batches(_rows(["old"], [1])),
+ DestinationBatchContext(run=first, batch_index=0, is_final_batch=True),
+ )
+ await first_writer.finalize_run(first)
+
+ await second_writer.write_batch(
+ _batches(_rows(["new"], [2])),
+ DestinationBatchContext(run=second, batch_index=0, is_final_batch=True),
+ )
+ await second_writer.finalize_run(second)
+
+ assert _read(dsn, table_name) == [(2, "new")]
+ finally:
+ _drop(dsn, table_name, staging_table_name(first), staging_table_name(second))
+
+
+class TestIncremental:
+ async def test_batches_share_one_merge_stage_that_finalize_drops(self, dsn, table_name) -> None:
+ # A stage table per batch writes catalog rows a customer's server then has to vacuum,
+ # so the run keeps one and empties it between batches.
+ ctx = _ctx(table_name, "incremental", primary_keys=("id",))
+ writer = LocalPostgresWriter(ctx, dsn)
+ stage = merge_stage_name(table_name, ctx)
+ try:
+ await writer.write_batch(
+ _batches(_rows(["a"], [1])),
+ DestinationBatchContext(run=ctx, batch_index=0, is_final_batch=False),
+ )
+ assert _table_exists(dsn, stage)
+
+ await writer.write_batch(
+ _batches(_rows(["b"], [2])),
+ DestinationBatchContext(run=ctx, batch_index=1, is_final_batch=True),
+ )
+ # Emptied between batches, so it never accumulates the run's rows.
+ assert _row_count(dsn, stage) == 1
+ assert _read(dsn, table_name) == [(1, "a"), (2, "b")]
+
+ await writer.finalize_run(ctx)
+ assert not _table_exists(dsn, stage)
+ finally:
+ _drop(dsn, table_name, stage)
+
+ async def test_rows_are_merged_on_the_primary_key(self, dsn, table_name) -> None:
+ ctx = _ctx(table_name, "incremental", primary_keys=("id",))
+ writer = LocalPostgresWriter(ctx, dsn)
+ try:
+ await writer.write_batch(
+ _batches(_rows(["first", "second"], [1, 2])),
+ DestinationBatchContext(run=ctx, batch_index=0, is_final_batch=False),
+ )
+ await writer.write_batch(
+ _batches(_rows(["updated"], [1])),
+ DestinationBatchContext(run=ctx, batch_index=1, is_final_batch=True),
+ )
+ await writer.finalize_run(ctx)
+
+ assert _read(dsn, table_name) == [(1, "updated"), (2, "second")]
+ finally:
+ _drop(dsn, table_name)
+
+ async def test_reapplying_a_batch_is_harmless(self, dsn, table_name) -> None:
+ ctx = _ctx(table_name, "incremental", primary_keys=("id",))
+ writer = LocalPostgresWriter(ctx, dsn)
+ try:
+ batch_ctx = DestinationBatchContext(run=ctx, batch_index=0, is_final_batch=True)
+ await writer.write_batch(_batches(_rows(["a"], [1])), batch_ctx)
+ await writer.write_batch(_batches(_rows(["a"], [1])), batch_ctx)
+
+ assert _read(dsn, table_name) == [(1, "a")]
+ finally:
+ _drop(dsn, table_name)
+
+ async def test_a_new_source_column_is_added_rather_than_dropped(self, dsn, table_name) -> None:
+ ctx = _ctx(table_name, "incremental", primary_keys=("id",))
+ writer = LocalPostgresWriter(ctx, dsn)
+ try:
+ await writer.write_batch(
+ _batches(_rows(["a"], [1])),
+ DestinationBatchContext(run=ctx, batch_index=0, is_final_batch=False),
+ )
+ widened = pa.RecordBatch.from_pydict({"id": [2], "name": ["b"], "extra": ["kept"]})
+ await writer.write_batch(
+ _batches(widened),
+ DestinationBatchContext(run=ctx, batch_index=1, is_final_batch=True),
+ )
+
+ with psycopg.connect(dsn, autocommit=True) as conn:
+ rows = conn.execute(f'SELECT id, extra FROM public."{table_name}" ORDER BY id').fetchall()
+ assert rows == [(1, None), (2, "kept")]
+ finally:
+ _drop(dsn, table_name)
+
+ async def test_a_table_name_already_at_the_identifier_limit_still_merges_correctly(self, dsn) -> None:
+ """Regression test for the merge-stage aliasing bug: an incremental run's live table
+ name is never truncated by this writer (unlike a full refresh's staging name), so it
+ can already sit at Postgres's 63-byte limit on its own. Each batch's merge stage must
+ still get a name distinct from it, or `_merge_stage`'s `delete=True` drops the live
+ table out from under the run instead of just its own short-lived stage.
+ """
+ long_name = "t" * 70
+ actual_table = long_name.encode()[:63].decode()
+ ctx = _ctx(long_name, "incremental", primary_keys=("id",))
+ writer = LocalPostgresWriter(ctx, dsn)
+ try:
+ await writer.write_batch(
+ _batches(_rows(["first", "second"], [1, 2])),
+ DestinationBatchContext(run=ctx, batch_index=0, is_final_batch=False),
+ )
+ await writer.write_batch(
+ _batches(_rows(["updated"], [1])),
+ DestinationBatchContext(run=ctx, batch_index=1, is_final_batch=True),
+ )
+
+ assert _read(dsn, actual_table) == [(1, "updated"), (2, "second")]
+ finally:
+ _drop(dsn, actual_table)
+
+
+class TestIncrementalTableOwnership:
+ """An incremental run writes straight into the live table, named after the source's
+ resource name. It must refuse a table it did not create, the same way a full refresh
+ refuses to replace one, rather than evolving its schema and merging rows into it.
+ """
+
+ async def test_an_incremental_run_refuses_to_write_into_a_table_it_did_not_create(self, dsn, table_name) -> None:
+ with psycopg.connect(dsn, autocommit=True) as conn:
+ conn.execute(f'CREATE TABLE public."{table_name}" (id BIGINT, name TEXT)')
+ conn.execute(f"INSERT INTO public.\"{table_name}\" VALUES (99, 'untouched')")
+
+ ctx = _ctx(table_name, "incremental", primary_keys=("id",))
+ writer = LocalPostgresWriter(ctx, dsn)
+ try:
+ with pytest.raises(UnrelatedTableExistsError):
+ await writer.write_batch(
+ _batches(_rows(["a"], [1])),
+ DestinationBatchContext(run=ctx, batch_index=0, is_final_batch=True),
+ )
+
+ # Neither the table's schema nor its rows were touched.
+ assert _read(dsn, table_name) == [(99, "untouched")]
+ finally:
+ _drop(dsn, table_name)
+
+ async def test_a_later_incremental_run_may_write_into_a_table_this_writer_created(self, dsn, table_name) -> None:
+ first = _ctx(table_name, "incremental", primary_keys=("id",))
+ first_writer = LocalPostgresWriter(first, dsn)
+ second = _ctx(table_name, "incremental", primary_keys=("id",))
+ second_writer = LocalPostgresWriter(second, dsn)
+ try:
+ await first_writer.write_batch(
+ _batches(_rows(["a"], [1])),
+ DestinationBatchContext(run=first, batch_index=0, is_final_batch=True),
+ )
+ await second_writer.write_batch(
+ _batches(_rows(["b"], [2])),
+ DestinationBatchContext(run=second, batch_index=0, is_final_batch=True),
+ )
+
+ assert _read(dsn, table_name) == [(1, "a"), (2, "b")]
+ finally:
+ _drop(dsn, table_name)
+
+
+class TestCrossSchemaTableOwnership:
+ """`table_name` is derived from the editable resource name, so two different schemas can
+ choose the same target name on the same destination. Ownership must be scoped to the
+ schema that created the table, not just "some posthog warehouse sync created this", or one
+ schema's resource could pass as the owner of another schema's table.
+ """
+
+ async def test_a_full_refresh_refuses_to_replace_a_table_a_different_schema_created(self, dsn, table_name) -> None:
+ first = _ctx(table_name, "full_refresh", schema_id="schema-a")
+ first_writer = LocalPostgresWriter(first, dsn)
+ second = _ctx(table_name, "full_refresh", schema_id="schema-b")
+ second_writer = LocalPostgresWriter(second, dsn)
+ try:
+ await first_writer.write_batch(
+ _batches(_rows(["a"], [1])),
+ DestinationBatchContext(run=first, batch_index=0, is_final_batch=True),
+ )
+ await first_writer.finalize_run(first)
+
+ await second_writer.write_batch(
+ _batches(_rows(["b"], [2])),
+ DestinationBatchContext(run=second, batch_index=0, is_final_batch=True),
+ )
+
+ with pytest.raises(UnrelatedTableExistsError):
+ await second_writer.finalize_run(second)
+
+ # The first schema's table is exactly as that schema's run left it.
+ assert _read(dsn, table_name) == [(1, "a")]
+ finally:
+ _drop(dsn, table_name, staging_table_name(first), staging_table_name(second))
+
+ async def test_an_incremental_run_refuses_to_write_into_a_table_a_different_schema_created(
+ self, dsn, table_name
+ ) -> None:
+ first = _ctx(table_name, "incremental", primary_keys=("id",), schema_id="schema-a")
+ first_writer = LocalPostgresWriter(first, dsn)
+ second = _ctx(table_name, "incremental", primary_keys=("id",), schema_id="schema-b")
+ second_writer = LocalPostgresWriter(second, dsn)
+ try:
+ await first_writer.write_batch(
+ _batches(_rows(["a"], [1])),
+ DestinationBatchContext(run=first, batch_index=0, is_final_batch=True),
+ )
+
+ with pytest.raises(UnrelatedTableExistsError):
+ await second_writer.write_batch(
+ _batches(_rows(["b"], [2])),
+ DestinationBatchContext(run=second, batch_index=0, is_final_batch=True),
+ )
+
+ assert _read(dsn, table_name) == [(1, "a")]
+ finally:
+ _drop(dsn, table_name)
+
+
+class TestValueFidelity:
+ async def test_values_holding_csv_control_characters_survive_the_copy(self, dsn, table_name) -> None:
+ # The bulk load is a COPY in CSV format, where a tab ends a field and a newline ends a
+ # row unless the value is quoted.
+ awkward = ["a\tb", "line\nbreak", 'say "hi"', "back\\slash", "", " padded "]
+ ctx = _ctx(table_name, "full_refresh")
+ writer = LocalPostgresWriter(ctx, dsn)
+ try:
+ batch = pa.RecordBatch.from_pydict(
+ {"id": list(range(len(awkward) + 1)), "name": [*awkward, None]},
+ )
+ await writer.write_batch(
+ _batches(batch),
+ DestinationBatchContext(run=ctx, batch_index=0, is_final_batch=True),
+ )
+ await writer.finalize_run(ctx)
+
+ assert _read(dsn, table_name) == [*enumerate(awkward), (len(awkward), None)]
+ finally:
+ _drop(dsn, table_name, staging_table_name(ctx))
+
+ async def test_nested_values_land_in_their_json_columns(self, dsn, table_name) -> None:
+ # Lists, structs and maps all map onto JSONB, which rejects both a Postgres array
+ # literal and a Python repr.
+ ctx = _ctx(table_name, "full_refresh")
+ writer = LocalPostgresWriter(ctx, dsn)
+ try:
+ batch = pa.RecordBatch.from_arrays(
+ [
+ pa.array([1, 2], type=pa.int64()),
+ pa.array([["a", "b"], None], type=pa.list_(pa.string())),
+ pa.array([{"k": "v", "n": 3}, None], type=pa.struct([("k", pa.string()), ("n", pa.int64())])),
+ pa.array([[("x", 1)], None], type=pa.map_(pa.string(), pa.int64())),
+ ],
+ names=["id", "tags", "meta", "labels"],
+ )
+ await writer.write_batch(
+ _batches(batch),
+ DestinationBatchContext(run=ctx, batch_index=0, is_final_batch=True),
+ )
+ await writer.finalize_run(ctx)
+
+ with psycopg.connect(dsn, autocommit=True) as conn:
+ rows = conn.execute(f'SELECT id, tags, meta, labels FROM public."{table_name}" ORDER BY id').fetchall()
+
+ assert rows == [
+ (1, ["a", "b"], {"k": "v", "n": 3}, {"x": 1}),
+ (2, None, None, None),
+ ]
+ finally:
+ _drop(dsn, table_name, staging_table_name(ctx))
+
+ async def test_a_nested_value_holding_a_delimiter_still_parses_as_json(self, dsn, table_name) -> None:
+ # The JSON text goes through the same CSV writer, so a tab or a quote inside a struct
+ # has to be quoted on the way out and parsed as JSON on the way in.
+ ctx = _ctx(table_name, "full_refresh")
+ writer = LocalPostgresWriter(ctx, dsn)
+ try:
+ batch = pa.RecordBatch.from_arrays(
+ [
+ pa.array([1], type=pa.int64()),
+ pa.array(
+ [{"note": 'has\ta tab, a "quote" and a\nnewline'}],
+ type=pa.struct([("note", pa.string())]),
+ ),
+ ],
+ names=["id", "meta"],
+ )
+ await writer.write_batch(
+ _batches(batch),
+ DestinationBatchContext(run=ctx, batch_index=0, is_final_batch=True),
+ )
+ await writer.finalize_run(ctx)
+
+ with psycopg.connect(dsn, autocommit=True) as conn:
+ rows = conn.execute(f'SELECT meta FROM public."{table_name}"').fetchall()
+
+ assert rows == [({"note": 'has\ta tab, a "quote" and a\nnewline'},)]
+ finally:
+ _drop(dsn, table_name, staging_table_name(ctx))
+
+
+class TestMergeConstraints:
+ """The merge target's unique constraint, which `ON CONFLICT` needs to exist."""
+
+ @staticmethod
+ def _unique_indexes(dsn: str, table: str) -> list[tuple[str, list[str]]]:
+ with psycopg.connect(dsn, autocommit=True) as conn:
+ rows = conn.execute(
+ """
+ SELECT ic.relname::text, array_agg(a.attname::text ORDER BY a.attname)
+ FROM pg_index i
+ JOIN pg_class c ON c.oid = i.indrelid
+ JOIN pg_class ic ON ic.oid = i.indexrelid
+ JOIN pg_attribute a ON a.attrelid = c.oid AND a.attnum = ANY (i.indkey)
+ WHERE i.indisunique AND c.relname = %s
+ GROUP BY ic.relname
+ """,
+ (table,),
+ ).fetchall()
+ return [(name, cols) for name, cols in rows]
+
+ async def test_the_merge_target_is_created_with_its_primary_key(self, dsn, table_name) -> None:
+ # Declared at creation by acreate_table rather than added as a separate index, so the
+ # table carries exactly one unique constraint over the merge keys.
+ ctx = _ctx(table_name, "incremental", primary_keys=("id",))
+ writer = LocalPostgresWriter(ctx, dsn)
+ try:
+ await writer.write_batch(
+ _batches(_rows(["a"], [1])),
+ DestinationBatchContext(run=ctx, batch_index=0, is_final_batch=True),
+ )
+
+ indexes = self._unique_indexes(dsn, table_name)
+ assert [cols for _, cols in indexes] == [["id"]], indexes
+ finally:
+ _drop(dsn, table_name)
+
+ async def test_a_table_the_customer_already_had_gains_one(self, dsn, table_name) -> None:
+ # This writer created the table on an earlier run, before unique index enforcement
+ # existed, so it carries the ownership comment but no key. Nothing declared a key on
+ # this table, so the writer has to add one before it can merge into it.
+ with psycopg.connect(dsn, autocommit=True) as conn:
+ conn.execute(f'CREATE TABLE "{table_name}" (id BIGINT, name TEXT)')
+ conn.execute(f"COMMENT ON TABLE \"{table_name}\" IS '{_owned_marker('schema')}'")
+
+ ctx = _ctx(table_name, "incremental", primary_keys=("id",))
+ writer = LocalPostgresWriter(ctx, dsn)
+ try:
+ await writer.write_batch(
+ _batches(_rows(["a"], [1])),
+ DestinationBatchContext(run=ctx, batch_index=0, is_final_batch=True),
+ )
+
+ assert [cols for _, cols in self._unique_indexes(dsn, table_name)] == [["id"]]
+ assert _read(dsn, table_name) == [(1, "a")]
+ finally:
+ _drop(dsn, table_name)
+
+ async def test_merging_many_batches_does_not_accumulate_indexes(self, dsn, table_name) -> None:
+ # The index step runs per merged batch. It used to CREATE ... IF NOT EXISTS, which
+ # matches on name, so a declared primary key would sit beside a duplicate of itself.
+ ctx = _ctx(table_name, "incremental", primary_keys=("id",))
+ writer = LocalPostgresWriter(ctx, dsn)
+ try:
+ for index in range(3):
+ await writer.write_batch(
+ _batches(_rows(["a"], [index])),
+ DestinationBatchContext(run=ctx, batch_index=index, is_final_batch=index == 2),
+ )
+
+ assert len(self._unique_indexes(dsn, table_name)) == 1
+ finally:
+ _drop(dsn, table_name)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/writers/__init__.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/writers/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/writers/postgres.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/writers/postgres.py
new file mode 100644
index 000000000000..485d9ac2ec90
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/writers/postgres.py
@@ -0,0 +1,646 @@
+"""Delivering a run's batches to a Postgres database.
+
+The connection, DDL, introspection and bulk load all come from batch exports'
+`PostgreSQLClient`, which is the same client its Postgres destination runs on. This writer adds
+only what a warehouse sync needs and a batch export does not:
+
+- A full refresh writes into a per-run staging table and swaps it into place on the final
+ batch, so the destination table holds the previous run's data right up to the moment the
+ new one is complete. A run that dies half way leaves the live table untouched. A batch
+ export commits per interval and has no run that spans many batches.
+- An incremental run merges each batch into the destination table on the schema's primary
+ keys. `amerge_mutable_tables` updates only where a column increases, which suits person
+ tables and not a source table with no monotonic column. (Redshift's `amerge_tables` puts no
+ such condition on a merge, so the Redshift writer does use it.)
+- Column types come from `sql_types`, not `get_postgres_fields_from_record_schema`. That
+ mapper raises on any type outside the event and person shapes, and a source table may hold
+ dates, decimals, binaries or structs.
+- Schema evolution is additive. Batch exports filter incoming data down to the columns the
+ destination already has, which silently drops new fields, and a synced table is supposed to
+ mirror its source.
+
+Every write is idempotent per batch index, because the consumer re-claims any batch whose
+outcome it could not confirm.
+"""
+
+from __future__ import annotations
+
+import io
+import csv
+import json
+from collections.abc import AsyncIterator
+from contextlib import asynccontextmanager
+from typing import Any, ClassVar
+
+import psycopg
+import pyarrow as pa
+from psycopg import sql
+
+from posthog.models.integration import Integration, PostgreSQLIntegration
+
+from products.batch_exports.backend.temporal.destinations.postgres_batch_export import (
+ Fields,
+ PostgreSQLClient,
+ PostgreSQLIntegrationNotFoundError,
+ run_in_retryable_transaction,
+)
+from products.batch_exports.backend.temporal.pipeline.transformer import CSVStreamTransformer
+from products.warehouse_sources.backend.temporal.data_imports.destinations.contracts import (
+ BatchWriteOutcome,
+ DestinationBatchContext,
+ DestinationRunContext,
+)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.destinations_load.writers.sql_types import (
+ is_nested_type,
+ postgres_type_for,
+)
+
+# Marks which batch of a run wrote a staged row, so re-applying a batch can delete exactly
+# what its previous attempt wrote instead of the whole staging table.
+BATCH_INDEX_COLUMN = "_ph_batch_index"
+
+# Proof this writer created a table, so a sync never drops or merges into one the customer
+# already had. `table_name` comes from the source's resource name, which a custom-source
+# manifest controls, so without it any table sharing that name is fair game.
+#
+# Stored as a Postgres comment because those follow the table's OID, surviving the rename in
+# `finalize_run`. Scoped by schema id because `table_name` collides across sources on purpose
+# and ownership must not.
+_OWNERSHIP_COMMENT = "posthog-warehouse-sync-owned"
+
+
+def _owned_marker(schema_id: str) -> str:
+ """Ownership marker scoped to the schema whose sync created the table."""
+ return f"{_OWNERSHIP_COMMENT}:{schema_id}"
+
+
+def _published_comment(schema_id: str, run_uuid: str) -> str:
+ """Ownership marker plus the run that last published, so a replay can recognize itself."""
+ return f"{_owned_marker(schema_id)}:{run_uuid}"
+
+
+class UnrelatedTableExistsError(RuntimeError):
+ """A sync would have replaced or mutated a table this writer never created."""
+
+
+# Postgres truncates identifiers past this, dropping the end — which is where our suffixes go.
+# A long `table_name` would therefore collapse its staging table, merge stage and index back
+# onto the base name. Truncate the base ourselves so the suffix always survives.
+_MAX_PG_IDENTIFIER_BYTES = 63
+
+
+def _scoped_identifier(base: str, suffix: str) -> str:
+ """Append `suffix` to `base`, truncating `base` first so `suffix` always survives
+ Postgres's own 63-byte identifier truncation."""
+ trimmed = base.encode()[: _MAX_PG_IDENTIFIER_BYTES - len(suffix)].decode(errors="ignore")
+ return f"{trimmed}{suffix}"
+
+
+def staging_table_name(ctx: DestinationRunContext) -> str:
+ # Run-scoped, so two runs of the same table never share a staging table.
+ return _scoped_identifier(ctx.table_name, f"__ph_stage_{ctx.run_uuid.replace('-', '')[:12]}")
+
+
+def merge_stage_name(target: str, ctx: DestinationRunContext) -> str:
+ # `target` is the live table on an incremental run, so it can already be at the identifier
+ # limit. Reserve room for the suffix or the stage name truncates onto the live table, and
+ # dropping the stage would drop it.
+ return _scoped_identifier(target, f"__ph_merge_{ctx.run_uuid.replace('-', '')[:8]}")
+
+
+def _to_json_text(value: Any, *, from_map: bool) -> str | None:
+ if value is None:
+ return None
+ if from_map:
+ # A map column reads back as key/value pairs rather than as a mapping.
+ value = dict(value)
+ # Dates, decimals and binaries can sit inside a struct, and none of them are JSON types.
+ return json.dumps(value, default=str)
+
+
+def json_encode_nested_columns(batch: pa.RecordBatch) -> pa.RecordBatch:
+ """Replace every nested column with its JSON text.
+
+ `sql_types` maps a list, struct or map onto JSONB, but the CSV transformer renders a list
+ as a Postgres array literal and a dict as a Python repr, and JSONB accepts neither.
+ """
+ for index, field in enumerate(batch.schema):
+ if not is_nested_type(field.type):
+ continue
+
+ encoded = [
+ _to_json_text(value, from_map=pa.types.is_map(field.type)) for value in batch.column(index).to_pylist()
+ ]
+ batch = batch.set_column(index, pa.field(field.name, pa.string()), pa.array(encoded, type=pa.string()))
+
+ return batch
+
+
+class PostgresDestinationWriter:
+ """Writes a run's batches into a Postgres table."""
+
+ holds_sync_lock: ClassVar[bool] = False
+ runs_post_load: ClassVar[bool] = False
+
+ # The kind of integration a destination of this type is backed by. Loading any other kind
+ # would hand this writer's client the credentials of a different service.
+ integration_kind: ClassVar[str] = PostgreSQLIntegration.integration_kind
+
+ def __init__(self, ctx: DestinationRunContext) -> None:
+ self._ctx = ctx
+ self._schema = (ctx.config or {}).get("schema") or "public"
+ self._database = (ctx.config or {}).get("database") or "postgres"
+
+ # --- connection -------------------------------------------------------------------
+
+ def _client_from_integration(self, integration: Integration) -> PostgreSQLClient:
+ # `from_inputs` accepts anything exposing credentials/authority/tls, which the
+ # integration wrapper does, so the batch export path and this one resolve credentials
+ # identically.
+ return PostgreSQLClient.from_inputs(PostgreSQLIntegration(integration), database=self._database)
+
+ async def _load_integration(self, integration_id: int) -> Integration:
+ try:
+ return await Integration.objects.aget(
+ id=integration_id, team_id=self._ctx.team_id, kind=self.integration_kind
+ )
+ except Integration.DoesNotExist as err:
+ # The same error batch exports raises, which its destinations never retry: a
+ # deleted or re-kinded integration cannot be recovered by trying again.
+ raise PostgreSQLIntegrationNotFoundError(
+ f"'{self.integration_kind}' integration with id '{integration_id}' not found"
+ ) from err
+
+ async def _make_client(self) -> PostgreSQLClient:
+ if self._ctx.integration_id is None:
+ raise ValueError(f"Destination {self._ctx.destination_name} has no integration to connect with")
+
+ integration = await self._load_integration(self._ctx.integration_id)
+ return self._client_from_integration(integration)
+
+ @asynccontextmanager
+ async def _client(self) -> AsyncIterator[PostgreSQLClient]:
+ client = await self._make_client()
+ # `connect()` resolves and dials the integration's hostname with no connection-time
+ # address validation or pinning, same as batch exports' own Postgres destination on
+ # this same client. An editor-controlled hostname could DNS-rebind to a private address
+ # between resolution and connect; closing that needs pinning inside `PostgreSQLClient`
+ # itself (posthog#86986 review discussion), which this product can't reach into, so
+ # every caller of this shared client is fixed together rather than patched here alone.
+ async with client.connect():
+ yield client
+
+ @asynccontextmanager
+ async def _write_cursor(self, client: PostgreSQLClient) -> AsyncIterator[psycopg.AsyncCursor]:
+ """A cursor in a transaction of its own that is declared read-write.
+
+ Every write path in batch exports declares this, because a cluster running with
+ `default_transaction_read_only = on` rejects the statement otherwise. Postgres only
+ accepts it as the first statement of a transaction, so each write gets its own.
+ """
+ async with client.connection.transaction():
+ async with client.connection.cursor() as cursor:
+ await cursor.execute("SET TRANSACTION READ WRITE")
+ yield cursor
+
+ # --- dialect seams ------------------------------------------------------------------
+ # Overridden by the SQL destinations that share this writer's shape but not its types.
+
+ @property
+ def _batch_index_column(self) -> str:
+ return BATCH_INDEX_COLUMN
+
+ def _column_type(self, arrow_type: pa.DataType) -> str:
+ return postgres_type_for(arrow_type)
+
+ def _fields_for(self, schema: pa.Schema, *, with_batch_index: bool) -> Fields:
+ fields: list[tuple[str, str]] = [(field.name, self._column_type(field.type)) for field in schema]
+ if with_batch_index:
+ fields.append((self._batch_index_column, "INTEGER"))
+ return fields # ty: ignore[invalid-return-type]
+
+ # --- schema -----------------------------------------------------------------------
+
+ async def _ensure_table(
+ self,
+ client: PostgreSQLClient,
+ table: str,
+ schema: pa.Schema,
+ *,
+ with_batch_index: bool,
+ primary_keys: list[str] | None = None,
+ ) -> None:
+ async with self._write_cursor(client) as cursor:
+ await cursor.execute(sql.SQL("CREATE SCHEMA IF NOT EXISTS {}").format(sql.Identifier(self._schema)))
+
+ fields = self._fields_for(schema, with_batch_index=with_batch_index)
+ # Declared at creation rather than added later, so the merge target carries its own
+ # constraint. `_ensure_unique_index` still covers a table the customer already had,
+ # which this never touches.
+ key = [(name, type_name) for name, type_name in fields if name in set(primary_keys or ())]
+
+ await client.acreate_table(
+ self._schema,
+ table,
+ fields,
+ exists_ok=True,
+ primary_key=key or None,
+ )
+
+ async def _evolve_table(self, client: PostgreSQLClient, table: str, schema: pa.Schema) -> None:
+ """Add columns the source has grown since the destination table was created."""
+ existing = set(await client.aget_table_columns(self._schema, table))
+
+ for field in schema:
+ if field.name in existing:
+ continue
+ async with self._write_cursor(client) as cursor:
+ await cursor.execute(
+ sql.SQL("ALTER TABLE {}.{} ADD COLUMN IF NOT EXISTS {} {}").format(
+ sql.Identifier(self._schema),
+ sql.Identifier(table),
+ sql.Identifier(field.name),
+ sql.SQL(self._column_type(field.type)),
+ )
+ )
+
+ # --- writer protocol ----------------------------------------------------------------
+
+ async def prepare_run(self, ctx: DestinationRunContext) -> None:
+ # Tables are created from the first batch's schema, once it is known.
+ return None
+
+ async def write_batch(
+ self, batches: AsyncIterator[pa.RecordBatch], ctx: DestinationBatchContext
+ ) -> BatchWriteOutcome:
+ run = ctx.run
+ full_refresh = run.is_full_refresh
+ target = staging_table_name(run) if full_refresh else run.table_name
+
+ rows_written = 0
+
+ async with self._client() as client:
+ if full_refresh and await self._already_published(client, run):
+ # This run's staging table is gone and the live table carries this run's
+ # publish stamp, so the run finished. Re-creating a staging table from this
+ # one batch and swapping it in would replace the whole table with it.
+ return BatchWriteOutcome(rows_written=0)
+
+ first = True
+ async for batch in batches:
+ if first:
+ # An incremental run writes straight into the live table, and a full
+ # refresh writes into what it treats as *its own* staging table — either
+ # way, a table that predates this sync and merely happens to share the
+ # generated name must be refused up front, before its schema is evolved or
+ # a row in it is touched. Reusing an unowned table as staging would mutate
+ # or delete unrelated data and, on the final batch, replace its ownership
+ # marker and swap it in under `finalize_run`'s nose. A full refresh's own
+ # table gets one further check at swap time, once the new data is known to
+ # be complete.
+ table_existed = await self._table_exists(client, target)
+ if table_existed and not await self._is_owned(client, target, run.schema_id):
+ raise UnrelatedTableExistsError(
+ f'"{self._schema}"."{target}" already exists and was not created by this sync; '
+ + (
+ "refusing to reuse it as a staging table."
+ if full_refresh
+ else "refusing to merge an incremental run's rows into it."
+ )
+ )
+
+ await self._ensure_table(
+ client,
+ target,
+ batch.schema,
+ with_batch_index=full_refresh,
+ primary_keys=list(run.primary_keys) if run.is_incremental and not full_refresh else None,
+ )
+ await self._evolve_table(client, target, batch.schema)
+ if full_refresh:
+ # This batch may be a re-apply after a crash, so clear whatever its
+ # previous attempt wrote before writing it again.
+ await self._delete_batch_rows(client, target, ctx.batch_index)
+ # Marked on the staging table, not the live one: the comment survives
+ # the rename in `finalize_run`, which is where it gets checked.
+ await self._mark_owned(client, target, run.schema_id)
+ elif not table_existed:
+ # A table this writer just created for an incremental run never gets
+ # renamed, so mark it in place rather than at swap time.
+ await self._mark_owned(client, target, run.schema_id)
+ first = False
+
+ rows_written += await self._write_record_batch(client, target, batch, ctx, full_refresh=full_refresh)
+
+ return BatchWriteOutcome(rows_written=rows_written)
+
+ async def _delete_batch_rows(self, client: PostgreSQLClient, target: str, batch_index: int) -> None:
+ async with self._write_cursor(client) as cursor:
+ await cursor.execute(
+ sql.SQL("DELETE FROM {}.{} WHERE {} = %s").format(
+ sql.Identifier(self._schema),
+ sql.Identifier(target),
+ sql.Identifier(self._batch_index_column),
+ ),
+ (batch_index,),
+ )
+
+ def _tsv_buffer(self, batch: pa.RecordBatch, column_names: list[str]) -> io.BytesIO:
+ """Render a record batch as TSV, using the same transformer the batch export uses.
+
+ The dialect has to be the one `copy_tsv_to_postgres` names in its COPY statement,
+ which is CSV with a tab delimiter. Postgres CSV has no backslash escape, so a value
+ holding a tab, a newline or a double quote only survives if the writer quotes it.
+ """
+ transformer = CSVStreamTransformer(
+ field_names=column_names,
+ delimiter="\t",
+ quote_char='"',
+ escape_char=None,
+ line_terminator="\n",
+ quoting=csv.QUOTE_STRINGS,
+ include_inserted_at=False,
+ )
+ return io.BytesIO(transformer.write_record_batch(json_encode_nested_columns(batch)))
+
+ async def _load_batch(
+ self, client: PostgreSQLClient, table: str, batch: pa.RecordBatch, column_names: list[str]
+ ) -> None:
+ """Put one record batch into a table, whatever the dialect's bulk load is."""
+ await client.copy_tsv_to_postgres(self._tsv_buffer(batch, column_names), self._schema, table, column_names)
+
+ async def _write_record_batch(
+ self,
+ client: PostgreSQLClient,
+ target: str,
+ batch: pa.RecordBatch,
+ ctx: DestinationBatchContext,
+ *,
+ full_refresh: bool,
+ ) -> int:
+ run = ctx.run
+ if batch.num_rows == 0:
+ return 0
+
+ column_names = list(batch.schema.names)
+
+ if full_refresh:
+ stamped = batch.append_column(
+ self._batch_index_column,
+ pa.array([ctx.batch_index] * batch.num_rows, type=pa.int32()),
+ )
+ await self._load_batch(client, target, stamped, [*column_names, self._batch_index_column])
+ return batch.num_rows
+
+ if run.is_incremental and run.primary_keys:
+ return await self._merge_batch(client, target, batch, column_names)
+
+ await self._load_batch(client, target, batch, column_names)
+ return batch.num_rows
+
+ async def _merge_batch(
+ self, client: PostgreSQLClient, target: str, batch: pa.RecordBatch, column_names: list[str]
+ ) -> int:
+ """Upsert a batch on the schema's primary keys, through a stage table."""
+ run = self._ctx
+ stage = merge_stage_name(target, run)
+
+ await self._ensure_merge_stage(client, stage, batch.schema)
+ await self._load_batch(client, stage, batch, column_names)
+ await self._upsert_from_stage(client, target, stage, column_names, list(run.primary_keys))
+
+ return batch.num_rows
+
+ async def _ensure_merge_stage(self, client: PostgreSQLClient, stage: str, schema: pa.Schema) -> None:
+ """Ready the run's stage table to receive one batch.
+
+ Created once per run and emptied between batches rather than created and dropped per
+ batch. A table per batch is not free on someone else's server: each one writes catalog
+ rows that later have to be vacuumed, and vacuuming catalog tables can need locks.
+ `abort_run` and `finalize_run` drop it.
+ """
+ await client.acreate_table(
+ self._schema, stage, self._fields_for(schema, with_batch_index=False), exists_ok=True
+ )
+ # The stage outlives the batch that created it, so a column the source grew mid-run has
+ # to reach it too, or the COPY names a column the stage does not have.
+ await self._evolve_table(client, stage, schema)
+ async with self._write_cursor(client) as cursor:
+ # Not DELETE: the stage is rewritten wholesale every batch, so truncating skips the
+ # dead rows a delete would leave for autovacuum.
+ await cursor.execute(
+ sql.SQL("TRUNCATE TABLE {}.{}").format(sql.Identifier(self._schema), sql.Identifier(stage))
+ )
+
+ async def _upsert_from_stage(
+ self,
+ client: PostgreSQLClient,
+ target: str,
+ stage: str,
+ column_names: list[str],
+ primary_keys: list[str],
+ ) -> None:
+ await self._ensure_unique_index(client, target, primary_keys)
+
+ updates = [c for c in column_names if c not in primary_keys]
+ set_clause = sql.SQL(", ").join(
+ sql.SQL("{col} = EXCLUDED.{col}").format(col=sql.Identifier(c)) for c in updates
+ )
+ columns = sql.SQL(", ").join(sql.Identifier(c) for c in column_names)
+ conflict = sql.SQL(", ").join(sql.Identifier(c) for c in primary_keys)
+
+ statement = sql.SQL(
+ "INSERT INTO {schema}.{target} ({columns}) SELECT {columns} FROM {schema}.{stage} "
+ "ON CONFLICT ({conflict}) DO {action}"
+ ).format(
+ schema=sql.Identifier(self._schema),
+ target=sql.Identifier(target),
+ stage=sql.Identifier(stage),
+ columns=columns,
+ conflict=conflict,
+ action=sql.SQL("UPDATE SET {}").format(set_clause) if updates else sql.SQL("NOTHING"),
+ )
+
+ async def upsert() -> None:
+ async with client.connection.cursor() as cursor:
+ await cursor.execute("SET TRANSACTION READ WRITE")
+ await cursor.execute(statement)
+
+ # A concurrent `INSERT ... ON CONFLICT` is the shape that raises SerializationFailure,
+ # and this is the one statement here that two runs of different schemas can contend on.
+ await run_in_retryable_transaction(client.connection, upsert)
+
+ async def _ensure_unique_index(self, client: PostgreSQLClient, target: str, primary_keys: list[str]) -> None:
+ """`ON CONFLICT` needs a unique constraint on the merge keys.
+
+ A table this writer created already carries one, declared as its primary key. This
+ covers the other case: a table the customer already had. `IF NOT EXISTS` matches on
+ the index name, not on the columns, so without the check below a table with a primary
+ key would carry a second unique index over the same columns and pay for it on every
+ write.
+ """
+ if await self._has_unique_index_on(client, target, primary_keys):
+ return
+
+ async with self._write_cursor(client) as cursor:
+ await cursor.execute(
+ sql.SQL("CREATE UNIQUE INDEX IF NOT EXISTS {} ON {}.{} ({})").format(
+ # Same truncation hazard as the merge stage above: an untruncated suffix
+ # on a `target` already at the byte limit collapses onto `target`'s own
+ # truncated name, and `IF NOT EXISTS` then silently skips creating the
+ # index at all because a relation by that name (the table itself) exists.
+ sql.Identifier(_scoped_identifier(target, "__ph_pk")),
+ sql.Identifier(self._schema),
+ sql.Identifier(target),
+ sql.SQL(", ").join(sql.Identifier(c) for c in primary_keys),
+ )
+ )
+
+ async def _has_unique_index_on(self, client: PostgreSQLClient, target: str, columns: list[str]) -> bool:
+ """Whether some unique index already covers exactly these columns, in any order."""
+ async with client.connection.cursor() as cursor:
+ await cursor.execute(
+ """
+ SELECT array_agg(a.attname::text ORDER BY a.attname)
+ FROM pg_index i
+ JOIN pg_class c ON c.oid = i.indrelid
+ JOIN pg_namespace n ON n.oid = c.relnamespace
+ JOIN pg_attribute a ON a.attrelid = c.oid AND a.attnum = ANY (i.indkey)
+ WHERE i.indisunique AND c.relname = %(table)s AND n.nspname = %(schema)s
+ GROUP BY i.indexrelid
+ """,
+ {"table": target, "schema": self._schema},
+ )
+ wanted = sorted(columns)
+ return any(sorted(row[0] or []) == wanted for row in await cursor.fetchall())
+
+ async def _mark_owned(self, client: PostgreSQLClient, table: str, schema_id: str) -> None:
+ async with self._write_cursor(client) as cursor:
+ # `COMMENT ON TABLE ... IS <text>` is a utility statement: Postgres's grammar
+ # only accepts a string literal there, not a bind parameter, so this can't go
+ # through the usual `%s` placeholder (it fails with a syntax error at `$1`).
+ # `schema_id` is the schema's immutable id, never user-editable input, so inlining
+ # it as a literal is safe the same way the fixed constant was.
+ await cursor.execute(
+ sql.SQL("COMMENT ON TABLE {}.{} IS {}").format(
+ sql.Identifier(self._schema), sql.Identifier(table), sql.Literal(_owned_marker(schema_id))
+ )
+ )
+
+ async def _is_owned(self, client: PostgreSQLClient, table: str, schema_id: str) -> bool:
+ # Not a plain `startswith`: schema ids are arbitrary strings, and one could be a
+ # character-prefix of another ("abc" of "abc123"), which would let a table another
+ # schema owns pass as owned here. Split on the marker's own `:` separators instead so
+ # the owning schema id is compared for exact equality; a published table carries the
+ # run uuid as a further segment after it, which this ignores.
+ comment = await self._table_comment(client, table)
+ if comment is None:
+ return False
+ marker, sep, rest = comment.partition(":")
+ if marker != _OWNERSHIP_COMMENT or not sep:
+ return False
+ owner = rest.split(":", 1)[0]
+ return owner == schema_id
+
+ async def _table_comment(self, client: PostgreSQLClient, table: str) -> str | None:
+ async with client.connection.cursor() as cursor:
+ await cursor.execute(
+ """
+ SELECT d.description
+ FROM pg_catalog.pg_description d
+ JOIN pg_catalog.pg_class c ON c.oid = d.objoid AND d.objsubid = 0
+ JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
+ WHERE c.relname = %(table)s AND n.nspname = %(schema)s
+ """,
+ {"table": table, "schema": self._schema},
+ )
+ row = await cursor.fetchone()
+ return row[0] if row else None
+
+ async def _already_published(self, client: PostgreSQLClient, ctx: DestinationRunContext) -> bool:
+ """Whether this run already swapped its staging table into place."""
+ if await self._table_exists(client, staging_table_name(ctx)):
+ return False
+ if not await self._table_exists(client, ctx.table_name):
+ return False
+ return await self._table_comment(client, ctx.table_name) == _published_comment(ctx.schema_id, ctx.run_uuid)
+
+ async def finalize_run(self, ctx: DestinationRunContext) -> None:
+ """Publish a full refresh by swapping the staging table into place."""
+ if not ctx.is_full_refresh:
+ # An incremental run publishes as it goes, but its merge stage lives for the whole
+ # run, so this is the point where it stops being needed.
+ async with self._client() as client:
+ await client.adelete_table(self._schema, merge_stage_name(ctx.table_name, ctx), not_found_ok=True)
+ return
+
+ staging = staging_table_name(ctx)
+
+ async with self._client() as client:
+ if not await self._table_exists(client, staging):
+ # Already swapped by an earlier attempt at this same final batch.
+ return
+
+ if await self._table_exists(client, ctx.table_name) and not await self._is_owned(
+ client, ctx.table_name, ctx.schema_id
+ ):
+ # A table with this name exists and this writer never created it. Refuse
+ # rather than drop it: `table_name` comes from the source's resource name,
+ # which a custom-source manifest controls, and a table that predates this
+ # sync could be anything the customer already had in this schema.
+ raise UnrelatedTableExistsError(
+ f'"{self._schema}"."{ctx.table_name}" already exists and was not created by this sync; '
+ "refusing to replace it with the full refresh's staging table."
+ )
+
+ async with self._write_cursor(client) as cursor:
+ await cursor.execute(
+ sql.SQL("ALTER TABLE {}.{} DROP COLUMN IF EXISTS {}").format(
+ sql.Identifier(self._schema),
+ sql.Identifier(staging),
+ sql.Identifier(self._batch_index_column),
+ )
+ )
+
+ async with self._write_cursor(client) as cursor:
+ await cursor.execute(
+ sql.SQL("DROP TABLE IF EXISTS {}.{}").format(
+ sql.Identifier(self._schema), sql.Identifier(ctx.table_name)
+ )
+ )
+ await cursor.execute(
+ sql.SQL("ALTER TABLE {}.{} RENAME TO {}").format(
+ sql.Identifier(self._schema),
+ sql.Identifier(staging),
+ sql.Identifier(ctx.table_name),
+ )
+ )
+ # Stamp the run that published, so a redelivery of the final batch can tell
+ # "already published" from "never started" and refuse to rebuild the table.
+ await cursor.execute(
+ sql.SQL("COMMENT ON TABLE {}.{} IS {}").format(
+ sql.Identifier(self._schema),
+ sql.Identifier(ctx.table_name),
+ sql.Literal(_published_comment(ctx.schema_id, ctx.run_uuid)),
+ )
+ )
+
+ async def _table_exists(self, client: PostgreSQLClient, table: str) -> bool:
+ # The probe batch exports uses. `information_schema.tables` would be the obvious
+ # query, but it only exists on the leader node of a Redshift cluster, and Redshift
+ # inherits this method.
+ try:
+ await client.aget_table_columns(self._schema, table)
+ except psycopg.errors.UndefinedTable:
+ return False
+ return True
+
+ async def abort_run(self, ctx: DestinationRunContext) -> None:
+ """Drop whatever a run that will not finish left staged."""
+ async with self._client() as client:
+ await self._drop_run_scratch(client, ctx)
+
+ async def _drop_run_scratch(self, client: PostgreSQLClient, ctx: DestinationRunContext) -> None:
+ """Drop the scratch tables a run owns, once it can no longer need them."""
+ await client.adelete_table(self._schema, staging_table_name(ctx), not_found_ok=True)
+ await client.adelete_table(self._schema, merge_stage_name(ctx.table_name, ctx), not_found_ok=True)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/writers/sql_types.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/writers/sql_types.py
new file mode 100644
index 000000000000..fd9c4c26c9df
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/writers/sql_types.py
@@ -0,0 +1,65 @@
+"""Mapping Arrow types onto SQL column types.
+
+Kept apart from any one writer because the mappings differ per dialect but the decisions do
+not: prefer the widest sensible type, and fall back to JSON for anything nested rather than
+flattening it, so a column that is a struct today and a wider struct tomorrow keeps working.
+"""
+
+from __future__ import annotations
+
+import pyarrow as pa
+
+_POSTGRES_BY_ARROW_ID = {
+ pa.bool_(): "BOOLEAN",
+ pa.int8(): "SMALLINT",
+ pa.int16(): "SMALLINT",
+ pa.int32(): "INTEGER",
+ pa.int64(): "BIGINT",
+ pa.uint8(): "SMALLINT",
+ pa.uint16(): "INTEGER",
+ pa.uint32(): "BIGINT",
+ # No unsigned 64-bit integer in Postgres; NUMERIC keeps the full range rather than
+ # overflowing BIGINT at half the values.
+ pa.uint64(): "NUMERIC",
+ pa.float16(): "REAL",
+ pa.float32(): "REAL",
+ pa.float64(): "DOUBLE PRECISION",
+ pa.string(): "TEXT",
+ pa.large_string(): "TEXT",
+ pa.binary(): "BYTEA",
+ pa.large_binary(): "BYTEA",
+ pa.date32(): "DATE",
+ pa.date64(): "DATE",
+}
+
+
+def is_nested_type(arrow_type: pa.DataType) -> bool:
+ """Whether an Arrow type holds a nested value, which every dialect here stores as JSON."""
+ return (
+ pa.types.is_list(arrow_type)
+ or pa.types.is_large_list(arrow_type)
+ or pa.types.is_struct(arrow_type)
+ or pa.types.is_map(arrow_type)
+ )
+
+
+def postgres_type_for(arrow_type: pa.DataType) -> str:
+ """The Postgres column type for an Arrow type."""
+ mapped = _POSTGRES_BY_ARROW_ID.get(arrow_type)
+ if mapped is not None:
+ return mapped
+
+ if pa.types.is_timestamp(arrow_type):
+ return "TIMESTAMPTZ" if arrow_type.tz else "TIMESTAMP"
+ if pa.types.is_time(arrow_type):
+ return "TIME"
+ if pa.types.is_decimal(arrow_type):
+ return f"NUMERIC({arrow_type.precision}, {arrow_type.scale})"
+ if pa.types.is_duration(arrow_type):
+ return "INTERVAL"
+ if is_nested_type(arrow_type):
+ return "JSONB"
+
+ # An unrecognized type is stored as text rather than failing the sync. The value survives,
+ # and the column can be widened later without another full re-sync.
+ return "TEXT"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/idempotency.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/idempotency.py
index dc27a166eee9..5d319d0894f5 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/idempotency.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/idempotency.py
@@ -44,9 +44,18 @@ def get_redis_client():
pass
-def get_idempotency_key(team_id: int, schema_id: str, run_uuid: str, batch_index: int) -> str:
- """Generate a unique idempotency key for a batch."""
- return f"{IDEMPOTENCY_KEY_PREFIX}:{team_id}:{schema_id}:{run_uuid}:{batch_index}"
+def get_idempotency_key(
+ team_id: int, schema_id: str, run_uuid: str, batch_index: int, destination_id: str | None = None
+) -> str:
+ """Generate a unique idempotency key for a batch at one destination.
+
+ The PostHog warehouse keeps the unsuffixed key it has always used, so keys written
+ before this change still match after a deploy. Every other destination gets its own,
+ which is what lets a retry skip the destinations that already took the batch instead
+ of re-writing all of them.
+ """
+ base = f"{IDEMPOTENCY_KEY_PREFIX}:{team_id}:{schema_id}:{run_uuid}:{batch_index}"
+ return base if destination_id is None else f"{base}:{destination_id}"
def is_batch_already_processed(
@@ -55,6 +64,7 @@ def is_batch_already_processed(
run_uuid: str,
batch_index: int,
delta_table_ref: DeltaTableRef | None = None,
+ destination_id: str | None = None,
) -> bool:
"""Check if a batch has already been processed.
@@ -70,7 +80,7 @@ def is_batch_already_processed(
"""
with get_redis_client() as redis_client:
if redis_client is not None:
- key = get_idempotency_key(team_id, schema_id, run_uuid, batch_index)
+ key = get_idempotency_key(team_id, schema_id, run_uuid, batch_index, destination_id)
if redis_client.exists(key) == 1:
return True
@@ -98,8 +108,10 @@ def is_batch_already_processed(
raise
-def mark_batch_as_processed(team_id: int, schema_id: str, run_uuid: str, batch_index: int) -> None:
- """Mark a batch as processed in the cache."""
+def mark_batch_as_processed(
+ team_id: int, schema_id: str, run_uuid: str, batch_index: int, destination_id: str | None = None
+) -> None:
+ """Mark a batch as processed at one destination."""
with get_redis_client() as redis_client:
if redis_client is None:
logger.warning(
@@ -111,5 +123,5 @@ def mark_batch_as_processed(team_id: int, schema_id: str, run_uuid: str, batch_i
)
return
- key = get_idempotency_key(team_id, schema_id, run_uuid, batch_index)
+ key = get_idempotency_key(team_id, schema_id, run_uuid, batch_index, destination_id)
redis_client.set(key, "1", ex=IDEMPOTENCY_TTL_SECONDS)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/processor.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/processor.py
index df49be649f3d..842e322a3937 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/processor.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/processor.py
@@ -754,6 +754,32 @@ def process_message(
_process_message_reported(message, export_signal, progress_callback, verify_ownership)
+def _process_external_destinations_only(
+ export_signal: "ExportSignalMessage",
+ verify_ownership: Callable[[], None] | None,
+) -> None:
+ """Deliver a batch for a run that writes to external destinations only.
+
+ Same lifecycle as any other run, minus everything Delta-specific. The batch is done when
+ every destination has taken it, and the final batch completes the job.
+ """
+
+ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.destinations_load.delivery import ( # noqa: PLC0415
+ deliver_batch_to_destinations,
+ )
+
+ deliver_batch_to_destinations(export_signal)
+
+ if not export_signal.is_final_batch:
+ return
+
+ # Minutes may have passed, so re-check ownership before completion promotes the cursor.
+ if verify_ownership is not None:
+ verify_ownership()
+
+ _mark_job_completed(export_signal)
+
+
def _process_message_reported(
message: Any,
export_signal: "ExportSignalMessage",
@@ -767,6 +793,13 @@ def _process_message_reported(
# previously closed event loop (async_to_sync creates/destroys loops).
s3fs.S3FileSystem.clear_instance_cache()
+ # Imported here, not at module scope: `load/__init__` imports this module, and delivery
+ # imports `load.idempotency`, so a module-level import closes the cycle.
+ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.destinations_load.delivery import ( # noqa: PLC0415
+ deliver_batch_to_destinations,
+ warehouse_is_a_destination,
+ )
+
try:
team_id_str = str(export_signal.team_id)
schema_id_str = str(export_signal.schema_id)
@@ -789,6 +822,12 @@ def _process_message_reported(
is_first_sync=export_signal.is_first_ever_sync,
)
+ if not warehouse_is_a_destination(export_signal):
+ # The customer asked for their data elsewhere and not here, so there is no delta
+ # write, no table to register and no post-import to run.
+ _process_external_destinations_only(export_signal, verify_ownership)
+ return
+
already_processed = is_batch_already_processed(
export_signal.team_id,
export_signal.schema_id,
@@ -797,6 +836,12 @@ def _process_message_reported(
delta_table_ref=delta_table_ref,
)
+ # The warehouse having this batch says nothing about the other destinations, so
+ # delivery runs on every path and decides for itself what is left to do. Gating it on
+ # the warehouse's marker would strand a destination that failed, and gating publication
+ # on the write marker would leave a full refresh staged and never swapped in.
+ deliver_batch_to_destinations(export_signal)
+
if already_processed and not export_signal.is_final_batch:
IDEMPOTENCY_HIT_TOTAL.labels(team_id=team_id_str, schema_id=schema_id_str).inc()
logger.info(
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/tests/__init__.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/tests/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/messages.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/messages.py
index c50398b48854..523217245dab 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/messages.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/messages.py
@@ -10,7 +10,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.typ
SyncTypeLiteral = Literal["full_refresh", "incremental", "append", "cdc"]
-@dataclass
+@dataclass(frozen=True)
class ExportSignalMessage:
"""One extracted batch's hand-off from the extraction side to the load consumer.
@@ -48,6 +48,9 @@ class ExportSignalMessage:
cumulative_row_count: int = 0
cdc_write_mode: Optional[str] = None
cdc_table_mode: Optional[str] = None
+ # Snapshotted when the run started. Empty means the PostHog warehouse only, which is
+ # also what an old message that predates destinations decodes to.
+ destination_ids: list[str] = field(default_factory=list)
def to_dict(self) -> dict[str, Any]:
return asdict(self)
@@ -83,4 +86,5 @@ class ExportSignalMessage:
cumulative_row_count=data.get("cumulative_row_count", 0),
cdc_write_mode=data.get("cdc_write_mode"),
cdc_table_mode=data.get("cdc_table_mode"),
+ destination_ids=data.get("destination_ids") or [],
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/pipeline.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/pipeline.py
index 3574fbe42fa3..54020ea2e80b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/pipeline.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/pipeline.py
@@ -218,6 +218,9 @@ class PipelineV3(Generic[ResumableData]):
is_first_ever_sync=is_first_ever_sync,
workflow_id=current_workflow_id(),
workflow_run_id=current_workflow_run_id(),
+ # Snapshotted on the job when the run started. Empty for every run before
+ # destinations, and every run of a team the flag is off for.
+ destination_ids=list(self._job.destination_ids or []),
)
self._resumable_source_manager = resumable_source_manager
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/consumer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/consumer.py
index 4b6de10d9db7..e1e988b995a2 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/consumer.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/consumer.py
@@ -42,6 +42,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline
ProcessBatchFn,
_group_by_key,
)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.messages import ExportSignalMessage
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.jobs_db import (
_UNSET,
FRESHNESS_WINDOW_SECONDS,
@@ -244,11 +245,34 @@ class DeltaBatchConsumerAdapter:
logger.exception("fail_run_queue_update_failed", batch_id=batch.id, run_uuid=batch.run_uuid)
capture_exception(e)
+ # A run that will not finish leaves scratch tables behind in someone else's database:
+ # a full refresh's staging table, and the run's merge stage. Nothing else drops them,
+ # because the next run stages under its own id.
+ if batch.destination_ids:
+ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.destinations_load.delivery import ( # noqa: PLC0415
+ abort_destinations,
+ )
+
+ try:
+ # `to_export_signal()` hands back a dict, so it needs parsing the same way the
+ # delivery path does before anything reads a field off it.
+ await sync_to_async(abort_destinations)(ExportSignalMessage.from_dict(batch.to_export_signal()))
+ except Exception as e:
+ # Best effort by design: a leftover table costs the customer storage, not
+ # correctness, and is not worth failing the fail path over.
+ logger.warning(
+ "fail_run_destination_abort_failed",
+ job_id=batch.job_id,
+ run_uuid=batch.run_uuid,
+ error=str(e),
+ )
+
try:
await sync_to_async(_update_job_status_to_failed)(
job_id=batch.job_id,
team_id=batch.team_id,
error=reason,
+ run_uuid=batch.run_uuid,
)
except Exception as e:
# Leave the job for the reconcile sweep rather than crashing the consumer.
@@ -738,7 +762,7 @@ def _get_job_status_and_error(*, job_id: str, team_id: int) -> tuple[str, str |
return ExternalDataJob.objects.filter(id=job_id, team_id=team_id).values_list("status", "latest_error").first()
-def _update_job_status_to_failed(*, job_id: str, team_id: int, error: str) -> None:
+def _update_job_status_to_failed(*, job_id: str, team_id: int, error: str, run_uuid: str = "") -> None:
from products.data_warehouse.backend.facade.api import update_external_job_status
from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/jobs_db.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/jobs_db.py
index 36c13a35f3c0..4da473023c48 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/jobs_db.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/jobs_db.py
@@ -17,7 +17,7 @@ from __future__ import annotations
import json
import time
-from dataclasses import dataclass
+from dataclasses import dataclass, field
from datetime import datetime
from typing import Any
@@ -91,7 +91,7 @@ def pending_batch_select_columns(status_alias: str) -> str:
b.run_uuid, b.batch_index, b.s3_path, b.row_count, b.byte_size,
b.is_final_batch, b.total_batches, b.total_rows, b.sync_type,
b.cumulative_row_count, b.resource_name, b.is_resume,
- b.is_first_ever_sync, b.metadata,
+ b.is_first_ever_sync, b.metadata, b.destination_ids,
COALESCE({status_alias}.attempt, 0) AS latest_attempt,
b.created_at
"""
@@ -473,6 +473,8 @@ class PendingBatch:
is_first_ever_sync: bool
metadata: dict[str, Any]
latest_attempt: int
+ # Snapshotted on the batch when the run started. Empty means the PostHog warehouse only.
+ destination_ids: list[str] = field(default_factory=list)
created_at: datetime | None = None
# Observed denormalized state clock at read time; None for sinks that don't surface it.
state_changed_at: datetime | None = None
@@ -510,6 +512,7 @@ class PendingBatch:
"partition_mode": self.metadata.get("partition_mode"),
"cdc_write_mode": self.metadata.get("cdc_write_mode"),
"cdc_table_mode": self.metadata.get("cdc_table_mode"),
+ "destination_ids": self.destination_ids or [],
}
@@ -763,7 +766,7 @@ class BatchQueue:
b.run_uuid, b.batch_index, b.s3_path, b.row_count, b.byte_size,
b.is_final_batch, b.total_batches, b.total_rows, b.sync_type,
b.cumulative_row_count, b.resource_name, b.is_resume,
- b.is_first_ever_sync, b.metadata,
+ b.is_first_ever_sync, b.metadata, b.destination_ids,
b.latest_attempt,
b.created_at
FROM {BATCH_TABLE} b
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/producer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/producer.py
index f80b990869a0..a055986e7171 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/producer.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/producer.py
@@ -72,6 +72,7 @@ class PostgresProducer:
cdc_table_mode: str | None = None,
workflow_id: str | None = None,
workflow_run_id: str | None = None,
+ destination_ids: list[str] | None = None,
) -> None:
self._team_id = team_id
self._job_id = job_id
@@ -93,6 +94,7 @@ class PostgresProducer:
self._cdc_table_mode = cdc_table_mode
self._workflow_id = workflow_id
self._workflow_run_id = workflow_run_id
+ self._destination_ids: list[str] = list(destination_ids or [])
self._conn = _connect_with_retry(database_url)
self._batches_sent = 0
@@ -162,17 +164,17 @@ class PostgresProducer:
self._conn.execute(
f"""
- INSERT INTO {BATCH_TABLE} (
- team_id, schema_id, source_id, job_id, run_uuid,
- batch_index, s3_path, row_count, byte_size, is_final_batch,
- total_batches, total_rows, sync_type, cumulative_row_count,
- resource_name, is_resume, is_first_ever_sync, metadata, created_at
- ) VALUES (
- %(team_id)s, %(schema_id)s, %(source_id)s, %(job_id)s, %(run_uuid)s,
- %(batch_index)s, %(s3_path)s, %(row_count)s, %(byte_size)s, %(is_final_batch)s,
- %(total_batches)s, %(total_rows)s, %(sync_type)s, %(cumulative_row_count)s,
- %(resource_name)s, %(is_resume)s, %(is_first_ever_sync)s, %(metadata)s, now()
- )
+ INSERT INTO {BATCH_TABLE} (
+ team_id, schema_id, source_id, job_id, run_uuid,
+ batch_index, s3_path, row_count, byte_size, is_final_batch,
+ total_batches, total_rows, sync_type, cumulative_row_count,
+ resource_name, is_resume, is_first_ever_sync, metadata, destination_ids, created_at
+ ) VALUES (
+ %(team_id)s, %(schema_id)s, %(source_id)s, %(job_id)s, %(run_uuid)s,
+ %(batch_index)s, %(s3_path)s, %(row_count)s, %(byte_size)s, %(is_final_batch)s,
+ %(total_batches)s, %(total_rows)s, %(sync_type)s, %(cumulative_row_count)s,
+ %(resource_name)s, %(is_resume)s, %(is_first_ever_sync)s, %(metadata)s, %(destination_ids)s, now()
+ )
""",
{
"team_id": self._team_id,
@@ -193,6 +195,7 @@ class PostgresProducer:
"is_resume": self._is_resume,
"is_first_ever_sync": self._is_first_ever_sync,
"metadata": json.dumps(metadata),
+ "destination_ids": json.dumps(self._destination_ids),
},
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_consumer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_consumer.py
index aedb1efb1f51..c96becb873b2 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_consumer.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_consumer.py
@@ -1479,6 +1479,34 @@ class TestFailRun:
mock_fail_run.assert_called_once() # queue batches still marked failed
+ @pytest.mark.asyncio
+ async def test_aborting_destinations_gets_a_parsed_export_signal(self):
+ # `to_export_signal()` returns a dict. Handing that straight to the abort path made every
+ # field access raise, so a destination that failed reported an AttributeError instead of
+ # the real error, and its scratch tables were never dropped.
+ consumer = _make_consumer()
+ batch = _make_batch(destination_ids=["11111111-1111-1111-1111-111111111111"])
+ seen: list[Any] = []
+
+ with (
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.fail_run",
+ new_callable=AsyncMock,
+ ),
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer._update_job_status_to_failed",
+ ),
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.destinations_load.delivery.abort_destinations",
+ side_effect=lambda signal: seen.append(signal),
+ ),
+ ):
+ await consumer._fail_run(batch, reason="boom", conn=consumer._poll_conn)
+
+ assert len(seen) == 1
+ assert seen[0].destination_ids == ["11111111-1111-1111-1111-111111111111"]
+ assert seen[0].team_id == 1
+
@pytest.mark.asyncio
async def test_attempts_job_status_update_even_when_queue_update_fails(self):
consumer = _make_consumer()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_jobs_db.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_jobs_db.py
index 1fb30b04937c..e48dcd8abede 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_jobs_db.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_jobs_db.py
@@ -72,6 +72,7 @@ def _ensure_tables(conn: psycopg.Connection[Any]) -> None:
is_resume BOOLEAN NOT NULL DEFAULT FALSE,
is_first_ever_sync BOOLEAN NOT NULL DEFAULT FALSE,
metadata JSONB NOT NULL DEFAULT '{{}}'::jsonb,
+ destination_ids JSONB NOT NULL DEFAULT '[]'::jsonb,
latest_state VARCHAR(32) NOT NULL DEFAULT 'pending',
latest_attempt SMALLINT NOT NULL DEFAULT 0,
state_changed_at TIMESTAMPTZ,
@@ -85,7 +86,8 @@ def _ensure_tables(conn: psycopg.Connection[Any]) -> None:
ADD COLUMN IF NOT EXISTS latest_state VARCHAR(32) NOT NULL DEFAULT 'pending',
ADD COLUMN IF NOT EXISTS latest_attempt SMALLINT NOT NULL DEFAULT 0,
ADD COLUMN IF NOT EXISTS state_changed_at TIMESTAMPTZ,
- ADD COLUMN IF NOT EXISTS superseded BOOLEAN NOT NULL DEFAULT FALSE
+ ADD COLUMN IF NOT EXISTS superseded BOOLEAN NOT NULL DEFAULT FALSE,
+ ADD COLUMN IF NOT EXISTS destination_ids JSONB NOT NULL DEFAULT '[]'::jsonb
""")
conn.execute(f"""
CREATE INDEX IF NOT EXISTS sb_claimable_idx ON {BATCH_TABLE} (team_id, created_at, batch_index)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/row_tracking.py b/products/warehouse_sources/backend/temporal/data_imports/row_tracking.py
index 181b492c2506..9bab76b58c7e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/row_tracking.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/row_tracking.py
@@ -25,7 +25,7 @@ from posthog.settings import EE_AVAILABLE
from posthog.settings.base_variables import TEST
from posthog.sync import database_sync_to_async_pool
-from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob
+from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob, billable_destination_multiplier
if TYPE_CHECKING:
from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
@@ -212,13 +212,15 @@ def _rows_synced_in_billing_period(
logger.warning("BillingLimits: cached row count is not a number, querying Postgres", error=str(e))
# Completed rows for every team in the org, excluding each source's first 7 free days.
+ # Rows bill once per destination the run delivered to. A run completes only when every
+ # destination took it, so the count is exact.
result = ExternalDataJob.objects.filter(
Q(finished_at__gte=F("pipeline__created_at") + timedelta(days=7)),
team_id__in=team_ids,
finished_at__gte=billing_cycle_start,
billable=True,
status=ExternalDataJob.Status.COMPLETED,
- ).aggregate(total_rows=Sum("rows_synced"))
+ ).aggregate(total_rows=Sum(F("rows_synced") * billable_destination_multiplier()))
rows_synced_in_billing_period = result.get("total_rows") or 0
if redis is not None:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_end_to_end.py b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_end_to_end.py
index 0d1fde15661b..ea86a8f0ee63 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_end_to_end.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_end_to_end.py
@@ -41,6 +41,7 @@ from temporalio.worker import UnsandboxedWorkflowRunner, Worker
from posthog.hogql.query import execute_hogql_query
from posthog.models.event.util import format_clickhouse_timestamp
+from posthog.models.integration import Integration
from posthog.models.team.team import Team
from posthog.temporal.common.shutdown import ShutdownMonitor, WorkerShuttingDownError
from posthog.temporal.utils import ExternalDataWorkflowInputs
@@ -59,6 +60,11 @@ from products.warehouse_sources.backend.facade.models import (
ExternalDataSource,
get_latest_run_if_exists,
)
+from products.warehouse_sources.backend.models.external_data_destination import (
+ ExternalDataDestination,
+ ExternalDataSourceDestination,
+ get_or_create_warehouse_destination,
+)
from products.warehouse_sources.backend.models.external_table_definitions import external_tables
from products.warehouse_sources.backend.models.oom_event import ExternalDataSchemaOOMEvent
from products.warehouse_sources.backend.temporal.data_imports.cdp_producer_job import CDPProducerJobWorkflow
@@ -151,7 +157,7 @@ class _PostgresQueueReplay:
through process_message(), mimicking what the real BatchConsumer does."""
def __init__(self) -> None:
- self._processed_batches: set[tuple[str, int]] = set()
+ self._processed_batches: set[tuple[str, int, str | None]] = set()
def replay_batches_for_run(self, run_uuid: str) -> None:
from django.db import connection as django_conn
@@ -162,7 +168,7 @@ class _PostgresQueueReplay:
SELECT id, team_id, schema_id, source_id, job_id, run_uuid,
batch_index, s3_path, row_count, byte_size, is_final_batch,
total_batches, total_rows, sync_type, cumulative_row_count,
- resource_name, is_resume, is_first_ever_sync, metadata
+ resource_name, is_resume, is_first_ever_sync, metadata, destination_ids
FROM {BATCH_TABLE}
WHERE run_uuid = %s
ORDER BY created_at ASC, batch_index ASC
@@ -178,6 +184,10 @@ class _PostgresQueueReplay:
for row in rows:
if isinstance(row.get("metadata"), str):
row["metadata"] = json.loads(row["metadata"])
+ # Same treatment as metadata: this cursor hands jsonb back as text, and iterating
+ # the string would feed "[" to the destination lookup as if it were an id.
+ if isinstance(row.get("destination_ids"), str):
+ row["destination_ids"] = json.loads(row["destination_ids"])
batch = PendingBatch(latest_attempt=0, **row)
try:
process_message(batch.to_export_signal())
@@ -201,8 +211,11 @@ class _PostgresQueueReplay:
run_uuid: str,
batch_index: int,
delta_table_ref: Any = None,
+ destination_id: str | None = None,
) -> bool:
- key = (run_uuid, batch_index)
+ # Keyed by destination as well, mirroring the real check: a batch the warehouse has
+ # taken is not yet done for a destination that has not.
+ key = (run_uuid, batch_index, destination_id)
if key in self._processed_batches:
return True
self._processed_batches.add(key)
@@ -383,26 +396,43 @@ async def _run(
billable: Optional[bool] = None,
ignore_assertions: Optional[bool] = False,
activity_environment: Optional[WorkflowEnvironment] = None,
+ destinations: Optional[list["ExternalDataDestination"]] = None,
+ existing_schema_id: Optional[int] = None,
):
- source = await sync_to_async(ExternalDataSource.objects.create)(
- source_id=uuid.uuid4(),
- connection_id=uuid.uuid4(),
- destination_id=uuid.uuid4(),
- team=team,
- status="running",
- source_type=source_type,
- job_inputs=job_inputs,
- )
- source.created_at = datetime(2024, 1, 1, tzinfo=ZoneInfo("UTC"))
- await sync_to_async(source.save)()
+ if existing_schema_id is not None:
+ # A genuine re-sync: the same schema (and so the same ownership identity a writer
+ # checks) runs again, rather than a fresh source and schema standing in for an
+ # unrelated one that happens to share a name.
+ schema = await sync_to_async(ExternalDataSchema.objects.get)(id=existing_schema_id)
+ source = await sync_to_async(lambda: schema.source)()
+ else:
+ source = await sync_to_async(ExternalDataSource.objects.create)(
+ source_id=uuid.uuid4(),
+ connection_id=uuid.uuid4(),
+ destination_id=uuid.uuid4(),
+ team=team,
+ status="running",
+ source_type=source_type,
+ job_inputs=job_inputs,
+ )
+ source.created_at = datetime(2024, 1, 1, tzinfo=ZoneInfo("UTC"))
+ await sync_to_async(source.save)()
- schema = await sync_to_async(ExternalDataSchema.objects.create)(
- name=schema_name,
- team_id=team.pk,
- source_id=source.pk,
- sync_type=sync_type,
- sync_type_config=sync_type_config or {},
- )
+ schema = await sync_to_async(ExternalDataSchema.objects.create)(
+ name=schema_name,
+ team_id=team.pk,
+ source_id=source.pk,
+ sync_type=sync_type,
+ sync_type_config=sync_type_config or {},
+ )
+
+ def _link(destination: "ExternalDataDestination") -> None:
+ ExternalDataSourceDestination.objects.for_team(team.pk).create(
+ team_id=team.pk, source=source, destination=destination
+ )
+
+ for destination in destinations or []:
+ await sync_to_async(_link)(destination)
workflow_id = str(uuid.uuid4())
inputs = ExternalDataWorkflowInputs(
@@ -420,6 +450,10 @@ async def _run(
mock.patch(
"products.warehouse_sources.backend.temporal.data_imports.metrics.get_producer"
) as mock_app_metrics_producer_cls,
+ mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.workflow_activities.create_job_model.is_multi_destination_enabled",
+ return_value=bool(destinations),
+ ),
):
await _execute_run(workflow_id, inputs, mock_data_response, activity_environment)
@@ -440,7 +474,12 @@ async def _run(
assert run.status == ExternalDataJobStatus.COMPLETED
assert run.finished_at is not None
assert run.storage_delta_mib is not None
- assert run.storage_delta_mib != 0
+ if existing_schema_id is None:
+ # A fresh schema's table grows from empty, so this always adds storage.
+ # A genuine re-sync of identical rows merges into the existing table and
+ # can legitimately add zero net storage (dedup, or even compaction shrink),
+ # so that case only checks storage_delta_mib was computed at all, above.
+ assert run.storage_delta_mib != 0
mock_compact_table.assert_called()
mock_get_data_import_finished_metric.assert_called_with(
@@ -456,10 +495,13 @@ async def _run(
)
produce_calls = mock_app_metrics_producer_cls.return_value.produce.call_args_list
emitted_payloads = [call.kwargs["data"] for call in produce_calls]
- status_rows = [
- p for p in emitted_payloads if p["app_source_id"] == str(source.pk) and p["metric_kind"] == "success"
+ # A run also repeats its metrics under each destination, so scope these to the schema's
+ # own rows. The destination-scoped ones are checked below.
+ schema_scoped = [
+ p for p in emitted_payloads if p["app_source_id"] == str(source.pk) and p["instance_id"] == str(schema.id)
]
- rows_rows = [p for p in emitted_payloads if p["app_source_id"] == str(source.pk) and p["metric_kind"] == "rows"]
+ status_rows = [p for p in schema_scoped if p["metric_kind"] == "success"]
+ rows_rows = [p for p in schema_scoped if p["metric_kind"] == "rows"]
assert len(status_rows) == 1, f"expected one success row, got {emitted_payloads}"
assert status_rows[0]["app_source"] == "warehouse_source_sync"
assert status_rows[0]["metric_name"] == "succeeded"
@@ -480,6 +522,15 @@ async def _run(
assert rows_rows[0]["instance_id"] == str(schema.id)
assert rows_rows[0]["timestamp"] == status_rows[0]["timestamp"]
+ # Each destination the run delivered to gets the same pair, keyed by "<schema>/<destination>"
+ # and by the destination alone, so a source-level view can ask for one destination directly.
+ for destination_id in run.destination_ids or []:
+ for instance_id in (f"{schema.id}/{destination_id}", str(destination_id)):
+ scoped = [p for p in emitted_payloads if p["instance_id"] == instance_id]
+ assert {p["metric_name"] for p in scoped} == {"succeeded", "rows_synced"}, (
+ f"expected a success and a rows row for {instance_id}, got {scoped}"
+ )
+
await sync_to_async(schema.refresh_from_db)()
assert schema.last_synced_at == run.created_at
@@ -4911,3 +4962,210 @@ async def test_postgres_switch_to_xmin_rebuilds_table(team, postgres_config, pos
schema = await ExternalDataSchema.objects.aget(id=inputs.external_data_schema_id)
assert schema.sync_type_config.get("reset_pipeline") is None
assert schema.xmin_last_value is not None
+
+
+# --- Destinations ------------------------------------------------------------------------
+#
+# A source can sync to destinations besides the PostHog warehouse. These run the whole
+# pipeline and then read the rows back out of a real Postgres, because the parts that break
+# are the joins between pieces: the ids reaching the batch, the batch reaching the consumer,
+# and the consumer resolving a writer. Each of those looks fine in isolation.
+
+DESTINATION_SCHEMA = "destination_schema"
+
+
+async def _destination_connection(postgres_config: dict):
+ """A short-lived connection to the destination database.
+
+ Deliberately not the `postgres_connection` fixture: the pipeline severs connections
+ mid-test, and a torn connection reaches these assertions as a closed cursor rather than
+ as anything that points at the cause.
+ """
+ connection = await psycopg.AsyncConnection.connect(
+ user=postgres_config["user"],
+ password=postgres_config["password"],
+ dbname=postgres_config["database"],
+ host=postgres_config["host"],
+ port=postgres_config["port"],
+ autocommit=True,
+ )
+ try:
+ yield connection
+ finally:
+ await connection.close()
+
+
+async def _postgres_destination(team: Team, postgres_config: dict) -> ExternalDataDestination:
+ """A Postgres destination pointed at the same database the source fixtures use."""
+ async with _destination_connection(postgres_config) as connection:
+ await connection.execute(f"CREATE SCHEMA IF NOT EXISTS {DESTINATION_SCHEMA}")
+
+ integration = await sync_to_async(Integration.objects.create)(
+ team=team,
+ kind=Integration.IntegrationKind.POSTGRESQL,
+ config={
+ "host": postgres_config["host"],
+ "port": postgres_config["port"],
+ "user": postgres_config["user"],
+ "ssl_mode": "prefer",
+ },
+ sensitive_config={"password": postgres_config["password"]},
+ )
+
+ def create() -> ExternalDataDestination:
+ # The whole call runs in the thread: `for_team` queries, so building the manager in
+ # the async context would raise SynchronousOnlyOperation before `create` is reached.
+ return ExternalDataDestination.objects.for_team(team.pk).create(
+ team_id=team.pk,
+ type=ExternalDataDestination.Type.POSTGRES,
+ name="customer postgres",
+ integration=integration,
+ config={"database": postgres_config["database"], "schema": DESTINATION_SCHEMA},
+ )
+
+ return await sync_to_async(create)()
+
+
+# The destination names its table the way the PostHog warehouse does, so a Stripe charge resource
+# lands as `stripe_charge` on both sides rather than as the connector's raw `Charge`.
+DESTINATION_TABLE_NAME = f"stripe_{STRIPE_CHARGE_RESOURCE_NAME}".lower()
+
+
+async def _destination_rows(postgres_config: dict, table: str) -> list[tuple]:
+ """Rows at the destination. Identifiers are quoted, so the table keeps its exact name."""
+ async with _destination_connection(postgres_config) as connection:
+ async with connection.cursor() as cursor:
+ await cursor.execute(f'SELECT id FROM "{DESTINATION_SCHEMA}"."{table}" ORDER BY id')
+ return await cursor.fetchall()
+
+
[email protected]_db(transaction=True)
+async def test_a_source_syncs_to_a_postgres_destination(
+ team, stripe_charge, mock_stripe_client, postgres_config, setup_postgres_test_db
+):
+ if _current_pipeline_mode != "v3":
+ pytest.skip("destinations only apply to pipeline_v3")
+
+ destination = await _postgres_destination(team, postgres_config)
+ warehouse = await sync_to_async(get_or_create_warehouse_destination)(team.pk)
+
+ await _run(
+ team=team,
+ schema_name=STRIPE_CHARGE_RESOURCE_NAME,
+ table_name="stripe_charge",
+ source_type="Stripe",
+ job_inputs=_STRIPE_JOB_INPUTS,
+ mock_data_response=stripe_charge["data"],
+ destinations=[warehouse, destination],
+ )
+
+ # The warehouse still has the rows, and so does the customer's Postgres.
+ res = await sync_to_async(execute_hogql_query)("SELECT id FROM stripe_charge", team)
+ assert len(res.results) > 0
+
+ rows = await _destination_rows(postgres_config, DESTINATION_TABLE_NAME)
+ assert len(rows) == len(res.results)
+
+
[email protected]_db(transaction=True)
+async def test_a_run_with_a_destination_bills_for_both(
+ team, stripe_charge, mock_stripe_client, postgres_config, setup_postgres_test_db
+):
+ if _current_pipeline_mode != "v3":
+ pytest.skip("destinations only apply to pipeline_v3")
+
+ destination = await _postgres_destination(team, postgres_config)
+ warehouse = await sync_to_async(get_or_create_warehouse_destination)(team.pk)
+
+ await _run(
+ team=team,
+ schema_name=STRIPE_CHARGE_RESOURCE_NAME,
+ table_name="stripe_charge",
+ source_type="Stripe",
+ job_inputs=_STRIPE_JOB_INPUTS,
+ mock_data_response=stripe_charge["data"],
+ destinations=[warehouse, destination],
+ )
+
+ run = await sync_to_async(ExternalDataJob.objects.filter(team_id=team.pk).order_by("-created_at").first)()
+ assert run is not None
+ # The warehouse and the Postgres destination, so rows bill twice over.
+ assert len(run.destination_ids) == 2
+ assert sorted(run.destination_ids) == sorted([str(warehouse.id), str(destination.id)])
+
+
[email protected]_db(transaction=True)
+async def test_a_second_sync_merges_into_the_destination_rather_than_duplicating(
+ team, stripe_charge, mock_stripe_client, postgres_config, setup_postgres_test_db
+):
+ if _current_pipeline_mode != "v3":
+ pytest.skip("destinations only apply to pipeline_v3")
+
+ destination = await _postgres_destination(team, postgres_config)
+ warehouse = await sync_to_async(get_or_create_warehouse_destination)(team.pk)
+ run_kwargs: dict[str, Any] = {
+ "team": team,
+ "schema_name": STRIPE_CHARGE_RESOURCE_NAME,
+ "table_name": "stripe_charge",
+ "source_type": "Stripe",
+ "job_inputs": _STRIPE_JOB_INPUTS,
+ "mock_data_response": stripe_charge["data"],
+ "destinations": [warehouse, destination],
+ }
+
+ _, first_inputs = await _run(**run_kwargs)
+ after_first = await _destination_rows(postgres_config, DESTINATION_TABLE_NAME)
+
+ # Re-syncs the same schema, not a fresh one of the same name: a writer's ownership
+ # check is scoped to the schema id, and a second sync of the same source must still
+ # recognize the table it created the first time.
+ await _run(**run_kwargs, existing_schema_id=first_inputs.external_data_schema_id)
+ after_second = await _destination_rows(postgres_config, DESTINATION_TABLE_NAME)
+
+ # Same source rows delivered twice must not double up at the destination.
+ assert after_second == after_first
+
+
[email protected]_db(transaction=True)
+async def test_a_source_can_sync_to_a_destination_and_not_to_posthog(
+ team, stripe_charge, mock_stripe_client, postgres_config, setup_postgres_test_db
+):
+ """Selecting destinations replaces the default rather than adding to it.
+
+ A source linked only to Postgres does not write Delta at all, so nothing is queryable in
+ PostHog. That is the point: a customer can ask us to move their data without keeping a
+ copy. It is also the trap, since selecting a destination and expecting to keep the
+ warehouse would silently stop the PostHog side.
+ """
+ if _current_pipeline_mode != "v3":
+ pytest.skip("destinations only apply to pipeline_v3")
+
+ destination = await _postgres_destination(team, postgres_config)
+
+ await _run(
+ team=team,
+ schema_name=STRIPE_CHARGE_RESOURCE_NAME,
+ table_name="stripe_charge",
+ source_type="Stripe",
+ job_inputs=_STRIPE_JOB_INPUTS,
+ mock_data_response=stripe_charge["data"],
+ destinations=[destination],
+ # No Delta write, so the run has no storage delta for `_run` to assert on.
+ ignore_assertions=True,
+ )
+
+ rows = await _destination_rows(postgres_config, DESTINATION_TABLE_NAME)
+ assert len(rows) > 0
+
+ # Nothing was registered in PostHog, so there is no table to query.
+ exists = await sync_to_async(DataWarehouseTable.objects.filter(team_id=team.pk, name="stripe_charge").exists)()
+ assert not exists
+
+ run = await sync_to_async(ExternalDataJob.objects.filter(team_id=team.pk).order_by("-created_at").first)()
+ assert run is not None
+ assert len(run.destination_ids) == 1
diff --git a/products/warehouse_sources/backend/temporal/data_imports/tests/test_metrics_app_metrics2.py b/products/warehouse_sources/backend/temporal/data_imports/tests/test_metrics_app_metrics2.py
index fbf64a4459bc..8f2045d4df78 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/tests/test_metrics_app_metrics2.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/tests/test_metrics_app_metrics2.py
@@ -22,8 +22,20 @@ def _make_job(
rows_synced: int | None = 1234,
finished_at: dt.datetime | None = None,
team_id: int = 42,
+ destination_ids: list[str] | None = None,
) -> mock.Mock:
- job = mock.Mock(spec_set=("id", "team_id", "status", "rows_synced", "finished_at", "pipeline_id", "schema_id"))
+ job = mock.Mock(
+ spec_set=(
+ "id",
+ "team_id",
+ "status",
+ "rows_synced",
+ "finished_at",
+ "pipeline_id",
+ "schema_id",
+ "destination_ids",
+ )
+ )
job.id = uuid4()
job.team_id = team_id
job.status = status
@@ -31,9 +43,85 @@ def _make_job(
job.finished_at = finished_at or dt.datetime(2026, 4, 15, 12, 30, 45, tzinfo=dt.UTC)
job.pipeline_id = uuid4()
job.schema_id = uuid4()
+ job.destination_ids = destination_ids or []
return job
+class TestDestinationScopedAppMetrics(TestCase):
+ def _payloads(self, job) -> list[dict]:
+ with mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.metrics.get_producer"
+ ) as mock_producer_cls:
+ emit_data_import_app_metrics(job)
+ return [call.kwargs["data"] for call in mock_producer_cls.return_value.produce.call_args_list]
+
+ def test_a_run_without_destinations_emits_what_it_always_did(self) -> None:
+ # Every existing chart filters instance_id by a bare schema id. Emitting anything else for
+ # these runs would change what they already show.
+ job = _make_job(status=ExternalDataJob.Status.COMPLETED)
+
+ payloads = self._payloads(job)
+
+ assert len(payloads) == 2
+ assert {p["instance_id"] for p in payloads} == {str(job.schema_id)}
+
+ def test_each_destination_repeats_the_metrics_under_its_own_instance_id(self) -> None:
+ job = _make_job(status=ExternalDataJob.Status.COMPLETED, destination_ids=["dest-a", "dest-b"])
+
+ payloads = self._payloads(job)
+
+ # Two per instance: the terminal status and the row count.
+ assert len(payloads) == 10
+ assert {p["instance_id"] for p in payloads} == {
+ str(job.schema_id),
+ f"{job.schema_id}/dest-a",
+ f"{job.schema_id}/dest-b",
+ "dest-a",
+ "dest-b",
+ }
+
+ def test_a_destination_is_queryable_without_naming_a_schema(self) -> None:
+ # The source-level surfaces want one series per destination across every table, and the
+ # API filters instance_id by equality.
+ job = _make_job(status=ExternalDataJob.Status.COMPLETED, destination_ids=["dest-a"])
+
+ rows = [p for p in self._payloads(job) if p["instance_id"] == "dest-a"]
+
+ assert [(p["metric_name"], p["count"]) for p in rows] == [("succeeded", 1), ("rows_synced", 1234)]
+ assert {p["app_source_id"] for p in rows} == {str(job.pipeline_id)}
+
+ def test_the_schema_scoped_rows_are_unchanged_by_destinations(self) -> None:
+ # The number a chart already shows must not move because a destination was added.
+ without = self._payloads(_make_job(status=ExternalDataJob.Status.COMPLETED))
+ job = _make_job(status=ExternalDataJob.Status.COMPLETED, destination_ids=["dest-a"])
+ schema_scoped = [p for p in self._payloads(job) if p["instance_id"] == str(job.schema_id)]
+
+ assert [(p["metric_kind"], p["metric_name"], p["count"]) for p in schema_scoped] == [
+ (p["metric_kind"], p["metric_name"], p["count"]) for p in without
+ ]
+
+ def test_destination_rows_reuse_the_existing_metric_names(self) -> None:
+ # metric_name is LowCardinality on a table several products share, so a destination id
+ # must never end up in it.
+ job = _make_job(status=ExternalDataJob.Status.COMPLETED, destination_ids=["dest-a"])
+
+ payloads = self._payloads(job)
+
+ assert {p["metric_name"] for p in payloads} == {"succeeded", "rows_synced"}
+ assert {p["metric_kind"] for p in payloads} == {"success", "rows"}
+
+ def test_a_run_with_no_rows_still_records_the_destination_outcome(self) -> None:
+ job = _make_job(status=ExternalDataJob.Status.FAILED, rows_synced=0, destination_ids=["dest-a"])
+
+ payloads = self._payloads(job)
+
+ assert [(p["instance_id"], p["metric_name"]) for p in payloads] == [
+ (str(job.schema_id), "failed"),
+ (f"{job.schema_id}/dest-a", "failed"),
+ ("dest-a", "failed"),
+ ]
+
+
class TestEmitDataImportAppMetrics(TestCase):
@parameterized.expand(
[
diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/create_job_model.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/create_job_model.py
index bd9a76498435..4575d4972d66 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/create_job_model.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/create_job_model.py
@@ -24,6 +24,10 @@ from products.warehouse_sources.backend.models.external_data_job import External
from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
from products.warehouse_sources.backend.models.table import HIDDEN_COLUMNS, DataWarehouseTable
+from products.warehouse_sources.backend.temporal.data_imports.destinations.enablement import (
+ destination_ids_for_run,
+ is_multi_destination_enabled,
+)
from products.warehouse_sources.backend.temporal.data_imports.external_product_hooks import (
data_quality_checks_needed_for,
emit_signals_enabled_for,
@@ -154,6 +158,7 @@ def _create_job(
pipeline_version: str,
billable: bool,
schema_snapshot: dict[str, Any],
+ destination_ids: list[str] | None = None,
) -> ExternalDataJob:
# A deadlock aborts the INSERT without creating a row, so retrying from scratch is safe. This
# activity has no Temporal-level retry (see external_data_job.py), because a retry after job
@@ -169,6 +174,7 @@ def _create_job(
pipeline_version=pipeline_version,
billable=billable,
schema_snapshot=schema_snapshot,
+ destination_ids=destination_ids or [],
)
@@ -312,6 +318,12 @@ def create_external_data_job_model_activity(
# behind it can never be finalized, so it would stay stuck on Running forever. With the job
# committed first, the workflow's finalizer can always resolve it and repaint the schema.
schema.status = ExternalDataSchema.Status.RUNNING
+ # Only v3 runs deliver to destinations; v2 has no per-batch queue to carry the ids.
+ destination_ids: list[str] = []
+ if pipeline_version == ExternalDataJob.PipelineVersion.V3 and is_multi_destination_enabled(
+ inputs.team_id, source.source_type
+ ):
+ destination_ids = destination_ids_for_run(schema)
job = _create_job(
team_id=inputs.team_id,
source_id=inputs.source_id,
@@ -319,6 +331,7 @@ def create_external_data_job_model_activity(
pipeline_version=pipeline_version,
billable=inputs.billable,
schema_snapshot=_build_schema_snapshot(schema),
+ destination_ids=destination_ids,
)
schema.save(update_fields=["status", "updated_at"])
diff --git a/products/warehouse_sources/backend/tests/api/test_external_data_destination.py b/products/warehouse_sources/backend/tests/api/test_external_data_destination.py
new file mode 100644
index 000000000000..5f355c6dfad1
--- /dev/null
+++ b/products/warehouse_sources/backend/tests/api/test_external_data_destination.py
@@ -0,0 +1,266 @@
+from posthog.test.base import APIBaseTest
+from unittest.mock import patch
+
+from rest_framework import status
+from rest_framework.exceptions import PermissionDenied
+
+from posthog.models.integration import Integration
+
+from products.warehouse_sources.backend.models.external_data_destination import (
+ ExternalDataDestination,
+ ExternalDataSchemaDestination,
+ ExternalDataSourceDestination,
+)
+from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
+from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
+from products.warehouse_sources.backend.presentation.views.external_data_destination import (
+ ExternalDataDestinationViewSet,
+)
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+class DestinationAPITestBase(APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.base = f"/api/projects/{self.team.pk}/external_data_destinations"
+ self.source = ExternalDataSource.objects.create(
+ team=self.team,
+ source_id="src",
+ connection_id="conn",
+ status="Running",
+ source_type=ExternalDataSourceType.STRIPE,
+ )
+ self.schema = ExternalDataSchema.objects.create(team=self.team, source=self.source, name="charges")
+
+ def _integration(self, kind: str = Integration.IntegrationKind.POSTGRESQL) -> Integration:
+ self._integration_seq = getattr(self, "_integration_seq", 0) + 1
+ return Integration.objects.create(
+ team=self.team, kind=kind, integration_id=f"{kind}-{self._integration_seq}", config={}
+ )
+
+ def _create_destination(self, **overrides) -> ExternalDataDestination:
+ payload = {
+ "type": ExternalDataDestination.Type.POSTGRES,
+ "name": "analytics postgres",
+ "integration": self._integration().pk,
+ **overrides,
+ }
+ response = self.client.post(self.base, payload)
+ assert response.status_code == status.HTTP_201_CREATED, response.json()
+ return ExternalDataDestination.objects.for_team(self.team.pk).get(id=response.json()["id"])
+
+
+class TestExternalDataDestinationAPI(DestinationAPITestBase):
+ def test_create_and_list(self) -> None:
+ destination = self._create_destination()
+
+ listing = self.client.get(self.base).json()
+
+ assert [d["id"] for d in listing["results"]] == [str(destination.id)]
+ assert listing["results"][0]["is_posthog_warehouse"] is False
+
+ def test_a_destination_needs_an_integration(self) -> None:
+ response = self.client.post(self.base, {"type": ExternalDataDestination.Type.POSTGRES, "name": "no creds"})
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert "integration" in response.json()["attr"]
+
+ def test_the_integration_must_match_the_destination_type(self) -> None:
+ # Postgres needs a postgresql integration, not a Snowflake one.
+ snowflake_integration = self._integration(Integration.IntegrationKind.SNOWFLAKE)
+
+ response = self.client.post(
+ self.base,
+ {
+ "type": ExternalDataDestination.Type.POSTGRES,
+ "name": "mismatched",
+ "integration": snowflake_integration.pk,
+ },
+ )
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert "integration" in response.json()["attr"]
+
+ def test_the_posthog_warehouse_is_not_user_managed(self) -> None:
+ response = self.client.post(self.base, {"type": ExternalDataDestination.Type.POSTHOG_WAREHOUSE, "name": "mine"})
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+
+ def test_the_connection_cannot_be_changed(self) -> None:
+ # Repointing at another server strands everything already synced there, so a second
+ # destination is the supported route rather than editing this one.
+ destination = self._create_destination()
+ other = self._integration()
+
+ response = self.client.patch(f"{self.base}/{destination.id}", {"integration": other.pk})
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert "integration" in response.json()["attr"]
+
+ def test_the_target_database_and_schema_cannot_be_changed(self) -> None:
+ destination = self._create_destination()
+
+ for field in ("database", "schema"):
+ response = self.client.patch(f"{self.base}/{destination.id}", {"config": {field: "somewhere_else"}})
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, field
+ assert "config" in response.json()["attr"], field
+
+ def test_the_name_can_still_be_changed(self) -> None:
+ destination = self._create_destination()
+
+ response = self.client.patch(f"{self.base}/{destination.id}", {"name": "renamed"})
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ destination.refresh_from_db()
+ assert destination.name == "renamed"
+
+ def test_resending_the_same_target_is_not_a_change(self) -> None:
+ # A form that posts every field back must not be rejected for the fields it left alone.
+ destination = self._create_destination()
+
+ response = self.client.patch(
+ f"{self.base}/{destination.id}",
+ {"name": "renamed", "integration": destination.integration_id, "config": destination.config},
+ )
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+
+ def test_delete_detaches_everything_that_synced_to_it(self) -> None:
+ destination = self._create_destination()
+ ExternalDataSourceDestination.objects.for_team(self.team.pk).create(
+ team_id=self.team.pk, source=self.source, destination=destination
+ )
+ ExternalDataSchemaDestination.objects.for_team(self.team.pk).create(
+ team_id=self.team.pk, schema=self.schema, destination=destination
+ )
+
+ response = self.client.delete(f"{self.base}/{destination.id}")
+
+ assert response.status_code == status.HTTP_204_NO_CONTENT
+ destination.refresh_from_db()
+ assert destination.deleted is True
+ assert ExternalDataSourceDestination.objects.for_team(self.team.pk).count() == 0
+ assert ExternalDataSchemaDestination.objects.for_team(self.team.pk).count() == 0
+
+ def test_another_teams_destinations_are_not_visible(self) -> None:
+ self._create_destination()
+ other_team = self.create_team_with_organization(self.organization)
+
+ listing = self.client.get(f"/api/projects/{other_team.pk}/external_data_destinations").json()
+
+ assert listing["results"] == []
+
+ def test_delete_requires_editor_on_every_wired_table(self) -> None:
+ destination = self._create_destination()
+ ExternalDataSourceDestination.objects.for_team(self.team.pk).create(
+ team_id=self.team.pk, source=self.source, destination=destination
+ )
+
+ with patch.object(ExternalDataDestinationViewSet, "_assert_can_mutate", side_effect=PermissionDenied("nope")):
+ response = self.client.delete(f"{self.base}/{destination.id}")
+
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+ destination.refresh_from_db()
+ assert destination.deleted is False
+ assert ExternalDataSourceDestination.objects.for_team(self.team.pk).count() == 1
+
+ def test_update_requires_editor_on_every_wired_table(self) -> None:
+ destination = self._create_destination()
+ ExternalDataSchemaDestination.objects.for_team(self.team.pk).create(
+ team_id=self.team.pk, schema=self.schema, destination=destination
+ )
+
+ with patch.object(ExternalDataDestinationViewSet, "_assert_can_mutate", side_effect=PermissionDenied("nope")):
+ response = self.client.patch(f"{self.base}/{destination.id}", {"name": "renamed"})
+
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+ destination.refresh_from_db()
+ assert destination.name == "analytics postgres"
+
+
+class TestDestinationLinkEndpoints(DestinationAPITestBase):
+ def setUp(self) -> None:
+ super().setUp()
+ self.destination = self._create_destination()
+ self.source_url = f"/api/projects/{self.team.pk}/external_data_sources/{self.source.id}/destinations"
+ self.schema_url = f"/api/projects/{self.team.pk}/external_data_schemas/{self.schema.id}/destinations"
+
+ def test_setting_source_destinations_round_trips(self) -> None:
+ patch = self.client.patch(self.source_url, {"destination_ids": [str(self.destination.id)]})
+
+ assert patch.status_code == status.HTTP_200_OK, patch.json()
+ assert self.client.get(self.source_url).json()["destination_ids"] == [str(self.destination.id)]
+
+ def test_setting_source_destinations_replaces_the_previous_set(self) -> None:
+ other = self._create_destination(name="second", integration=self._integration().pk)
+ self.client.patch(self.source_url, {"destination_ids": [str(self.destination.id)]})
+
+ self.client.patch(self.source_url, {"destination_ids": [str(other.id)]})
+
+ assert self.client.get(self.source_url).json()["destination_ids"] == [str(other.id)]
+
+ def test_an_unknown_destination_is_rejected(self) -> None:
+ response = self.client.patch(self.source_url, {"destination_ids": ["00000000-0000-0000-0000-000000000000"]})
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+
+ def test_a_table_inherits_its_source_until_it_is_overridden(self) -> None:
+ self.client.patch(self.source_url, {"destination_ids": [str(self.destination.id)]})
+
+ body = self.client.get(self.schema_url).json()
+
+ assert body["inherits_from_source"] is True
+ assert body["destination_ids"] is None
+ assert body["effective_destination_ids"] == [str(self.destination.id)]
+
+ def test_overriding_a_table_stops_it_following_the_source(self) -> None:
+ other = self._create_destination(name="table only", integration=self._integration().pk)
+ self.client.patch(self.source_url, {"destination_ids": [str(self.destination.id)]})
+
+ self.client.patch(self.schema_url, {"destination_ids": [str(other.id)]})
+
+ body = self.client.get(self.schema_url).json()
+ assert body["inherits_from_source"] is False
+ assert body["effective_destination_ids"] == [str(other.id)]
+
+ def test_clearing_the_override_restores_inheritance(self) -> None:
+ other = self._create_destination(name="table only", integration=self._integration().pk)
+ self.client.patch(self.source_url, {"destination_ids": [str(self.destination.id)]})
+ self.client.patch(self.schema_url, {"destination_ids": [str(other.id)]})
+
+ self.client.patch(self.schema_url, {"destination_ids": None})
+
+ body = self.client.get(self.schema_url).json()
+ assert body["inherits_from_source"] is True
+ assert body["effective_destination_ids"] == [str(self.destination.id)]
+
+ def test_an_empty_set_is_rejected_rather_than_silently_inheriting(self) -> None:
+ # With no rows left there is nothing to tell "override with nothing" apart from "no
+ # override", so accepting it would quietly fall back to the source's destinations.
+ self.client.patch(self.source_url, {"destination_ids": [str(self.destination.id)]})
+
+ response = self.client.patch(self.schema_url, {"destination_ids": []})
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ body = self.client.get(self.schema_url).json()
+ assert body["effective_destination_ids"] == [str(self.destination.id)]
+
+ def test_a_source_cannot_be_left_with_no_destinations(self) -> None:
+ response = self.client.patch(self.source_url, {"destination_ids": []})
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+
+ def test_a_rejected_override_leaves_the_previous_one_in_place(self) -> None:
+ # There are no ATOMIC_REQUESTS, so clearing the override before validating the
+ # replacement would commit the clear and re-route the table to its source.
+ other = self._create_destination(name="table only", integration=self._integration().pk)
+ self.client.patch(self.source_url, {"destination_ids": [str(self.destination.id)]})
+ self.client.patch(self.schema_url, {"destination_ids": [str(other.id)]})
+
+ response = self.client.patch(self.schema_url, {"destination_ids": ["00000000-0000-0000-0000-000000000000"]})
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ body = self.client.get(self.schema_url).json()
+ assert body["inherits_from_source"] is False
+ assert body["destination_ids"] == [str(other.id)]
diff --git a/products/warehouse_sources/backend/tests/api/test_external_data_source.py b/products/warehouse_sources/backend/tests/api/test_external_data_source.py
index 5ce5fea3d929..e83aa7c51f92 100644
--- a/products/warehouse_sources/backend/tests/api/test_external_data_source.py
+++ b/products/warehouse_sources/backend/tests/api/test_external_data_source.py
@@ -55,6 +55,10 @@ from products.warehouse_sources.backend.facade.models import (
)
from products.warehouse_sources.backend.facade.types import IncrementalFieldType
from products.warehouse_sources.backend.models.custom_oauth2_integration import CustomOAuth2Integration
+from products.warehouse_sources.backend.models.external_data_destination import (
+ ExternalDataDestination,
+ ExternalDataSourceDestination,
+)
from products.warehouse_sources.backend.presentation.views.external_data_schema import ExternalDataSchemaSerializer
from products.warehouse_sources.backend.presentation.views.external_data_source import (
DIRECT_QUERY_UNSUPPORTED_SOURCE_MESSAGE,
@@ -324,6 +328,84 @@ class TestExternalDataSource(APIBaseTest):
source = ExternalDataSource.objects.get(id=payload["id"])
self.assertEqual(source.api_version, "2024-09-30.acacia")
+ @patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.stripe.source.StripeSource.validate_credentials",
+ return_value=(True, None),
+ )
+ def test_destinations_are_attached_before_the_first_sync_is_scheduled(self, _mock_validate):
+ # Extraction snapshots the destination set onto the run. Attaching after the schedule
+ # starts means the opening run writes to the warehouse alone, and reaching the chosen
+ # destination costs a full resync of every table.
+ integration = Integration.objects.create(
+ team=self.team, kind=Integration.IntegrationKind.POSTGRESQL, integration_id="pg-1", config={}
+ )
+ destination = ExternalDataDestination.objects.for_team(self.team.pk).create(
+ team_id=self.team.pk,
+ type=ExternalDataDestination.Type.POSTGRES,
+ name="customer postgres",
+ integration=integration,
+ config={"database": "posthog", "schema": "export"},
+ )
+
+ attached_when_scheduled: list[list[str]] = []
+
+ def record_links(schemas):
+ source_ids = {schema.source_id for schema, _ in schemas}
+ attached_when_scheduled.append(
+ [
+ str(link.destination_id)
+ for link in ExternalDataSourceDestination.objects.for_team(self.team.pk).filter(
+ source_id__in=source_ids, enabled=True
+ )
+ ]
+ )
+ return []
+
+ with patch(
+ "products.warehouse_sources.backend.presentation.views.external_data_source.bulk_create_external_data_job_schedules",
+ side_effect=record_links,
+ ):
+ response = self.client.post(
+ f"/api/environments/{self.team.pk}/external_data_sources/",
+ data={
+ "source_type": "Stripe",
+ "created_via": "web",
+ "destination_ids": [str(destination.pk)],
+ "payload": {
+ "auth_method": {"selection": "api_key", "stripe_secret_key": "sk_test_123"},
+ "schemas": [{"name": "Customer", "should_sync": True, "sync_type": "full_refresh"}],
+ },
+ },
+ )
+
+ assert response.status_code == status.HTTP_201_CREATED, response.json()
+ assert attached_when_scheduled, "the schedules were never created"
+ assert str(destination.pk) in attached_when_scheduled[0]
+
+ @patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.stripe.source.StripeSource.validate_credentials",
+ return_value=(True, None),
+ )
+ def test_a_source_created_without_destinations_is_unchanged(self, _mock_validate):
+ response = self.client.post(
+ f"/api/environments/{self.team.pk}/external_data_sources/",
+ data={
+ "source_type": "Stripe",
+ "created_via": "web",
+ "payload": {
+ "auth_method": {"selection": "api_key", "stripe_secret_key": "sk_test_123"},
+ "schemas": [{"name": "Customer", "should_sync": True, "sync_type": "full_refresh"}],
+ },
+ },
+ )
+
+ assert response.status_code == status.HTTP_201_CREATED, response.json()
+ assert (
+ not ExternalDataSourceDestination.objects.for_team(self.team.pk)
+ .filter(source_id=response.json()["id"])
+ .exists()
+ )
+
@patch(
"products.warehouse_sources.backend.temporal.data_imports.sources.stripe.source.StripeSource.validate_credentials",
side_effect=AttributeError("boom"),
diff --git a/products/warehouse_sources/backend/tests/test_external_data_destination.py b/products/warehouse_sources/backend/tests/test_external_data_destination.py
new file mode 100644
index 000000000000..c3ee4f194c9f
--- /dev/null
+++ b/products/warehouse_sources/backend/tests/test_external_data_destination.py
@@ -0,0 +1,100 @@
+from posthog.test.base import BaseTest
+
+from posthog.models.team import Team
+
+from products.warehouse_sources.backend.models.external_data_destination import (
+ ExternalDataDestination,
+ ExternalDataSchemaDestination,
+ ExternalDataSourceDestination,
+ get_or_create_warehouse_destination,
+ resolve_destinations,
+)
+from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
+from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+class TestResolveDestinations(BaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.source = ExternalDataSource.objects.create(
+ team=self.team,
+ source_id="src",
+ connection_id="conn",
+ status="Running",
+ source_type=ExternalDataSourceType.STRIPE,
+ )
+ self.schema = ExternalDataSchema.objects.create(team=self.team, source=self.source, name="charges")
+
+ def _destination(
+ self, name: str, type_: str = str(ExternalDataDestination.Type.REDSHIFT)
+ ) -> ExternalDataDestination:
+ return ExternalDataDestination.objects.for_team(self.team.pk).create(
+ team_id=self.team.pk, type=type_, name=name
+ )
+
+ def test_no_links_resolves_to_the_warehouse(self) -> None:
+ resolved = resolve_destinations(self.schema)
+
+ assert [d.type for d in resolved] == [ExternalDataDestination.Type.POSTHOG_WAREHOUSE]
+
+ def test_source_links_apply_when_the_schema_has_no_override(self) -> None:
+ redshift = self._destination("redshift")
+ ExternalDataSourceDestination.objects.for_team(self.team.pk).create(
+ team_id=self.team.pk, source=self.source, destination=redshift
+ )
+
+ assert [d.id for d in resolve_destinations(self.schema)] == [redshift.id]
+
+ def test_schema_links_override_source_links(self) -> None:
+ source_level = self._destination("source-level")
+ schema_level = self._destination("schema-level", ExternalDataDestination.Type.SNOWFLAKE)
+ ExternalDataSourceDestination.objects.for_team(self.team.pk).create(
+ team_id=self.team.pk, source=self.source, destination=source_level
+ )
+ ExternalDataSchemaDestination.objects.for_team(self.team.pk).create(
+ team_id=self.team.pk, schema=self.schema, destination=schema_level
+ )
+
+ assert [d.id for d in resolve_destinations(self.schema)] == [schema_level.id]
+
+ def test_a_disabled_schema_link_does_not_fall_back_to_the_source(self) -> None:
+ source_level = self._destination("source-level")
+ schema_level = self._destination("schema-level", ExternalDataDestination.Type.SNOWFLAKE)
+ ExternalDataSourceDestination.objects.for_team(self.team.pk).create(
+ team_id=self.team.pk, source=self.source, destination=source_level
+ )
+ ExternalDataSchemaDestination.objects.for_team(self.team.pk).create(
+ team_id=self.team.pk, schema=self.schema, destination=schema_level, enabled=False
+ )
+
+ assert resolve_destinations(self.schema) == []
+
+ def test_deleted_destinations_are_excluded(self) -> None:
+ live = self._destination("live")
+ gone = self._destination("gone", ExternalDataDestination.Type.SNOWFLAKE)
+ gone.deleted = True
+ gone.save()
+ for destination in (live, gone):
+ ExternalDataSourceDestination.objects.for_team(self.team.pk).create(
+ team_id=self.team.pk, source=self.source, destination=destination
+ )
+
+ assert [d.id for d in resolve_destinations(self.schema)] == [live.id]
+
+
+class TestGetOrCreateWarehouseDestination(BaseTest):
+ def test_repeated_calls_return_the_same_row(self) -> None:
+ first = get_or_create_warehouse_destination(self.team.pk)
+ second = get_or_create_warehouse_destination(self.team.pk)
+
+ assert first.id == second.id
+ assert ExternalDataDestination.objects.for_team(self.team.pk).count() == 1
+
+ def test_each_team_gets_its_own_row(self) -> None:
+ other_team = Team.objects.create(organization=self.organization, name="Other team")
+
+ mine = get_or_create_warehouse_destination(self.team.pk)
+ theirs = get_or_create_warehouse_destination(other_team.pk)
+
+ assert mine.id != theirs.id
diff --git a/products/warehouse_sources/frontend/generated/api.schemas.ts b/products/warehouse_sources/frontend/generated/api.schemas.ts
index 779832099a79..37345e6d1696 100644
--- a/products/warehouse_sources/frontend/generated/api.schemas.ts
+++ b/products/warehouse_sources/frontend/generated/api.schemas.ts
@@ -7,6 +7,107 @@
* PostHog API - generated
* OpenAPI spec version: 1.0.0
*/
+/**
+ * * `PostHogWarehouse` - PostHog warehouse
+ * * `Redshift` - Redshift
+ * * `Snowflake` - Snowflake
+ * * `BigQuery` - BigQuery
+ * * `Postgres` - Postgres
+ * * `Databricks` - Databricks
+ * * `AzureBlob` - Azure Blob
+ * * `S3` - S3
+ */
+export type ExternalDataDestinationTypeEnumApi =
+ (typeof ExternalDataDestinationTypeEnumApi)[keyof typeof ExternalDataDestinationTypeEnumApi]
+
+export const ExternalDataDestinationTypeEnumApi = {
+ PostHogWarehouse: 'PostHogWarehouse',
+ Redshift: 'Redshift',
+ Snowflake: 'Snowflake',
+ BigQuery: 'BigQuery',
+ Postgres: 'Postgres',
+ Databricks: 'Databricks',
+ AzureBlob: 'AzureBlob',
+ S3: 'S3',
+} as const
+
+export interface ExternalDataDestinationApi {
+ readonly id: string
+ /** Where synced rows are written. The PostHog warehouse is managed for you, so you cannot create one here.
+ *
+ * * `PostHogWarehouse` - PostHog warehouse
+ * * `Redshift` - Redshift
+ * * `Snowflake` - Snowflake
+ * * `BigQuery` - BigQuery
+ * * `Postgres` - Postgres
+ * * `Databricks` - Databricks
+ * * `AzureBlob` - Azure Blob
+ * * `S3` - S3 */
+ type: ExternalDataDestinationTypeEnumApi
+ /**
+ * Human-readable name shown when picking destinations for a source or table.
+ * @maxLength 400
+ */
+ name: string
+ /** Settings for this destination: target database, schema or dataset, bucket and prefix, file format. Credentials are not stored here. They live on the linked integration. */
+ config?: unknown
+ /**
+ * Integration holding this destination's credentials. Required for every type except the PostHog warehouse.
+ * @nullable
+ */
+ integration?: number | null
+ /** Whether this is the managed PostHog warehouse destination. */
+ readonly is_posthog_warehouse: boolean
+ readonly created_at: string
+ /** @nullable */
+ readonly created_by: number | null
+ /** @nullable */
+ readonly updated_at: string | null
+}
+
+export interface PaginatedExternalDataDestinationListApi {
+ count: number
+ /** @nullable */
+ next?: string | null
+ /** @nullable */
+ previous?: string | null
+ results: ExternalDataDestinationApi[]
+}
+
+export interface PatchedExternalDataDestinationApi {
+ readonly id?: string
+ /** Where synced rows are written. The PostHog warehouse is managed for you, so you cannot create one here.
+ *
+ * * `PostHogWarehouse` - PostHog warehouse
+ * * `Redshift` - Redshift
+ * * `Snowflake` - Snowflake
+ * * `BigQuery` - BigQuery
+ * * `Postgres` - Postgres
+ * * `Databricks` - Databricks
+ * * `AzureBlob` - Azure Blob
+ * * `S3` - S3 */
+ type?: ExternalDataDestinationTypeEnumApi
+ /**
+ * Human-readable name shown when picking destinations for a source or table.
+ * @maxLength 400
+ */
+ name?: string
+ /** Settings for this destination: target database, schema or dataset, bucket and prefix, file format. Credentials are not stored here. They live on the linked integration. */
+ config?: unknown
+ /**
+ * Integration holding this destination's credentials. Required for every type except the PostHog warehouse.
+ * @nullable
+ */
+ integration?: number | null
+ /** Whether this is the managed PostHog warehouse destination. */
+ readonly is_posthog_warehouse?: boolean
+ readonly created_at?: string
+ /** @nullable */
+ readonly created_by?: number | null
+ /** @nullable */
+ readonly updated_at?: string | null
+}
+
/**
* * `full_refresh` - full_refresh
* * `incremental` - incremental
@@ -418,6 +519,29 @@ export interface PatchedExternalDataSchemaApi {
readonly user_access_level?: string | null
}
+/**
+ * Response shape for a table's destination override.
+ */
+export interface SchemaDestinationsApi {
+ /**
+ * The table's own destinations, or null when it follows its source.
+ * @nullable
+ */
+ destination_ids: string[] | null
+ /** Whether this table follows its source rather than having its own destinations. */
+ inherits_from_source: boolean
+ /** Where the table actually syncs, after inheritance is resolved. */
+ effective_destination_ids?: string[]
+}
+
+export interface PatchedDestinationLinkApi {
+ /**
+ * Destinations to sync to. On a table, null clears the override so the table follows its source again.
+ * @nullable
+ */
+ destination_ids?: string[] | null
+}
+
/**
* * `web` - web
* * `api` - api
@@ -4597,6 +4721,8 @@ export interface ExternalDataSourceCreateApi {
created_via?: ExternalDataSourceCreateCreatedViaEnumApi
/** Whether a synced source should also be live-queryable via direct connection. Defaults to false; ignored for pure direct-query sources. */
direct_query_enabled?: boolean
+ /** Destinations every table on this source writes to. Set here rather than afterwards, so the opening sync already carries them. Omit to write to the PostHog warehouse only. */
+ destination_ids?: string[]
}
export interface ExternalDataSourceCreateResponseApi {
@@ -4755,6 +4881,14 @@ export interface PatchedExternalDataSourceBulkUpdateSchemasApi {
schemas?: ExternalDataSourceBulkUpdateSchemaApi[]
}
+/**
+ * Response shape for a source's destination set.
+ */
+export interface SourceDestinationsApi {
+ /** Destinations every table on this source syncs to. */
+ destination_ids: string[]
+}
+
/**
* * `oauth` - oauth
* * `credentials` - credentials
@@ -13035,6 +13169,17 @@ export interface PaginatedWarehouseColumnStatisticsListApi {
results: WarehouseColumnStatisticsApi[]
}
+export type ExternalDataDestinationsListParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number
+}
+
export type ExternalDataSchemasListParams = {
/**
* Number of results to return per page.
diff --git a/products/warehouse_sources/frontend/generated/api.ts b/products/warehouse_sources/frontend/generated/api.ts
index 8df1c3577a23..7f10bc06dba0 100644
--- a/products/warehouse_sources/frontend/generated/api.ts
+++ b/products/warehouse_sources/frontend/generated/api.ts
@@ -13,6 +13,8 @@ import type {
DirectConnectionSourceOptionApi,
DraftCustomManifestRequestApi,
DraftCustomManifestResponseApi,
+ ExternalDataDestinationApi,
+ ExternalDataDestinationsListParams,
ExternalDataSchemaApi,
ExternalDataSchemasCancelCreate200,
ExternalDataSchemasListParams,
@@ -31,15 +33,20 @@ import type {
ExternalDataSourcesStoredCredentialsListParams,
ExternalDataSourcesWizardRetrieveParams,
IntegrationAccountsResponseApi,
+ PaginatedExternalDataDestinationListApi,
PaginatedExternalDataSchemaListApi,
PaginatedExternalDataSourceSerializersListApi,
PaginatedWarehouseColumnStatisticsListApi,
+ PatchedDestinationLinkApi,
+ PatchedExternalDataDestinationApi,
PatchedExternalDataSchemaApi,
PatchedExternalDataSourceBulkUpdateSchemasApi,
PatchedExternalDataSourceSerializersApi,
+ SchemaDestinationsApi,
SourceConnectLinkApi,
SourceCredentialApi,
SourceCredentialCreateApi,
+ SourceDestinationsApi,
SourcePreviewRequestApi,
SourcePreviewResponseApi,
SourceSetupApi,
@@ -65,6 +72,153 @@ type NonReadonly<T> = [T] extends [UnionToIntersection<T>]
}
: DistributeReadOnlyOverUnions<T>
+export const getExternalDataDestinationsListUrl = (projectId: string, params?: ExternalDataDestinationsListParams) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/external_data_destinations/?${stringifiedParams}`
+ : `/api/projects/${projectId}/external_data_destinations/`
+}
+
+/**
+ * Manage where warehouse sources write their synced rows.
+ *
+ * A destination can be attached to several sources, or to a single table on a source.
+ * Credentials come from an integration, so one connection can be reused across syncs.
+ */
+export const externalDataDestinationsList = async (
+ projectId: string,
+ params?: ExternalDataDestinationsListParams,
+ options?: RequestInit
+): Promise<PaginatedExternalDataDestinationListApi> => {
+ return apiMutator<PaginatedExternalDataDestinationListApi>(getExternalDataDestinationsListUrl(projectId, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getExternalDataDestinationsCreateUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/external_data_destinations/`
+}
+
+/**
+ * Manage where warehouse sources write their synced rows.
+ *
+ * A destination can be attached to several sources, or to a single table on a source.
+ * Credentials come from an integration, so one connection can be reused across syncs.
+ */
+export const externalDataDestinationsCreate = async (
+ projectId: string,
+ externalDataDestinationApi: NonReadonly<ExternalDataDestinationApi>,
+ options?: RequestInit
+): Promise<ExternalDataDestinationApi> => {
+ return apiMutator<ExternalDataDestinationApi>(getExternalDataDestinationsCreateUrl(projectId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(externalDataDestinationApi),
+ })
+}
+
+export const getExternalDataDestinationsRetrieveUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/external_data_destinations/${id}/`
+}
+
+/**
+ * Manage where warehouse sources write their synced rows.
+ *
+ * A destination can be attached to several sources, or to a single table on a source.
+ * Credentials come from an integration, so one connection can be reused across syncs.
+ */
+export const externalDataDestinationsRetrieve = async (
+ projectId: string,
+ id: string,
+ options?: RequestInit
+): Promise<ExternalDataDestinationApi> => {
+ return apiMutator<ExternalDataDestinationApi>(getExternalDataDestinationsRetrieveUrl(projectId, id), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getExternalDataDestinationsUpdateUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/external_data_destinations/${id}/`
+}
+
+/**
+ * Manage where warehouse sources write their synced rows.
+ *
+ * A destination can be attached to several sources, or to a single table on a source.
+ * Credentials come from an integration, so one connection can be reused across syncs.
+ */
+export const externalDataDestinationsUpdate = async (
+ projectId: string,
+ id: string,
+ externalDataDestinationApi: NonReadonly<ExternalDataDestinationApi>,
+ options?: RequestInit
+): Promise<ExternalDataDestinationApi> => {
+ return apiMutator<ExternalDataDestinationApi>(getExternalDataDestinationsUpdateUrl(projectId, id), {
+ ...options,
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(externalDataDestinationApi),
+ })
+}
+
+export const getExternalDataDestinationsPartialUpdateUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/external_data_destinations/${id}/`
+}
+
+/**
+ * Manage where warehouse sources write their synced rows.
+ *
+ * A destination can be attached to several sources, or to a single table on a source.
+ * Credentials come from an integration, so one connection can be reused across syncs.
+ */
+export const externalDataDestinationsPartialUpdate = async (
+ projectId: string,
+ id: string,
+ patchedExternalDataDestinationApi?: NonReadonly<PatchedExternalDataDestinationApi>,
+ options?: RequestInit
+): Promise<ExternalDataDestinationApi> => {
+ return apiMutator<ExternalDataDestinationApi>(getExternalDataDestinationsPartialUpdateUrl(projectId, id), {
+ ...options,
+ method: 'PATCH',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(patchedExternalDataDestinationApi),
+ })
+}
+
+export const getExternalDataDestinationsDestroyUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/external_data_destinations/${id}/`
+}
+
+/**
+ * Soft-delete, and detach it from everything that syncs to it.
+ *
+ * Runs already in flight keep their own snapshot of the destination, so deleting one
+ * never strands a run part-way through. The next run of each affected table resolves
+ * without it.
+ */
+export const externalDataDestinationsDestroy = async (
+ projectId: string,
+ id: string,
+ options?: RequestInit
+): Promise<void> => {
+ return apiMutator<void>(getExternalDataDestinationsDestroyUrl(projectId, id), {
+ ...options,
+ method: 'DELETE',
+ })
+}
+
export const getExternalDataSchemasListUrl = (projectId: string, params?: ExternalDataSchemasListParams) => {
const normalizedParams = new URLSearchParams()
@@ -188,6 +342,49 @@ export const externalDataSchemasDeleteDataDestroy = async (
})
}
+export const getExternalDataSchemasDestinationsRetrieveUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/external_data_schemas/${id}/destinations/`
+}
+
+/**
+ * Read or replace this table's destination override.
+ *
+ * Send `destination_ids: null` to clear the override so the table follows its source again.
+ */
+export const externalDataSchemasDestinationsRetrieve = async (
+ projectId: string,
+ id: string,
+ options?: RequestInit
+): Promise<SchemaDestinationsApi> => {
+ return apiMutator<SchemaDestinationsApi>(getExternalDataSchemasDestinationsRetrieveUrl(projectId, id), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getExternalDataSchemasDestinationsPartialUpdateUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/external_data_schemas/${id}/destinations/`
+}
+
+/**
+ * Read or replace this table's destination override.
+ *
+ * Send `destination_ids: null` to clear the override so the table follows its source again.
+ */
+export const externalDataSchemasDestinationsPartialUpdate = async (
+ projectId: string,
+ id: string,
+ patchedDestinationLinkApi?: PatchedDestinationLinkApi,
+ options?: RequestInit
+): Promise<SchemaDestinationsApi> => {
+ return apiMutator<SchemaDestinationsApi>(getExternalDataSchemasDestinationsPartialUpdateUrl(projectId, id), {
+ ...options,
+ method: 'PATCH',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(patchedDestinationLinkApi),
+ })
+}
+
export const getExternalDataSchemasIncrementalFieldsCreateUrl = (projectId: string, id: string) => {
return `/api/projects/${projectId}/external_data_schemas/${id}/incremental_fields/`
}
@@ -532,6 +729,49 @@ export const externalDataSourcesDeleteWebhookCreate = async (
})
}
+export const getExternalDataSourcesDestinationsRetrieveUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/external_data_sources/${id}/destinations/`
+}
+
+/**
+ * Read or replace the destinations every table on this source syncs to.
+ *
+ * A table with its own override ignores this set until the override is cleared.
+ */
+export const externalDataSourcesDestinationsRetrieve = async (
+ projectId: string,
+ id: string,
+ options?: RequestInit
+): Promise<SourceDestinationsApi> => {
+ return apiMutator<SourceDestinationsApi>(getExternalDataSourcesDestinationsRetrieveUrl(projectId, id), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getExternalDataSourcesDestinationsPartialUpdateUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/external_data_sources/${id}/destinations/`
+}
+
+/**
+ * Read or replace the destinations every table on this source syncs to.
+ *
+ * A table with its own override ignores this set until the override is cleared.
+ */
+export const externalDataSourcesDestinationsPartialUpdate = async (
+ projectId: string,
+ id: string,
+ patchedDestinationLinkApi?: PatchedDestinationLinkApi,
+ options?: RequestInit
+): Promise<SourceDestinationsApi> => {
+ return apiMutator<SourceDestinationsApi>(getExternalDataSourcesDestinationsPartialUpdateUrl(projectId, id), {
+ ...options,
+ method: 'PATCH',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(patchedDestinationLinkApi),
+ })
+}
+
export const getExternalDataSourcesDisableCdcCreateUrl = (projectId: string, id: string) => {
return `/api/projects/${projectId}/external_data_sources/${id}/disable_cdc/`
}
diff --git a/products/warehouse_sources/frontend/generated/api.zod.ts b/products/warehouse_sources/frontend/generated/api.zod.ts
index 38269aac70ae..1e71a1b911cd 100644
--- a/products/warehouse_sources/frontend/generated/api.zod.ts
+++ b/products/warehouse_sources/frontend/generated/api.zod.ts
@@ -9,6 +9,113 @@
*/
import * as zod from 'zod'
+/**
+ * Manage where warehouse sources write their synced rows.
+ *
+ * A destination can be attached to several sources, or to a single table on a source.
+ * Credentials come from an integration, so one connection can be reused across syncs.
+ */
+export const externalDataDestinationsCreateBodyNameMax = 400
+
+export const ExternalDataDestinationsCreateBody = /* @__PURE__ */ zod.object({
+ type: zod
+ .enum(['PostHogWarehouse', 'Redshift', 'Snowflake', 'BigQuery', 'Postgres', 'Databricks', 'AzureBlob', 'S3'])
+ .describe(
+ '\* `PostHogWarehouse` - PostHog warehouse\n\* `Redshift` - Redshift\n\* `Snowflake` - Snowflake\n\* `BigQuery` - BigQuery\n\* `Postgres` - Postgres\n\* `Databricks` - Databricks\n\* `AzureBlob` - Azure Blob\n\* `S3` - S3'
+ )
+ .describe(
+ 'Where synced rows are written. The PostHog warehouse is managed for you, so you cannot create one here.\n\n\* `PostHogWarehouse` - PostHog warehouse\n\* `Redshift` - Redshift\n\* `Snowflake` - Snowflake\n\* `BigQuery` - BigQuery\n\* `Postgres` - Postgres\n\* `Databricks` - Databricks\n\* `AzureBlob` - Azure Blob\n\* `S3` - S3'
+ ),
+ name: zod
+ .string()
+ .max(externalDataDestinationsCreateBodyNameMax)
+ .describe('Human-readable name shown when picking destinations for a source or table.'),
+ config: zod
+ .unknown()
+ .optional()
+ .describe(
+ 'Settings for this destination: target database, schema or dataset, bucket and prefix, file format. Credentials are not stored here. They live on the linked integration.'
+ ),
+ integration: zod
+ .number()
+ .nullish()
+ .describe(
+ "Integration holding this destination's credentials. Required for every type except the PostHog warehouse."
+ ),
+})
+
+/**
+ * Manage where warehouse sources write their synced rows.
+ *
+ * A destination can be attached to several sources, or to a single table on a source.
+ * Credentials come from an integration, so one connection can be reused across syncs.
+ */
+export const externalDataDestinationsUpdateBodyNameMax = 400
+
+export const ExternalDataDestinationsUpdateBody = /* @__PURE__ */ zod.object({
+ type: zod
+ .enum(['PostHogWarehouse', 'Redshift', 'Snowflake', 'BigQuery', 'Postgres', 'Databricks', 'AzureBlob', 'S3'])
+ .describe(
+ '\* `PostHogWarehouse` - PostHog warehouse\n\* `Redshift` - Redshift\n\* `Snowflake` - Snowflake\n\* `BigQuery` - BigQuery\n\* `Postgres` - Postgres\n\* `Databricks` - Databricks\n\* `AzureBlob` - Azure Blob\n\* `S3` - S3'
+ )
+ .describe(
+ 'Where synced rows are written. The PostHog warehouse is managed for you, so you cannot create one here.\n\n\* `PostHogWarehouse` - PostHog warehouse\n\* `Redshift` - Redshift\n\* `Snowflake` - Snowflake\n\* `BigQuery` - BigQuery\n\* `Postgres` - Postgres\n\* `Databricks` - Databricks\n\* `AzureBlob` - Azure Blob\n\* `S3` - S3'
+ ),
+ name: zod
+ .string()
+ .max(externalDataDestinationsUpdateBodyNameMax)
+ .describe('Human-readable name shown when picking destinations for a source or table.'),
+ config: zod
+ .unknown()
+ .optional()
+ .describe(
+ 'Settings for this destination: target database, schema or dataset, bucket and prefix, file format. Credentials are not stored here. They live on the linked integration.'
+ ),
+ integration: zod
+ .number()
+ .nullish()
+ .describe(
+ "Integration holding this destination's credentials. Required for every type except the PostHog warehouse."
+ ),
+})
+
+/**
+ * Manage where warehouse sources write their synced rows.
+ *
+ * A destination can be attached to several sources, or to a single table on a source.
+ * Credentials come from an integration, so one connection can be reused across syncs.
+ */
+export const externalDataDestinationsPartialUpdateBodyNameMax = 400
+
+export const ExternalDataDestinationsPartialUpdateBody = /* @__PURE__ */ zod.object({
+ type: zod
+ .enum(['PostHogWarehouse', 'Redshift', 'Snowflake', 'BigQuery', 'Postgres', 'Databricks', 'AzureBlob', 'S3'])
+ .describe(
+ '\* `PostHogWarehouse` - PostHog warehouse\n\* `Redshift` - Redshift\n\* `Snowflake` - Snowflake\n\* `BigQuery` - BigQuery\n\* `Postgres` - Postgres\n\* `Databricks` - Databricks\n\* `AzureBlob` - Azure Blob\n\* `S3` - S3'
+ )
+ .optional()
+ .describe(
+ 'Where synced rows are written. The PostHog warehouse is managed for you, so you cannot create one here.\n\n\* `PostHogWarehouse` - PostHog warehouse\n\* `Redshift` - Redshift\n\* `Snowflake` - Snowflake\n\* `BigQuery` - BigQuery\n\* `Postgres` - Postgres\n\* `Databricks` - Databricks\n\* `AzureBlob` - Azure Blob\n\* `S3` - S3'
+ ),
+ name: zod
+ .string()
+ .max(externalDataDestinationsPartialUpdateBodyNameMax)
+ .optional()
+ .describe('Human-readable name shown when picking destinations for a source or table.'),
+ config: zod
+ .unknown()
+ .optional()
+ .describe(
+ 'Settings for this destination: target database, schema or dataset, bucket and prefix, file format. Credentials are not stored here. They live on the linked integration.'
+ ),
+ integration: zod
+ .number()
+ .nullish()
+ .describe(
+ "Integration holding this destination's credentials. Required for every type except the PostHog warehouse."
+ ),
+})
+
export const externalDataSchemasUpdateBodyIncrementalFieldLookbackSecondsMin = 0
export const externalDataSchemasUpdateBodyIncrementalFieldLookbackSecondsMax = 5184000
@@ -211,6 +318,20 @@ export const ExternalDataSchemasPartialUpdateBody = /* @__PURE__ */ zod
})
.describe('A schema of an external data source: its sync configuration and the warehouse table it syncs into.')
+/**
+ * Read or replace this table's destination override.
+ *
+ * Send `destination_ids: null` to clear the override so the table follows its source again.
+ */
+export const ExternalDataSchemasDestinationsPartialUpdateBody = /* @__PURE__ */ zod.object({
+ destination_ids: zod
+ .array(zod.uuid())
+ .nullish()
+ .describe(
+ 'Destinations to sync to. On a table, null clears the override so the table follows its source again.'
+ ),
+})
+
export const externalDataSchemasIncrementalFieldsCreateBodyIncrementalFieldLookbackSecondsMin = 0
export const externalDataSchemasIncrementalFieldsCreateBodyIncrementalFieldLookbackSecondsMax = 5184000
@@ -437,6 +558,20 @@ export const ExternalDataSourcesDeleteWebhookCreateBody = /* @__PURE__ */ zod
.record(zod.string(), zod.unknown())
.describe('Deep\/recursive schema (opaque in Zod — use TypeScript types for full shape)')
+/**
+ * Read or replace the destinations every table on this source syncs to.
+ *
+ * A table with its own override ignores this set until the override is cleared.
+ */
+export const ExternalDataSourcesDestinationsPartialUpdateBody = /* @__PURE__ */ zod.object({
+ destination_ids: zod
+ .array(zod.uuid())
+ .nullish()
+ .describe(
+ 'Destinations to sync to. On a table, null clears the override so the table follows its source again.'
+ ),
+})
+
/**
* Disable CDC on an existing source.
*
diff --git a/products/warehouse_sources/mcp/tools.yaml b/products/warehouse_sources/mcp/tools.yaml
index 5ad90c0badc6..67bab6d56fda 100644
--- a/products/warehouse_sources/mcp/tools.yaml
+++ b/products/warehouse_sources/mcp/tools.yaml
@@ -89,6 +89,47 @@ tools:
the connect page, take the newest credential_id for the source type and call 'data-warehouse-source-setup'
with {'credential_id': '<uuid>'} in the payload. Stored credentials are single-use — they are deleted as
soon as setup consumes them — and expire after 24 hours if never used.
+ external-data-destinations-create:
+ operation: external_data_destinations_create
+ enabled: false
+ external-data-destinations-destroy:
+ operation: external_data_destinations_destroy
+ enabled: false
+ external-data-destinations-list:
+ operation: external_data_destinations_list
+ enabled: true
+ scopes:
+ - external_data_source:read
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ title: List warehouse destinations
+ description: >
+ List the places this project's warehouse sources can write synced rows to. The PostHog warehouse is one of
+ them, and it is where a source writes when nothing else is configured.
+ feature_flag: warehouse-multi-destination
+ external-data-destinations-partial-update:
+ operation: external_data_destinations_partial_update
+ enabled: false
+ external-data-destinations-retrieve:
+ operation: external_data_destinations_retrieve
+ enabled: true
+ scopes:
+ - external_data_source:read
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ enrich_url: '{id}'
+ title: Get a warehouse destination
+ description: >
+ Read one warehouse destination, including the target database or schema it writes to. Credentials live on
+ the linked integration and are never returned here.
+ feature_flag: warehouse-multi-destination
+ external-data-destinations-update:
+ operation: external_data_destinations_update
+ enabled: false
external-data-schemas-cancel:
operation: external_data_schemas_cancel_create
enabled: true
@@ -115,6 +156,23 @@ tools:
description: >
Delete the synced table data from PostHog but keep the schema entry. The schema remains visible in the
source and can be re-synced. Use this to clear stale or corrupt data before triggering a fresh sync.
+ external-data-schemas-destinations-partial-update:
+ operation: external_data_schemas_destinations_partial_update
+ enabled: false
+ external-data-schemas-destinations-retrieve:
+ operation: external_data_schemas_destinations_retrieve
+ enabled: true
+ scopes:
+ - external_data_source:read
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ title: Get a table's destinations
+ description: >
+ Read one table's destination override. `inherits_from_source` tells you whether the table follows its
+ source; `effective_destination_ids` is where it actually syncs once inheritance is resolved.
+ feature_flag: warehouse-multi-destination
external-data-schemas-destroy:
operation: external_data_schemas_destroy
enabled: false
@@ -340,6 +398,23 @@ tools:
are preserved — only the webhook is removed. After deletion, schemas can be switched to a polling sync_type
(incremental/full_refresh) via external-data-schemas-partial-update, or a new webhook can be created with
create-webhook.
+ external-data-sources-destinations-partial-update:
+ operation: external_data_sources_destinations_partial_update
+ enabled: false
+ external-data-sources-destinations-retrieve:
+ operation: external_data_sources_destinations_retrieve
+ enabled: true
+ scopes:
+ - external_data_source:read
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ title: Get a source's destinations
+ description: >
+ Read the destinations every table on this source syncs to. An empty list means the source writes to the
+ PostHog warehouse only, which is the default for any source nobody configured destinations for.
+ feature_flag: warehouse-multi-destination
external-data-sources-destroy:
operation: external_data_sources_destroy
enabled: true
diff --git a/products/warehouse_sources/skills/diagnosing-failed-warehouse-syncs/SKILL.md b/products/warehouse_sources/skills/diagnosing-failed-warehouse-syncs/SKILL.md
index c774c2ca1023..853de440e060 100644
--- a/products/warehouse_sources/skills/diagnosing-failed-warehouse-syncs/SKILL.md
+++ b/products/warehouse_sources/skills/diagnosing-failed-warehouse-syncs/SKILL.md
@@ -227,6 +227,11 @@ Agent:
- **Delete-data preserves config.** When a user says "I just want to start this table over from scratch", prefer
`delete-data` + `reload` over `resync` + new schema entry — it keeps the configured sync_type / incremental_field
/ PK setup.
+- **A failure can belong to a destination, not the source.** Some projects sync a source to their own database as
+ well as to PostHog. When they do, `latest_error` is prefixed with the destination's name, e.g.
+ `customer postgres: connection refused`. That is the customer's database refusing the write, not the source failing
+ to extract — check their database and its credentials rather than the source's. Every destination shares one
+ lifecycle, so one unreachable destination holds up the whole sync, PostHog included.
- **Billing limits aren't technical failures.** Don't try to retry or reconfigure your way out. Route to billing.
- **Webhook failures can hide behind a green status.** A webhook-type schema whose bulk fallback sync succeeded looks
`Completed` even when the push channel is broken. When users say "my data is hours behind" on a webhook schema,
diff --git a/products/warehouse_sources/skills/setting-up-a-data-warehouse-source/SKILL.md b/products/warehouse_sources/skills/setting-up-a-data-warehouse-source/SKILL.md
index 6f0b596bde01..e6d66331ef9b 100644
--- a/products/warehouse_sources/skills/setting-up-a-data-warehouse-source/SKILL.md
+++ b/products/warehouse_sources/skills/setting-up-a-data-warehouse-source/SKILL.md
@@ -337,6 +337,12 @@ If the user wants near-real-time replication from Postgres:
— row counts and relevance matter for billing. Let the user opt in explicitly.
- **Don't invent schemas.** Every entry in the `schemas` array must correspond to a real table from the db-schema
response. You can't "also add an orders table" unless db-schema found one.
+- **A new source syncs to the PostHog warehouse.** That is the default and it needs no setup: a source nobody
+ configured destinations for writes here and nowhere else. Some projects can also send a source's tables to their
+ own database (`external-data-sources-destinations-retrieve` shows where a source writes, when the feature is on for
+ the project). Setting that up is a separate step and never something to do as part of creating a source — adding a
+ destination to a source that has already synced leaves it holding none of the history until the tables are resynced,
+ and a resync bills every destination the source writes to.
- **Prefix is load-bearing.** It's part of every HogQL query the user will ever write against these tables. Pick
something short, descriptive, and not already taken.
- **Prefer the secure connect-link for any credentials.** Use `data-warehouse-source-connect-link` so the user
diff --git a/products/warehouse_sources_queue/backend/migrations/0010_sourcebatch_destination_ids.py b/products/warehouse_sources_queue/backend/migrations/0010_sourcebatch_destination_ids.py
new file mode 100644
index 000000000000..a9503c1e6e14
--- /dev/null
+++ b/products/warehouse_sources_queue/backend/migrations/0010_sourcebatch_destination_ids.py
@@ -0,0 +1,56 @@
+from django.db import migrations, models
+
+# Guarded with to_regclass so the migration no-ops on DBs without the sourcebatch table,
+# following 0006 and 0008. ADD COLUMN ... DEFAULT is metadata-only on PG11+, but it still
+# takes a brief ACCESS EXCLUSIVE lock on the parent and every child — lock_timeout keeps a
+# blocked attempt from queueing behind long claim queries (bin/migrate retries). The raw
+# DEFAULT is load-bearing: producer INSERTs list their columns explicitly and never mention
+# destination_ids, and it is what keeps CDC batches warehouse-only.
+_ADD_COLUMN_SQL = """
+DO $$
+BEGIN
+ IF to_regclass('public.sourcebatch') IS NOT NULL THEN
+ SET LOCAL lock_timeout = '5s';
+ ALTER TABLE sourcebatch
+ ADD COLUMN IF NOT EXISTS destination_ids jsonb NOT NULL DEFAULT '[]'::jsonb;
+ END IF;
+END
+$$;
+"""
+
+_DROP_COLUMN_SQL = """
+DO $$
+BEGIN
+ IF to_regclass('public.sourcebatch') IS NOT NULL THEN
+ SET LOCAL lock_timeout = '5s';
+ ALTER TABLE sourcebatch DROP COLUMN IF EXISTS destination_ids;
+ END IF;
+END
+$$;
+"""
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("warehouse_sources_queue", "0009_sourcebatch_job_id_idx"),
+ ]
+
+ operations = [
+ migrations.SeparateDatabaseAndState(
+ state_operations=[
+ migrations.AddField(
+ model_name="sourcebatch",
+ name="destination_ids",
+ field=models.JSONField(
+ blank=True,
+ db_default=[],
+ default=list,
+ help_text="ExternalDataDestination ids this batch is delivered to. Empty means the PostHog warehouse only.",
+ ),
+ ),
+ ],
+ database_operations=[
+ migrations.RunSQL(sql=_ADD_COLUMN_SQL, reverse_sql=_DROP_COLUMN_SQL),
+ ],
+ ),
+ ]
diff --git a/products/warehouse_sources_queue/backend/migrations/max_migration.txt b/products/warehouse_sources_queue/backend/migrations/max_migration.txt
index c20d00388cb0..fba75b8ea0ec 100644
--- a/products/warehouse_sources_queue/backend/migrations/max_migration.txt
+++ b/products/warehouse_sources_queue/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0009_sourcebatch_job_id_idx
+0010_sourcebatch_destination_ids
diff --git a/products/warehouse_sources_queue/backend/models.py b/products/warehouse_sources_queue/backend/models.py
index f5b73afcaf88..69bd1df56f7a 100644
--- a/products/warehouse_sources_queue/backend/models.py
+++ b/products/warehouse_sources_queue/backend/models.py
@@ -46,6 +46,19 @@ class SourceBatch(UUIDModel):
help_text="Stores partitioning config, CDC mode, primary keys, schema path, data folder, etc.",
)
+ # The destinations this batch is delivered to, snapshotted when the run started so a
+ # config change mid-run cannot alter where an in-flight batch lands. The batch is done
+ # only once every id here has taken it, which is what keeps destinations in step.
+ # db_default matters: `jobs_db.insert_batch` writes this table with raw SQL that does not
+ # list this column, so without a Postgres-level default that insert would violate NOT NULL.
+ # It also gives CDC batches the right value, since CDC stays warehouse-only for now.
+ destination_ids = models.JSONField(
+ default=list,
+ blank=True,
+ db_default=[],
+ help_text="ExternalDataDestination ids this batch is delivered to. Empty means the PostHog warehouse only.",
+ )
+
# Denormalized mirror of the latest sourcebatchstatus row, maintained by the
# dual-write CTEs in jobs_db so hot readers don't re-derive state from the
# append-only log. sourcebatchstatus remains the source of truth.
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 849c1882272d..ab40d9d9b926 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -4439,6 +4439,36 @@
},
"feature_flag": "experiment-behavior-comparison"
},
+ "external-data-destinations-list": {
+ "description": "List the places this project's warehouse sources can write synced rows to. The PostHog warehouse is one of them, and it is where a source writes when nothing else is configured.",
+ "category": "Warehouse sources",
+ "feature": "warehouse_sources",
+ "summary": "List warehouse destinations",
+ "title": "List warehouse destinations",
+ "required_scopes": ["external_data_source:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "warehouse-multi-destination"
+ },
+ "external-data-destinations-retrieve": {
+ "description": "Read one warehouse destination, including the target database or schema it writes to. Credentials live on the linked integration and are never returned here.",
+ "category": "Warehouse sources",
+ "feature": "warehouse_sources",
+ "summary": "Get a warehouse destination",
+ "title": "Get a warehouse destination",
+ "required_scopes": ["external_data_source:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "warehouse-multi-destination"
+ },
"external-data-schemas-cancel": {
"description": "Cancel a currently running sync job for a specific table schema. If no sync is running, returns an error. Use 'external-data-schemas-list' to check which schemas have status 'Running' before calling this.",
"category": "Warehouse sources",
@@ -4467,6 +4497,21 @@
"readOnlyHint": false
}
},
+ "external-data-schemas-destinations-retrieve": {
+ "description": "Read one table's destination override. `inherits_from_source` tells you whether the table follows its source; `effective_destination_ids` is where it actually syncs once inheritance is resolved.",
+ "category": "Warehouse sources",
+ "feature": "warehouse_sources",
+ "summary": "Get a table's destinations",
+ "title": "Get a table's destinations",
+ "required_scopes": ["external_data_source:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "warehouse-multi-destination"
+ },
"external-data-schemas-incremental-fields-create": {
"description": "Re-inspect the source for a single table schema and return the currently available incremental fields, detected primary keys, column list, and which sync methods (incremental/append/cdc/webhook) are available. Use this when the source schema has changed, an incremental field has been dropped, or the user wants to switch to a different incremental_field/sync_type on an existing schema. The operation_id is external_data_schemas_incremental_fields_create but semantically this is a read-only refresh.",
"category": "Warehouse sources",
@@ -4621,6 +4666,21 @@
"readOnlyHint": false
}
},
+ "external-data-sources-destinations-retrieve": {
+ "description": "Read the destinations every table on this source syncs to. An empty list means the source writes to the PostHog warehouse only, which is the default for any source nobody configured destinations for.",
+ "category": "Warehouse sources",
+ "feature": "warehouse_sources",
+ "summary": "Get a source's destinations",
+ "title": "Get a source's destinations",
+ "required_scopes": ["external_data_source:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "warehouse-multi-destination"
+ },
"external-data-sources-destroy": {
"description": "Delete a data warehouse source and all its table schemas, synced tables, and sync schedules. This is a soft delete. Any running syncs are cancelled first. This cannot be undone — the source must be recreated to resume syncing.",
"category": "Warehouse sources",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index bb4b36a4c866..a680b0152b6c 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -4538,6 +4538,36 @@
},
"feature_flag": "experiment-behavior-comparison"
},
+ "external-data-destinations-list": {
+ "description": "List the places this project's warehouse sources can write synced rows to. The PostHog warehouse is one of them, and it is where a source writes when nothing else is configured.",
+ "category": "Warehouse sources",
+ "feature": "warehouse_sources",
+ "summary": "List warehouse destinations",
+ "title": "List warehouse destinations",
+ "required_scopes": ["external_data_source:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "warehouse-multi-destination"
+ },
+ "external-data-destinations-retrieve": {
+ "description": "Read one warehouse destination, including the target database or schema it writes to. Credentials live on the linked integration and are never returned here.",
+ "category": "Warehouse sources",
+ "feature": "warehouse_sources",
+ "summary": "Get a warehouse destination",
+ "title": "Get a warehouse destination",
+ "required_scopes": ["external_data_source:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "warehouse-multi-destination"
+ },
"external-data-schemas-cancel": {
"description": "Cancel a currently running sync job for a specific table schema. If no sync is running, returns an error. Use 'external-data-schemas-list' to check which schemas have status 'Running' before calling this.",
"category": "Warehouse sources",
@@ -4566,6 +4596,21 @@
"readOnlyHint": false
}
},
+ "external-data-schemas-destinations-retrieve": {
+ "description": "Read one table's destination override. `inherits_from_source` tells you whether the table follows its source; `effective_destination_ids` is where it actually syncs once inheritance is resolved.",
+ "category": "Warehouse sources",
+ "feature": "warehouse_sources",
+ "summary": "Get a table's destinations",
+ "title": "Get a table's destinations",
+ "required_scopes": ["external_data_source:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "warehouse-multi-destination"
+ },
"external-data-schemas-incremental-fields-create": {
"description": "Re-inspect the source for a single table schema and return the currently available incremental fields, detected primary keys, column list, and which sync methods (incremental/append/cdc/webhook) are available. Use this when the source schema has changed, an incremental field has been dropped, or the user wants to switch to a different incremental_field/sync_type on an existing schema. The operation_id is external_data_schemas_incremental_fields_create but semantically this is a read-only refresh.",
"category": "Warehouse sources",
@@ -4734,6 +4779,21 @@
"readOnlyHint": false
}
},
+ "external-data-sources-destinations-retrieve": {
+ "description": "Read the destinations every table on this source syncs to. An empty list means the source writes to the PostHog warehouse only, which is the default for any source nobody configured destinations for.",
+ "category": "Warehouse sources",
+ "feature": "warehouse_sources",
+ "summary": "Get a source's destinations",
+ "title": "Get a source's destinations",
+ "required_scopes": ["external_data_source:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "warehouse-multi-destination"
+ },
"external-data-sources-destroy": {
"description": "Delete a data warehouse source and all its table schemas, synced tables, and sync schedules. This is a soft delete. Any running syncs are cancelled first. This cannot be undone — the source must be recreated to resume syncing.",
"category": "Warehouse sources",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 4950c0322ea3..e597014190b7 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -35760,6 +35760,64 @@ export namespace Schemas {
error: ExternalAccountListValidationErrorError;
}
+ /**
+ * * `PostHogWarehouse` - PostHog warehouse
+ * * `Redshift` - Redshift
+ * * `Snowflake` - Snowflake
+ * * `BigQuery` - BigQuery
+ * * `Postgres` - Postgres
+ * * `Databricks` - Databricks
+ * * `AzureBlob` - Azure Blob
+ * * `S3` - S3
+ */
+ export type ExternalDataDestinationTypeEnum = typeof ExternalDataDestinationTypeEnum[keyof typeof ExternalDataDestinationTypeEnum];
+
+
+ export const ExternalDataDestinationTypeEnum = {
+ PostHogWarehouse: 'PostHogWarehouse',
+ Redshift: 'Redshift',
+ Snowflake: 'Snowflake',
+ BigQuery: 'BigQuery',
+ Postgres: 'Postgres',
+ Databricks: 'Databricks',
+ AzureBlob: 'AzureBlob',
+ S3: 'S3',
+ } as const;
+
+ export interface ExternalDataDestination {
+ readonly id: string;
+ /** Where synced rows are written. The PostHog warehouse is managed for you, so you cannot create one here.
+ *
+ * * `PostHogWarehouse` - PostHog warehouse
+ * * `Redshift` - Redshift
+ * * `Snowflake` - Snowflake
+ * * `BigQuery` - BigQuery
+ * * `Postgres` - Postgres
+ * * `Databricks` - Databricks
+ * * `AzureBlob` - Azure Blob
+ * * `S3` - S3 */
+ type: ExternalDataDestinationTypeEnum;
+ /**
+ * Human-readable name shown when picking destinations for a source or table.
+ * @maxLength 400
+ */
+ name: string;
+ /** Settings for this destination: target database, schema or dataset, bucket and prefix, file format. Credentials are not stored here. They live on the linked integration. */
+ config?: unknown;
+ /**
+ * Integration holding this destination's credentials. Required for every type except the PostHog warehouse.
+ * @nullable
+ */
+ integration?: number | null;
+ /** Whether this is the managed PostHog warehouse destination. */
+ readonly is_posthog_warehouse: boolean;
+ readonly created_at: string;
+ /** @nullable */
+ readonly created_by: number | null;
+ /** @nullable */
+ readonly updated_at: string | null;
+ }
+
/**
* @nullable
*/
@@ -38809,6 +38867,8 @@ export namespace Schemas {
created_via?: ExternalDataSourceCreateCreatedViaEnum;
/** Whether a synced source should also be live-queryable via direct connection. Defaults to false; ignored for pure direct-query sources. */
direct_query_enabled?: boolean;
+ /** Destinations every table on this source writes to. Set here rather than afterwards, so the opening sync already carries them. Omit to write to the PostHog warehouse only. */
+ destination_ids?: string[];
}
export interface ExternalDataSourceCreateResponse {
@@ -54441,6 +54501,15 @@ export namespace Schemas {
results: ExportedAsset[];
}
+ export interface PaginatedExternalDataDestinationList {
+ count: number;
+ /** @nullable */
+ next?: string | null;
+ /** @nullable */
+ previous?: string | null;
+ results: ExternalDataDestination[];
+ }
+
export interface PaginatedExternalDataSchemaList {
count: number;
/** @nullable */
@@ -61411,6 +61480,14 @@ export namespace Schemas {
operations?: DesignOperation[];
}
+ export interface PatchedDestinationLink {
+ /**
+ * Destinations to sync to. On a table, null clears the override so the table follows its source again.
+ * @nullable
+ */
+ destination_ids?: string[] | null;
+ }
+
/**
* Feature flag payload for this early access feature
*/
@@ -62330,6 +62407,40 @@ export namespace Schemas {
readonly user_access_level?: string | null;
}
+ export interface PatchedExternalDataDestination {
+ readonly id?: string;
+ /** Where synced rows are written. The PostHog warehouse is managed for you, so you cannot create one here.
+ *
+ * * `PostHogWarehouse` - PostHog warehouse
+ * * `Redshift` - Redshift
+ * * `Snowflake` - Snowflake
+ * * `BigQuery` - BigQuery
+ * * `Postgres` - Postgres
+ * * `Databricks` - Databricks
+ * * `AzureBlob` - Azure Blob
+ * * `S3` - S3 */
+ type?: ExternalDataDestinationTypeEnum;
+ /**
+ * Human-readable name shown when picking destinations for a source or table.
+ * @maxLength 400
+ */
+ name?: string;
+ /** Settings for this destination: target database, schema or dataset, bucket and prefix, file format. Credentials are not stored here. They live on the linked integration. */
+ config?: unknown;
+ /**
+ * Integration holding this destination's credentials. Required for every type except the PostHog warehouse.
+ * @nullable
+ */
+ integration?: number | null;
+ /** Whether this is the managed PostHog warehouse destination. */
+ readonly is_posthog_warehouse?: boolean;
+ readonly created_at?: string;
+ /** @nullable */
+ readonly created_by?: number | null;
+ /** @nullable */
+ readonly updated_at?: string | null;
+ }
+
/**
* @nullable
*/
@@ -76418,6 +76529,21 @@ export namespace Schemas {
by_type: ScannerStatsByType;
}
+ /**
+ * Response shape for a table's destination override.
+ */
+ export interface SchemaDestinations {
+ /**
+ * The table's own destinations, or null when it follows its source.
+ * @nullable
+ */
+ destination_ids: string[] | null;
+ /** Whether this table follows its source rather than having its own destinations. */
+ inherits_from_source: boolean;
+ /** Where the table actually syncs, after inheritance is resolved. */
+ effective_destination_ids?: string[];
+ }
+
export interface ScoreDefinitionCreate {
/**
* Human-readable scorer name.
@@ -79367,6 +79493,14 @@ export namespace Schemas {
payload: SourceCredentialCreatePayload;
}
+ /**
+ * Response shape for a source's destination set.
+ */
+ export interface SourceDestinations {
+ /** Destinations every table on this source syncs to. */
+ destination_ids: string[];
+ }
+
export interface SourceMappingSuggestion {
/** The raw utm_source value seen on events */
raw_utm_source: string;
@@ -94027,6 +94161,17 @@ export namespace Schemas {
offset?: number;
};
+ export type ExternalDataDestinationsListParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number;
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number;
+ };
+
export type ExternalDataSchemasListParams = {
/**
* Number of results to return per page.
diff --git a/services/mcp/src/generated/warehouse_sources/api.ts b/services/mcp/src/generated/warehouse_sources/api.ts
index f9da62f520f6..0c15497e8af2 100644
--- a/services/mcp/src/generated/warehouse_sources/api.ts
+++ b/services/mcp/src/generated/warehouse_sources/api.ts
@@ -3,11 +3,45 @@
* MCP service uses these Zod schemas for generated tool handlers.
* To regenerate: hogli build:openapi
*
- * PostHog API - MCP 26 enabled ops
+ * PostHog API - MCP 30 enabled ops
* OpenAPI spec version: 1.0.0
*/
import * as zod from 'zod'
+/**
+ * Manage where warehouse sources write their synced rows.
+ *
+ * A destination can be attached to several sources, or to a single table on a source.
+ * Credentials come from an integration, so one connection can be reused across syncs.
+ */
+export const ExternalDataDestinationsListParams = /* @__PURE__ */ zod.object({
+ project_id: zod
+ .string()
+ .describe(
+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."
+ ),
+})
+
+export const ExternalDataDestinationsListQueryParams = /* @__PURE__ */ zod.object({
+ limit: zod.number().optional().describe('Number of results to return per page.'),
+ offset: zod.number().optional().describe('The initial index from which to return the results.'),
+})
+
+/**
+ * Manage where warehouse sources write their synced rows.
+ *
+ * A destination can be attached to several sources, or to a single table on a source.
+ * Credentials come from an integration, so one connection can be reused across syncs.
+ */
+export const ExternalDataDestinationsRetrieveParams = /* @__PURE__ */ zod.object({
+ id: zod.string().describe('A UUID string identifying this external data destination.'),
+ project_id: zod
+ .string()
+ .describe(
+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."
+ ),
+})
+
export const ExternalDataSchemasListParams = /* @__PURE__ */ zod.object({
project_id: zod
.string()
@@ -159,6 +193,20 @@ export const ExternalDataSchemasDeleteDataDestroyParams = /* @__PURE__ */ zod.ob
),
})
+/**
+ * Read or replace this table's destination override.
+ *
+ * Send `destination_ids: null` to clear the override so the table follows its source again.
+ */
+export const ExternalDataSchemasDestinationsRetrieveParams = /* @__PURE__ */ zod.object({
+ id: zod.string().describe('A UUID string identifying this external data schema.'),
+ project_id: zod
+ .string()
+ .describe(
+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."
+ ),
+})
+
export const ExternalDataSchemasIncrementalFieldsCreateParams = /* @__PURE__ */ zod.object({
id: zod.string().describe('A UUID string identifying this external data schema.'),
project_id: zod
@@ -1687,6 +1735,12 @@ export const ExternalDataSourcesCreateBody = /* @__PURE__ */ zod.object({
.describe(
'Whether a synced source should also be live-queryable via direct connection. Defaults to false; ignored for pure direct-query sources.'
),
+ destination_ids: zod
+ .array(zod.string())
+ .optional()
+ .describe(
+ 'Destinations every table on this source writes to. Set here rather than afterwards, so the opening sync already carries them. Omit to write to the PostHog warehouse only.'
+ ),
})
/**
@@ -1914,6 +1968,20 @@ export const ExternalDataSourcesDeleteWebhookCreateBody = /* @__PURE__ */ zod
})
.describe('Mixin for serializers to add user access control fields')
+/**
+ * Read or replace the destinations every table on this source syncs to.
+ *
+ * A table with its own override ignores this set until the override is cleared.
+ */
+export const ExternalDataSourcesDestinationsRetrieveParams = /* @__PURE__ */ zod.object({
+ id: zod.string().describe('A UUID string identifying this external data source.'),
+ project_id: zod
+ .string()
+ .describe(
+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."
+ ),
+})
+
/**
* Fetch current schema/table list from the source and create any new ExternalDataSchema rows (no data sync).
*/
diff --git a/services/mcp/src/tools/generated/warehouse_sources.ts b/services/mcp/src/tools/generated/warehouse_sources.ts
index c964e4838817..7ed66e04dd23 100644
--- a/services/mcp/src/tools/generated/warehouse_sources.ts
+++ b/services/mcp/src/tools/generated/warehouse_sources.ts
@@ -3,8 +3,11 @@ import { z } from 'zod'
import type { Schemas } from '@/api/generated'
import {
+ ExternalDataDestinationsListQueryParams,
+ ExternalDataDestinationsRetrieveParams,
ExternalDataSchemasCancelCreateParams,
ExternalDataSchemasDeleteDataDestroyParams,
+ ExternalDataSchemasDestinationsRetrieveParams,
ExternalDataSchemasIncrementalFieldsCreateBody,
ExternalDataSchemasIncrementalFieldsCreateParams,
ExternalDataSchemasListQueryParams,
@@ -19,6 +22,7 @@ import {
ExternalDataSourcesCreateWebhookCreateParams,
ExternalDataSourcesDeleteWebhookCreateBody,
ExternalDataSourcesDeleteWebhookCreateParams,
+ ExternalDataSourcesDestinationsRetrieveParams,
ExternalDataSourcesDestroyParams,
ExternalDataSourcesListQueryParams,
ExternalDataSourcesPartialUpdateBody,
@@ -119,6 +123,46 @@ const dataWarehouseStoredCredentialsList = (): ToolBase<
},
})
+const ExternalDataDestinationsListSchema = ExternalDataDestinationsListQueryParams
+
+const externalDataDestinationsList = (): ToolBase<
+ typeof ExternalDataDestinationsListSchema,
+ Schemas.PaginatedExternalDataDestinationList
+> => ({
+ name: 'external-data-destinations-list',
+ schema: ExternalDataDestinationsListSchema,
+ handler: async (context: Context, params: z.infer<typeof ExternalDataDestinationsListSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.PaginatedExternalDataDestinationList>({
+ method: 'GET',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/external_data_destinations/`,
+ query: {
+ limit: params.limit,
+ offset: params.offset,
+ },
+ })
+ return result
+ },
+})
+
+const ExternalDataDestinationsRetrieveSchema = ExternalDataDestinationsRetrieveParams.omit({ project_id: true })
+
+const externalDataDestinationsRetrieve = (): ToolBase<
+ typeof ExternalDataDestinationsRetrieveSchema,
+ WithPostHogUrl<Schemas.ExternalDataDestination>
+> => ({
+ name: 'external-data-destinations-retrieve',
+ schema: ExternalDataDestinationsRetrieveSchema,
+ handler: async (context: Context, params: z.infer<typeof ExternalDataDestinationsRetrieveSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.ExternalDataDestination>({
+ method: 'GET',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/external_data_destinations/${encodeURIComponent(String(params.id))}/`,
+ })
+ return await withPostHogUrl(context, result, `/data-management/sources/${result.id}`)
+ },
+})
+
const ExternalDataSchemasCancelSchema = ExternalDataSchemasCancelCreateParams.omit({ project_id: true })
const externalDataSchemasCancel = (): ToolBase<typeof ExternalDataSchemasCancelSchema, unknown> => ({
@@ -149,6 +193,26 @@ const externalDataSchemasDeleteData = (): ToolBase<typeof ExternalDataSchemasDel
},
})
+const ExternalDataSchemasDestinationsRetrieveSchema = ExternalDataSchemasDestinationsRetrieveParams.omit({
+ project_id: true,
+})
+
+const externalDataSchemasDestinationsRetrieve = (): ToolBase<
+ typeof ExternalDataSchemasDestinationsRetrieveSchema,
+ Schemas.SchemaDestinations
+> => ({
+ name: 'external-data-schemas-destinations-retrieve',
+ schema: ExternalDataSchemasDestinationsRetrieveSchema,
+ handler: async (context: Context, params: z.infer<typeof ExternalDataSchemasDestinationsRetrieveSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.SchemaDestinations>({
+ method: 'GET',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/external_data_schemas/${encodeURIComponent(String(params.id))}/destinations/`,
+ })
+ return result
+ },
+})
+
const ExternalDataSchemasIncrementalFieldsCreateSchema = ExternalDataSchemasIncrementalFieldsCreateParams.omit({
project_id: true,
}).extend(ExternalDataSchemasIncrementalFieldsCreateBody.shape)
@@ -418,6 +482,9 @@ const externalDataSourcesCreate = (): ToolBase<
if (params.direct_query_enabled !== undefined) {
body['direct_query_enabled'] = params.direct_query_enabled
}
+ if (params.destination_ids !== undefined) {
+ body['destination_ids'] = params.destination_ids
+ }
body['created_via'] = 'mcp'
const result = await context.api.request<Schemas.ExternalDataSourceCreateResponse>({
method: 'POST',
@@ -526,6 +593,26 @@ const externalDataSourcesDeleteWebhookCreate = (): ToolBase<
},
})
+const ExternalDataSourcesDestinationsRetrieveSchema = ExternalDataSourcesDestinationsRetrieveParams.omit({
+ project_id: true,
+})
+
+const externalDataSourcesDestinationsRetrieve = (): ToolBase<
+ typeof ExternalDataSourcesDestinationsRetrieveSchema,
+ Schemas.SourceDestinations
+> => ({
+ name: 'external-data-sources-destinations-retrieve',
+ schema: ExternalDataSourcesDestinationsRetrieveSchema,
+ handler: async (context: Context, params: z.infer<typeof ExternalDataSourcesDestinationsRetrieveSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.SourceDestinations>({
+ method: 'GET',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/external_data_sources/${encodeURIComponent(String(params.id))}/destinations/`,
+ })
+ return result
+ },
+})
+
const ExternalDataSourcesDestroySchema = ExternalDataSourcesDestroyParams.omit({ project_id: true })
const externalDataSourcesDestroy = (): ToolBase<typeof ExternalDataSourcesDestroySchema, unknown> => ({
@@ -817,8 +904,11 @@ export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {
'data-warehouse-source-connect-link': dataWarehouseSourceConnectLink,
'data-warehouse-source-setup': dataWarehouseSourceSetup,
'data-warehouse-stored-credentials-list': dataWarehouseStoredCredentialsList,
+ 'external-data-destinations-list': externalDataDestinationsList,
+ 'external-data-destinations-retrieve': externalDataDestinationsRetrieve,
'external-data-schemas-cancel': externalDataSchemasCancel,
'external-data-schemas-delete-data': externalDataSchemasDeleteData,
+ 'external-data-schemas-destinations-retrieve': externalDataSchemasDestinationsRetrieve,
'external-data-schemas-incremental-fields-create': externalDataSchemasIncrementalFieldsCreate,
'external-data-schemas-list': externalDataSchemasList,
'external-data-schemas-partial-update': externalDataSchemasPartialUpdate,
@@ -830,6 +920,7 @@ export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {
'external-data-sources-create': externalDataSourcesCreate,
'external-data-sources-create-webhook-create': externalDataSourcesCreateWebhookCreate,
'external-data-sources-delete-webhook-create': externalDataSourcesDeleteWebhookCreate,
+ 'external-data-sources-destinations-retrieve': externalDataSourcesDestinationsRetrieve,
'external-data-sources-destroy': externalDataSourcesDestroy,
'external-data-sources-list': externalDataSourcesList,
'external-data-sources-partial-update': externalDataSourcesPartialUpdate,
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/external-data-sources-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/external-data-sources-create.json
index b68a523b43a5..a2e32a7b943e 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/external-data-sources-create.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/external-data-sources-create.json
@@ -19,6 +19,13 @@
],
"description": "Human-readable description."
},
+ "destination_ids": {
+ "description": "Destinations every table on this source writes to. Set here rather than afterwards, so the opening sync already carries them. Omit to write to the PostHog warehouse only.",
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ },
"direct_query_enabled": {
"default": false,
"description": "Whether a synced source should also be live-queryable via direct connection. Defaults to false; ignored for pure direct-query sources.",
diff --git a/services/mcp/tests/unit/tool-filtering.test.ts b/services/mcp/tests/unit/tool-filtering.test.ts
index 0a5fb0108dd7..18a1db22263c 100644
--- a/services/mcp/tests/unit/tool-filtering.test.ts
+++ b/services/mcp/tests/unit/tool-filtering.test.ts
@@ -942,9 +942,10 @@ describe('Tool Filtering - Feature Flags', () => {
'data-warehouse-scene',
'data-quality-checks',
'context-layer',
+ 'warehouse-multi-destination',
])
)
- expect(flags).toHaveLength(33)
+ expect(flags).toHaveLength(34)
})
it('every loops tool is gated on the loops flag', () => {
diff --git a/tach.toml b/tach.toml
index 6a8d9f7ab744..01c0ce2a2eb9 100644
--- a/tach.toml
+++ b/tach.toml
@@ -322,6 +322,7 @@ path = "products.warehouse_sources"
depends_on = [
"ee",
"posthog",
+ "products.batch_exports",
"products.cdp",
"products.data_modeling",
"products.data_tools",
diff --git a/tools/hogli-commands/hogli_commands/product/isolation.py b/tools/hogli-commands/hogli_commands/product/isolation.py
index 5a5617cbf8d4..e5938cb230a0 100644
--- a/tools/hogli-commands/hogli_commands/product/isolation.py
+++ b/tools/hogli-commands/hogli_commands/product/isolation.py
@@ -522,9 +522,12 @@ MODEL_CROSSINGS: frozenset[tuple[str, str]] = frozenset(
("product_analytics", "InsightVariable"),
("warehouse_sources", "DataWarehouseCredential"),
("warehouse_sources", "DataWarehouseTable"),
+ ("warehouse_sources", "ExternalDataDestination"),
("warehouse_sources", "ExternalDataJob"),
("warehouse_sources", "ExternalDataSchema"),
+ ("warehouse_sources", "ExternalDataSchemaDestination"),
("warehouse_sources", "ExternalDataSource"),
+ ("warehouse_sources", "ExternalDataSourceDestination"),
("warehouse_sources", "PendingSourceCredential"),
("warehouse_sources", "WarehouseColumnAnnotation"),
("warehouse_sources", "WarehouseColumnStatistics"),