: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-modeling): keep unsigned columns from forcing a full refresh (#102910)
Thiago Salvatore5afd2808cbd2
diff --git a/posthog/temporal/data_modeling/activities/materialize_view.py b/posthog/temporal/data_modeling/activities/materialize_view.pyindex bf3fbf10b155..1527e7ec6f99 100644--- a/posthog/temporal/data_modeling/activities/materialize_view.py+++ b/posthog/temporal/data_modeling/activities/materialize_view.py@@ -186,6 +186,17 @@ class EmptyHogQLResponseColumnsError(Exception):super().__init__("After running a HogQL query, no columns were returned")+class UnstorableIntegerError(NonReportableError):+ """A column holds a whole number too large for the signed integer types Delta Lake has."""++ def __init__(self, column: str) -> None:+ super().__init__(+ f'Column "{column}" has whole numbers larger than {2**63 - 1}, which is the largest a '+ f"materialized table can store. Wrap the column in toString() to store it as text."+ )+ self.column = column++class DuplicateOutputColumnError(NonReportableError):"""Both consumers of the probe address a column by name: the type wrapper rebuilds the selectlist from it, and the arrow transform looks it up on the batch. Neither can say which of two@@ -543,6 +554,53 @@ def _transform_unsupported_decimals(batch: pa.RecordBatch) -> pa.RecordBatch:return pa.RecordBatch.from_arrays(new_columns, schema=pa.schema(new_fields, metadata=new_metadata))+_SIGNED_EQUIVALENT_BY_BIT_WIDTH = {8: pa.int16(), 16: pa.int32(), 32: pa.int64(), 64: pa.int64()}+++def _signed_equivalent(arrow_type: pa.DataType) -> pa.DataType:+ """The type Delta Lake stores this as. Unchanged unless an unsigned integer is in it."""+ if pa.types.is_unsigned_integer(arrow_type):+ return _SIGNED_EQUIVALENT_BY_BIT_WIDTH[arrow_type.bit_width]++ if pa.types.is_large_list(arrow_type):+ return pa.large_list(_signed_equivalent_field(arrow_type.value_field))++ if pa.types.is_list(arrow_type):+ return pa.list_(_signed_equivalent_field(arrow_type.value_field))++ if pa.types.is_struct(arrow_type):+ return pa.struct([_signed_equivalent_field(field) for field in arrow_type])++ if pa.types.is_map(arrow_type):+ return pa.map_(_signed_equivalent(arrow_type.key_type), _signed_equivalent(arrow_type.item_type))++ return arrow_type+++def _signed_equivalent_field(field: pa.Field) -> pa.Field:+ return field.with_type(_signed_equivalent(field.type))+++def _transform_unsigned_integers(batch: pa.RecordBatch) -> pa.RecordBatch:+ """Cast unsigned integer columns to the signed types Delta Lake stores them as."""+ signed_fields = [_signed_equivalent_field(field) for field in batch.schema]+ if all(signed.type.equals(field.type) for signed, field in zip(signed_fields, batch.schema)):+ return batch++ columns: list[pa.Array] = []+ for field in signed_fields:+ try:+ columns.append(pc.cast(batch.column(field.name), field.type))+ except pa.ArrowInvalid as err:+ raise UnstorableIntegerError(field.name) from err++ signed_schema = pa.schema(+ signed_fields,+ metadata=typing.cast("dict[bytes | str, bytes | str] | None", batch.schema.metadata),+ )+ return pa.RecordBatch.from_arrays(columns, schema=signed_schema)++async def _write_empty_parquet_for_zero_rows(table_uri: str, schema: pa.Schema, logger: FilteringBoundLogger) -> str:"""Write a single empty parquet file under ``table_uri`` so a zero-row materializationis still queryable.@@ -913,6 +971,7 @@ async def _materialize_fully(async for batch, ch_types in hogql_table(hogql_query, objects.team, logger):batch = _transform_unsupported_decimals(batch)batch = _transform_date_and_datetimes(batch, ch_types)+ batch = _transform_unsigned_integers(batch)batch = _force_nullable(batch)if tracker is not None:await asyncio.to_thread(tracker.check, batch)@@ -1008,6 +1067,7 @@ async def _materialize_incrementally(async for batch, ch_types in hogql_table(hogql_query, objects.team, logger, window=window):batch = _transform_unsupported_decimals(batch)batch = _transform_date_and_datetimes(batch, ch_types)+ batch = _transform_unsigned_integers(batch)batch = _force_nullable(batch)if batch.num_rows == 0:diff --git a/posthog/temporal/data_modeling/workflows/materialize_view.py b/posthog/temporal/data_modeling/workflows/materialize_view.pyindex 67964172ffb5..dbfad7ddc54c 100644--- a/posthog/temporal/data_modeling/workflows/materialize_view.py+++ b/posthog/temporal/data_modeling/workflows/materialize_view.py@@ -100,6 +100,7 @@ NON_RETRYABLE_ERRORS = ["NodeNotFoundException","EmptyHogQLResponseColumnsError","DuplicateOutputColumnError",+ "UnstorableIntegerError",]diff --git a/posthog/temporal/tests/data_modeling/test_materialize_view_incremental.py b/posthog/temporal/tests/data_modeling/test_materialize_view_incremental.pyindex 029846a95bc0..11a67ac8e500 100644--- a/posthog/temporal/tests/data_modeling/test_materialize_view_incremental.py+++ b/posthog/temporal/tests/data_modeling/test_materialize_view_incremental.py@@ -44,6 +44,18 @@ def _batch(days: list[datetime | None], counts: list[int], *, value_column: strreturn pa.RecordBatch.from_arrays(arrays, names=["day", value_column])+def _unsigned_batch(day: datetime, count: int, flag: int) -> pa.RecordBatch:+ arrays = cast(+ Collection[pa.Array],+ [+ pa.array([day], type=pa.timestamp("us", tz="UTC")),+ pa.array([count], type=pa.uint64()),+ pa.array([flag], type=pa.uint8()),+ ],+ )+ return pa.RecordBatch.from_arrays(arrays, names=["day", "c", "flag"])++def _rows(table_uri: str) -> list[tuple[Any, Any]]:"""Stored rows as (day, value), sorted, so tests assert content rather than counts."""table = deltalake.DeltaTable(table_uri, storage_options=get_aws_storage_options()).to_pyarrow_table()@@ -52,13 +64,21 @@ def _rows(table_uri: str) -> list[tuple[Any, Any]]:return sorted(pairs, key=lambda pair: (pair[0] is None, pair[0]))-def _mock_hogql_table(*batches: pa.RecordBatch, value_column: str = "c", windows: list[Any] | None = None):+def _mock_hogql_table(+ *batches: pa.RecordBatch,+ value_column: str = "c",+ windows: list[Any] | None = None,+ column_types: list[tuple[str, str]] | None = None,+):"""Stand in for one run: yields the given batches, ignoring the window.The window's effect on the generated SQL is covered by the filter-injection tests; what mattershere is what the write path does with the rows that come back. ``windows`` collects the windoweach run was given, for tests that assert on the computed lower bound."""+ # DateTime64 so the activity's arrow transform passes an already-typed timestamp+ # through, the way it does for a real ClickHouse DateTime64 column.+ types = column_types or [("day", "DateTime64(6, 'UTC')"), (value_column, "Int64")]def factory(*args, **kwargs):if windows is not None:@@ -67,9 +87,7 @@ def _mock_hogql_table(*batches: pa.RecordBatch, value_column: str = "c", windowsasync def generator():for batch in batches:- # DateTime64 so the activity's arrow transform passes an already-typed timestamp- # through, the way it does for a real ClickHouse DateTime64 column.- yield batch, [("day", "DateTime64(6, 'UTC')"), (value_column, "Int64")]+ yield batch, typesreturn generator()@@ -95,11 +113,12 @@ async def _run(enabled: bool = True,value_column: str = "c",windows: list[Any] | None = None,+ column_types: list[tuple[str, str]] | None = None,):with (unittest.mock.patch("posthog.temporal.data_modeling.activities.materialize_view.hogql_table",- _mock_hogql_table(*batches, value_column=value_column, windows=windows),+ _mock_hogql_table(*batches, value_column=value_column, windows=windows, column_types=column_types),),unittest.mock.patch("posthog.temporal.data_modeling.activities.materialize_view._incremental_enabled",@@ -279,6 +298,36 @@ class TestIncrementalMaterialization:await database_sync_to_async(asaved_query.refresh_from_db)()assert get_incremental_state(asaved_query).watermark is None+ async def test_an_unsigned_column_stays_incremental_across_runs(+ self, activity_environment, ateam, anode, asaved_query, ajob, bucket_name, adag+ ):+ await _configure(asaved_query)+ column_types = [("day", "DateTime64(6, 'UTC')"), ("c", "UInt64"), ("flag", "UInt8")]++ with _settings(bucket_name):+ first = await _run(+ activity_environment, ateam, anode, ajob, adag, _unsigned_batch(DAY1, 10, 1), column_types=column_types+ )+ await _run(+ activity_environment,+ ateam,+ anode,+ ajob,+ adag,+ _unsigned_batch(DAY2, 20, 200),+ column_types=column_types,+ )++ await database_sync_to_async(ajob.refresh_from_db)()+ assert ajob.run_mode == "incremental"+ assert ajob.full_refresh_reason is None++ table = deltalake.DeltaTable(first.table_uri, storage_options=get_aws_storage_options()).to_pyarrow_table()+ stored = sorted(+ zip(table.column("day").to_pylist(), table.column("c").to_pylist(), table.column("flag").to_pylist())+ )+ assert stored == [(DAY1, 10, 1), (DAY2, 20, 200)]+async def test_a_definition_change_forces_a_rebuild(self, activity_environment, ateam, anode, asaved_query, ajob, bucket_name, adag):diff --git a/posthog/temporal/tests/data_modeling/test_unsigned_transform.py b/posthog/temporal/tests/data_modeling/test_unsigned_transform.pynew file mode 100644index 000000000000..d704eae9b409--- /dev/null+++ b/posthog/temporal/tests/data_modeling/test_unsigned_transform.py@@ -0,0 +1,62 @@+"""The unsigned-to-signed cast in isolation: pure pyarrow, no database, no delta table.++The incremental suite proves the cast is wired into both write paths. These cover the type+mapping itself, where Delta Lake's lack of an unsigned integer reaches values nested in a+list, a struct or a map.+"""++import pytest++import pyarrow as pa++from posthog.temporal.data_modeling.activities.materialize_view import (+ UnstorableIntegerError,+ _transform_unsigned_integers,+)+++ "column,expected_type",+ [+ pytest.param(pa.array([200], pa.uint8()), pa.int16(), id="uint8_widens_past_its_signed_max"),+ pytest.param(pa.array([60000], pa.uint16()), pa.int32(), id="uint16_widens_past_its_signed_max"),+ pytest.param(pa.array([4000000000], pa.uint32()), pa.int64(), id="uint32_widens_past_its_signed_max"),+ pytest.param(pa.array([5000000000], pa.uint64()), pa.int64(), id="uint64_has_no_wider_signed_type"),+ pytest.param(pa.array([[1, 2]], pa.list_(pa.uint64())), pa.list_(pa.int64()), id="list_value"),+ pytest.param(pa.array([[1, 2]], pa.large_list(pa.uint64())), pa.large_list(pa.int64()), id="large_list_value"),+ pytest.param(+ pa.array([{"a": 250}], pa.struct([pa.field("a", pa.uint8())])),+ pa.struct([pa.field("a", pa.int16())]),+ id="struct_field",+ ),+ pytest.param(+ pa.array([[("k", 7)]], pa.map_(pa.string(), pa.uint32())),+ pa.map_(pa.string(), pa.int64()),+ id="map_value",+ ),+ pytest.param(pa.array(["x"], pa.string()), pa.string(), id="a_type_delta_already_stores_is_untouched"),+ ],+)+def test_unsigned_integers_become_the_type_delta_stores(column: pa.Array, expected_type: pa.DataType) -> None:+ batch = pa.RecordBatch.from_arrays([column], names=["c"])++ transformed = _transform_unsigned_integers(batch)++ assert transformed.schema.field("c").type.equals(expected_type)+ assert transformed.column("c").to_pylist() == column.to_pylist()+++ "column",+ [+ pytest.param(pa.array([2**64 - 1], pa.uint64()), id="scalar"),+ pytest.param(pa.array([[2**64 - 1]], pa.list_(pa.uint64())), id="nested_in_a_list"),+ ],+)+def test_a_uint64_above_the_signed_maximum_names_its_column(column: pa.Array) -> None:+ batch = pa.RecordBatch.from_arrays([column], names=["hash_id"])++ with pytest.raises(UnstorableIntegerError) as raised:+ _transform_unsigned_integers(batch)++ assert raised.value.column == "hash_id"