:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(data-warehouse): record the warehouse as a run's destination (#111794)
Tom Owers00d9ff4f7eed
diff --git a/products/warehouse_sources/backend/temporal/data_imports/destinations/enablement.py b/products/warehouse_sources/backend/temporal/data_imports/destinations/enablement.pyindex 2ea06593d4c1..e0161a58ebb5 100644--- a/products/warehouse_sources/backend/temporal/data_imports/destinations/enablement.py+++ b/products/warehouse_sources/backend/temporal/data_imports/destinations/enablement.py@@ -7,6 +7,7 @@ in-flight run's remaining batches land, and cannot change what the run bills.from __future__ import annotations+from collections.abc import Sequencefrom typing import TYPE_CHECKINGimport posthoganalytics@@ -14,7 +15,10 @@ import posthoganalyticsfrom posthog.exceptions_capture import capture_exceptionfrom posthog.models.team.team import Team-from products.warehouse_sources.backend.models.external_data_destination import resolve_destinations+from products.warehouse_sources.backend.models.external_data_destination import (+ ExternalDataDestination,+ resolve_destinations,+)if TYPE_CHECKING:from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema@@ -56,13 +60,32 @@ def is_multi_destination_enabled(team_id: int, source_type: str) -> bool:def destination_ids_for_run(schema: ExternalDataSchema) -> list[str]:- """The destination ids this run delivers to, in a stable order.+ """Every destination id this run writes to, the PostHog warehouse included, 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.+ The warehouse is a destination like any other, so a run that writes there says so rather+ than recording nothing. Readers that still receive an empty list — a job that predates+ destinations, a CDC companion lane, a run of a team the flag is off for — keep reading it+ as the warehouse alone, which is what `warehouse_is_a_destination` does.++ This list is the run's whole destination set. Anything that needs the external subset asks+ `external_destination_ids_for` for it rather than reading "non-empty" as "has external+ destinations": the warehouse is delivered through delta, not through a destination writer.+ """+ return sorted(str(destination.id) for destination in resolve_destinations(schema))+++def external_destination_ids_for(team_id: int, destination_ids: Sequence[str]) -> list[str]:+ """The subset of `destination_ids` a destination writer delivers, so without the warehouse.++ Resolved once per run and carried on each batch, because the consumer reads it per batch+ while deciding what may share a write, and a query there would run for every batch in the+ fleet."""- destinations = resolve_destinations(schema)- if len(destinations) == 1 and destinations[0].is_posthog_warehouse:+ if not destination_ids:return []- return sorted(str(destination.id) for destination in destinations)+ return sorted(+ str(destination.id)+ for destination in ExternalDataDestination.objects.for_team(team_id).filter(id__in=list(destination_ids))+ if destination.type != ExternalDataDestination.Type.POSTHOG_WAREHOUSE+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/metrics.py b/products/warehouse_sources/backend/temporal/data_imports/metrics.pyindex 50bc06b474a8..f4785d7171fe 100644--- a/products/warehouse_sources/backend/temporal/data_imports/metrics.py+++ b/products/warehouse_sources/backend/temporal/data_imports/metrics.py@@ -131,10 +131,9 @@ def emit_data_import_app_metrics(job: "ExternalDataJob") -> None:# 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.- # `destination_ids_for_run` returns an empty list when a schema resolves to the PostHog- # warehouse alone, so the run stays byte-for-byte on the path it took before destinations- # existed. Without this fallback those runs report no destination at all, and a project- # that never configured one sees an empty rows-by-destination chart.+ # A run still reaches here with no ids: a job that predates destinations, a CDC companion+ # lane, or a run of a team the flag was off for. Without this fallback those runs report no+ # destination at all, and a project sees a gap in its rows-by-destination chart.destination_ids = list(job.destination_ids or [])if not destination_ids:try:diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/coalescing.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/coalescing.pyindex 4b2e2dbc991b..e21ca92dc4e5 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/coalescing.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/coalescing.py@@ -44,7 +44,10 @@ class LoadShape:partition_format: str | Noneis_first_ever_sync: boolcdc_write_mode: str | None- has_destinations: bool+ # The external destinations the batch is delivered to, as a key rather than a flag: two+ # batches bound for different destinations are written under different configurations and+ # must never share a set, the same as two batches with different primary keys.+ external_destination_ids: tuple[str, ...]@frozen@@ -84,7 +87,7 @@ class CoalesceMember:partition_format=metadata.get("partition_format"),is_first_ever_sync=batch.is_first_ever_sync,cdc_write_mode=metadata.get("cdc_write_mode"),- has_destinations=bool(batch.destination_ids),+ external_destination_ids=_external_ids(metadata.get("external_destination_ids"), batch.destination_ids),),)@@ -110,7 +113,7 @@ class CoalesceMember:partition_format=signal.partition_format,is_first_ever_sync=signal.is_first_ever_sync,cdc_write_mode=signal.cdc_write_mode,- has_destinations=bool(signal.destination_ids),+ external_destination_ids=_external_ids(signal.external_destination_ids, signal.destination_ids),),)@@ -136,8 +139,23 @@ def _key_tuple(keys: Sequence[str] | None) -> tuple[str, ...] | None:return None if keys is None else tuple(keys)+def _external_ids(external: Sequence[str] | None, snapshot: Sequence[str] | None) -> tuple[str, ...]:+ """The batch's external destinations, from the run's whole set when it carries no subset.++ A batch queued before the producer started recording the subset has no way to say which of+ its ids is the warehouse, so every id counts. That keeps such a batch out of every set,+ exactly as it was before, rather than guessing it has none and folding it into a write that+ would skip its per-batch delivery.+ """+ return tuple(snapshot or ()) if external is None else tuple(external)++def loadable_in_set(shape: LoadShape) -> bool:- return shape.sync_type in COALESCABLE_SYNC_TYPES and shape.cdc_write_mode is None and not shape.has_destinations+ return (+ shape.sync_type in COALESCABLE_SYNC_TYPES+ and shape.cdc_write_mode is None+ and not shape.external_destination_ids+ )def join_violation(current: Sequence[CoalesceMember], candidate: CoalesceMember) -> str | None:diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/lanes.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/lanes.pyindex 9069e2a9d6f7..0b3b616b083c 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/lanes.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/lanes.py@@ -159,8 +159,10 @@ class LanedPipelineV3(PipelineV3[ResumableData]):"workflow_run_id": None,# The history table has no destination mapping: delivery names the destination# table from the schema, and SCD2 rows merged by key there would clobber the- # consolidated table's rows.+ # consolidated table's rows. Both lists are cleared so batches remain eligible+ # for coalescing when they have no destinations to deliver to."destination_ids": [],+ "external_destination_ids": [],})writer = _LaneWriter(lane, s3_batch_writer, producer, job=job)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.pyindex 523217245dab..38cdd059ddd7 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@@ -51,6 +51,10 @@ class ExportSignalMessage:# 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)+ # The subset of `destination_ids` a destination writer delivers, so without the warehouse.+ # None on a message queued before the producer recorded it, which readers treat as unknown+ # rather than as none. Resolved once per run, because the consumer reads it per batch.+ external_destination_ids: Optional[list[str]] = Nonedef to_dict(self) -> dict[str, Any]:return asdict(self)@@ -87,4 +91,5 @@ class ExportSignalMessage:cdc_write_mode=data.get("cdc_write_mode"),cdc_table_mode=data.get("cdc_table_mode"),destination_ids=data.get("destination_ids") or [],+ external_destination_ids=data.get("external_destination_ids"),)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.pyindex 6ab052e5f8d2..f736bc59cceb 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@@ -227,6 +227,10 @@ class PipelineV3(Generic[ResumableData]):self._resumable_source_manager = resolve_resume_manager(resumable_source_manager, self._resource)is_resume = self._resumable_source_manager is not None and self._resumable_source_manager.can_resume()+ # Resolved in `_get_models`, not here: the pipeline is built inside an async activity,+ # so the query that tells the warehouse from an external destination cannot run here.+ self._external_destination_ids: list[str] = list(models.external_destination_ids)+self._producer_kwargs: dict[str, Any] = {"sync_type": sync_type,"is_resume": is_resume,@@ -296,6 +300,7 @@ class PipelineV3(Generic[ResumableData]):# 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 []),+ "external_destination_ids": list(self._external_destination_ids),**self._producer_kwargs,}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.pyindex e798d563a3e2..a22d083f6dde 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@@ -70,6 +70,7 @@ class PostgresProducer:workflow_id: str | None = None,workflow_run_id: str | None = None,destination_ids: list[str] | None = None,+ external_destination_ids: list[str] | None = None,) -> None:self._team_id = team_idself._job_id = job_id@@ -92,6 +93,12 @@ class PostgresProducer:self._workflow_id = workflow_idself._workflow_run_id = workflow_run_idself._destination_ids: list[str] = list(destination_ids or [])+ # Kept beside the whole set rather than derived from it: telling the warehouse from+ # an external destination needs the destination rows, and the consumer reads this+ # once per batch while deciding what may share a write.+ self._external_destination_ids: list[str] | None = (+ None if external_destination_ids is None else list(external_destination_ids)+ )self._conn = _connect_with_retry(database_url)self._batches_sent = 0@@ -252,6 +259,8 @@ class PostgresProducer:if self._workflow_run_id is not None:metadata["workflow_run_id"] = self._workflow_run_idmetadata["timestamp_ns"] = batch_result.timestamp_ns+ if self._external_destination_ids is not None:+ metadata["external_destination_ids"] = self._external_destination_idsself._conn.execute(f"""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.pyindex 25319d2ceff8..debb61a6bdf8 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@@ -3937,6 +3937,43 @@ class TestCoalesceGroup:[("run-1", 7)],]+ @pytest.mark.parametrize(+ "destination_ids",+ [["warehouse-1"], ["warehouse-1", "warehouse-2"]],+ ids=["warehouse_only", "two_warehouse_rows"],+ )+ def test_batches_bound_only_for_the_warehouse_still_share_a_write(self, destination_ids: list[str]):+ # Every run now snapshots the PostHog warehouse, which delta writes rather than a+ # destination writer delivers. Reading a non-empty snapshot as "has destinations" would+ # stop the whole fleet coalescing.+ batches = [+ _make_batch(+ id=f"00000000-0000-0000-0000-{i:012d}",+ run_uuid="run-1",+ batch_index=i,+ sync_type="incremental",+ destination_ids=destination_ids,+ metadata={"external_destination_ids": []},+ )+ for i in range(3)+ ]+ assert self._sets(batches) == [[0, 1, 2]]++ def test_batches_for_different_destinations_never_share_a_write(self):+ # The external set is a key, not a flag: one write cannot deliver to two different places.+ batches = [+ _make_batch(+ id=f"00000000-0000-0000-0000-{i:012d}",+ run_uuid="run-1",+ batch_index=i,+ sync_type="incremental",+ destination_ids=["warehouse-1", dest],+ metadata={"external_destination_ids": [dest]},+ )+ for i, dest in enumerate(["dest-a", "dest-a", "dest-b"])+ ]+ assert self._sets(batches) == [[0], [1], [2]]+def test_a_final_only_marker_row_stays_alone(self):# An older producer repeats the last batch's index as a final-only row; it is not a new batch.batches = _run_batches(2)@@ -3954,10 +3991,12 @@ class TestCoalesceGroup:[{"sync_type": "cdc"},{"metadata": {"cdc_write_mode": "scd2_append"}},+ {"destination_ids": ["dest-1"], "metadata": {"external_destination_ids": ["dest-1"]}},+ # Queued before the producer recorded the subset, so every id counts as external.{"destination_ids": ["dest-1"]},{"latest_attempt": 1},],- ids=["cdc", "scd2_companion", "external_destinations", "redelivery"],+ ids=["cdc", "scd2_companion", "external_destinations", "unknown_subset", "redelivery"],)def test_batches_the_sink_loads_one_at_a_time(self, overrides: dict[str, Any]):batches = [diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/import_data_sync.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/import_data_sync.pyindex c43686ca1f80..a806f5b1797b 100644--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/import_data_sync.py+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/import_data_sync.py@@ -38,6 +38,9 @@ from products.warehouse_sources.backend.models.external_data_schema import ()from products.warehouse_sources.backend.models.external_data_source import ExternalDataSourcefrom products.warehouse_sources.backend.models.table import DataWarehouseTable+from products.warehouse_sources.backend.temporal.data_imports.destinations.enablement import (+ external_destination_ids_for,+)from products.warehouse_sources.backend.temporal.data_imports.metrics import (TERMINAL_JOB_STATUSES,get_worker_shutdown_handoff_metric,@@ -653,6 +656,10 @@ class ImportJobModels:schema: ExternalDataSchemasource: ExternalDataSourcetable: DataWarehouseTable | None+ # The run's destinations minus the PostHog warehouse. Resolved here because this is the+ # run's one async-safe ORM fetch: the pipeline is built inside an async activity, where+ # the same query raises `SynchronousOnlyOperation`.+ external_destination_ids: list[str] = dataclasses.field(default_factory=list)@database_sync_to_async_pool@@ -672,7 +679,13 @@ def _get_models(raise Exception("No source attached to job")table: DataWarehouseTable | None = schema.table- return ImportJobModels(job=job, schema=schema, source=source, table=table)+ return ImportJobModels(+ job=job,+ schema=schema,+ source=source,+ table=table,+ external_destination_ids=external_destination_ids_for(job.team_id, list(job.destination_ids or [])),+ )# What a customer reads when a PostHog-managed credential is unavailable. Deliberately saysdiff --git a/products/warehouse_sources/backend/tests/test_external_data_destination.py b/products/warehouse_sources/backend/tests/test_external_data_destination.pyindex 41996f61f1b3..5ac25e125ffe 100644--- a/products/warehouse_sources/backend/tests/test_external_data_destination.py+++ b/products/warehouse_sources/backend/tests/test_external_data_destination.py@@ -17,6 +17,10 @@ from products.warehouse_sources.backend.models.external_data_destination import)from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchemafrom products.warehouse_sources.backend.models.external_data_source import ExternalDataSource+from products.warehouse_sources.backend.temporal.data_imports.destinations.enablement import (+ destination_ids_for_run,+ external_destination_ids_for,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@@ -203,3 +207,59 @@ class TestBackfillWarehouseSourceDestinations(BaseTest):call_command("backfill_warehouse_source_destinations", "--live-run")assert not ExternalDataSourceDestination.objects.for_team(self.team.pk).filter(source=source).exists()+++class TestDestinationIdsForRun(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 _link(self, destination: ExternalDataDestination) -> None:+ ExternalDataSourceDestination.objects.for_team(self.team.pk).create(+ team_id=self.team.pk, source=self.source, destination=destination+ )++ def _destination(self, name: str, type_: str) -> ExternalDataDestination:+ return ExternalDataDestination.objects.for_team(self.team.pk).create(+ team_id=self.team.pk, type=type_, name=name+ )++ def test_a_run_that_writes_only_to_the_warehouse_still_records_it(self) -> None:+ # The Syncs tab reads this to name where a run landed, and an empty list reads there as+ # "went nowhere" rather than "the warehouse".+ warehouse = get_or_create_warehouse_destination(self.team.pk)++ assert destination_ids_for_run(self.schema) == [str(warehouse.id)]++ def test_a_run_records_the_warehouse_alongside_an_external_destination(self) -> None:+ warehouse = get_or_create_warehouse_destination(self.team.pk)+ snowflake = self._destination("snowflake", ExternalDataDestination.Type.SNOWFLAKE)+ self._link(warehouse)+ self._link(snowflake)++ assert destination_ids_for_run(self.schema) == sorted([str(warehouse.id), str(snowflake.id)])++ def test_external_ids_leave_out_the_warehouse(self) -> None:+ # What the consumer keys a coalesced write on. Counting the warehouse here would stop+ # every sync in the fleet sharing a write, because every run now records it.+ warehouse = get_or_create_warehouse_destination(self.team.pk)+ snowflake = self._destination("snowflake", ExternalDataDestination.Type.SNOWFLAKE)++ assert external_destination_ids_for(self.team.pk, [str(warehouse.id), str(snowflake.id)]) == [str(snowflake.id)]+ assert external_destination_ids_for(self.team.pk, [str(warehouse.id)]) == []+ assert external_destination_ids_for(self.team.pk, []) == []++ def test_external_ids_ignore_another_teams_destination(self) -> None:+ other = Team.objects.create(organization=self.organization, name="other")+ theirs = ExternalDataDestination.objects.for_team(other.pk).create(+ team_id=other.pk, type=ExternalDataDestination.Type.SNOWFLAKE, name="theirs"+ )++ assert external_destination_ids_for(self.team.pk, [str(theirs.id)]) == []diff --git a/products/warehouse_sources_queue/backend/core/jobs_db.py b/products/warehouse_sources_queue/backend/core/jobs_db.pyindex 28840cadd713..959c6d521c7d 100644--- a/products/warehouse_sources_queue/backend/core/jobs_db.py+++ b/products/warehouse_sources_queue/backend/core/jobs_db.py@@ -836,6 +836,7 @@ class PendingBatch:"cdc_write_mode": self.metadata.get("cdc_write_mode"),"cdc_table_mode": self.metadata.get("cdc_table_mode"),"destination_ids": self.destination_ids or [],+ "external_destination_ids": self.metadata.get("external_destination_ids"),}