: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
feat(warehouse-sources): resolve CDC batch ordering and verify delete enrichment before the write (#82568)
Daniel RCb097fdfe76f6
diff --git a/products/warehouse_sources/backend/management/commands/validate_cdc_buffer.py b/products/warehouse_sources/backend/management/commands/validate_cdc_buffer.pyindex 41ad19520798..2cf9731ce41c 100644--- a/products/warehouse_sources/backend/management/commands/validate_cdc_buffer.py+++ b/products/warehouse_sources/backend/management/commands/validate_cdc_buffer.py@@ -24,8 +24,8 @@ Known windows where sums legitimately diverge:began streaming (or spans the entire snapshot phase).- After a mid-run activity retry: the legacy lane re-inserts the replayed prefixof an in-flight transaction (accepted duplicate scd2 rows) while the buffer's- same-named files overwrite. Multiple run_uuids in the window therefore- downgrade the scd2 exact-match to a warning.+ same-named files overwrite. A `(run_uuid, batch_index)` dispatched more than+ once in the window therefore downgrades the scd2 exact-match to a warning."""from datetime import UTC, datetime, timedelta@@ -69,7 +69,7 @@ class Command(BaseCommand):if not schemas:raise CommandError(f"Source {source.id} has no CDC schemas")- legacy_rows, run_counts = self._fetch_legacy_row_sums(source, cutoff)+ legacy_rows, retried_batches = self._fetch_legacy_row_sums(source, cutoff)s3 = get_s3_client()violations: list[str] = []@@ -105,13 +105,15 @@ class Command(BaseCommand):if scd2_rows is not None and scd2_rows != buffer_rows:# Legacy re-inserts replayed rows on activity retry while buffer- # files overwrite — with multiple runs in the window the exact- # match is expected to skew, so it warns instead of failing.- if run_counts.get(str(schema.id), 0) > 1:+ # files overwrite, so a re-dispatched batch is expected to skew the+ # exact match — that case warns instead of failing.+ retried = retried_batches.get(str(schema.id), 0)+ if retried > 0:self.stdout.write(self.style.WARNING(f"WARNING: {schema.name}: scd2 rows ({scd2_rows}) != buffer rows ({buffer_rows}) "- "with multiple runs in the window — likely retry-replay skew, verify manually"+ f"with {retried} re-dispatched batch(es) in the window — likely retry-replay skew, "+ "verify manually"))else:@@ -183,32 +185,46 @@ class Command(BaseCommand):def _fetch_legacy_row_sums(self, source: ExternalDataSource, cutoff: datetime) -> tuple[dict[tuple[str, str], int], dict[str, int]]:- """Sum sourcebatch row_count per (schema_id, lane) since cutoff, plus the- distinct run count per schema (for retry-replay downgrades).+ """Sum sourcebatch row_count per (schema_id, lane) since cutoff, plus the number of+ re-dispatched batches per schema (for retry-replay downgrades).Only `sync_type = 'cdc'` dispatches count: snapshots and resyncs flow intothe same table as full_refresh/incremental and would otherwise inflate theconsolidated lane into a guaranteed false violation. Lane is derived fromresource_name via the shared companion suffix.++ A retry is a `(run_uuid, batch_index)` pair dispatched more than once — that is the+ replay the scd2 exact-match cannot survive. Counting distinct run_uuids instead (as this+ did originally) counts *scheduled ticks*: a healthy 5-min source mints a fresh run_uuid+ every tick, so any window longer than one tick looked like a retry and permanently+ downgraded the exact match to a warning, which is precisely the check this gate exists to+ make."""companion_pattern = "%" + CDC_COMPANION_SUFFIX.replace("_", r"\_")with psycopg.connect(WAREHOUSE_SOURCES_DATABASE_URL) as conn:rows = conn.execute(f"""- SELECT schema_id,- CASE WHEN resource_name LIKE %(companion_pattern)s THEN 'scd2' ELSE 'consolidated' END AS lane,- COALESCE(SUM(row_count), 0),- COUNT(DISTINCT run_uuid)- FROM {BATCH_TABLE}- WHERE source_id = %(source_id)s AND created_at >= %(cutoff)s AND sync_type = 'cdc'+ SELECT schema_id, lane, COALESCE(SUM(batch_rows), 0), COUNT(*) FILTER (WHERE dispatches > 1)+ FROM (+ SELECT schema_id,+ CASE WHEN resource_name LIKE %(companion_pattern)s+ THEN 'scd2' ELSE 'consolidated' END AS lane,+ run_uuid,+ batch_index,+ SUM(row_count) AS batch_rows,+ COUNT(*) AS dispatches+ FROM {BATCH_TABLE}+ WHERE source_id = %(source_id)s AND created_at >= %(cutoff)s AND sync_type = 'cdc'+ GROUP BY schema_id, lane, run_uuid, batch_index+ ) per_batchGROUP BY schema_id, lane""",{"source_id": str(source.id), "cutoff": cutoff, "companion_pattern": companion_pattern},).fetchall()sums: dict[tuple[str, str], int] = {}- run_counts: dict[str, int] = {}- for schema_id, lane, total, runs in rows:+ retried_batches: dict[str, int] = {}+ for schema_id, lane, total, retried in rows:sums[(str(schema_id), lane)] = int(total)- run_counts[str(schema_id)] = max(run_counts.get(str(schema_id), 0), int(runs))- return sums, run_counts+ retried_batches[str(schema_id)] = max(retried_batches.get(str(schema_id), 0), int(retried))+ return sums, retried_batchesdiff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.pyindex 380da9b8dc26..2aa251b321aa 100644--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.py+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.py@@ -68,6 +68,7 @@ from products.warehouse_sources.backend.temporal.data_imports.cdc.errors importCDCSlotNotConfiguredError,classify_cdc_error,)+from products.warehouse_sources.backend.temporal.data_imports.cdc.load_resolution import has_engine_seqfrom products.warehouse_sources.backend.temporal.data_imports.cdc.naming import cdc_qualified_table_namefrom products.warehouse_sources.backend.temporal.data_imports.cdc.types import ChangeEventfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.helpers import resolve_table_and_folder_names@@ -628,10 +629,7 @@ class CDCExtractActivity:"""if not self._shadow_enabled or self._shadow_disabled_for_run:return- # The engine seq column is always LAST when the batcher appended it; a- # same-named source column (collision → append skipped) is never last.- # Checking by name would let the user's column masquerade as positions.- if table.num_rows == 0 or table.schema.field(table.num_columns - 1).name != CDC_SEQ_COLUMN:+ if table.num_rows == 0 or not has_engine_seq(table):returnfile_index = self._shadow_file_index.get(table_name, 0)@@ -645,7 +643,7 @@ class CDCExtractActivity:# past where this run restarted (batch boundaries are not stable# across attempts — see buffer.py). The batch's min seq IS the# restart floor for this schema.- restart_seq = pc.min(table.column(table.num_columns - 1)).as_py()+ restart_seq = pc.min(table.column(CDC_SEQ_COLUMN)).as_py()self._shadow_buffer_writer.cleanup_superseded_files(team_id=schema.team_id, schema_id=schema_id, restart_seq=restart_seq)@@ -720,15 +718,11 @@ class CDCExtractActivity:enriched_table = enrich_toast_omitted_rows(raw_table, key_columns)enriched_table = enrich_delete_rows(enriched_table, key_columns)- # Shadow buffered ingress: persist the raw (pre-dedup/SCD2) stream, then- # strip the seq column so the legacy write path stays byte-identical.- # Strip by LAST field only — the batcher appends its seq column last and- # skips the append on collision, so a source column that happens to be- # named _ph_cdc_seq is never ours and must pass through untouched.+ # Buffer the raw (pre-dedup/SCD2) stream, then strip the seq column so the legacy write+ # path stays byte-identical. Only ours — a source column of the same name stays.self._maybe_shadow_write_buffer(schema, table_name, enriched_table)- last_field_idx = enriched_table.num_columns - 1- if enriched_table.schema.field(last_field_idx).name == CDC_SEQ_COLUMN:- enriched_table = enriched_table.remove_column(last_field_idx)+ if has_engine_seq(enriched_table):+ enriched_table = enriched_table.remove_column(enriched_table.column_names.index(CDC_SEQ_COLUMN))# Consolidated shares the snapshot's canonical folder; the `_cdc` companion is# CDC-only and stays self-consistent with its `name`-keyed snapshot seed.diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/batcher.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/batcher.pyindex bebd10a29392..b06cece1adbf 100644--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/batcher.py+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/batcher.py@@ -18,6 +18,9 @@ DELETED_AT_COLUMN = "_ph_deleted_at"# real positions never approach 2^63. Names the buffer files' position range# and (in Phase B) drives the merge's monotonicity guard.CDC_SEQ_COLUMN = "_ph_cdc_seq"+# Marks CDC_SEQ_COLUMN as engine-produced, so readers can tell it from a source column of the same+# name (see the collision skip in _events_to_table).+CDC_SEQ_PROVENANCE = {b"posthog_cdc": b"engine_position"}# Suffix of the SCD2 companion table's resource name ({schema.name}_cdc). Shared# so lane classification (validate_cdc_buffer) can never drift from the writers.@@ -543,12 +546,11 @@ def _events_to_table(events: list[ChangeEvent], position_to_seq: Callable[[str],# Skip on collision: a source column literally named _ph_cdc_seq must pass# through to the legacy lane untouched. The batch then carries no engine seq- # and the shadow writer skips it. Appended LAST by construction — the caller- # relies on that to strip our column without touching a same-named user one.+ # and the shadow writer skips it.if position_to_seq is not None and CDC_SEQ_COLUMN not in column_names:seq_values = [position_to_seq(event.position_serialized) for event in events]arrays.append(pa.array(seq_values, type=pa.int64()))- fields.append(pa.field(CDC_SEQ_COLUMN, pa.int64()))+ fields.append(pa.field(CDC_SEQ_COLUMN, pa.int64(), metadata=CDC_SEQ_PROVENANCE))schema = pa.schema(fields)return pa.table(arrays, schema=schema)diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/load_resolution.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/load_resolution.pynew file mode 100644index 000000000000..493a0cf9d6f7--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/load_resolution.py@@ -0,0 +1,260 @@+"""Resolve a CDC batch against what its table already holds, before the write.++The engine that performs the write replaces whole rows by primary key and accepts no predicates, so+ordering and delete safety have to be settled on the batch rather than in merge clauses.+"""++from __future__ import annotations++from functools import lru_cache+from typing import Any++import pyarrow as pa++from posthog.dataclasses import frozen++from products.warehouse_sources.backend.temporal.data_imports.cdc.batcher import (+ _CDC_METADATA_COLUMNS,+ CDC_OP_COLUMN,+ CDC_SEQ_COLUMN,+ CDC_SEQ_PROVENANCE,+)++WRITE_RESOLUTION_FLAG = "dwh-cdc-write-resolution"++# Highest position applied, per lane resource name. Sibling of `cdc_last_log_position`, which+# tracks capture — buffered ingress lets the two diverge, since capture runs ahead of load.+LOAD_POSITION_CONFIG_KEY = "cdc_load_position"++# Verification is a diagnostic; cap it so a delete-heavy batch can't dominate the write path.+MAX_VERIFIED_DELETE_ROWS = 1_000+MAX_REPORTED_COLUMNS = 10++# The companion lane. Its table is append-only history, so deduping it would delete versions.+SCD2_APPEND_MODE = "scd2_append"+++@frozen+class ResolutionStats:+ superseded: int+ duplicate_key: int+++@frozen+class DeleteEnrichmentReport:+ delete_rows_checked: int+ rows_with_nulled_columns: int+ columns: tuple[str, ...]++ @property+ def ok(self) -> bool:+ return self.rows_with_nulled_columns == 0+++def _data_columns(table: pa.Table, primary_keys: list[str]) -> list[str]:+ pk_set = set(primary_keys)+ return [c for c in table.column_names if c not in _CDC_METADATA_COLUMNS and c not in pk_set]+++def _pk_tuples(table: pa.Table, primary_keys: list[str]) -> list[tuple]:+ arrays = [table.column(c).to_pylist() for c in primary_keys]+ return [tuple(a[i] for a in arrays) for i in range(table.num_rows)]+++def has_engine_seq(table: pa.Table) -> bool:+ """Whether the position column is ours.++ A source table may have its own `_ph_cdc_seq`, which the batcher passes through untouched, so+ the name proves nothing. Trusting a source value would let it poison the position and have its+ own later rows dropped.+ """+ if CDC_SEQ_COLUMN not in table.column_names:+ return False+ field = table.schema.field(CDC_SEQ_COLUMN)+ return (field.metadata or {}).get(b"posthog_cdc") == CDC_SEQ_PROVENANCE[b"posthog_cdc"]+++def batch_max_seq(table: pa.Table) -> int | None:+ if not has_engine_seq(table) or table.num_rows == 0:+ return None+ values = [v for v in table.column(CDC_SEQ_COLUMN).to_pylist() if v is not None]+ return max(values) if values else None+++def drop_superseded_rows(table: pa.Table, watermark: int | None) -> tuple[pa.Table, int]:+ """Drop rows strictly below `watermark`.++ Rows exactly at it stay: one Postgres transaction shares a commit LSN across every event, and a+ transaction bigger than the flush budget spans batches, so dropping equality would truncate it.+ Re-applying is cheap by comparison — the write is a primary-key upsert.+ """+ if watermark is None or not has_engine_seq(table) or table.num_rows == 0:+ return table, 0++ seqs = table.column(CDC_SEQ_COLUMN).to_pylist()+ # A null position can't be proven stale, so it survives.+ keep = [i for i, s in enumerate(seqs) if s is None or s >= watermark]+ if len(keep) == table.num_rows:+ return table, 0+ return table.take(pa.array(keep, type=pa.int64())), table.num_rows - len(keep)+++def dedupe_keep_highest_seq(table: pa.Table, primary_keys: list[str]) -> tuple[pa.Table, int]:+ """Collapse each primary key to its highest-position row, preserving batch order otherwise.++ deltalite rejects duplicate keys outright, and the writer's keep-last dedupe only matches+ keep-highest while a batch stays ordered by position.+ """+ present_pks = [c for c in primary_keys if c in table.column_names]+ if not has_engine_seq(table) or not present_pks or table.num_rows == 0:+ return table, 0++ seqs = table.column(CDC_SEQ_COLUMN).to_pylist()+ keys = _pk_tuples(table, present_pks)++ best: dict[tuple, int] = {}+ for i, key in enumerate(keys):+ current = best.get(key)+ if current is None:+ best[key] = i+ continue+ incoming, existing = seqs[i], seqs[current]+ if incoming is None or existing is None or incoming >= existing: # ties fall back to keep-last+ best[key] = i++ if len(best) == table.num_rows:+ return table, 0+ keep = sorted(best.values())+ return table.take(pa.array(keep, type=pa.int64())), table.num_rows - len(keep)+++def read_load_position(sync_type_config: dict | None, resource_name: str) -> int | None:+ positions = (sync_type_config or {}).get(LOAD_POSITION_CONFIG_KEY) or {}+ value = positions.get(resource_name)+ return int(value) if isinstance(value, int) or (isinstance(value, str) and value.isdigit()) else None+++def persist_load_position(schema_id: Any, team_id: int, resource_name: str, position: int) -> None:+ """Record the position — only ever after the commit lands.++ That ordering is the safety argument: this value can then only lag the table, never lead it.+ Lagging re-applies rows, which the upsert makes a no-op; leading would skip rows that were never+ written. The locked merge keeps capture's concurrent write to the same JSON column intact.+ """+ from products.warehouse_sources.backend.models.external_data_schema import update_sync_type_config_keys++ def _merge(config: dict[str, Any]) -> None:+ positions = config.setdefault(LOAD_POSITION_CONFIG_KEY, {})+ current = positions.get(resource_name)+ # Monotonic, so a retried older batch can't rewind the guard for later ones.+ if current is None or int(current) < position:+ positions[resource_name] = position++ update_sync_type_config_keys(schema_id, team_id, mutate=_merge)+++def resolve_batch(+ table: pa.Table,+ primary_keys: list[str],+ *,+ watermark: int | None,+ cdc_write_mode: str | None,+) -> tuple[pa.Table, ResolutionStats]:+ """Resolve one lane's batch. Only the consolidated lane dedupes — see SCD2_APPEND_MODE."""+ table, superseded = drop_superseded_rows(table, watermark)++ duplicates = 0+ if cdc_write_mode != SCD2_APPEND_MODE:+ table, duplicates = dedupe_keep_highest_seq(table, primary_keys)++ return table, ResolutionStats(superseded=superseded, duplicate_key=duplicates)+++def verify_delete_enrichment(+ table: pa.Table,+ primary_keys: list[str],+ existing_rows: pa.Table | None,+) -> DeleteEnrichmentReport:+ """Report DELETE rows that would null a data column the target still holds.++ The upsert replaces whole rows, so an unenriched delete erases data with nothing downstream to+ catch it. Reuses the `existing_rows` enrichment already fetched.+ """+ empty = DeleteEnrichmentReport(delete_rows_checked=0, rows_with_nulled_columns=0, columns=())+ if existing_rows is None or existing_rows.num_rows == 0 or table.num_rows == 0:+ return empty+ if CDC_OP_COLUMN not in table.column_names:+ return empty++ present_pks = [c for c in primary_keys if c in table.column_names and c in existing_rows.column_names]+ if not present_pks:+ return empty++ data_cols = [c for c in _data_columns(table, present_pks) if c in existing_rows.column_names]+ if not data_cols:+ return empty++ # Narrow before materializing: a wide table would otherwise pull every data column of the whole+ # batch into Python to inspect a capped handful of rows.+ ops = table.column(CDC_OP_COLUMN).to_pylist()+ delete_indices = [i for i, op in enumerate(ops) if op == "D"][:MAX_VERIFIED_DELETE_ROWS]+ if not delete_indices:+ return empty+ deletes = table.take(pa.array(delete_indices, type=pa.int64()))++ existing_keys = _pk_tuples(existing_rows, present_pks)+ existing_values = {c: existing_rows.column(c).to_pylist() for c in data_cols}+ existing_by_key = {key: {c: existing_values[c][i] for c in data_cols} for i, key in enumerate(existing_keys)}++ keys = _pk_tuples(deletes, present_pks)+ outgoing = {c: deletes.column(c).to_pylist() for c in data_cols}++ checked = 0+ rows_with_nulls = 0+ columns: set[str] = set()+ for i in range(deletes.num_rows):+ previous = existing_by_key.get(keys[i])+ if previous is None:+ continue+ checked += 1+ nulled = [c for c in data_cols if outgoing[c][i] is None and previous[c] is not None]+ if nulled:+ rows_with_nulls += 1+ columns.update(nulled)++ return DeleteEnrichmentReport(+ delete_rows_checked=checked,+ rows_with_nulled_columns=rows_with_nulls,+ columns=tuple(sorted(columns)[:MAX_REPORTED_COLUMNS]),+ )+++@lru_cache(maxsize=2048)+def is_cdc_write_resolution_enabled(team_id: int, schema_id: str, run_uuid: str) -> bool:+ """Per-team rollout gate, resolved once per schema per run.++ Keyed on `run_uuid` to keep a flags round trip off every batch's write path. Fails closed: a+ flags blip must not start dropping rows.+ """+ import posthoganalytics++ from posthog.models import Team++ try:+ team = Team.objects.only("uuid", "organization_id").get(id=team_id)+ return bool(+ posthoganalytics.feature_enabled(+ WRITE_RESOLUTION_FLAG,+ str(team.uuid),+ groups={"organization": str(team.organization_id), "project": str(team_id)},+ person_properties={"team_id": str(team_id), "schema_id": str(schema_id)},+ group_properties={+ "organization": {"id": str(team.organization_id)},+ "project": {"id": str(team_id)},+ },+ only_evaluate_locally=False,+ send_feature_flag_events=False,+ )+ )+ except Exception: # noqa: BLE001+ return Falsediff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_batcher.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_batcher.pyindex 8cb7a51ba58b..d8818487f461 100644--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_batcher.py+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_batcher.py@@ -9,6 +9,7 @@ from parameterized import parameterizedfrom products.warehouse_sources.backend.temporal.data_imports.cdc.batcher import (CDC_OP_COLUMN,CDC_SEQ_COLUMN,+ CDC_SEQ_PROVENANCE,CDC_TIMESTAMP_COLUMN,DELETED_AT_COLUMN,DELETED_COLUMN,@@ -683,6 +684,51 @@ class TestSeqColumn:assert table.column(CDC_SEQ_COLUMN).to_pylist() == [42]# Not last: the caller's strip-by-last-field rule must not remove it.assert table.schema.field(table.num_columns - 1).name != CDC_SEQ_COLUMN+ # Unstamped, so the load side cannot mistake these user values for engine positions.+ assert table.schema.field(CDC_SEQ_COLUMN).metadata is None++ def test_engine_seq_stamp_survives_the_whole_transform_chain(self):+ # The load side gates every position decision on this stamp, and each transform below+ # rebuilds the table. If one of them ever reconstructs the seq field instead of carrying+ # it through, resolution silently turns itself off and every other test still passes.+ from products.warehouse_sources.backend.temporal.data_imports.cdc.load_resolution import has_engine_seq++ batcher = ChangeEventBatcher(position_to_seq=_pg_position_to_seq)+ batcher.add(_make_event(op="I", position="0/100", columns={"id": 1, "name": "a", "big": "x"}))+ batcher.add(+ _make_event(op="U", position="0/150", columns={"id": 1, "name": "b"}, omitted_columns=frozenset({"big"}))+ )+ batcher.add(_make_event(op="D", position="0/200", columns={"id": 1}))+ table = batcher.flush()["users"]++ toasted = enrich_toast_omitted_rows(table, ["id"])+ enriched = enrich_delete_rows(toasted, ["id"])++ assert has_engine_seq(table)+ assert has_engine_seq(toasted)+ assert has_engine_seq(enriched)+ assert has_engine_seq(deduplicate_table(enriched, ["id"]))+ assert has_engine_seq(build_scd2_table(enriched, ["id"]))++ def test_engine_seq_is_stamped_and_survives_a_parquet_round_trip(self):+ # The load side tells our column from a same-named source column by this stamp, and it+ # reads batches back from parquet — so the metadata has to survive the file, not just+ # the in-memory table.+ import io++ import pyarrow.parquet as pq++ batcher = ChangeEventBatcher(position_to_seq=_pg_position_to_seq)+ batcher.add(_make_event(op="I", position="0/100"))+ table = batcher.flush()["users"]++ assert table.schema.field(CDC_SEQ_COLUMN).metadata == CDC_SEQ_PROVENANCE++ buf = io.BytesIO()+ pq.write_table(table, buf)+ restored = pq.read_table(io.BytesIO(buf.getvalue()))++ assert restored.schema.field(CDC_SEQ_COLUMN).metadata == CDC_SEQ_PROVENANCEdef test_seq_survives_enrichment_untouched(self):# Seq is CDC metadata: DELETE/TOAST enrichment must never fill or copy it.diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_extract_activity.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_extract_activity.pyindex 01e714a9a968..135a8c325a42 100644--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_extract_activity.py+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_extract_activity.py@@ -28,7 +28,7 @@ from products.warehouse_sources.backend.temporal.data_imports.cdc.activities impcdc_extract_activity,cleanup_orphan_slots_activity,)-from products.warehouse_sources.backend.temporal.data_imports.cdc.batcher import CDC_SEQ_COLUMN+from products.warehouse_sources.backend.temporal.data_imports.cdc.batcher import CDC_SEQ_COLUMN, CDC_SEQ_PROVENANCEfrom products.warehouse_sources.backend.temporal.data_imports.cdc.errors import CDCErrorCategory, cdc_error_infofrom products.warehouse_sources.backend.temporal.data_imports.cdc.types import ChangeEventfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.jobs_db import (@@ -670,13 +670,42 @@ class TestShadowBufferWrite:legacy_table = mock_s3.write_batch.call_args[0][0]assert legacy_table.column(CDC_SEQ_COLUMN).to_pylist() == [42]- def _hook_activity(self):+ def _hook_activity(self, trailing_column: bool = False):source = _make_source()act = _make_extract_activity(source)schema = _make_schema("users", cdc_mode="streaming", source=source)- table = pa.table({"id": pa.array([1], type=pa.int64()), CDC_SEQ_COLUMN: pa.array([256], type=pa.int64())})+ table = pa.table({"id": pa.array([1], type=pa.int64())}).append_column(+ pa.field(CDC_SEQ_COLUMN, pa.int64(), metadata=CDC_SEQ_PROVENANCE),+ pa.array([256], type=pa.int64()),+ )+ if trailing_column:+ table = table.append_column(pa.field("added_later", pa.string()), pa.array(["x"], type=pa.string()))return act, schema, table+ @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.CDCBufferWriter")+ def test_shadow_writes_when_a_column_sits_after_the_seq_column(self, MockBufferWriter):+ # The hook used to locate the position by index, assuming the batcher appended it last. A+ # column added after it would silently stop buffering, or feed cleanup a restart floor read+ # off the wrong column.+ act, schema, table = self._hook_activity(trailing_column=True)+ MockBufferWriter.return_value.write_batch.return_value = MagicMock(write_duration_seconds=0.01)+ act._shadow_enabled = True++ act._maybe_shadow_write_buffer(schema, "users", table)++ MockBufferWriter.return_value.write_batch.assert_called_once()+ assert MockBufferWriter.return_value.cleanup_superseded_files.call_args.kwargs["restart_seq"] == 256++ @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.CDCBufferWriter")+ def test_shadow_skips_a_source_owned_seq_column(self, MockBufferWriter):+ act, schema, _ = self._hook_activity()+ unstamped = pa.table({"id": pa.array([1], type=pa.int64()), CDC_SEQ_COLUMN: pa.array([999], type=pa.int64())})+ act._shadow_enabled = True++ act._maybe_shadow_write_buffer(schema, "users", unstamped)++ MockBufferWriter.return_value.write_batch.assert_not_called()+@patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.CDCBufferWriter")def test_shadow_file_index_increments_per_table_including_failures(self, MockBufferWriter):act, schema, table = self._hook_activity()diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_load_resolution.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_load_resolution.pynew file mode 100644index 000000000000..7003670ab799--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_load_resolution.py@@ -0,0 +1,367 @@+from typing import Any++import pytest+from unittest.mock import MagicMock, patch++import pyarrow as pa+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.cdc.batcher import (+ CDC_OP_COLUMN,+ CDC_SEQ_COLUMN,+ CDC_SEQ_PROVENANCE,+ DELETED_COLUMN,+)+from products.warehouse_sources.backend.temporal.data_imports.cdc.load_resolution import (+ LOAD_POSITION_CONFIG_KEY,+ MAX_VERIFIED_DELETE_ROWS,+ SCD2_APPEND_MODE,+ batch_max_seq,+ dedupe_keep_highest_seq,+ drop_superseded_rows,+ has_engine_seq,+ is_cdc_write_resolution_enabled,+ persist_load_position,+ read_load_position,+ resolve_batch,+ verify_delete_enrichment,+)+++def _batch(ids, names, ops, seqs=None, engine_seq=True):+ """A CDC batch. `engine_seq=False` builds the seq column WITHOUT the batcher's provenance+ stamp — i.e. a source table that happens to have its own `_ph_cdc_seq` column."""+ columns = {+ "id": pa.array(ids, pa.int64()),+ "name": pa.array(names, pa.string()),+ CDC_OP_COLUMN: pa.array(ops, pa.string()),+ DELETED_COLUMN: pa.array([op == "D" for op in ops], pa.bool_()),+ }+ table = pa.table(columns)+ if seqs is None:+ return table++ metadata = CDC_SEQ_PROVENANCE if engine_seq else None+ field = pa.field(CDC_SEQ_COLUMN, pa.int64(), metadata=metadata)+ return table.append_column(field, pa.array(seqs, pa.int64()))+++def _existing(ids, names):+ return pa.table({"id": pa.array(ids, pa.int64()), "name": pa.array(names, pa.string())})+++class TestBatchMaxSeq:+ def test_none_without_seq_column(self):+ assert batch_max_seq(_batch([1], ["a"], ["I"])) is None++ def test_none_when_empty(self):+ assert batch_max_seq(_batch([], [], [], seqs=[])) is None++ def test_ignores_nulls(self):+ table = _batch([1, 2, 3], ["a", "b", "c"], ["I", "I", "I"], seqs=[10, None, 30])+ assert batch_max_seq(table) == 30+++class TestDropSupersededRows:+ def test_passthrough_without_watermark(self):+ table = _batch([1, 2], ["a", "b"], ["I", "I"], seqs=[10, 20])+ result, dropped = drop_superseded_rows(table, None)+ assert dropped == 0+ assert result is table++ def test_passthrough_without_seq_column(self):+ table = _batch([1, 2], ["a", "b"], ["I", "I"])+ result, dropped = drop_superseded_rows(table, 99)+ assert dropped == 0+ assert result is table++ def test_drops_only_rows_strictly_below_watermark(self):+ table = _batch([1, 2, 3], ["a", "b", "c"], ["I", "I", "I"], seqs=[10, 20, 30])+ result, dropped = drop_superseded_rows(table, 20)++ assert dropped == 1+ assert result.column("id").to_pylist() == [2, 3]++ def test_keeps_later_chunks_of_a_split_transaction(self):+ # Every event in one Postgres transaction shares its commit LSN, and a transaction bigger+ # than the flush budget spans micro-batches. Dropping seq == watermark would discard the+ # rest of the transaction outright.+ table = _batch([3, 4], ["c", "d"], ["I", "I"], seqs=[20, 20])+ result, dropped = drop_superseded_rows(table, 20)++ assert dropped == 0+ assert result.column("id").to_pylist() == [3, 4]++ def test_keeps_null_positions(self):+ # An unknown position cannot be proven stale; dropping it would lose data.+ table = _batch([1, 2], ["a", "b"], ["I", "I"], seqs=[None, 5])+ result, dropped = drop_superseded_rows(table, 10)++ assert dropped == 1+ assert result.column("id").to_pylist() == [1]++ def test_drops_replayed_rows_below_the_watermark(self):+ table = _batch([1, 2], ["a", "b"], ["I", "I"], seqs=[10, 20])+ result, dropped = drop_superseded_rows(table, 30)++ assert dropped == 2+ assert result.num_rows == 0++ def test_ignores_a_source_owned_seq_column(self):+ # The batcher passes through a source column named _ph_cdc_seq untouched, so its values+ # are user data. Trusting them would let a source set a high value, poison the watermark,+ # and have its own later rows dropped.+ table = _batch([1, 2], ["a", "b"], ["I", "I"], seqs=[10, 20], engine_seq=False)+ result, dropped = drop_superseded_rows(table, 15)++ assert dropped == 0+ assert result is table+ assert not has_engine_seq(table)+ assert batch_max_seq(table) is None+++class TestDedupeKeepHighestSeq:+ def test_passthrough_without_seq_column(self):+ table = _batch([1, 1], ["a", "b"], ["I", "U"])+ result, dropped = dedupe_keep_highest_seq(table, ["id"])+ assert dropped == 0+ assert result is table++ def test_keeps_highest_position_per_key(self):+ table = _batch([1, 1, 2], ["old", "new", "other"], ["I", "U", "I"], seqs=[10, 20, 15])+ result, dropped = dedupe_keep_highest_seq(table, ["id"])++ assert dropped == 1+ assert result.column("name").to_pylist() == ["new", "other"]++ def test_keeps_highest_even_when_batch_is_out_of_order(self):+ table = _batch([1, 1], ["new", "old"], ["U", "I"], seqs=[20, 10])+ result, dropped = dedupe_keep_highest_seq(table, ["id"])++ assert dropped == 1+ assert result.column("name").to_pylist() == ["new"]++ def test_ties_keep_later_row(self):+ table = _batch([1, 1], ["first", "second"], ["U", "U"], seqs=[10, 10])+ result, _ = dedupe_keep_highest_seq(table, ["id"])++ assert result.column("name").to_pylist() == ["second"]++ def test_composite_keys(self):+ table = pa.table(+ {+ "a": pa.array([1, 1, 1], pa.int64()),+ "b": pa.array(["x", "x", "y"], pa.string()),+ CDC_OP_COLUMN: pa.array(["I", "U", "I"], pa.string()),+ }+ ).append_column(+ pa.field(CDC_SEQ_COLUMN, pa.int64(), metadata=CDC_SEQ_PROVENANCE),+ pa.array([10, 20, 30], pa.int64()),+ )+ result, dropped = dedupe_keep_highest_seq(table, ["a", "b"])++ assert dropped == 1+ assert result.column(CDC_SEQ_COLUMN).to_pylist() == [20, 30]++ def test_no_duplicates_returns_original(self):+ table = _batch([1, 2], ["a", "b"], ["I", "I"], seqs=[10, 20])+ result, dropped = dedupe_keep_highest_seq(table, ["id"])+ assert dropped == 0+ assert result is table+++class TestResolveBatch:+ def test_consolidated_lane_drops_superseded_and_dedupes(self):+ table = _batch([1, 1, 2], ["old", "new", "other"], ["I", "U", "I"], seqs=[10, 20, 30])+ result, stats = resolve_batch(table, ["id"], watermark=None, cdc_write_mode="incremental_merge")++ assert stats.superseded == 0+ assert stats.duplicate_key == 1+ assert result.column("name").to_pylist() == ["new", "other"]++ def test_history_lane_keeps_every_version_of_a_key(self):+ # The companion table is append-only history: deduping it would delete versions, not+ # resolve a conflict.+ table = _batch([1, 1], ["v1", "v2"], ["I", "U"], seqs=[10, 20])+ result, stats = resolve_batch(table, ["id"], watermark=None, cdc_write_mode=SCD2_APPEND_MODE)++ assert stats.duplicate_key == 0+ assert result.column("name").to_pylist() == ["v1", "v2"]++ def test_history_lane_still_drops_already_applied_rows(self):+ # Replaying a buffer file into the companion is how duplicate history rows arise.+ table = _batch([1, 1], ["v1", "v2"], ["I", "U"], seqs=[10, 20])+ result, stats = resolve_batch(table, ["id"], watermark=15, cdc_write_mode=SCD2_APPEND_MODE)++ assert stats.superseded == 1+ assert result.column("name").to_pylist() == ["v2"]++ def test_source_owned_seq_column_disables_resolution_entirely(self):+ table = _batch([1, 1], ["old", "new"], ["I", "U"], seqs=[99, 1], engine_seq=False)+ result, stats = resolve_batch(table, ["id"], watermark=50, cdc_write_mode="incremental_merge")++ assert (stats.superseded, stats.duplicate_key) == (0, 0)+ assert result is table++ def test_noop_on_batches_without_positions(self):+ table = _batch([1, 2], ["a", "b"], ["I", "I"])+ result, stats = resolve_batch(table, ["id"], watermark=99, cdc_write_mode="incremental_merge")++ assert (stats.superseded, stats.duplicate_key) == (0, 0)+ assert result is table+++class TestVerifyDeleteEnrichment:+ def test_enriched_delete_is_clean(self):+ table = _batch([1], ["alice"], ["D"])+ report = verify_delete_enrichment(table, ["id"], _existing([1], ["alice"]))++ assert report.ok+ assert report.delete_rows_checked == 1+ assert report.columns == ()++ def test_unenriched_delete_is_reported(self):+ table = _batch([1], [None], ["D"])+ report = verify_delete_enrichment(table, ["id"], _existing([1], ["alice"]))++ assert not report.ok+ assert report.rows_with_nulled_columns == 1+ assert report.columns == ("name",)++ def test_ignores_non_delete_rows(self):+ # A NULL on an UPDATE is the source's own value, not lost data.+ table = _batch([1], [None], ["U"])+ report = verify_delete_enrichment(table, ["id"], _existing([1], ["alice"]))++ assert report.ok+ assert report.delete_rows_checked == 0++ def test_ignores_deletes_with_no_existing_row(self):+ # Unmatched delete becomes a tombstone insert; there is no data to lose.+ table = _batch([2], [None], ["D"])+ report = verify_delete_enrichment(table, ["id"], _existing([1], ["alice"]))++ assert report.ok+ assert report.delete_rows_checked == 0++ def test_null_in_target_is_not_a_violation(self):+ table = _batch([1], [None], ["D"])+ report = verify_delete_enrichment(table, ["id"], _existing([1], [None]))++ assert report.ok++ @parameterized.expand(+ [("no_existing_rows", None), ("empty_existing_rows", pa.table({"id": pa.array([], pa.int64())}))]+ )+ def test_returns_empty_without_target_state(self, _name, existing):+ table = _batch([1], [None], ["D"])+ assert verify_delete_enrichment(table, ["id"], existing).ok++ def test_checked_rows_are_capped(self):+ n = MAX_VERIFIED_DELETE_ROWS + 10+ ids = list(range(n))+ table = _batch(ids, [None] * n, ["D"] * n)+ report = verify_delete_enrichment(table, ["id"], _existing(ids, [f"name{i}" for i in ids]))++ assert report.delete_rows_checked == MAX_VERIFIED_DELETE_ROWS+++class TestLoadPosition:+ @parameterized.expand(+ [+ ("absent_config", None, None),+ ("empty_config", {}, None),+ ("other_lane_only", {LOAD_POSITION_CONFIG_KEY: {"users_cdc": 99}}, None),+ ("int_value", {LOAD_POSITION_CONFIG_KEY: {"users": 42}}, 42),+ # JSON round-trips can hand back strings; a bad value must read as "unknown", not 0.+ ("string_value", {LOAD_POSITION_CONFIG_KEY: {"users": "42"}}, 42),+ ("garbage_value", {LOAD_POSITION_CONFIG_KEY: {"users": "not-a-number"}}, None),+ ("null_value", {LOAD_POSITION_CONFIG_KEY: {"users": None}}, None),+ ]+ )+ def test_read(self, _name, config, expected):+ assert read_load_position(config, "users") == expected++ def test_persist_creates_the_key_and_leaves_siblings_alone(self):+ captured: dict[str, Any] = {"cdc_last_log_position": "0/ABC"}++ def fake_update(schema_id, team_id, *, mutate=None, **kwargs):+ mutate(captured)++ with patch(+ "products.warehouse_sources.backend.models.external_data_schema.update_sync_type_config_keys",+ side_effect=fake_update,+ ):+ persist_load_position("schema-1", 2, "users", 100)++ assert captured[LOAD_POSITION_CONFIG_KEY] == {"users": 100}+ # Capture's own position lives in the same JSON column and must survive.+ assert captured["cdc_last_log_position"] == "0/ABC"++ @parameterized.expand([("advances", 50, 100, 100), ("never_rewinds", 100, 50, 100), ("equal", 100, 100, 100)])+ def test_persist_is_monotonic(self, _name, existing, incoming, expected):+ captured = {LOAD_POSITION_CONFIG_KEY: {"users": existing}}++ def fake_update(schema_id, team_id, *, mutate=None, **kwargs):+ mutate(captured)++ with patch(+ "products.warehouse_sources.backend.models.external_data_schema.update_sync_type_config_keys",+ side_effect=fake_update,+ ):+ persist_load_position("schema-1", 2, "users", incoming)++ assert captured[LOAD_POSITION_CONFIG_KEY]["users"] == expected+++class TestIsCdcWriteResolutionEnabled:+ @pytest.fixture(autouse=True)+ def _clear_cache(self):+ # The helper memoizes per run; tests reuse ids, so a stale entry would leak between them.+ is_cdc_write_resolution_enabled.cache_clear()+ yield+ is_cdc_write_resolution_enabled.cache_clear()++ def _team(self):+ team = MagicMock()+ team.uuid = "team-uuid"+ team.organization_id = "org-id"+ return team++ @parameterized.expand([("on", True), ("off", False)])+ def test_follows_the_flag(self, _name, flag_value):+ with (+ patch("posthog.models.Team.objects") as objects,+ patch("posthoganalytics.feature_enabled", return_value=flag_value) as feature_enabled,+ ):+ objects.only.return_value.get.return_value = self._team()+ assert is_cdc_write_resolution_enabled(2, "schema-1", "run-1") is flag_value++ assert feature_enabled.call_args.kwargs["person_properties"] == {"team_id": "2", "schema_id": "schema-1"}++ def test_evaluates_once_per_run_then_again_on_the_next_run(self):+ with (+ patch("posthog.models.Team.objects") as objects,+ patch("posthoganalytics.feature_enabled", return_value=True) as feature_enabled,+ ):+ objects.only.return_value.get.return_value = self._team()+ for _ in range(5):+ assert is_cdc_write_resolution_enabled(2, "schema-1", "run-1") is True+ assert feature_enabled.call_count == 1++ # A new run re-reads it, so a flag flip lands within one run rather than one pod.+ assert is_cdc_write_resolution_enabled(2, "schema-1", "run-2") is True+ assert feature_enabled.call_count == 2++ def test_fails_closed_when_flag_service_raises(self):+ with (+ patch("posthog.models.Team.objects") as objects,+ patch("posthoganalytics.feature_enabled", side_effect=Exception("flags down")),+ ):+ objects.only.return_value.get.return_value = self._team()+ assert is_cdc_write_resolution_enabled(2, "schema-1", "run-1") is False++ def test_fails_closed_when_team_is_missing(self):+ with patch("posthog.models.Team.objects") as objects:+ objects.only.return_value.get.side_effect = Exception("no such team")+ assert is_cdc_write_resolution_enabled(2, "schema-1", "run-1") is Falsediff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/metrics.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/metrics.pyindex 363981780069..2fd0faec4abd 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/metrics.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/metrics.py@@ -57,6 +57,20 @@ DELTA_COARSEN_DECLINE_TOTAL = Counter(labelnames=["reason"],)+CDC_SEQ_GUARD_ROWS_DROPPED_TOTAL = Counter(+ "warehouse_load_cdc_seq_guard_rows_dropped_total",+ "CDC rows dropped before the write as already-applied, by reason",+ labelnames=["team_id", "reason"],+)++# Non-zero means a DELETE is about to erase data the target still holds. Alert on this; enrichment+# failing has no other detector.+CDC_DELETE_ENRICHMENT_VIOLATIONS_TOTAL = Counter(+ "warehouse_load_cdc_delete_enrichment_violations_total",+ "DELETE rows that would null a data column the target currently holds",+ labelnames=["team_id"],+)+# deltalite real-write path (phase 2). `outcome` is one of:# written - deltalite performed the incremental merge and committed# fallback - deltalite was enabled but failed (or refused), so the delta-rs MERGE ran insteaddiff --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.pyindex ded1d3e2d71d..1b3ebbe7a85c 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@@ -33,6 +33,15 @@ from products.warehouse_sources.backend.temporal.data_imports.cdc.batcher importenrich_delete_rows,enrich_toast_omitted_rows,)+from products.warehouse_sources.backend.temporal.data_imports.cdc.load_resolution import (+ batch_max_seq,+ has_engine_seq,+ is_cdc_write_resolution_enabled,+ persist_load_position,+ read_load_position,+ resolve_batch,+ verify_delete_enrichment,+)from products.warehouse_sources.backend.temporal.data_imports.pipelines.common.load import (run_post_load_operations,supports_partial_data_loading,@@ -64,6 +73,8 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipelinemark_batch_as_processed,)from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.load.metrics import (+ CDC_DELETE_ENRICHMENT_VIOLATIONS_TOTAL,+ CDC_SEQ_GUARD_ROWS_DROPPED_TOTAL,DELTA_ROWS_WRITTEN_TOTAL,DELTA_WRITE_DURATION_SECONDS,IDEMPOTENCY_HIT_TOTAL,@@ -123,6 +134,8 @@ def _enrich_cdc_rows(cdc_write_mode: str | None,existing_delta_table: deltalake.DeltaTable | None,batch_index: int,+ verify_deletes: bool = False,+ team_id: str = "",) -> pa.Table:"""Cross-batch CDC enrichment against the existing DeltaLake state.@@ -198,12 +211,60 @@ def _enrich_cdc_rows(pa_table = enrich_toast_omitted_rows(pa_table, primary_keys, existing_rows)pa_table = enrich_delete_rows(pa_table, primary_keys, existing_rows)+ # Only place the previous state is still in hand to compare against.+ if verify_deletes and delete_key_set:+ report = verify_delete_enrichment(pa_table, present_pks, existing_rows)+ if not report.ok:+ CDC_DELETE_ENRICHMENT_VIOLATIONS_TOTAL.labels(team_id=team_id).inc(+ report.rows_with_nulled_columns+ )+ logger.warning(+ "cdc_delete_enrichment_violation",+ delete_rows_checked=report.delete_rows_checked,+ rows_with_nulled_columns=report.rows_with_nulled_columns,+ columns=list(report.columns),+ cdc_write_mode=cdc_write_mode,+ batch_index=batch_index,+ )+if TOAST_OMITTED_COLUMN in pa_table.column_names:pa_table = pa_table.drop_columns([TOAST_OMITTED_COLUMN])return pa_table+def _resolve_cdc_positions(+ pa_table: pa.Table,+ *,+ sync_type_config: dict | None,+ resource_name: str,+ primary_keys: list[str],+ cdc_write_mode: str | None,+ team_id: str,+) -> tuple[pa.Table, int | None]:+ """Drop rows this lane's table has already applied.++ Returns the batch and the position to record, which the caller persists only once the write+ commits — a position ahead of the table would skip rows that never landed.+ """+ if not has_engine_seq(pa_table):+ return pa_table, None++ watermark = read_load_position(sync_type_config, resource_name)++ pa_table, stats = resolve_batch(+ pa_table,+ primary_keys,+ watermark=watermark,+ cdc_write_mode=cdc_write_mode,+ )+ for reason, dropped in (("superseded", stats.superseded), ("duplicate_key", stats.duplicate_key)):+ if dropped:+ CDC_SEQ_GUARD_ROWS_DROPPED_TOTAL.labels(team_id=team_id, reason=reason).inc(dropped)++ return pa_table, batch_max_seq(pa_table)++def _apply_partitioning(export_signal: ExportSignalMessage,pa_table: pa.Table,@@ -813,14 +874,31 @@ def _process_message_reported("batch_index": str(export_signal.batch_index),}+ resolution_enabled = cdc_write_mode is not None and is_cdc_write_resolution_enabled(+ export_signal.team_id, schema_id_str, export_signal.run_uuid+ )+pa_table = _enrich_cdc_rows(pa_table,primary_keys=primary_keys,cdc_write_mode=cdc_write_mode,existing_delta_table=existing_delta_table,batch_index=export_signal.batch_index,+ verify_deletes=resolution_enabled,+ team_id=team_id_str,)+ pending_load_position: int | None = None+ if resolution_enabled:+ pa_table, pending_load_position = _resolve_cdc_positions(+ pa_table,+ sync_type_config=schema.sync_type_config,+ resource_name=export_signal.resource_name,+ primary_keys=primary_keys or [],+ cdc_write_mode=cdc_write_mode,+ team_id=team_id_str,+ )+if existing_delta_table is not None:try:pa_table = evolve_pyarrow_schema(pa_table, existing_delta_table.schema())@@ -885,6 +963,16 @@ def _process_message_reported(DELTA_ROWS_WRITTEN_TOTAL.labels(team_id=team_id_str, schema_id=schema_id_str).inc(pa_table.num_rows)+ if pending_load_position is not None:+ # Best-effort: failing here would fail a batch that is already written, and the cost of+ # losing the position is re-applying rows next time, which is a no-op.+ try:+ persist_load_position(+ schema.id, export_signal.team_id, export_signal.resource_name, pending_load_position+ )+ except Exception: # noqa: BLE001 - bookkeeping must never fail a committed write+ logger.warning("cdc_load_position_persist_failed", exc_info=True)+internal_schema = HogQLSchema()# Build from the Delta table schema first to cover all columns from# all batches, then overlay the current batch for JSON detection.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.pyindex 6e746ca292aa..d675c98612fe 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@@ -12,9 +12,11 @@ from temporalio.service import RPCError, RPCStatusCodefrom products.warehouse_sources.backend.temporal.data_imports.cdc.batcher import (CDC_OP_COLUMN,+ CDC_SEQ_COLUMN,SCD2_VALID_TO_COLUMN,TOAST_OMITTED_COLUMN,)+from products.warehouse_sources.backend.temporal.data_imports.cdc.load_resolution import LOAD_POSITION_CONFIG_KEYfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.core.consts import PARTITION_KEYfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.load.processor import (_apply_partitioning,@@ -23,6 +25,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_mark_job_completed,_promote_staged_cursor,_read_existing_rows_by_first_pk,+ _resolve_cdc_positions,_run_post_load_for_already_processed_batch,_trigger_post_import_workflow,process_message,@@ -698,6 +701,147 @@ class TestEnrichCdcRows:})+ def _stamped(self, ids: list[int], ops: list[str], seqs: list[int]) -> pa.Table:+ from products.warehouse_sources.backend.temporal.data_imports.cdc.batcher import CDC_SEQ_PROVENANCE++ table = pa.table(+ {+ "id": pa.array(ids, pa.int64()),+ "name": pa.array([f"n{i}" for i in ids], pa.string()),+ CDC_OP_COLUMN: pa.array(ops, pa.string()),+ }+ )+ return table.append_column(+ pa.field(CDC_SEQ_COLUMN, pa.int64(), metadata=CDC_SEQ_PROVENANCE), pa.array(seqs, pa.int64())+ )++ def _resolve(self, table: pa.Table, *, watermark: int | None, cdc_write_mode: str = "incremental_merge"):+ config = {LOAD_POSITION_CONFIG_KEY: {"users": watermark}} if watermark is not None else {}+ return _resolve_cdc_positions(+ table,+ sync_type_config=config,+ resource_name="users",+ primary_keys=["id"],+ cdc_write_mode=cdc_write_mode,+ team_id="2",+ )++ def test_resolution_drops_applied_rows_and_returns_the_new_position(self):+ table = self._stamped([1, 2, 3], ["I", "I", "I"], [10, 20, 30])+ result, position = self._resolve(table, watermark=20)++ # Strictly-below only: 20 stays, because a split transaction shares its commit position.+ assert result.column("id").to_pylist() == [2, 3]+ assert position == 30++ def test_resolution_is_skipped_without_an_engine_stamped_position(self):+ # A source column named _ph_cdc_seq must not drive the guard.+ table = self._stamped([1, 2], ["I", "I"], [10, 20]).drop_columns([CDC_SEQ_COLUMN])+ table = table.append_column(pa.field(CDC_SEQ_COLUMN, pa.int64()), pa.array([10, 20], pa.int64()))+ result, position = self._resolve(table, watermark=99)++ assert result is table+ assert position is None++ def test_resolution_keeps_every_row_on_the_first_batch_ever(self):+ # No recorded position yet: nothing is provably applied, so nothing may be dropped.+ table = self._stamped([1, 2], ["I", "I"], [10, 20])+ result, position = self._resolve(table, watermark=None)++ assert result.column("id").to_pylist() == [1, 2]+ assert position == 20++ def test_resolution_reads_the_position_for_its_own_lane_only(self):+ # Consolidated and companion tables advance independently; one must not gate the other.+ table = self._stamped([1, 2], ["I", "I"], [10, 20])+ result, _ = _resolve_cdc_positions(+ table,+ sync_type_config={LOAD_POSITION_CONFIG_KEY: {"users_cdc": 99}},+ resource_name="users",+ primary_keys=["id"],+ cdc_write_mode="incremental_merge",+ team_id="2",+ )++ assert result.num_rows == 2++ def test_resolution_does_not_dedupe_the_history_lane(self):+ table = self._stamped([1, 1], ["I", "U"], [10, 20])+ result, _ = self._resolve(table, watermark=None, cdc_write_mode="scd2_append")++ assert result.num_rows == 2++ def _write_existing(self, path: str) -> None:+ write_deltalake(+ path,+ pa.table(+ {+ "id": pa.array([1], pa.int64()),+ "name": pa.array(["one"], pa.string()),+ "big": pa.array(["toasted-1"], pa.string()),+ }+ ),+ mode="overwrite",+ )++ def test_verification_stays_quiet_when_enrichment_filled_the_delete(self):+ with tempfile.TemporaryDirectory() as path:+ self._write_existing(path)++ with patch(f"{_PROCESSOR}.CDC_DELETE_ENRICHMENT_VIOLATIONS_TOTAL") as violations:+ _enrich_cdc_rows(+ self._batch([{"id": 1, "op": "D"}]),+ primary_keys=["id"],+ cdc_write_mode="incremental_merge",+ existing_delta_table=DeltaTable(path),+ batch_index=0,+ verify_deletes=True,+ team_id="2",+ )++ violations.labels.assert_not_called()++ def test_verification_reports_a_delete_that_would_null_target_data(self):+ with tempfile.TemporaryDirectory() as path:+ self._write_existing(path)++ # Enrichment silently doing nothing is the failure this lane exists to catch: under+ # deltalite the upsert replaces the whole row, so those nulls would land in the table.+ with (+ patch(f"{_PROCESSOR}.enrich_delete_rows", side_effect=lambda table, *_a, **_kw: table),+ patch(f"{_PROCESSOR}.CDC_DELETE_ENRICHMENT_VIOLATIONS_TOTAL") as violations,+ ):+ _enrich_cdc_rows(+ self._batch([{"id": 1, "op": "D"}]),+ primary_keys=["id"],+ cdc_write_mode="incremental_merge",+ existing_delta_table=DeltaTable(path),+ batch_index=0,+ verify_deletes=True,+ team_id="2",+ )++ violations.labels.assert_called_once_with(team_id="2")+ violations.labels.return_value.inc.assert_called_once_with(1)++ def test_verification_is_skipped_when_the_flag_is_off(self):+ with tempfile.TemporaryDirectory() as path:+ self._write_existing(path)++ with (+ patch(f"{_PROCESSOR}.enrich_delete_rows", side_effect=lambda table, *_a, **_kw: table),+ patch(f"{_PROCESSOR}.verify_delete_enrichment") as verify,+ ):+ _enrich_cdc_rows(+ self._batch([{"id": 1, "op": "D"}]),+ primary_keys=["id"],+ cdc_write_mode="incremental_merge",+ existing_delta_table=DeltaTable(path),+ batch_index=0,+ )++ verify.assert_not_called()+def test_fills_toast_and_delete_rows_from_delta_state_and_drops_marker(self):with tempfile.TemporaryDirectory() as path:write_deltalake(diff --git a/products/warehouse_sources/backend/tests/management/test_validate_cdc_buffer.py b/products/warehouse_sources/backend/tests/management/test_validate_cdc_buffer.pyindex d8527d8ac764..5be491955de8 100644--- a/products/warehouse_sources/backend/tests/management/test_validate_cdc_buffer.py+++ b/products/warehouse_sources/backend/tests/management/test_validate_cdc_buffer.py@@ -66,7 +66,7 @@ def _schema_mock(mode: str = "consolidated", cdc_mode: str = "streaming"):class TestValidateCDCBuffer:- def _run(self, schema, files, legacy: dict[tuple[str, str], int], runs: dict[str, int] | None = None):+ def _run(self, schema, files, legacy: dict[tuple[str, str], int], retried: dict[str, int] | None = None):source = MagicMock()source.id = uuid.uuid4()@@ -77,7 +77,7 @@ class TestValidateCDCBuffer:patch.object(__import__(_CMD, fromlist=["Command"]).Command,"_fetch_legacy_row_sums",- return_value=(legacy, runs or {}),+ return_value=(legacy, retried or {}),),):MockSource.objects.get.return_value = source@@ -106,12 +106,21 @@ class TestValidateCDCBuffer:with pytest.raises(CommandError, match="violation"):self._run(schema, files, {(str(schema.id), "scd2"): 5})- def test_scd2_mismatch_downgrades_to_warning_with_multiple_runs(self):+ def test_scd2_mismatch_downgrades_to_warning_after_a_retry(self):# Legacy re-inserts replayed rows on activity retry while buffer files- # overwrite, so with >1 run in the window the exact match only warns.+ # overwrite, so a re-dispatched batch makes the exact match only warn.schema = _schema_mock(mode="cdc_only")files = {self._key(schema, build_buffer_file_name(100, 200, 0)): _parquet_bytes(3)}- self._run(schema, files, {(str(schema.id), "scd2"): 5}, runs={str(schema.id): 2})+ self._run(schema, files, {(str(schema.id), "scd2"): 5}, retried={str(schema.id): 1})++ def test_scd2_mismatch_still_fails_when_no_batch_was_retried(self):+ # Regression: the downgrade used to key on the count of distinct run_uuids, which a+ # healthy 5-min source increments every tick — so any window longer than one tick+ # waived the exact match entirely and the gate asserted nothing.+ schema = _schema_mock(mode="cdc_only")+ files = {self._key(schema, build_buffer_file_name(100, 200, 0)): _parquet_bytes(3)}+ with pytest.raises(CommandError, match="violation"):+ self._run(schema, files, {(str(schema.id), "scd2"): 5}, retried={str(schema.id): 0})def test_fails_when_buffer_below_consolidated(self):schema = _schema_mock(mode="consolidated")@@ -222,7 +231,7 @@ class TestFetchLegacyRowSums:asyncio.run(seed())- def test_counts_only_cdc_dispatches_and_distinct_runs(self):+ def test_counts_only_cdc_dispatches_and_reports_no_retry(self):command_module = __import__(_CMD, fromlist=["Command"])source = MagicMock()source.id = "source-1"@@ -267,9 +276,47 @@ class TestFetchLegacyRowSums:)with patch.object(command_module, "WAREHOUSE_SOURCES_DATABASE_URL", self._url):- sums, run_counts = command_module.Command()._fetch_legacy_row_sums(+ sums, retried_batches = command_module.Command()._fetch_legacy_row_sums(source, datetime.now(UTC) - timedelta(hours=1))assert sums == {(schema_id, "consolidated"): 15, (schema_id, "scd2"): 7}- assert run_counts[schema_id] == 2+ # Two distinct runs, but every (run_uuid, batch_index) dispatched once: no retry.+ assert retried_batches[schema_id] == 0++ def test_detects_a_redispatched_batch_as_a_retry(self):+ command_module = __import__(_CMD, fromlist=["Command"])+ source = MagicMock()+ source.id = "source-1"+ schema_id = "schema-1"++ self._seed(+ [+ {+ "schema_id": schema_id,+ "sync_type": "cdc",+ "resource_name": "users_cdc",+ "row_count": 7,+ "run_uuid": "r1",+ "batch_index": 0,+ },+ # Same (run_uuid, batch_index) dispatched again — the replay an activity+ # retry produces, and the only thing that legitimately skews the exact match.+ {+ "schema_id": schema_id,+ "sync_type": "cdc",+ "resource_name": "users_cdc",+ "row_count": 7,+ "run_uuid": "r1",+ "batch_index": 0,+ },+ ]+ )++ with patch.object(command_module, "WAREHOUSE_SOURCES_DATABASE_URL", self._url):+ sums, retried_batches = command_module.Command()._fetch_legacy_row_sums(+ source, datetime.now(UTC) - timedelta(hours=1)+ )++ assert sums == {(schema_id, "scd2"): 14}+ assert retried_batches[schema_id] == 1