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(warehouse-sources): stop wiping cdc companion history on redelivery (#82696)

Daniel RCe44d02354b17
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/load.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/load.py
index 5aa1e82aaf16..6bf1bb240181 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/load.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/load.py
@@ -414,6 +414,7 @@ async def _run_cdc_post_load(
queryable_folder: str,
cdc_write_mode: Optional[str],
is_cdc_companion: bool,
+ is_initial_load: bool,
logger: FilteringBoundLogger,
) -> None:
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_sync import (
@@ -438,13 +439,16 @@ async def _run_cdc_post_load(
return
# After the initial snapshot load for a CDC schema, seed the companion _cdc table
- # with the snapshot rows as synthetic INSERT events. Only fires when cdc_write_mode
- # is None (initial non-CDC load), NOT on every CDC consolidated streaming batch.
- should_seed = cdc_write_mode is None and schema.cdc_table_mode in ("cdc_only", "both")
+ # with the snapshot rows as synthetic INSERT events. Seeding resets the companion, so
+ # it must happen only on the initial load: a missing cdc_write_mode alone does not mean
+ # "initial" — a redelivered final batch reaches post-load without one, and re-seeding
+ # there throws away every SCD2 version the stream has accumulated since.
+ should_seed = is_initial_load and cdc_write_mode is None and schema.cdc_table_mode in ("cdc_only", "both")
logger.info(
"cdc_seed_check",
should_seed=should_seed,
cdc_write_mode=cdc_write_mode,
+ is_initial_load=is_initial_load,
sync_type=schema.sync_type,
cdc_table_mode=schema.cdc_table_mode,
)
@@ -581,6 +585,9 @@ async def run_post_load_operations(
# table independently, otherwise we overwrite the snapshot queryable_folder with the SCD2 path.
is_cdc_companion = cdc_write_mode == "scd2_append"
is_cdc_schema = schema.sync_type == ExternalDataSchema.SyncType.CDC
+ # Read before the bookkeeping below sets the flag, which would otherwise make every run
+ # look like a continuation.
+ is_initial_load = not schema.initial_sync_complete
await _run_delta_maintenance(schema, delta_table_ref, is_cdc_companion, logger)
@@ -610,6 +617,7 @@ async def run_post_load_operations(
queryable_folder=queryable_folder,
cdc_write_mode=cdc_write_mode,
is_cdc_companion=is_cdc_companion,
+ is_initial_load=is_initial_load,
logger=logger,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/test/test_load.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/test/test_load.py
index 815cdaaf7852..5fc091df605b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/test/test_load.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/test/test_load.py
@@ -25,7 +25,14 @@ _PIPELINE_SYNC_MODULE = "products.warehouse_sources.backend.temporal.data_import
_REPARTITION_MODULE = "products.warehouse_sources.backend.temporal.data_imports.pipelines.core.repartition_controller"
-def _make_schema(*, is_cdc: bool, sync_type_config: dict | None = None, partition_count: int | None = 7) -> MagicMock:
+def _make_schema(
+ *,
+ is_cdc: bool,
+ sync_type_config: dict | None = None,
+ partition_count: int | None = 7,
+ cdc_table_mode: str = "consolidated",
+ initial_sync_complete: bool = True,
+) -> MagicMock:
config = sync_type_config if sync_type_config is not None else {}
schema = MagicMock()
schema.id = uuid.uuid4()
@@ -36,8 +43,8 @@ def _make_schema(*, is_cdc: bool, sync_type_config: dict | None = None, partitio
schema.last_vacuum_version = config.get("last_vacuum_version")
schema.last_vacuum_version_cdc = config.get("last_vacuum_version_cdc")
schema.partition_count = partition_count
- schema.cdc_table_mode = "consolidated"
- schema.initial_sync_complete = True
+ schema.cdc_table_mode = cdc_table_mode
+ schema.initial_sync_complete = initial_sync_complete
return schema
@@ -68,6 +75,7 @@ async def _run_post_load(
patch(f"{_LOAD_MODULE}.notify_revenue_analytics_that_sync_has_completed", AsyncMock()),
patch(f"{_LOAD_MODULE}.sync_revenue_analytics_views", MagicMock()),
patch(f"{_LOAD_MODULE}.DataWarehouseTable", MagicMock()),
+ patch(f"{_LOAD_MODULE}.set_initial_sync_complete", AsyncMock()),
patch.object(DeltaMaintenance, "run_scheduled", run_scheduled),
patch.object(DeltaMaintenance, "compact_table", compact_table),
patch(f"{_PIPELINE_SYNC_MODULE}.update_last_synced_at", AsyncMock()),
@@ -172,6 +180,44 @@ class TestRunPostLoadDeltaMaintenance:
prepare_s3.assert_awaited_once()
+class TestCdcCompanionSeeding:
+ @parameterized.expand(
+ [
+ # The seed exists for exactly this: the companion starts as the snapshot's rows.
+ ("initial_snapshot_seeds", "both", False, None, True),
+ # The incident this guards: seeding resets the companion table, so re-running it on a
+ # streaming schema throws away every SCD2 version the stream has accumulated. A
+ # redelivered final batch reaches post-load with no write mode (the loader's
+ # already-processed path), which used to be indistinguishable from an initial load.
+ ("streaming_tick_without_write_mode_does_not_reseed", "both", True, None, False),
+ ("cdc_only_streaming_tick_does_not_reseed", "cdc_only", True, None, False),
+ # A consolidated schema has no companion table to seed.
+ ("consolidated_never_seeds", "consolidated", False, None, False),
+ # A companion write is the stream appending to the companion, never a reason to reset it.
+ ("companion_write_never_seeds", "both", False, "scd2_append", False),
+ ]
+ )
+ @pytest.mark.asyncio
+ async def test_seeds_only_on_the_initial_snapshot(
+ self,
+ _name: str,
+ cdc_table_mode: str,
+ initial_sync_complete: bool,
+ cdc_write_mode: str | None,
+ expect_seed: bool,
+ ) -> None:
+ schema = _make_schema(
+ is_cdc=True,
+ cdc_table_mode=cdc_table_mode,
+ initial_sync_complete=initial_sync_complete,
+ )
+
+ with patch(f"{_LOAD_MODULE}._seed_cdc_companion_from_snapshot", AsyncMock()) as seed:
+ await _run_post_load(schema, _make_helper(), cdc_write_mode=cdc_write_mode)
+
+ assert seed.await_count == (1 if expect_seed else 0)
+
+
class TestGetIncrementalFieldValue:
def _schema(self, incremental_field: str, sync_type: str = ExternalDataSchema.SyncType.INCREMENTAL) -> MagicMock:
schema = MagicMock()
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 4d358a4defd1..ded1d3e2d71d 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
@@ -385,6 +385,7 @@ def _run_post_load_for_already_processed_batch(export_signal: ExportSignalMessag
table_schema_dict=table_schema_dict,
resource_name=export_signal.resource_name,
logger=logger,
+ cdc_write_mode=export_signal.cdc_write_mode,
)
logger.debug("post_load_operations_complete_for_already_processed_batch")
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/test_processor.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/test_processor.py
index 17c20ad7795d..6e746ca292aa 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/test_processor.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/test_processor.py
@@ -23,6 +23,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline
_mark_job_completed,
_promote_staged_cursor,
_read_existing_rows_by_first_pk,
+ _run_post_load_for_already_processed_batch,
_trigger_post_import_workflow,
process_message,
)
@@ -468,6 +469,40 @@ class TestMarkJobCompleted:
mock_release.assert_not_called()
+class TestRedeliveredFinalBatchPostLoad:
+ @parameterized.expand([("companion", "scd2_append"), ("consolidated", "incremental_merge"), ("snapshot", None)])
+ @patch(f"{_PROCESSOR}.run_post_load_operations", new_callable=AsyncMock, return_value="folder")
+ @patch(f"{_PROCESSOR}.read_parquet", return_value=pa.table({"id": [1]}))
+ @patch(f"{_PROCESSOR}.DeltaTableRef")
+ @patch(f"{_PROCESSOR}.ExternalDataJob")
+ @patch(f"{_PROCESSOR}.s3fs")
+ def test_forwards_the_batch_write_mode(
+ self,
+ _case: str,
+ cdc_write_mode: str | None,
+ _s3fs: MagicMock,
+ mock_job_model: MagicMock,
+ mock_helper_cls: MagicMock,
+ _read: MagicMock,
+ mock_post_load: AsyncMock,
+ ) -> None:
+ # Post-load derives the whole CDC branch from the write mode: whether this is a companion
+ # write (register the _cdc table, leave schema.table alone) or a snapshot to seed the
+ # companion from. Dropping it here let a redelivered streaming batch re-seed the companion,
+ # wiping its SCD2 history, and point schema.table at the companion's folder.
+ delta_table = MagicMock(schema=MagicMock(return_value=pa.schema([_COL_ID])))
+ mock_job_model.objects.prefetch_related.return_value.aget = AsyncMock(return_value=MagicMock())
+ mock_helper_cls.return_value.get_delta_table = AsyncMock(return_value=delta_table)
+
+ signal = MagicMock()
+ signal.cdc_write_mode = cdc_write_mode
+
+ _run_post_load_for_already_processed_batch(signal)
+
+ assert mock_post_load.await_args is not None
+ assert mock_post_load.await_args.kwargs["cdc_write_mode"] == cdc_write_mode
+
+
class TestPostImportTrigger:
"""The V3 hand-off to `data-import-post-import`: without it the load-dependent
post-import steps (signals, enrichment, statistics, table size, DuckLake copy)