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.

fix(data-warehouse): flip cdc snapshot to streaming at load completion on v3 (#71933)

estefania82c504d78158
diff --git a/products/warehouse_sources/backend/models/external_data_schema.py b/products/warehouse_sources/backend/models/external_data_schema.py
index 28550e93c3b1..f6114f849be3 100644
--- a/products/warehouse_sources/backend/models/external_data_schema.py
+++ b/products/warehouse_sources/backend/models/external_data_schema.py
@@ -825,6 +825,35 @@ def update_sync_type_config_keys(
return config
+def mark_initial_sync_complete(schema_id: str | uuid.UUID, team_id: int) -> None:
+ """Mark a schema's first successful sync complete. Shared by the V2 pipelines and the V3 loader.
+
+ On the False→True transition, a CDC schema still in snapshot mode moves to
+ ``cdc_mode="streaming"`` in the same row lock. Callers must only invoke this once the
+ run's data has durably landed in the destination table — the streaming flip is what lets
+ the CDC workflow start enqueuing (and flushing deferred) WAL merge runs, and merges
+ against a half-loaded snapshot corrupt the table. Locked for the same reason as
+ ``update_sync_type_config_keys``: the CDC extract activity appends ``cdc_deferred_runs``
+ to ``sync_type_config`` concurrently, and an unlocked read-modify-write here could
+ clobber a deferred run.
+ """
+ with transaction.atomic():
+ schema = ExternalDataSchema.objects.select_for_update().exclude(deleted=True).get(id=schema_id, team_id=team_id)
+ if schema.initial_sync_complete:
+ return
+
+ schema.initial_sync_complete = True
+ update_fields = ["initial_sync_complete", "updated_at"]
+
+ if schema.is_cdc and schema.cdc_mode == "snapshot":
+ config = schema.sync_type_config or {}
+ config["cdc_mode"] = "streaming"
+ schema.sync_type_config = config
+ update_fields.append("sync_type_config")
+
+ schema.save(update_fields=update_fields, skip_activity_log=True)
+
+
def get_all_schemas_for_source_id(source_id: str, team_id: int):
return list(ExternalDataSchema.objects.exclude(deleted=True).filter(team_id=team_id, source_id=source_id).all())
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_sync.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_sync.py
index 227c4f429f17..119f081875c0 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_sync.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_sync.py
@@ -22,7 +22,10 @@ from posthog.sync import database_sync_to_async_pool
from posthog.temporal.common.logger import get_logger
from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob
-from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
+from products.warehouse_sources.backend.models.external_data_schema import (
+ ExternalDataSchema,
+ mark_initial_sync_complete,
+)
from products.warehouse_sources.backend.models.table import DataWarehouseTable
from products.warehouse_sources.backend.temporal.data_imports.naming_convention import NamingConvention
from products.warehouse_sources.backend.temporal.data_imports.pipelines.helpers import (
@@ -120,21 +123,7 @@ async def update_last_synced_at(job_id: str, schema_id: str, team_id: int) -> No
async def set_initial_sync_complete(schema_id: str, team_id: int) -> None:
- @database_sync_to_async_pool
- def _update():
- schema = ExternalDataSchema.objects.exclude(deleted=True).get(id=schema_id, team_id=team_id)
- if not schema.initial_sync_complete:
- schema.initial_sync_complete = True
- update_fields = ["initial_sync_complete"]
-
- # CDC snapshot → streaming transition
- if schema.is_cdc and schema.cdc_mode == "snapshot":
- schema.sync_type_config["cdc_mode"] = "streaming"
- update_fields.append("sync_type_config")
-
- schema.save(update_fields=update_fields)
-
- await _update()
+ await database_sync_to_async_pool(mark_initial_sync_complete)(schema_id=schema_id, team_id=team_id)
async def validate_schema_and_update_table(
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 8ca0b6ecd559..5c7b40f44c10 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
@@ -69,7 +69,6 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline
observe_and_project_table,
source_uses_delta_write_column_selection,
)
-from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_sync import set_initial_sync_complete
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.metrics import (
get_batches_produced_metric,
get_pipeline_run_duration_metric,
@@ -516,9 +515,7 @@ class PipelineV3(Generic[ResumableData]):
await advance_xmin_state(self._resource, self._schema, self._logger, log_prefix="V3 Pipeline: ")
- if not self._schema.initial_sync_complete:
- await self._logger.adebug("V3 Pipeline: Setting initial_sync_complete on schema")
- await set_initial_sync_complete(schema_id=self._schema.id, team_id=self._job.team_id)
+ # initial_sync_complete is set by the loader's post-load after data lands in Delta.
await self._logger.ainfo(
f"V3 Pipeline: Extraction complete",
diff --git a/products/warehouse_sources/backend/tests/test_models.py b/products/warehouse_sources/backend/tests/test_models.py
index 927dd976e7f1..2264bfeaa71e 100644
--- a/products/warehouse_sources/backend/tests/test_models.py
+++ b/products/warehouse_sources/backend/tests/test_models.py
@@ -18,6 +18,7 @@ from products.warehouse_sources.backend.models.external_data_job import External
from products.warehouse_sources.backend.models.external_data_schema import (
ExternalDataSchema,
apply_incremental_lookback,
+ mark_initial_sync_complete,
process_incremental_value,
update_sync_type_config_keys,
)
@@ -375,6 +376,90 @@ class TestUpdateSyncTypeConfigKeys(BaseTest):
assert schema.sync_type_config["cdc_last_log_position"] == "0/900"
+class TestMarkInitialSyncComplete(BaseTest):
+ """The shared first-sync-complete transition (V2 pipelines + V3 loader post-load), whose
+ False→True edge is what moves a CDC schema out of snapshot mode into streaming."""
+
+ def setUp(self) -> None:
+ super().setUp()
+ self.source = ExternalDataSource.objects.create(
+ team_id=self.team.pk,
+ source_id=str(uuid.uuid4()),
+ connection_id=str(uuid.uuid4()),
+ status="Completed",
+ source_type="Postgres",
+ )
+
+ def _create(
+ self, sync_type: str, sync_type_config: dict, *, initial_sync_complete: bool = False
+ ) -> ExternalDataSchema:
+ return ExternalDataSchema.objects.create(
+ team_id=self.team.pk,
+ source=self.source,
+ name="users",
+ sync_type=sync_type,
+ sync_type_config=sync_type_config,
+ initial_sync_complete=initial_sync_complete,
+ )
+
+ @parameterized.expand(
+ [
+ (
+ # First completion of a CDC snapshot flips it to streaming; keys written
+ # concurrently by the CDC extract activity (deferred runs) must survive the flip.
+ "cdc_snapshot_flips_to_streaming_preserving_other_keys",
+ "cdc",
+ {"cdc_mode": "snapshot", "cdc_deferred_runs": [{"run_uuid": "a"}], "dwh_storage_key": "users"},
+ False,
+ True,
+ {"cdc_mode": "streaming", "cdc_deferred_runs": [{"run_uuid": "a"}], "dwh_storage_key": "users"},
+ ),
+ (
+ # Already-streaming CDC schema (re-run after a reset) completes without a config rewrite.
+ "cdc_already_streaming_config_unchanged",
+ "cdc",
+ {"cdc_mode": "streaming"},
+ False,
+ True,
+ {"cdc_mode": "streaming"},
+ ),
+ (
+ # Non-CDC schemas must never get a cdc_mode key injected.
+ "non_cdc_config_untouched",
+ "incremental",
+ {"incremental_field": "id"},
+ False,
+ True,
+ {"incremental_field": "id"},
+ ),
+ (
+ # Only the False→True transition flips: a schema manually put back into snapshot
+ # mode must not be flipped to streaming by a later run's completion.
+ "already_complete_is_noop_even_in_snapshot_mode",
+ "cdc",
+ {"cdc_mode": "snapshot"},
+ True,
+ True,
+ {"cdc_mode": "snapshot"},
+ ),
+ ]
+ )
+ def test_transition(
+ self,
+ _name: str,
+ sync_type: str,
+ config: dict,
+ initial_flag: bool,
+ expected_flag: bool,
+ expected_config: dict,
+ ) -> None:
+ schema = self._create(sync_type, config, initial_sync_complete=initial_flag)
+ mark_initial_sync_complete(schema.id, self.team.pk)
+ schema.refresh_from_db()
+ assert schema.initial_sync_complete == expected_flag
+ assert schema.sync_type_config == expected_config
+
+
@pytest.mark.parametrize(
"clickhouse_type,expected",
[