: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-imports): normalize TIME columns to seconds to stop schema oscillation (#74355)
Tom Owerse05c71ee93d8
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/test/test_pipeline_utils.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/test/test_pipeline_utils.pyindex 0b89bb01fff9..363d9b7198b5 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/test/test_pipeline_utils.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/test/test_pipeline_utils.py@@ -783,8 +783,8 @@ def test_evolve_pyarrow_schema_whole_valued_floats_cast_into_stored_integer_colu# A value that overflows the stored decimal precision (Cannot convert ... overflow).(pa.decimal128(3, 1), pa.array([1.0, 999999999.0], type=pa.float64())),# A cast pyarrow has no kernel for at all — raised as ArrowNotImplementedError, not- # ArrowInvalid (e.g. a source column that used to be numeric now arrives as a time).- (pa.float64(), pa.array([datetime.time(12, 30, 0), datetime.time(1, 0, 0)], type=pa.time64("us"))),+ # ArrowInvalid (a binary column now arriving where a numeric one is stored).+ (pa.float64(), pa.array([b"\x01", b"\x02"], type=pa.binary())),],)def test_evolve_pyarrow_schema_incompatible_cast_raises_actionable_error(@@ -807,6 +807,45 @@ def test_evolve_pyarrow_schema_incompatible_cast_raises_actionable_error(evolve_pyarrow_schema(arrow_table, delta_schema)+ "incoming_column, expected_values",+ [+ # Batch with values: a SQL TIME arrives as a Python timedelta and infers as duration.+ (+ pa.array([datetime.timedelta(hours=1), datetime.timedelta(hours=2, minutes=30)], type=pa.duration("us")),+ [3600.0, 9000.0],+ ),+ # All-null batch: keeps the source's declared time64, which used to fail to reconcile.+ (pa.array([None, None], type=pa.time64("us")), [None, None]),+ # Batch whose TIME values arrive typed as time64 rather than duration.+ (pa.array([datetime.time(1, 0, 0), datetime.time(2, 30, 0)], type=pa.time64("us")), [3600.0, 9000.0]),+ ],+)+def test_evolve_pyarrow_schema_time_columns_reconcile_to_stored_seconds(+ incoming_column: pa.Array, expected_values: list[float | None]+):+ """A SQL TIME column oscillates between time64 (all-null batch) and duration (batch with+ values, arriving as Python timedelta) across syncs. Both must normalize to the same float+ seconds so they reconcile against a column already stored as double, instead of raising an+ unretryable type-changed error on every all-null batch."""+ arrow_table = pa.table(+ {+ "id": pa.array([1, 2], type=pa.int64()),+ "redeem_time": incoming_column,+ }+ )+ fields: list[pa.Field] = [+ pa.field("id", pa.int64(), nullable=False),+ pa.field("redeem_time", pa.float64(), nullable=True),+ ]+ delta_schema = deltalake.Schema.from_arrow(pa.schema(fields))++ evolved_table = evolve_pyarrow_schema(arrow_table, delta_schema)++ assert evolved_table.schema.field("redeem_time").type == pa.float64()+ assert evolved_table.column("redeem_time").to_pylist() == expected_values++def test_evolve_pyarrow_schema_with_struct_containing_datetime_and_decimal():"""Test that evolve_pyarrow_schema can handle struct columns with non-JSON-serializable types."""metadata_struct_type = pa.struct(diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/utils.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/utils.pyindex b420a300f395..f7d289d5cf54 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/utils.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/utils.py@@ -182,6 +182,10 @@ def get_default_value_for_pyarrow_type(arrow_type: pa.DataType) -> Any:raise ValueError(f"Unsupported PyArrow type: {arrow_type}")+def _time_to_seconds(value: datetime.time) -> float:+ return value.hour * 3600 + value.minute * 60 + value.second + value.microsecond / 1_000_000++def evolve_pyarrow_schema(incoming_table: pa.Table, delta_schema: deltalake.Schema | None) -> pa.Table:# First pass: normalize types that Delta write path does not handle well.for column_name in incoming_table.column_names:@@ -206,6 +210,21 @@ def evolve_pyarrow_schema(incoming_table: pa.Table, delta_schema: deltalake.Scheincoming_table.schema.get_field_index(column_name), column_name, seconds_column)incoming_column = incoming_table.column(column_name)+ # Convert time-of-day to numeric seconds. SQL sources map a TIME column to time64, but a+ # batch whose TIME values arrive as Python timedelta infers as duration and lands as float+ # seconds above — so the same column oscillates between time64 and double across batches+ # (a batch with values vs an all-null batch), and time64 has no cast to double. Collapsing+ # time to seconds here keeps the stored Delta type stable across both shapes.+ elif pa.types.is_time(incoming_column.type):+ time_values = cast(list[datetime.time | None], incoming_column.to_pylist())+ seconds_column = pa.array(+ [_time_to_seconds(value) if value is not None else None for value in time_values],+ type=pa.float64(),+ )+ incoming_table = incoming_table.set_column(+ incoming_table.schema.get_field_index(column_name), column_name, seconds_column+ )+ incoming_column = incoming_table.column(column_name)# Normalize timestamps to microseconds and no timezone.if pa.types.is_timestamp(incoming_field.type) and (@@ -305,8 +324,8 @@ def evolve_pyarrow_schema(incoming_table: pa.Table, delta_schema: deltalake.Sche# was truncated converting to int64"), non-numeric text arriving for a numeric# column ("Failed to parse string: '80-150' as a scalar of type int32"), a# value that overflows the stored decimal precision, or a cast pyarrow has no- # kernel for at all (e.g. `time64` → `double`, raised as ArrowNotImplementedError- # rather than ArrowInvalid). delta-rs cannot change a column's type in place, so+ # kernel for at all (raised as ArrowNotImplementedError rather than+ # ArrowInvalid). delta-rs cannot change a column's type in place, so# retrying is futile — surface an actionable error telling the user to reset and# fully re-sync. Lossless widening (e.g. a whole-valued float into an integer# column) still casts fine and never reaches here.