Skip to content

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

fix(data-warehouse): accept batches that declare a null column NOT NULL (#88540)

Tom Owers143c4fecb0d5
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/arrow_utils.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/arrow_utils.py
index c1848ebeaac9..7bd5faaada16 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/arrow_utils.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/arrow_utils.py
@@ -856,6 +856,37 @@ def align_incoming_decimals_to_delta(pa_table: pa.Table, delta_schema: deltalake
return pa_table
+def relax_batch_nullability(pa_table: pa.Table) -> pa.Table:
+ """Mark every batch column that actually holds nulls as nullable in the batch's own schema.
+
+ SQL sources build the batch schema from the source database's own `is_nullable` metadata, so a
+ column the source declares NOT NULL can still arrive holding nulls: the value was dropped by a
+ projection or a join, or its conversion failed. pyarrow does not check the claim when it builds
+ the table in Python, so the batch reaches the writers with a schema that contradicts its data.
+
+ Every delta path checks it and refuses the batch: `write_deltalake` raises a DeltaError,
+ `DeltaTable.merge` panics in Rust before it can plan the merge, and deltalite's
+ `RecordBatch::try_new` rejects it, which sends the write to the MERGE that then panics. All
+ three report "declared as non-nullable but contains null values". Correcting the claim before
+ the write also lets deltalite relax a stored column that a past batch already poisoned.
+
+ The cast rewrites field metadata only, so the column buffers are shared and not copied.
+ """
+ relaxed: list[pa.Field] = []
+ changed = False
+ for index, field in enumerate(pa_table.schema):
+ if not field.nullable and pa_table.column(index).null_count > 0:
+ relaxed.append(field.with_nullable(True))
+ changed = True
+ else:
+ relaxed.append(field)
+
+ if not changed:
+ return pa_table
+
+ return pa_table.cast(pa.schema(relaxed).with_metadata(pa_table.schema.metadata or {}))
+
+
def raise_on_nullability_drift(pa_table: pa.Table, delta_schema: deltalake.Schema) -> None:
"""Stop the sync when a batch has nulls in a column the table declares non-nullable.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/scd2.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/scd2.py
index 293931b8761f..8e457c7db91c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/scd2.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/scd2.py
@@ -10,6 +10,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arr
first_per_pk_table,
normalize_column_name,
realign_decimal_buffers,
+ relax_batch_nullability,
)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.evolution import evolve_delta_schema
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.ops import (
@@ -57,6 +58,11 @@ class Scd2DeltaWriter:
# close and the append.
data = realign_decimal_buffers(data)
+ # A source can declare a column NOT NULL and still send nulls in it, and both delta calls
+ # below refuse such a batch. Correct the claim before either runs (see
+ # relax_batch_nullability).
+ data = relax_batch_nullability(data)
+
delta_table = await self._table.get_delta_table()
if delta_table:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/test/test_scd2.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/test/test_scd2.py
index 4671551608fa..6d6d6b689579 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/test/test_scd2.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/test/test_scd2.py
@@ -63,6 +63,43 @@ class TestScd2Write:
closed = final.filter(pc.equal(final.column("amount"), pa.scalar(Decimal("5.00"), type=pa.decimal128(10, 2))))
assert closed.column("valid_to").to_pylist() == [ts2]
+ @pytest.mark.asyncio
+ async def test_write_batch_declaring_a_null_column_not_null(self, tmp_path: Path) -> None:
+ # CDC reads SQL sources, whose batch schema copies the source database's is_nullable
+ # metadata, so a column can claim NOT NULL and still arrive holding nulls. Both delta
+ # calls in the SCD2 write reject that batch: write_deltalake raises and merge panics.
+ delta_path = str(tmp_path / "scd2_table")
+ ts1 = datetime(2026, 1, 1, tzinfo=UTC)
+ ts2 = datetime(2026, 2, 1, tzinfo=UTC)
+ deltalake.write_deltalake(
+ delta_path,
+ pa.table(
+ {
+ "id": pa.array([1]),
+ "note": pa.array(["first"]),
+ "valid_from": pa.array([ts1], type=_TS_TYPE),
+ "valid_to": pa.array([None], type=_TS_TYPE),
+ }
+ ),
+ )
+
+ batch_fields: list[pa.Field] = [
+ pa.field("id", pa.int64(), nullable=False),
+ pa.field("note", pa.string(), nullable=False),
+ pa.field("valid_from", _TS_TYPE, nullable=False),
+ pa.field("valid_to", _TS_TYPE, nullable=True),
+ ]
+ batch = pa.table(
+ {"id": [1], "note": [None], "valid_from": [ts2], "valid_to": [None]},
+ schema=pa.schema(batch_fields),
+ )
+
+ result = await _make_writer(delta_path).write(data=batch, primary_keys=["id"])
+
+ final = result.to_pyarrow_table()
+ assert final.num_rows == 2
+ assert sorted(final.column("note").to_pylist(), key=lambda x: x is not None) == [None, "first"]
+
@pytest.mark.asyncio
async def test_only_terminal_append_commit_carries_metadata(self, tmp_path: Path) -> None:
# SCD2 is a two-step write (close-existing merge, then append). If the intermediate
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/test/test_writer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/test/test_writer.py
index bce6c4bde17e..4284b3d4263b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/test/test_writer.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/test/test_writer.py
@@ -17,6 +17,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arr
SchemaColumnTypeChangedException,
evolve_pyarrow_schema,
first_per_pk_table,
+ pyarrow_schema_from_arrow_exportable,
realign_decimal_buffers,
)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.consts import PARTITION_KEY
@@ -292,6 +293,71 @@ class TestNullabilityDriftGuardOrder:
assert result is not None
+class TestLyingBatchNullability:
+ """A source can declare a column NOT NULL and still send nulls in it (SQL sources build the
+ batch schema from the source database's own is_nullable metadata). Every delta path rejects
+ such a batch, so the writer has to correct the claim before any of them sees it."""
+
+ def _lying_batch(self) -> pa.Table:
+ return pa.table(
+ {"id": [1, 2], "v": [None, 5]},
+ schema=pa.schema(
+ [
+ pa.field("id", pa.int64(), nullable=False),
+ pa.field("v", pa.int64(), nullable=False),
+ ]
+ ),
+ )
+
+ @pytest.mark.asyncio
+ async def test_first_sync_creates_the_table_with_nullability_matching_its_data(self, tmp_path: Path) -> None:
+ # Without the correction write_deltalake raises DeltaError ("declared as non-nullable but
+ # contains null values") and the very first sync of the table fails.
+ delta_path = str(tmp_path / "table")
+ table_ref = make_local_table_ref(delta_path)
+
+ await DeltaWriter(table_ref).write(
+ data=self._lying_batch(),
+ write_type="incremental",
+ should_overwrite_table=False,
+ primary_keys=["id"],
+ )
+
+ stored = deltalake.DeltaTable(delta_path)
+ stored_schema = pyarrow_schema_from_arrow_exportable(stored.schema())
+ assert {field.name: field.nullable for field in stored_schema} == {"id": False, "v": True}
+ assert sorted(stored.to_pyarrow_table().column("v").to_pylist(), key=lambda x: (x is not None, x)) == [None, 5]
+
+ @pytest.mark.asyncio
+ async def test_incremental_merge_accepts_nulls_the_stored_column_allows(self, tmp_path: Path) -> None:
+ # Without the correction delta-rs panics inside create_merge_builder (a pyo3
+ # PanicException, not a DeltaError), so the merge cannot even be planned.
+ delta_path = str(tmp_path / "table")
+ deltalake.write_deltalake(
+ delta_path,
+ pa.table(
+ {"id": [1, 2], "v": [9, 9]},
+ schema=pa.schema(
+ [
+ pa.field("id", pa.int64(), nullable=False),
+ pa.field("v", pa.int64(), nullable=True),
+ ]
+ ),
+ ),
+ )
+ table_ref = make_local_table_ref(delta_path)
+
+ await DeltaWriter(table_ref).write(
+ data=self._lying_batch(),
+ write_type="incremental",
+ should_overwrite_table=False,
+ primary_keys=["id"],
+ )
+
+ stored = deltalake.DeltaTable(delta_path).to_pyarrow_table().to_pydict()
+ assert dict(zip(stored["id"], stored["v"])) == {1: None, 2: 5}
+
+
class TestLegacyDltTableReconciliation:
"""Pipeline_v3 must handle dlt-created Delta tables with NOT NULL _dlt_* columns."""
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/writer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/writer.py
index 0139235ba6f4..e0050de6a3fe 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/writer.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/writer.py
@@ -21,6 +21,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arr
normalize_column_name,
raise_on_nullability_drift,
realign_decimal_buffers,
+ relax_batch_nullability,
)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.consts import PARTITION_KEY
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.evolution import evolve_delta_schema
@@ -294,6 +295,11 @@ class DeltaWriter:
# freshly allocated by pyarrow and so inherit safe alignment.
data = realign_decimal_buffers(data)
+ # A source can declare a column NOT NULL and still send nulls in it, and every delta path
+ # below refuses such a batch. Correct the claim first, which also creates a new table with
+ # nullability that matches its data (see relax_batch_nullability).
+ data = relax_batch_nullability(data)
+
delta_table = await self._table.get_delta_table()
if delta_table:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_utils.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_utils.py
index 2c234237ab90..c610bde3f02e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_utils.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_utils.py
@@ -34,6 +34,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arr
observe_and_project_table,
observed_schema_metadata_columns,
raise_on_nullability_drift,
+ relax_batch_nullability,
restrict_schema_to_columns,
source_uses_delta_write_column_selection,
table_from_py_list,
@@ -1058,6 +1059,66 @@ def test_raise_on_nullability_drift_permits_valid_batches(
raise_on_nullability_drift(pa_table, delta_schema)
+ "fields, columns, expected_nullable",
+ [
+ # The source declared the column NOT NULL but sent a null in it, so the claim is corrected.
+ (
+ [pa.field("id", pa.int64(), nullable=False), pa.field("v", pa.int64(), nullable=False)],
+ {"id": [1, 2], "v": [None, 5]},
+ {"id": False, "v": True},
+ ),
+ # No nulls arrived, so the source's NOT NULL claim is true and stands.
+ (
+ [pa.field("id", pa.int64(), nullable=False), pa.field("v", pa.int64(), nullable=False)],
+ {"id": [1, 2], "v": [4, 5]},
+ {"id": False, "v": False},
+ ),
+ # The column is already nullable, so there is nothing to correct.
+ (
+ [pa.field("id", pa.int64(), nullable=False), pa.field("v", pa.int64(), nullable=True)],
+ {"id": [1, 2], "v": [None, 5]},
+ {"id": False, "v": True},
+ ),
+ # Only the column that holds nulls is relaxed; its neighbours keep their declared nullability.
+ (
+ [
+ pa.field("id", pa.int64(), nullable=False),
+ pa.field("v", pa.int64(), nullable=False),
+ pa.field("name", pa.string(), nullable=False),
+ ],
+ {"id": [1, 2], "v": [None, 5], "name": ["a", "b"]},
+ {"id": False, "v": True, "name": False},
+ ),
+ ],
+)
+def test_relax_batch_nullability_corrects_only_columns_that_hold_nulls(
+ fields: list[pa.Field], columns: dict[str, list], expected_nullable: dict[str, bool]
+):
+ pa_table = pa.table(columns, schema=pa.schema(fields))
+
+ relaxed = relax_batch_nullability(pa_table)
+
+ assert {field.name: field.nullable for field in relaxed.schema} == expected_nullable
+ assert relaxed.to_pydict() == pa_table.to_pydict()
+ assert relaxed.schema.types == pa_table.schema.types
+
+
+def test_relax_batch_nullability_keeps_schema_metadata():
+ # The observed-column metadata rides on the schema, so rebuilding the schema must carry it over
+ # or the batch loses the column observations the sync persists.
+ metadata: dict[bytes | str, bytes | str] = {b"ph_observed_columns": b"[]"}
+ pa_table = pa.table(
+ {"v": [None, 5]},
+ schema=pa.schema([pa.field("v", pa.int64(), nullable=False)], metadata=metadata),
+ )
+
+ relaxed = relax_batch_nullability(pa_table)
+
+ assert relaxed.schema.field("v").nullable is True
+ assert relaxed.schema.metadata == metadata
+
+
def test_evolve_pyarrow_schema_with_struct_containing_datetime_and_decimal():
metadata_struct_type = pa.struct(
[