: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): preserve unchanged TOAST columns in postgres CDC updates (#72435)
Daniel RC90e9183c6921
diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.pyindex 060c6782ecff..ac42163bc861 100644--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.py+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.py@@ -48,6 +48,7 @@ from products.warehouse_sources.backend.temporal.data_imports.cdc.batcher importbuild_scd2_table,deduplicate_table,enrich_delete_rows,+ enrich_toast_omitted_rows,)from products.warehouse_sources.backend.temporal.data_imports.cdc.broken import mark_cdc_brokenfrom products.warehouse_sources.backend.temporal.data_imports.cdc.errors import (@@ -609,7 +610,10 @@ class CDCExtractActivity:key_columns = self.pk_columns_by_table.get(table_name, [])cdc_table_mode = schema.cdc_table_mode- enriched_table = enrich_delete_rows(raw_table, key_columns)+ # TOAST fill first so DELETE enrichment copies resolved values, not the+ # nulls standing in for omitted columns.+ enriched_table = enrich_toast_omitted_rows(raw_table, key_columns)+ enriched_table = enrich_delete_rows(enriched_table, key_columns)# Consolidated shares the snapshot's canonical folder; the `_cdc` companion is# CDC-only and stays self-consistent with its `name`-keyed snapshot seed.@@ -953,7 +957,10 @@ class CDCExtractActivity:if retained is None:return eventfiltered = {name: value for name, value in event.columns.items() if name in retained}- if filtered.keys() == event.columns.keys():+ # Omitted (unchanged-TOAST) markers for disabled columns must go too, or the+ # batcher would materialize a disabled column just to carry the marker.+ filtered_omitted = frozenset(name for name in event.omitted_columns if name in retained)+ if filtered.keys() == event.columns.keys() and filtered_omitted == event.omitted_columns:return eventreturn ChangeEvent(operation=event.operation,@@ -962,6 +969,7 @@ class CDCExtractActivity:timestamp=event.timestamp,columns=filtered,column_types=event.column_types,+ omitted_columns=filtered_omitted,)def _qualified_table_name(self, schema: ExternalDataSchema) -> str:diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/batcher.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/batcher.pyindex e44df3b008e4..0b00d3b1b9f3 100644--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/batcher.py+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/batcher.py@@ -11,6 +11,11 @@ CDC_OP_COLUMN = "_ph_cdc_op"CDC_TIMESTAMP_COLUMN = "_ph_cdc_timestamp"DELETED_COLUMN = "_ph_deleted"DELETED_AT_COLUMN = "_ph_deleted_at"+# Per-row list of source columns the change stream omitted because they are+# unchanged from the previous row version (Postgres: unchanged TOAST values).+# Consumed by enrich_toast_omitted_rows; the load processor drops it before+# writing to DeltaLake.+TOAST_OMITTED_COLUMN = "_ph_toast_omitted"# SCD Type 2 columns added to the _cdc history tableSCD2_VALID_FROM_COLUMN = "valid_from"@@ -24,6 +29,7 @@ _CDC_METADATA_COLUMNS: frozenset[str] = frozenset(CDC_TIMESTAMP_COLUMN,DELETED_COLUMN,DELETED_AT_COLUMN,+ TOAST_OMITTED_COLUMN,SCD2_VALID_FROM_COLUMN,SCD2_VALID_TO_COLUMN,}@@ -102,6 +108,8 @@ class ChangeEventBatcher:size += len(val)elif val is not None:size += 8+ for name in event.omitted_columns:+ size += len(name) + 50 # marker name + set entry overheadreturn size@@ -249,6 +257,116 @@ def enrich_delete_rows(return result+def enrich_toast_omitted_rows(+ table: pa.Table,+ pk_columns: list[str],+ existing_rows: pa.Table | None = None,+) -> pa.Table:+ """Fill unchanged-TOAST (omitted) UPDATE columns from the last known row state.++ Postgres does not send a TOASTed column's value in an UPDATE when it is+ unchanged (default REPLICA IDENTITY). The batcher stores such columns as null+ and records their names per row in TOAST_OMITTED_COLUMN. Left as-is, the null+ would overwrite the real value in the consolidated merge and be recorded in+ the _cdc history row.++ Resolution order per omitted column (mirrors enrich_delete_rows):+ 1. The last preceding row with the same PK in this batch where the column was+ not omitted — its value may legitimately be null (an explicit SET col=NULL).+ 2. The corresponding row in `existing_rows` (current DeltaLake state, passed+ in by the load processor for cross-batch enrichment).++ Columns still unresolved keep their marker entry so a later stage can retry;+ the load processor drops the marker column just before writing, leaving the+ column null only when the previous value is genuinely unknowable (PK absent+ from the target table).+ """+ if not pk_columns or table.num_rows == 0 or TOAST_OMITTED_COLUMN not in table.column_names:+ return table++ omitted_per_row: list[list[str] | None] = table.column(TOAST_OMITTED_COLUMN).to_pylist()+ if not any(omitted_per_row):+ return table++ present_pks = [col for col in pk_columns if col in table.column_names]+ if not present_pks:+ return table++ target_cols = sorted({col for row in omitted_per_row if row for col in row if col in table.column_names})+ if not target_cols:+ return table++ ops = table.column(CDC_OP_COLUMN).to_pylist()+ pk_arrays = [table.column(col).to_pylist() for col in present_pks]+ row_data: dict[str, list] = {col: table.column(col).to_pylist() for col in target_cols}++ existing_lookup: dict[tuple, dict[str, object]] = {}+ if existing_rows is not None and existing_rows.num_rows > 0:+ ex_present_pks = [col for col in present_pks if col in existing_rows.column_names]+ if len(ex_present_pks) == len(present_pks):+ ex_pk_arrays = [existing_rows.column(col).to_pylist() for col in present_pks]+ for i in range(existing_rows.num_rows):+ key = tuple(arr[i] for arr in ex_pk_arrays)+ existing_lookup[key] = {+ col: existing_rows.column(col)[i].as_py()+ for col in target_cols+ if col in existing_rows.column_names+ }++ # Walk rows in WAL order, carrying the last known value per (PK, column).+ # "Known" and "null" are distinct here: a null carried by a non-omitted row is+ # a real value and must propagate, not be skipped.+ batch_state: dict[tuple, dict[str, object]] = {}+ new_omitted: list[list[str] | None] = list(omitted_per_row)+ for i in range(table.num_rows):+ key = tuple(arr[i] for arr in pk_arrays)+ omitted = omitted_per_row[i]+ if omitted:+ state = batch_state.get(key)+ existing = existing_lookup.get(key)+ remaining: list[str] = []+ for col in omitted:+ if state is not None and col in state:+ row_data[col][i] = state[col]+ elif existing is not None and col in existing:+ row_data[col][i] = existing[col]+ else:+ remaining.append(col)+ new_omitted[i] = remaining or None++ # DELETE rows carry only identity columns — they neither resolve nor+ # invalidate the last known state.+ if ops[i] != "D":+ still_omitted = set(new_omitted[i] or [])+ state = batch_state.setdefault(key, {})+ for col in target_cols:+ if col not in still_omitted:+ state[col] = row_data[col][i]++ new_columns: dict[str, pa.Array | pa.ChunkedArray] = {}+ new_fields: list[pa.Field] = []+ for field in table.schema:+ col = field.name+ if col in row_data:+ col_type = field.type+ # Same all-null type upgrade as enrich_delete_rows: a column PyArrow+ # inferred as null() needs a real type before non-null fills.+ if col_type == pa.null() and existing_rows is not None and col in existing_rows.column_names:+ col_type = existing_rows.schema.field(col).type+ arr = _safe_pa_array(row_data[col], col_type)+ new_columns[col] = arr+ new_fields.append(pa.field(col, arr.type))+ elif col == TOAST_OMITTED_COLUMN:+ arr = pa.array(new_omitted, type=pa.list_(pa.string()))+ new_columns[col] = arr+ new_fields.append(pa.field(col, arr.type))+ else:+ new_columns[col] = table.column(col)+ new_fields.append(field)++ return pa.table(new_columns, schema=pa.schema(new_fields))++def deduplicate_table(pa_table: pa.Table, pk_columns: list[str]) -> pa.Table:"""Keep only the last row per primary key in a CDC batch.@@ -329,11 +447,17 @@ def build_scd2_table(pa_table: pa.Table, pk_columns: list[str]) -> pa.Table:def _events_to_table(events: list[ChangeEvent]) -> pa.Table:"""Convert a list of ChangeEvents (same table) to a PyArrow table with CDC metadata."""- # Collect all column names across all events (order-preserving)+ # Collect all column names across all events (order-preserving). Omitted+ # (unchanged-TOAST) columns are included so the batch table always carries a+ # column for them — as null plus a TOAST_OMITTED_COLUMN marker — otherwise the+ # load path would align the batch to the target schema with a plain null column+ # and merge that null over the real value.all_columns: dict[str, None] = {}for event in events:for col_name in event.columns:all_columns[col_name] = None+ for col_name in event.omitted_columns:+ all_columns[col_name] = Nonecolumn_names = list(all_columns.keys())# Authoritative Arrow type per column from the source schema (same for every event@@ -346,6 +470,7 @@ def _events_to_table(events: list[ChangeEvent]) -> pa.Table:cdc_timestamps: list[int] = [] # microseconds since epochdeleted_flags: list[bool] = []deleted_at: list[int | None] = []+ omitted_lists: list[list[str] | None] = []for event in events:for col_name in column_names:@@ -357,6 +482,7 @@ def _events_to_table(events: list[ChangeEvent]) -> pa.Table:is_delete = event.operation == "D"deleted_flags.append(is_delete)deleted_at.append(ts_us if is_delete else None)+ omitted_lists.append(sorted(event.omitted_columns) if event.omitted_columns else None)# Build PyArrow arrays for source columns.# If type inference fails (e.g. mixed int/str from a schema change mid-WAL),@@ -394,5 +520,10 @@ def _events_to_table(events: list[ChangeEvent]) -> pa.Table:arrays.append(pa.array(deleted_at, type=pa.timestamp("us", tz="UTC")))fields.append(pa.field(DELETED_AT_COLUMN, pa.timestamp("us", tz="UTC")))+ # Only batches that actually contain omissions carry the marker column.+ if any(omitted_lists):+ arrays.append(pa.array(omitted_lists, type=pa.list_(pa.string())))+ fields.append(pa.field(TOAST_OMITTED_COLUMN, pa.list_(pa.string())))+schema = pa.schema(fields)return pa.table(arrays, schema=schema)diff --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 1ea388af0543..12622d61f1f8 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@@ -13,10 +13,12 @@ from products.warehouse_sources.backend.temporal.data_imports.cdc.batcher importDELETED_COLUMN,SCD2_VALID_FROM_COLUMN,SCD2_VALID_TO_COLUMN,+ TOAST_OMITTED_COLUMN,ChangeEventBatcher,build_scd2_table,deduplicate_table,enrich_delete_rows,+ enrich_toast_omitted_rows,)from products.warehouse_sources.backend.temporal.data_imports.cdc.types import ChangeEvent@@ -28,6 +30,7 @@ def _make_event(columns: dict | None = None,timestamp: datetime | None = None,column_types: Mapping[str, pa.DataType] | None = None,+ omitted_columns: frozenset[str] = frozenset(),) -> ChangeEvent:return ChangeEvent(operation=op,@@ -36,6 +39,7 @@ def _make_event(timestamp=timestamp or datetime(2025, 6, 15, 12, 0, 0, tzinfo=UTC),columns=columns or {"id": 1, "name": "Alice"},column_types=column_types,+ omitted_columns=omitted_columns,)@@ -187,6 +191,31 @@ class TestChangeEventBatcher:batcher.flush() # type: ignore[unreachable]assert batcher.should_flush is False # noqa: E712+ def test_toast_omitted_columns_materialized_with_marker(self):+ # An UPDATE whose TOASTed column was unchanged carries no value for it. The+ # batch must still materialize the column (null) plus a per-row marker —+ # without the column, the load path aligns the batch to the target schema+ # with a plain null column and merges NULL over the real value.+ batcher = ChangeEventBatcher()+ batcher.add(+ _make_event(+ op="U",+ columns={"id": 1, "name": "renamed"},+ column_types={"id": pa.int64(), "name": pa.string(), "big": pa.string()},+ omitted_columns=frozenset({"big"}),+ )+ )+ table = batcher.flush()["users"]++ assert table.column("big").to_pylist() == [None]+ assert table.column("big").type == pa.string()+ assert table.column(TOAST_OMITTED_COLUMN).to_pylist() == [["big"]]++ # A flush without omissions must not carry the marker column.+ batcher.add(_make_event(op="U", columns={"id": 1, "name": "again"}))+ table = batcher.flush()["users"]+ assert TOAST_OMITTED_COLUMN not in table.column_names+def test_should_flush_byte_threshold(self):batcher = ChangeEventBatcher(max_bytes=500)batcher.add(_make_event(columns={"id": 1, "data": "x"}))@@ -533,3 +562,87 @@ class TestEnrichDeleteRows:result = enrich_delete_rows(table, ["id"], existing_rows=existing)# The DELETE row should be enriched — exact type may be coerced to stringassert result.column("amount")[1].as_py() is not None+++class TestEnrichToastOmittedRows:+ def _make_raw_table(self, events):+ batcher = ChangeEventBatcher()+ for ev in events:+ batcher.add(ev)+ return batcher.flush()["users"]++ def _omitted_update(self, columns: dict, omitted: set[str]) -> ChangeEvent:+ return _make_event(op="U", columns=columns, omitted_columns=frozenset(omitted))++ @parameterized.expand(+ [+ # (name, first event (op, columns), expected fill for the omitted row)+ ("from_insert", ("I", {"id": 1, "big": "v1"}), "v1"),+ ("from_update", ("U", {"id": 1, "big": "v2"}), "v2"),+ # An explicit NULL set by a prior event is a real value: it must+ # propagate, not be resurrected from any older state.+ ("real_null_propagates", ("I", {"id": 1, "big": None}), None),+ ]+ )+ def test_fills_from_last_batch_row_and_clears_marker(self, _name, first_event, expected):+ op, columns = first_event+ events = [+ _make_event(op=op, columns=columns),+ self._omitted_update({"id": 1, "name": "renamed"}, {"big"}),+ ]+ table = self._make_raw_table(events)+ result = enrich_toast_omitted_rows(table, ["id"])++ assert result.column("big")[1].as_py() == expected+ assert result.column(TOAST_OMITTED_COLUMN)[1].as_py() is None++ def test_filled_value_chains_to_later_omitted_rows(self):+ events = [+ _make_event(op="I", columns={"id": 1, "big": "v1"}),+ self._omitted_update({"id": 1, "name": "a"}, {"big"}),+ self._omitted_update({"id": 1, "name": "b"}, {"big"}),+ ]+ table = self._make_raw_table(events)+ result = enrich_toast_omitted_rows(table, ["id"])++ assert result.column("big").to_pylist() == ["v1", "v1", "v1"]+ assert result.column(TOAST_OMITTED_COLUMN).to_pylist() == [None, None, None]++ def test_fills_from_existing_rows_when_not_in_batch(self):+ table = self._make_raw_table([self._omitted_update({"id": 1, "name": "renamed"}, {"big"})])+ existing = pa.table(+ {+ "id": pa.array([1], type=pa.int64()),+ "big": pa.array(["persisted"], type=pa.string()),+ }+ )+ result = enrich_toast_omitted_rows(table, ["id"], existing_rows=existing)++ assert result.column("big")[0].as_py() == "persisted"+ assert result.column(TOAST_OMITTED_COLUMN)[0].as_py() is None++ def test_batch_value_beats_existing_rows(self):+ events = [+ _make_event(op="U", columns={"id": 1, "big": "fresh"}),+ self._omitted_update({"id": 1, "name": "renamed"}, {"big"}),+ ]+ table = self._make_raw_table(events)+ existing = pa.table(+ {+ "id": pa.array([1], type=pa.int64()),+ "big": pa.array(["stale"], type=pa.string()),+ }+ )+ result = enrich_toast_omitted_rows(table, ["id"], existing_rows=existing)++ assert result.column("big")[1].as_py() == "fresh"++ def test_unresolvable_row_keeps_marker(self):+ # PK absent from both batch and existing state: value unknowable at this+ # stage — the marker must survive so a later stage (or the final drop in+ # the load processor) makes the call, not a silent NULL.+ table = self._make_raw_table([self._omitted_update({"id": 1, "name": "renamed"}, {"big"})])+ result = enrich_toast_omitted_rows(table, ["id"])++ assert result.column("big")[0].as_py() is None+ assert result.column(TOAST_OMITTED_COLUMN)[0].as_py() == ["big"]diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/types.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/types.pyindex eb21db18da95..e502d8af76fd 100644--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/types.py+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/types.py@@ -56,6 +56,12 @@ class ChangeEvent:# flush is inferred as string while a concrete flush is int64, and the two Parquet# schemas fail to merge. Shared across all events of one relation; None when unknown.column_types: Mapping[str, pa.DataType] | None = None+ # Columns whose value the change stream did not include because it is unchanged+ # from the previous row version (Postgres: unchanged TOAST values in UPDATEs).+ # These are absent from `columns`, but unlike a plain absence they are known to+ # still hold their previous value — downstream must fill them from the last known+ # row state instead of writing NULL.+ omitted_columns: frozenset[str] = frozenset()class CDCStreamReader(Protocol):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.pyindex 9f65a86a25fc..d5c53259bbbe 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@@ -18,6 +18,13 @@ from products.data_warehouse.backend.facade.api import update_external_job_statufrom products.warehouse_sources.backend.models.external_data_job import ExternalDataJobfrom products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchemafrom products.warehouse_sources.backend.models.table import DataWarehouseTable+from products.warehouse_sources.backend.temporal.data_imports.cdc.batcher import (+ CDC_OP_COLUMN,+ SCD2_VALID_TO_COLUMN,+ TOAST_OMITTED_COLUMN,+ enrich_delete_rows,+ enrich_toast_omitted_rows,+)from products.warehouse_sources.backend.temporal.data_imports.pipelines.common.load import (run_post_load_operations,supports_partial_data_loading,@@ -94,6 +101,93 @@ def _read_existing_rows_by_first_pk(return existing.filter(pc.is_in(key, value_set=wanted))+def _enrich_cdc_rows(+ pa_table: pa.Table,+ *,+ primary_keys: list[str] | None,+ cdc_write_mode: str | None,+ existing_delta_table: deltalake.DeltaTable | None,+ batch_index: int,+) -> pa.Table:+ """Cross-batch CDC enrichment against the existing DeltaLake state.++ Batch-internal enrichment was already applied in the extraction activity; this+ fills what only the target table knows:+ - DELETE rows with no preceding INSERT/UPDATE for the same PK in the batch.+ - Unchanged-TOAST (omitted) UPDATE columns whose last value is not in the batch.++ Always strips TOAST_OMITTED_COLUMN before returning — it is transport metadata+ for this enrichment and must never reach DeltaLake.+ """+ if cdc_write_mode is None:+ return pa_table++ if primary_keys and existing_delta_table is not None and CDC_OP_COLUMN in pa_table.column_names:+ present_pks = [col for col in primary_keys if col in pa_table.column_names]+ if present_pks:+ ops = pa_table.column(CDC_OP_COLUMN).to_pylist()+ pk_arrays = [pa_table.column(col).to_pylist() for col in present_pks]+ delete_key_set: set[tuple[Any, ...]] = set()+ for i, op in enumerate(ops):+ if op == "D":+ delete_key_set.add(tuple(arr[i] for arr in pk_arrays))++ toast_key_set: set[tuple[Any, ...]] = set()+ if TOAST_OMITTED_COLUMN in pa_table.column_names:+ omitted_lists = pa_table.column(TOAST_OMITTED_COLUMN).to_pylist()+ for i, omitted in enumerate(omitted_lists):+ if omitted:+ toast_key_set.add(tuple(arr[i] for arr in pk_arrays))++ enrich_key_set = delete_key_set | toast_key_set+ if enrich_key_set:+ logger.debug(+ "cdc_delete_enrichment",+ delete_row_count=len(delete_key_set),+ toast_omitted_row_count=len(toast_key_set),+ primary_key_count=len(present_pks),+ cdc_write_mode=cdc_write_mode,+ batch_index=batch_index,+ )+ # Delta-rs: single-column IN avoids tuple filters (weak NULL semantics).+ # For composite PKs that IN is a superset — narrow in PyArrow below.+ first_pk = present_pks[0]+ first_components = list({t[0] for t in enrich_key_set})+ existing_rows = _read_existing_rows_by_first_pk(existing_delta_table, first_pk, first_components)++ # For composite PKs the IN filter is a superset — narrow to exact matches.+ if len(present_pks) > 1 and existing_rows.num_rows > 0:+ if all(col in existing_rows.column_names for col in present_pks):+ ex_pk_arrays = [existing_rows.column(col).to_pylist() for col in present_pks]+ match_indices = [+ j+ for j in range(existing_rows.num_rows)+ if tuple(arr[j] for arr in ex_pk_arrays) in enrich_key_set+ ]+ existing_rows = existing_rows.take(match_indices)+ else:+ existing_rows = existing_rows.take([])++ # For SCD2 tables, keep only "current" rows (valid_to IS NULL) so we+ # enrich with the most recent state rather than a historical one.+ if (+ cdc_write_mode == "scd2_append"+ and existing_rows.num_rows > 0+ and SCD2_VALID_TO_COLUMN in existing_rows.column_names+ ):+ existing_rows = existing_rows.filter(pc.is_null(existing_rows.column(SCD2_VALID_TO_COLUMN)))++ # TOAST fill first so DELETE enrichment copies resolved values,+ # not the nulls standing in for omitted columns.+ pa_table = enrich_toast_omitted_rows(pa_table, primary_keys, existing_rows)+ pa_table = enrich_delete_rows(pa_table, primary_keys, existing_rows)++ if TOAST_OMITTED_COLUMN in pa_table.column_names:+ pa_table = pa_table.drop_columns([TOAST_OMITTED_COLUMN])++ return pa_table++def _apply_partitioning(export_signal: ExportSignalMessage,pa_table: pa.Table,@@ -511,66 +605,13 @@ def process_message("batch_index": str(export_signal.batch_index),}- # Cross-batch DELETE enrichment: fill data columns on DELETE rows from the- # existing DeltaLake state. Batch-internal enrichment was already applied- # in the extraction activity; this handles standalone DELETEs that arrive- # in a batch with no preceding INSERT/UPDATE for the same PK.- if cdc_write_mode is not None and primary_keys and existing_delta_table is not None:- from products.warehouse_sources.backend.temporal.data_imports.cdc.batcher import (- CDC_OP_COLUMN,- SCD2_VALID_TO_COLUMN,- enrich_delete_rows,- )-- if CDC_OP_COLUMN in pa_table.column_names:- present_pks = [col for col in primary_keys if col in pa_table.column_names]- if present_pks:- ops = pa_table.column(CDC_OP_COLUMN).to_pylist()- pk_arrays = [pa_table.column(col).to_pylist() for col in present_pks]- delete_key_set: set[tuple[Any, ...]] = set()- for i, op in enumerate(ops):- if op == "D":- delete_key_set.add(tuple(arr[i] for arr in pk_arrays))-- if delete_key_set:- logger.debug(- "cdc_delete_enrichment",- delete_row_count=len(delete_key_set),- primary_key_count=len(present_pks),- cdc_write_mode=cdc_write_mode,- batch_index=export_signal.batch_index,- )- # Delta-rs: single-column IN avoids tuple filters (weak NULL semantics).- # For composite PKs that IN is a superset — narrow in PyArrow below.- first_pk = present_pks[0]- first_components = list({t[0] for t in delete_key_set})- existing_rows = _read_existing_rows_by_first_pk(- existing_delta_table, first_pk, first_components- )-- # For composite PKs the IN filter is a superset — narrow to exact matches.- if len(present_pks) > 1 and existing_rows.num_rows > 0:- if all(col in existing_rows.column_names for col in present_pks):- ex_pk_arrays = [existing_rows.column(col).to_pylist() for col in present_pks]- match_indices = [- j- for j in range(existing_rows.num_rows)- if tuple(arr[j] for arr in ex_pk_arrays) in delete_key_set- ]- existing_rows = existing_rows.take(match_indices)- else:- existing_rows = existing_rows.take([])-- # For SCD2 tables, keep only "current" rows (valid_to IS NULL) so we- # enrich the DELETE with the most recent state rather than a historical one.- if (- cdc_write_mode == "scd2_append"- and existing_rows.num_rows > 0- and SCD2_VALID_TO_COLUMN in existing_rows.column_names- ):- existing_rows = existing_rows.filter(pc.is_null(existing_rows.column(SCD2_VALID_TO_COLUMN)))-- pa_table = enrich_delete_rows(pa_table, primary_keys, existing_rows)+ 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,+ )if existing_delta_table is not None:pa_table = evolve_pyarrow_schema(pa_table, existing_delta_table.schema())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 0d5570040a86..a0d6bdaeaa33 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@@ -8,9 +8,15 @@ import pyarrow as pafrom deltalake import DeltaTable, write_deltalakefrom parameterized import parameterized+from products.warehouse_sources.backend.temporal.data_imports.cdc.batcher import (+ CDC_OP_COLUMN,+ SCD2_VALID_TO_COLUMN,+ TOAST_OMITTED_COLUMN,+)from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.consts import PARTITION_KEYfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.load.processor import (_apply_partitioning,+ _enrich_cdc_rows,_get_write_type,_mark_job_completed,_promote_staged_cursor,@@ -458,6 +464,98 @@ class TestMarkJobCompleted:# Regression guard for #70476: pyarrow 21+ string_view broke delta pushdown on string PKs.+class TestEnrichCdcRows:+ """Cross-batch CDC enrichment against a real local Delta table."""++ @staticmethod+ def _batch(rows: list[dict[str, Any]]) -> pa.Table:+ return pa.table(+ {+ "id": pa.array([r["id"] for r in rows], pa.int64()),+ "name": pa.array([r.get("name") for r in rows], pa.string()),+ "big": pa.array([r.get("big") for r in rows], pa.string()),+ CDC_OP_COLUMN: pa.array([r["op"] for r in rows], pa.string()),+ TOAST_OMITTED_COLUMN: pa.array([r.get("omitted") for r in rows], pa.list_(pa.string())),+ }+ )++ def test_fills_toast_and_delete_rows_from_delta_state_and_drops_marker(self):+ with tempfile.TemporaryDirectory() as path:+ write_deltalake(+ path,+ pa.table(+ {+ "id": pa.array([1, 2], pa.int64()),+ "name": pa.array(["one", "two"], pa.string()),+ "big": pa.array(["toasted-1", "toasted-2"], pa.string()),+ }+ ),+ mode="overwrite",+ )++ batch = self._batch(+ [+ {"id": 1, "op": "U", "name": "renamed", "omitted": ["big"]},+ {"id": 2, "op": "D"},+ ]+ )+ result = _enrich_cdc_rows(+ batch,+ primary_keys=["id"],+ cdc_write_mode="incremental_merge",+ existing_delta_table=DeltaTable(path),+ batch_index=0,+ )++ # The unchanged-TOAST column keeps its persisted value instead of+ # merging NULL over it; the DELETE row is enriched as before.+ assert result.column("big").to_pylist() == ["toasted-1", "toasted-2"]+ assert result.column("name").to_pylist() == ["renamed", "two"]+ assert TOAST_OMITTED_COLUMN not in result.column_names++ def test_scd2_fill_uses_current_row_not_history(self):+ with tempfile.TemporaryDirectory() as path:+ ts = pa.timestamp("us", tz="UTC")+ write_deltalake(+ path,+ pa.table(+ {+ "id": pa.array([1, 1], pa.int64()),+ "name": pa.array(["v1", "v2"], pa.string()),+ "big": pa.array(["old-toast", "current-toast"], pa.string()),+ SCD2_VALID_TO_COLUMN: pa.array([1_000_000, None], ts),+ }+ ),+ mode="overwrite",+ )++ batch = self._batch([{"id": 1, "op": "U", "name": "v3", "omitted": ["big"]}])+ result = _enrich_cdc_rows(+ batch,+ primary_keys=["id"],+ cdc_write_mode="scd2_append",+ existing_delta_table=DeltaTable(path),+ batch_index=0,+ )++ assert result.column("big").to_pylist() == ["current-toast"]++ def test_marker_dropped_when_enrichment_cannot_run(self):+ # First-ever CDC batch: no existing Delta table to fill from. The value is+ # unknowable (stays null) but the transport marker must never reach the write.+ batch = self._batch([{"id": 1, "op": "U", "name": "renamed", "omitted": ["big"]}])+ result = _enrich_cdc_rows(+ batch,+ primary_keys=["id"],+ cdc_write_mode="incremental_merge",+ existing_delta_table=None,+ batch_index=0,+ )++ assert TOAST_OMITTED_COLUMN not in result.column_names+ assert result.column("big").to_pylist() == [None]++class TestReadExistingRowsByFirstPk:@staticmethoddef _string_view_table(path: str) -> DeltaTable:diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/decoder.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/decoder.pyindex c9b514681769..dc4821bcba57 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/decoder.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/decoder.py@@ -246,7 +246,7 @@ class PgOutputDecoder:if relation is None:return- columns = _decode_tuple(tuple_data, relation)+ columns, omitted = _decode_tuple(tuple_data, relation)self._buffer_event(ChangeEvent(@@ -256,6 +256,7 @@ class PgOutputDecoder:timestamp=self._tx_timestamp or datetime.now(tz=UTC),columns=columns,column_types=relation.column_arrow_types,+ omitted_columns=frozenset(omitted),))@@ -263,7 +264,6 @@ class PgOutputDecoder:"""U message: relation_id(4) + ['K'|'O' + old_tuple] + 'N' + new_tupleThe old tuple is optional (depends on REPLICA IDENTITY setting).- We only need the new tuple for CDC upserts."""relation_id = struct.unpack("!I", payload[0:4])[0]offset = 4@@ -272,11 +272,12 @@ class PgOutputDecoder:if relation is None:return- # Skip optional old key/old tuple+ # Optional old key ('K') / old full row ('O', REPLICA IDENTITY FULL)+ old_columns: dict[str, Any] = {}marker = chr(payload[offset])if marker in ("K", "O"):offset += 1- _, offset = _skip_tuple(payload, offset, relation)+ old_columns, offset = _skip_tuple(payload, offset, relation)# New tuple starts with 'N'if chr(payload[offset]) != "N":@@ -284,7 +285,14 @@ class PgOutputDecoder:returnoffset += 1- columns = _decode_tuple(payload[offset:], relation)+ columns, omitted = _decode_tuple(payload[offset:], relation)++ # An unchanged-TOAST column holds its previous value by definition, so any+ # old-tuple value for it (REPLICA IDENTITY FULL) is the current value.+ for col_name in list(omitted):+ if col_name in old_columns:+ columns[col_name] = old_columns[col_name]+ omitted.discard(col_name)self._buffer_event(ChangeEvent(@@ -294,6 +302,7 @@ class PgOutputDecoder:timestamp=self._tx_timestamp or datetime.now(tz=UTC),columns=columns,column_types=relation.column_arrow_types,+ omitted_columns=frozenset(omitted),))@@ -315,7 +324,7 @@ class PgOutputDecoder:# marker = chr(payload[offset])offset += 1- columns = _decode_tuple(payload[offset:], relation)+ columns, omitted = _decode_tuple(payload[offset:], relation)self._buffer_event(ChangeEvent(@@ -325,6 +334,7 @@ class PgOutputDecoder:timestamp=self._tx_timestamp or datetime.now(tz=UTC),columns=columns,column_types=relation.column_arrow_types,+ omitted_columns=frozenset(omitted),))@@ -376,12 +386,14 @@ def _read_cstring(data: bytes, offset: int) -> tuple[str, int]:return data[offset:end].decode("utf-8"), end + 1-def _decode_tuple(data: bytes, relation: Relation) -> dict[str, Any]:- """Decode a pgoutput tuple into a dict of column_name → Python value.+def _decode_tuple(data: bytes, relation: Relation) -> tuple[dict[str, Any], set[str]]:+ """Decode a pgoutput tuple into (column_name → Python value, unchanged-TOAST column names).Tuple format: n_cols(2) + for each column: type_byte + [data]- 'n': NULL- - 'u': unchanged TOAST value (skipped)+ - 'u': unchanged TOAST value — not sent; the column still holds its previous+ value, so it must be tracked separately from NULL or the pipeline would+ overwrite the real value with NULL downstream- 't': text value → int32 length + UTF-8 bytes"""offset = 0@@ -389,6 +401,7 @@ def _decode_tuple(data: bytes, relation: Relation) -> dict[str, Any]:offset += 2columns: dict[str, Any] = {}+ omitted: set[str] = set()for i in range(n_cols):if i >= len(relation.columns):@@ -401,8 +414,7 @@ def _decode_tuple(data: bytes, relation: Relation) -> dict[str, Any]:if col_type == "n":columns[col_meta.name] = Noneelif col_type == "u":- # Unchanged TOAST — value not sent. Skip.- pass+ omitted.add(col_meta.name)elif col_type == "t":length = struct.unpack("!I", data[offset : offset + 4])[0]offset += 4@@ -412,7 +424,7 @@ def _decode_tuple(data: bytes, relation: Relation) -> dict[str, Any]:else:logger.warning("Unknown tuple column type '%s' for column %s", col_type, col_meta.name)- return columns+ return columns, omitteddef _skip_tuple(data: bytes, offset: int, relation: Relation) -> tuple[dict[str, Any], int]:@@ -437,7 +449,7 @@ def _skip_tuple(data: bytes, offset: int, relation: Relation) -> tuple[dict[str,offset += 4 + length# Decode the tuple we just skipped for return value- columns = _decode_tuple(data[start:offset], relation)+ columns, _ = _decode_tuple(data[start:offset], relation)return columns, offsetdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/tests/test_decoder.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/tests/test_decoder.pyindex 1ba5757c4a91..53604e9c668d 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/tests/test_decoder.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/tests/test_decoder.py@@ -104,10 +104,11 @@ def _make_update(relation_id: int,new_values: list[tuple[str, str] | None],old_values: list[tuple[str, str] | None] | None = None,+ old_marker: bytes = b"K",) -> bytes:data = b"U" + struct.pack("!I", relation_id)if old_values is not None:- data += b"K" + _make_tuple_data(old_values)+ data += old_marker + _make_tuple_data(old_values)data += b"N" + _make_tuple_data(new_values)return data@@ -299,8 +300,29 @@ class TestPgOutputDecoder:assert len(events) == 1assert events[0].columns["id"] == 1- # TOAST unchanged column should not appear in columns+ # Not in columns (no value was sent), but marked omitted so downstream+ # fills it from the last known state instead of writing NULL over it.assert "big_text" not in events[0].columns+ assert events[0].omitted_columns == frozenset({"big_text"})++ def test_unchanged_toast_filled_from_replica_identity_full_old_tuple(self):+ # With REPLICA IDENTITY FULL the old tuple carries the TOAST value; since the+ # column is unchanged, the old value IS the current value — no marker needed.+ decoder = self._setup_decoder_with_relation(columns=[("id", _OID_INT4, -1), ("big_text", _OID_TEXT, -1)])++ decoder.decode_message(_make_begin(), "0/100")+ update = _make_update(+ 1,+ new_values=[("t", "1"), ("u", "")],+ old_values=[("t", "1"), ("t", "big toasted value")],+ old_marker=b"O",+ )+ decoder.decode_message(update, "0/150")+ events = decoder.decode_message(_make_commit(), "0/200")++ assert len(events) == 1+ assert events[0].columns["big_text"] == "big toasted value"+ assert events[0].omitted_columns == frozenset()def test_transaction_buffering(self):decoder = self._setup_decoder_with_relation(columns=[("id", _OID_INT4, -1)])