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-imports): align repartition rewrite batches to the live delta schema (#76373)

Tom Owers5f64c5591d95
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 88fa587ed46b..b6295b0bcdc2 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
@@ -339,9 +339,13 @@ def evolve_pyarrow_schema(incoming_table: pa.Table, delta_schema: deltalake.Sche
incoming_column = incoming_table.column(delta_field.name)
- # Delta column is non-nullable: backfill nulls before write.
+ # Delta column is non-nullable: backfill nulls before write. Checked against the column's
+ # actual null count, not its field's own `nullable` flag, because that flag is just metadata
+ # and can say non-nullable while the batch still carries a real null (e.g. a batch scanned
+ # from a table whose column is otherwise declared non-nullable), which would otherwise
+ # skip the backfill and let the null reach the write.
incoming_field = incoming_table.field(delta_field.name)
- if not delta_field.nullable and incoming_field.nullable:
+ if not delta_field.nullable and incoming_column.null_count > 0:
filled_nulls_arr = incoming_column.fill_null(
fill_value=get_default_value_for_pyarrow_type(incoming_field.type)
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/repartition.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/repartition.py
index 4ce45e0031eb..383c76d29694 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/repartition.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/repartition.py
@@ -32,6 +32,7 @@ from structlog.types import FilteringBoundLogger
from products.data_warehouse.backend.facade.api import aget_s3_client
from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrow_utils import (
+ evolve_pyarrow_schema,
normalize_column_name,
realign_decimal_buffers,
)
@@ -386,6 +387,7 @@ async def _rewrite_into_temp(
"""
dataset = await asyncio.to_thread(old_delta.to_pyarrow_dataset)
reader = await asyncio.to_thread(lambda: dataset.scanner(batch_size=batch_size).to_reader())
+ live_schema = await asyncio.to_thread(old_delta.schema)
resolved: RepartitionTarget | None = None
rows_written = 0
@@ -427,6 +429,14 @@ async def _rewrite_into_temp(
partition_keys=used_keys,
)
+ # Align each batch against the live table's own declared schema before writing. Without
+ # this, whichever batch happens to build temp's schema on the first write fixes its
+ # nullability from what that one batch's data looked like. So if a column the live schema
+ # already declares non-nullable slips through with a real null (e.g. a source NOT NULL
+ # constraint later relaxed upstream), the write aborts with "declared as non-nullable but
+ # contains null values" partway through the rewrite. Every other Delta write path in this
+ # pipeline runs incoming data through this same alignment first, so the rewrite must too.
+ partitioned_table = evolve_pyarrow_schema(partitioned_table, live_schema)
partitioned_table = realign_decimal_buffers(partitioned_table)
await asyncio.to_thread(
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test_repartition.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test_repartition.py
index b2ecf1bc0193..28255c932d76 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test_repartition.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test_repartition.py
@@ -368,6 +368,60 @@ class TestRewriteIntoTemp:
assert resolved.partition_mode == "datetime"
assert resolved.partition_keys == ["created_at"]
+ def test_batch_with_real_null_in_non_nullable_column_is_backfilled_not_crashed(self, tmp_path):
+ # The live table's own declared schema can mark a column non-nullable (e.g. a source NOT
+ # NULL constraint recorded on first sync) while a scanned batch still carries an actual
+ # null for it (the constraint was later relaxed upstream). Writing that batch straight to
+ # `write_deltalake` without aligning it to the live schema first raises "declared as
+ # non-nullable but contains null values" and aborts the rewrite.
+ live_pa_schema = pa.schema(
+ [ # type: ignore[arg-type]
+ pa.field("id", pa.int64(), nullable=False),
+ pa.field("real_model", pa.string(), nullable=False),
+ ]
+ )
+ # Bypasses delta-rs's own write-time validation (which would reject this) to stand in for
+ # a batch scanned off a live table whose data no longer matches its declared schema. The
+ # scanned batch's own field still says non-nullable too, matching the live table's.
+ batch_table = pa.Table.from_arrays(
+ [pa.array([1, 2], type=pa.int64()), pa.array(["gpt-4", None], type=pa.string())],
+ schema=live_pa_schema,
+ )
+
+ class _FakeReader:
+ def __init__(self, table):
+ self._batches = table.to_batches()
+
+ def read_next_batch(self):
+ if not self._batches:
+ raise StopIteration
+ return self._batches.pop(0)
+
+ old_delta = SimpleNamespace(
+ to_pyarrow_dataset=lambda: SimpleNamespace(
+ scanner=lambda batch_size: SimpleNamespace(to_reader=lambda: _FakeReader(batch_table))
+ ),
+ schema=lambda: deltalake.Schema.from_arrow(live_pa_schema),
+ )
+
+ rows_written, _ = asyncio.run(
+ _rewrite_into_temp(
+ old_delta=old_delta, # type: ignore[arg-type]
+ temp_uri=str(tmp_path / "tmp"),
+ storage_options={},
+ target=RepartitionTarget(
+ partition_keys=["id"], trigger_reason="test", partition_mode="md5", partition_count=1
+ ),
+ batch_size=10,
+ logger=logger,
+ )
+ )
+
+ assert rows_written == 2
+ new_table = deltalake.DeltaTable(str(tmp_path / "tmp")).to_pyarrow_table().sort_by("id")
+ # The real null is backfilled to the column's default rather than reaching the Delta write.
+ assert new_table.column("real_model").to_pylist() == ["gpt-4", ""]
+
class _FakeS3CM:
"""Minimal async-context-manager stand-in for `aget_s3_client()`."""