: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-imports): stop wrongly requiring a primary key on a retried first sync (#79230)
Tom Owers8c039548d09c
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v2/pipeline.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v2/pipeline.pyindex 1777da42b9bb..5337347fc544 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v2/pipeline.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v2/pipeline.py@@ -122,7 +122,15 @@ class PipelineNonDLT(Generic[ResumableData]):# as a full_refresh overwrite, which would wipe earlier data on the second (delta-only) sync.self._is_incremental = models.schema.is_incremental or models.schema.is_webhook or models.schema.is_xmin- self._delta_table_ref = DeltaTableRef(self._resource_name, self._job, self._logger)+ # Mirrors the `is_first_sync` passed to `validate_incremental_sync` below: a schema with no+ # `DataWarehouseTable` row yet is a fresh (or retried-fresh) sync even when a Delta table+ # already exists in storage from an earlier attempt at writing the same first sync. Without+ # this, the writer's own is-first-sync detection (no physical table found) never fires for+ # that case, and an incremental write with no primary key wrongly takes the merge path+ # instead of overwriting, raising MissingPrimaryKeysException on an otherwise-healthy sync.+ self._delta_table_ref = DeltaTableRef(+ self._resource_name, self._job, self._logger, is_first_sync=self._table is None+ )self._resumable_source_manager = resumable_source_manager# A source can shrink the batcher chunk (e.g. document sources with large rows) so the# source->Arrow conversion doesn't materialise an oversized table; None falls back to defaults.diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v2/test/test_pipeline.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v2/test/test_pipeline.pyindex 6e9b6a58d602..01738c2744e3 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v2/test/test_pipeline.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v2/test/test_pipeline.py@@ -4,8 +4,13 @@ from typing import castimport pytestfrom unittest.mock import AsyncMock, MagicMock, patch+from parameterized import parameterized+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v2.pipeline import PipelineNonDLTfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.workflow_activities.import_data_sync import (+ ImportJobModels,+)_PIPELINE_MODULE = "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v2.pipeline"@@ -68,3 +73,55 @@ async def test_post_run_operations_routes_through_shared_post_load():assert kwargs["resource"] is pipeline._resourceassert kwargs["last_incremental_field_value"] == 5assert kwargs["row_count"] == 10+++class TestDeltaTableRefFirstSyncWiring:+ @parameterized.expand(+ [+ ("no_table_row_yet", None, True),+ ("table_row_already_exists", MagicMock(), False),+ ]+ )+ def test_is_first_sync_matches_whether_a_table_row_exists(+ self, _name: str, table: MagicMock | None, expected_is_first_sync: bool+ ) -> None:+ # Regression: a schema with no DataWarehouseTable row yet is treated as a first sync by+ # `validate_incremental_sync` (which skips the primary-key requirement), but the writer's+ # own first-sync detection only fires when no Delta table physically exists in storage.+ # If a Delta table happens to already exist there (e.g. left over from an earlier attempt+ # at this same first sync), those two checks used to disagree and the writer wrongly took+ # the merge path, raising MissingPrimaryKeysException on a keyless incremental table that+ # `validate_incremental_sync` had just waved through. The `DeltaTableRef` must be+ # constructed with `is_first_sync` set from the same `table is None` check.+ mock_job = MagicMock(team_id=1)+ mock_schema = MagicMock(+ id="schema-1",+ name="orders",+ is_incremental=True,+ is_webhook=False,+ is_xmin=False,+ incremental_field_earliest_value=None,+ incremental_field_type=None,+ )+ mock_source = MagicMock(source_type="Redshift")+ mock_resource = MagicMock(name="orders", chunk_size=None, chunk_size_bytes=None)++ with (+ patch(f"{_PIPELINE_MODULE}.resolve_primary_keys", return_value=None),+ patch(f"{_PIPELINE_MODULE}.Batcher"),+ patch(f"{_PIPELINE_MODULE}.HogQLSchema"),+ patch(f"{_PIPELINE_MODULE}.build_pipeline_sinks"),+ patch(f"{_PIPELINE_MODULE}.source_uses_delta_write_column_selection", return_value=False),+ patch(f"{_PIPELINE_MODULE}.DeltaTableRef") as mock_delta_table_ref_cls,+ ):+ PipelineNonDLT(+ source_response=mock_resource,+ logger=MagicMock(),+ job_id="job-1",+ reset_pipeline=False,+ shutdown_monitor=MagicMock(),+ resumable_source_manager=None,+ models=ImportJobModels(job=mock_job, schema=mock_schema, source=mock_source, table=table),+ )++ assert mock_delta_table_ref_cls.call_args.kwargs["is_first_sync"] is expected_is_first_sync