Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(warehouse): null-safe incremental merge predicate (#75601)

Tom Owers41e174c3089a
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta_table_helper.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta_table_helper.py
index 5054c0910b45..4b5c460aeffb 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta_table_helper.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta_table_helper.py
@@ -284,6 +284,24 @@ def _first_per_pk_table(
return pa_table.take(kept_indices)
+def _merge_predicate_ops(normalized_primary_keys: list[str]) -> list[str]:
+ """Per-key merge match conditions, using NULL-safe equality.
+
+ delta-rs matches source↔target with plain `source.c = target.c`, which is NULL-*un*safe:
+ `NULL = NULL` evaluates to NULL (not true). Composite keys with nullable columns — e.g. the
+ GoogleAds report resources keyed on `segments.ad_network_type` / `segments.click_type` /
+ `segments.device`, which are frequently NULL — therefore never match their existing target row,
+ so `when_not_matched_insert_all` re-inserts them on *every* incremental sync and the table
+ silently accumulates a duplicate per NULL-keyed row. `IS NOT DISTINCT FROM` treats NULL == NULL,
+ matching the source dedup (`_first_per_pk_table` groups NULLs together) and stopping the drift.
+
+ Each term is parenthesised: delta-rs's predicate parser (1.6.1) mis-associates a bare
+ `a IS NOT DISTINCT FROM b AND c IS NOT DISTINCT FROM d` (it groups `b AND c`), so the parens are
+ required for it to plan.
+ """
+ return [f"(source.{c} IS NOT DISTINCT FROM target.{c})" for c in normalized_primary_keys]
+
+
def delta_storage_options() -> dict[str, str]:
"""delta-rs storage options for the data-warehouse bucket, independent of any import job — so a
read path (e.g. the person-property backfill) can open a Delta table without constructing a full
@@ -641,7 +659,7 @@ class DeltaTableHelper:
if n in py_table_column_names:
normalized_primary_keys.append(n)
- predicate_ops = [f"source.{c} = target.{c}" for c in normalized_primary_keys]
+ predicate_ops = _merge_predicate_ops(normalized_primary_keys)
if use_partitioning:
predicate_ops.append(f"source.{PARTITION_KEY} = target.{PARTITION_KEY}")
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_delta_table_helper.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_delta_table_helper.py
index 1104500088a4..e16e16e291aa 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_delta_table_helper.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_delta_table_helper.py
@@ -25,6 +25,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.del
DeltaTableHelper,
_delta_merge_spill_kwargs,
_first_per_pk_table,
+ _merge_predicate_ops,
_realign_decimal_buffers,
is_transient_delta_maintenance_error,
is_transient_object_store_error,
@@ -1296,3 +1297,77 @@ class TestIsTransientObjectStoreError:
)
def test_classifies_transient_errors(self, _name: str, error: Exception, expected: bool):
assert is_transient_object_store_error(error) is expected
+
+
+class TestNullSafeMergePredicate:
+ """The incremental-merge match must be NULL-safe.
+
+ Regression for the duplicate-accumulation bug found by the deltalite shadow canary: composite
+ keys with nullable columns (e.g. GoogleAds report resources keyed on `segments.*`) matched with
+ bare `source.c = target.c` never match on NULL (`NULL = NULL` is NULL), so the row is re-inserted
+ on every incremental sync and the table silently grows.
+ """
+
+ def test_predicate_ops_are_null_safe(self):
+ assert _merge_predicate_ops(["id", "seg"]) == [
+ "(source.id IS NOT DISTINCT FROM target.id)",
+ "(source.seg IS NOT DISTINCT FROM target.seg)",
+ ]
+
+ @staticmethod
+ def _seed_then_merge(path: Path, predicate_ops: list[str]) -> pa.Table:
+ # Seed one row whose composite key has a NULL component, then merge the same key with a new value.
+ seed = pa.table(
+ {
+ "id": pa.array([1], pa.int64()),
+ "seg": pa.array([None], pa.string()),
+ "val": pa.array(["a"], pa.string()),
+ }
+ )
+ deltalake.write_deltalake(str(path), seed, mode="overwrite")
+ source = pa.table(
+ {
+ "id": pa.array([1], pa.int64()),
+ "seg": pa.array([None], pa.string()),
+ "val": pa.array(["b"], pa.string()),
+ }
+ )
+ (
+ deltalake.DeltaTable(str(path))
+ .merge(source=source, source_alias="source", target_alias="target", predicate=" AND ".join(predicate_ops))
+ .when_matched_update_all()
+ .when_not_matched_insert_all()
+ .execute()
+ )
+ return deltalake.DeltaTable(str(path)).to_pyarrow_table()
+
+ def test_null_composite_key_row_matches_instead_of_duplicating(self, tmp_path):
+ result = self._seed_then_merge(tmp_path / "safe", _merge_predicate_ops(["id", "seg"]))
+ assert result.num_rows == 1
+ assert result.column("val").to_pylist() == ["b"]
+
+ def test_non_null_key_still_matches(self, tmp_path):
+ # The null-safe form must not change behaviour for ordinary (non-NULL) keys.
+ seed = pa.table({"id": pa.array([1], pa.int64()), "seg": pa.array(["MOBILE"]), "val": pa.array(["a"])})
+ deltalake.write_deltalake(str(tmp_path / "nn"), seed, mode="overwrite")
+ source = pa.table({"id": pa.array([1], pa.int64()), "seg": pa.array(["MOBILE"]), "val": pa.array(["b"])})
+ (
+ deltalake.DeltaTable(str(tmp_path / "nn"))
+ .merge(
+ source=source,
+ source_alias="source",
+ target_alias="target",
+ predicate=" AND ".join(_merge_predicate_ops(["id", "seg"])),
+ )
+ .when_matched_update_all()
+ .when_not_matched_insert_all()
+ .execute()
+ )
+ result = deltalake.DeltaTable(str(tmp_path / "nn")).to_pyarrow_table()
+ assert result.num_rows == 1
+ assert result.column("val").to_pylist() == ["b"]
+
+ def test_bare_equality_duplicates_null_key_row(self, tmp_path):
+ # Documents the pre-fix behaviour the null-safe predicate corrects.
+ result = self._seed_then_merge(tmp_path / "unsafe", ["source.id = target.id", "source.seg = target.seg"])
+ assert result.num_rows == 2
diff --git a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_end_to_end.py b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_end_to_end.py
index f365535c48f8..c5fb501ea659 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_end_to_end.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_end_to_end.py
@@ -2590,7 +2590,7 @@ async def test_partition_folders_delta_merge_called_with_partition_predicate(
"source": mock.ANY,
"source_alias": "source",
"target_alias": "target",
- "predicate": f"source.id = target.id AND source.{PARTITION_KEY} = target.{PARTITION_KEY} AND target.{PARTITION_KEY} = '0'",
+ "predicate": f"(source.id IS NOT DISTINCT FROM target.id) AND source.{PARTITION_KEY} = target.{PARTITION_KEY} AND target.{PARTITION_KEY} = '0'",
"streamed_exec": True,
"commit_properties": mock.ANY,
}