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): realign decimal buffers before delta writes (#61566)

Tom Owersbb21a69138c4
diff --git a/posthog/temporal/data_imports/pipelines/pipeline/delta_table_helper.py b/posthog/temporal/data_imports/pipelines/pipeline/delta_table_helper.py
index 5f7a1c2294c7..3b8810e7a556 100644
--- a/posthog/temporal/data_imports/pipelines/pipeline/delta_table_helper.py
+++ b/posthog/temporal/data_imports/pipelines/pipeline/delta_table_helper.py
@@ -45,6 +45,43 @@ def _write_deltalake(
)
+def _realign_decimal_buffers(table: pa.Table) -> pa.Table:
+ """Re-materialize any Decimal128/256 column whose values buffer isn't 16-byte aligned.
+
+ delta-rs (arrow-rs) aborts the entire worker — not a catchable Python exception,
+ an `abort()` at the `extern "C"` boundary that can't unwind — when it's handed a
+ decimal values buffer aligned to 8 bytes instead of the 16 that Rust's i128 requires.
+ The misalignment arrives across the Arrow C Data Interface, which only recommends
+ 8-byte alignment. We funnel every Delta write/merge through here so a single guard
+ covers both pipeline versions. See delta-io/delta-rs#3884.
+
+ Only the values buffer (`buffers()[1]`) holds the i128 payload that must be aligned;
+ the validity bitmap has no such requirement, so we don't bother checking it.
+
+ `pa.concat_arrays` forces a fresh allocation through pyarrow's allocator (64-byte
+ aligned), which satisfies the requirement. `combine_chunks()` is zero-copy and would
+ keep the misaligned buffer, so it can't be used here. The buffer scan is cheap and
+ the copy only fires on the rare misaligned batch, so the common path is untouched.
+ """
+ new_columns: dict[str, pa.ChunkedArray] = {}
+ realigned = False
+ for i in range(table.num_columns):
+ field = table.field(i)
+ column = table.column(i)
+ if pa.types.is_decimal(field.type) and any(
+ (values := chunk.buffers()[1]) is not None and values.address % 16 for chunk in column.chunks
+ ):
+ new_columns[field.name] = pa.chunked_array([pa.concat_arrays(column.chunks)], type=field.type)
+ realigned = True
+ else:
+ new_columns[field.name] = column
+
+ if not realigned:
+ return table
+
+ return pa.table(new_columns, schema=table.schema)
+
+
def _first_per_pk_table(pa_table: pa.Table, pk_columns: list[str]) -> pa.Table:
"""Return a table containing only the first row per PK tuple (in original row order).
@@ -204,6 +241,11 @@ class DeltaTableHelper:
progress_callback: Callable[[], None] | None = None,
commit_metadata: dict[str, str] | None = None,
) -> deltalake.DeltaTable:
+ # Guard against delta-rs aborting the worker on misaligned decimal buffers (see
+ # _realign_decimal_buffers). Sub-tables derived below via filter()/take() are
+ # freshly allocated by pyarrow and so inherit safe alignment.
+ data = _realign_decimal_buffers(data)
+
delta_table = await self.get_delta_table()
if delta_table:
@@ -400,6 +442,11 @@ class DeltaTableHelper:
`data` is expected to already have valid_from / valid_to columns as produced
by batcher.build_scd2_table().
"""
+ # See write_to_deltalake / _realign_decimal_buffers. The close-existing merge uses
+ # _first_per_pk_table(data), whose take() output is freshly allocated, so realigning
+ # `data` here covers both the close and the append.
+ data = _realign_decimal_buffers(data)
+
delta_table = await self.get_delta_table()
if delta_table:
diff --git a/posthog/temporal/data_imports/pipelines/pipeline/test/test_delta_table_helper.py b/posthog/temporal/data_imports/pipelines/pipeline/test/test_delta_table_helper.py
index bd21bb25b1ae..69c3e495d7c1 100644
--- a/posthog/temporal/data_imports/pipelines/pipeline/test/test_delta_table_helper.py
+++ b/posthog/temporal/data_imports/pipelines/pipeline/test/test_delta_table_helper.py
@@ -1,6 +1,8 @@
import json
+from datetime import UTC, datetime
+from decimal import Decimal
from pathlib import Path
-from typing import Any
+from typing import Any, cast
import pytest
from unittest.mock import AsyncMock, MagicMock, patch
@@ -11,10 +13,45 @@ import pyarrow.compute as pc
from parameterized import parameterized
from posthog.temporal.data_imports.pipelines.pipeline.consts import PARTITION_KEY
-from posthog.temporal.data_imports.pipelines.pipeline.delta_table_helper import DeltaTableHelper
+from posthog.temporal.data_imports.pipelines.pipeline.delta_table_helper import (
+ DeltaTableHelper,
+ _realign_decimal_buffers,
+)
from posthog.temporal.data_imports.pipelines.pipeline.utils import evolve_pyarrow_schema
+def _decimal_array(values: list, *, precision: int = 10, scale: int = 2, misaligned: bool) -> pa.Array:
+ """Build a Decimal128 array. When `misaligned`, its data buffer is 8-byte but NOT
+ 16-byte aligned — the exact FFI case delta-rs (arrow-rs) aborts the worker on.
+
+ pyarrow's allocator always returns 64-byte-aligned memory, so the only way to
+ reproduce the bad case is to over-allocate and slice off 8 bytes, mimicking what
+ arrives across the Arrow C Data Interface from polars / external producers.
+ """
+ aligned = pa.array(values, type=pa.decimal128(precision, scale))
+ if not misaligned:
+ return aligned
+
+ data_buffer = aligned.buffers()[1]
+ assert data_buffer is not None
+ padded = pa.allocate_buffer(data_buffer.size + 16)
+ memoryview(padded)[8 : 8 + data_buffer.size] = memoryview(data_buffer)
+ misaligned_buffer = padded.slice(8, data_buffer.size)
+ assert misaligned_buffer.address % 16 == 8
+ # The validity buffer is legitimately None here; pyarrow accepts it but the stub types
+ # the list as list[Buffer], so cast rather than fight the (over-strict) annotation.
+ buffers = cast("list[pa.Buffer]", [None, misaligned_buffer])
+ return pa.Array.from_buffers(pa.decimal128(precision, scale), len(values), buffers)
+
+
+def _table_is_misaligned(table: pa.Table) -> bool:
+ return any(
+ pa.types.is_decimal(table.field(i).type)
+ and any((b := chunk.buffers()[1]) is not None and b.address % 16 for chunk in table.column(i).chunks)
+ for i in range(table.num_columns)
+ )
+
+
def _make_logger():
logger = MagicMock()
logger.adebug = AsyncMock()
@@ -333,3 +370,153 @@ class TestLegacyDltTableReconciliation:
final = result.to_pyarrow_table()
assert final.num_rows == 3
assert set(final.column("id").to_pylist()) == {1, 2, 3}
+
+
+class TestRealignDecimalBuffers:
+ """delta-rs aborts the worker on 8-byte-aligned Decimal128 buffers; we realign them
+ to pyarrow's 64-byte allocator before any Delta write. See delta-io/delta-rs#3884."""
+
+ def test_misaligned_decimal_is_realigned(self) -> None:
+ table = pa.table({"amount": _decimal_array([1, 2, 3, 4], misaligned=True), "id": pa.array([1, 2, 3, 4])})
+ assert _table_is_misaligned(table) is True
+
+ result = _realign_decimal_buffers(table)
+
+ assert _table_is_misaligned(result) is False
+ # Values and schema are preserved exactly
+ assert result.column("amount").to_pylist() == table.column("amount").to_pylist()
+ assert result.column("id").to_pylist() == [1, 2, 3, 4]
+ assert result.schema == table.schema
+
+ @pytest.mark.parametrize(
+ "table",
+ [
+ pa.table({"amount": _decimal_array([1, 2, 3], misaligned=False), "id": pa.array([1, 2, 3])}),
+ pa.table({"id": pa.array([1, 2, 3]), "name": pa.array(["a", "b", "c"])}),
+ ],
+ ids=["already_aligned_decimal", "no_decimal_columns"],
+ )
+ def test_unmisaligned_table_is_returned_unchanged(self, table: pa.Table) -> None:
+ assert _table_is_misaligned(table) is False
+
+ result = _realign_decimal_buffers(table)
+
+ # No misalignment found → identity return (no needless copy)
+ assert result is table
+
+ def test_only_misaligned_columns_are_rebuilt(self) -> None:
+ aligned_dec = _decimal_array([10, 20], misaligned=False)
+ misaligned_dec = _decimal_array([30, 40], misaligned=True)
+ table = pa.table({"good": aligned_dec, "bad": misaligned_dec, "id": pa.array([1, 2])})
+
+ result = _realign_decimal_buffers(table)
+
+ assert _table_is_misaligned(result) is False
+ assert result.column("good").to_pylist() == [10, 20]
+ assert result.column("bad").to_pylist() == [30, 40]
+ # The already-aligned column keeps its original buffer (rebuilt only what was broken)
+ good_buffer = result.column("good").chunks[0].buffers()[1]
+ orig_buffer = aligned_dec.buffers()[1]
+ assert good_buffer is not None and orig_buffer is not None
+ assert good_buffer.address == orig_buffer.address
+
+ def test_multi_chunk_misaligned_column(self) -> None:
+ chunked = pa.chunked_array(
+ [_decimal_array([1, 2], misaligned=True), _decimal_array([3, 4], misaligned=True)],
+ type=pa.decimal128(10, 2),
+ )
+ table = pa.table({"amount": chunked, "id": pa.array([1, 2, 3, 4])})
+ assert _table_is_misaligned(table) is True
+
+ result = _realign_decimal_buffers(table)
+
+ assert _table_is_misaligned(result) is False
+ assert result.column("amount").to_pylist() == [1, 2, 3, 4]
+
+ def test_empty_decimal_table(self) -> None:
+ table = pa.table({"amount": pa.array([], type=pa.decimal128(10, 2)), "id": pa.array([], type=pa.int64())})
+
+ result = _realign_decimal_buffers(table)
+
+ assert result.num_rows == 0
+ assert result.schema == table.schema
+
+
+class TestWriteMisalignedDecimalEndToEnd:
+ """Writes a misaligned-decimal batch through the real delta-rs write path. Without the
+ realignment guard, delta-rs would abort the process; with it, the write succeeds."""
+
+ @pytest.mark.parametrize(
+ "write_type,should_overwrite",
+ [("full_refresh", True), ("append", False), ("incremental", False)],
+ )
+ @pytest.mark.asyncio
+ async def test_write_misaligned_decimal_to_local_delta(
+ self, write_type: str, should_overwrite: bool, tmp_path: Path
+ ) -> None:
+ delta_path = str(tmp_path / "table")
+ # Seed the table so incremental/append have an existing target to write into.
+ deltalake.write_deltalake(
+ delta_path,
+ pa.table({"id": pa.array([1, 2]), "amount": _decimal_array([5, 6], misaligned=False)}),
+ )
+
+ helper = _make_local_helper(delta_path)
+ batch = pa.table({"id": pa.array([3, 4]), "amount": _decimal_array([7, 8], misaligned=True)})
+ assert _table_is_misaligned(batch) is True
+
+ result = await helper.write_to_deltalake(
+ data=batch,
+ write_type=write_type, # type: ignore[arg-type]
+ should_overwrite_table=should_overwrite,
+ primary_keys=["id"] if write_type == "incremental" else None,
+ )
+
+ final = result.to_pyarrow_table()
+ amounts = set(final.column("amount").to_pylist())
+ if should_overwrite:
+ assert set(final.column("id").to_pylist()) == {3, 4}
+ else:
+ assert {3, 4}.issubset(set(final.column("id").to_pylist()))
+ assert {7, 8}.issubset(amounts)
+
+ @pytest.mark.asyncio
+ async def test_write_scd2_misaligned_decimal_to_local_delta(self, tmp_path: Path) -> None:
+ # write_scd2_to_deltalake carries its own realignment guard; without it the
+ # close-existing merge would hand delta-rs a misaligned decimal and abort the worker.
+ delta_path = str(tmp_path / "scd2_table")
+ ts1 = datetime(2026, 1, 1, tzinfo=UTC)
+ ts2 = datetime(2026, 2, 1, tzinfo=UTC)
+ ts_type = pa.timestamp("us", tz="UTC")
+ # Seed a current (valid_to IS NULL) row for id=1 so the new batch closes it.
+ deltalake.write_deltalake(
+ delta_path,
+ pa.table(
+ {
+ "id": pa.array([1]),
+ "amount": _decimal_array([5], misaligned=False),
+ "valid_from": pa.array([ts1], type=ts_type),
+ "valid_to": pa.array([None], type=ts_type),
+ }
+ ),
+ )
+
+ helper = _make_local_helper(delta_path)
+ batch = pa.table(
+ {
+ "id": pa.array([1]),
+ "amount": _decimal_array([7], misaligned=True),
+ "valid_from": pa.array([ts2], type=ts_type),
+ "valid_to": pa.array([None], type=ts_type),
+ }
+ )
+ assert _table_is_misaligned(batch) is True
+
+ result = await helper.write_scd2_to_deltalake(data=batch, primary_keys=["id"])
+
+ final = result.to_pyarrow_table()
+ # The seeded row is closed (valid_to set) and the new misaligned row is appended.
+ assert final.num_rows == 2
+ assert set(final.column("amount").to_pylist()) == {5, 7}
+ closed = final.filter(pc.equal(final.column("amount"), Decimal("5.00")))
+ assert closed.column("valid_to").to_pylist() == [ts2]