: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-warehouse): keep revenuecat event price columns as double (#71002)
Luke Beltone1236c125a66
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 f3dec4963a8b..a31b012571a2 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@@ -682,14 +682,17 @@ def test_evolve_pyarrow_schema_decimal_does_not_widen_unnecessarily_and_can_wide(pa.int32(), pa.int64(), 6178466636), # > int32 max (2147483647)(pa.int16(), pa.int64(), 6178466636), # > int16 max, fits int64(pa.int16(), pa.int32(), 100000), # > int16 max (32767), fits int32+ (pa.int64(), pa.float64(), 19.99), # fractional float into an int column+ (pa.int64(), pa.decimal128(4, 2), decimal.Decimal("19.99")), # fractional decimal into an int column],)def test_evolve_pyarrow_schema_integer_overflow_raises_actionable_error(- delta_type: pa.DataType, incoming_type: pa.DataType, overflowing_value: int+ delta_type: pa.DataType, incoming_type: pa.DataType, overflowing_value: int | float | decimal.Decimal):- """An incoming integer value that overflows the stored (narrower) Delta type raises a- clear, actionable error instructing the user to reset and re-sync — rather than a raw- pyarrow ArrowInvalid."""+ """An incoming value that doesn't fit the stored integer Delta type — a wider integer+ that overflows, or a fractional float/decimal that would be truncated — raises a clear,+ actionable error instructing the user to reset and re-sync, rather than a raw pyarrow+ ArrowInvalid."""arrow_table = pa.table({"id": pa.array([1, 2], type=pa.int64()),@@ -723,6 +726,25 @@ def test_evolve_pyarrow_schema_integer_narrowing_within_range_is_preserved():assert evolved_table.column("val").to_pylist() == [10, 20]+def test_evolve_pyarrow_schema_whole_valued_floats_cast_into_stored_integer_column():+ # The type-changed error must only fire on genuine truncation: a float column whose+ # values are all whole numbers still casts losslessly into a stored integer column.+ arrow_table = pa.table(+ {+ "id": pa.array([1, 2], type=pa.int64()),+ "val": pa.array([10.0, 20.0], type=pa.float64()),+ }+ )+ delta_schema = deltalake.Schema.from_arrow(+ pa.schema([pa.field("id", pa.int64(), nullable=False), pa.field("val", pa.int64(), nullable=True)])+ )++ evolved_table = evolve_pyarrow_schema(arrow_table, delta_schema)++ assert evolved_table.schema.field("val").type == pa.int64()+ assert evolved_table.column("val").to_pylist() == [10, 20]++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 19d794eeca35..c8f2ad62eed3 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@@ -293,12 +293,20 @@ def evolve_pyarrow_schema(incoming_table: pa.Table, delta_schema: deltalake.Schetry:casted_column = incoming_column.cast(delta_field.type).combine_chunks()except pa.ArrowInvalid as e:- # A narrowing cast overflowed. The usual cause is the source column's type+ # A narrowing cast overflowed. The usual causes are the source column's type# being widened upstream (e.g. Postgres `integer` → `bigint`) after the Delta- # column was created with the narrower type. delta-rs cannot widen an existing- # column in place, so retrying is futile — surface an actionable error telling- # the user to reset and fully re-sync the table.- if pa.types.is_integer(delta_field.type) and pa.types.is_integer(incoming_column.type):+ # column was created with the narrower type, or an integer-created column now+ # receiving fractional values — e.g. a price field whose first-synced rows were+ # all whole numbers, later failing with "ArrowInvalid: Float value 19.990000+ # was truncated converting to int64". delta-rs cannot widen an existing column+ # in place, so retrying is futile — surface an actionable error telling the+ # user to reset and fully re-sync the table. Whole-valued floats/decimals still+ # cast into an integer column losslessly, so this only fires on genuine data loss.+ if pa.types.is_integer(delta_field.type) and (+ pa.types.is_integer(incoming_column.type)+ or pa.types.is_floating(incoming_column.type)+ or pa.types.is_decimal(incoming_column.type)+ ):raise SchemaColumnTypeChangedException(f"Source column type changed: '{delta_field.name}' has values that no longer "f"fit its stored type {delta_field.type} (incoming data is now "diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/consumer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/consumer.pyindex bc2acb265a8b..c9474838f7eb 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/consumer.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/consumer.py@@ -73,6 +73,9 @@ NON_RETRYABLE_ERROR_PATTERNS: tuple[str, ...] = ("is too large to store in a Decimal128",# schema configured as incremental without a primary key — config error"Primary key required for incremental syncs",+ # incoming values no longer fit the stored Delta column type+ # (SchemaColumnTypeChangedException) — only a reset and full re-sync can fix it+ "Source column type changed",)# How long an "alive" job-status lookup stays cached before re-checking the app DB.diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_consumer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_consumer.pyindex 7140d66a36a7..ef1f7f19bdbb 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_consumer.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_consumer.py@@ -146,6 +146,7 @@ class TestProcessSingle:["20009.59457503306999908717 is too large to store in a Decimal128 of precision 24.","Primary key required for incremental syncs",+ "Source column type changed: 'price' has values that no longer fit its stored type int64",],)@pytest.mark.asynciodiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/revenuecat/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/revenuecat/source.pyindex c1f8291a4709..d1fc02cf1e1a 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/revenuecat/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/revenuecat/source.py@@ -57,6 +57,24 @@ if TYPE_CHECKING:REVENUECAT_API_KEYS_URL = "https://app.revenuecat.com/projects/_/api-keys"+# Event-payload fields RevenueCat documents as doubles. JSON drops the decimal point on+# whole values (`0`, `20`), so they parse as Python ints, and events like TRANSFER carry+# them as nulls. If the batch that creates the Delta table holds only whole values, the+# column gets locked to int64 and the first fractional price (e.g. 19.99) fails every+# subsequent sync with an Arrow truncation error; if it holds only nulls, the column is+# stored as string (Delta has no null type) and later prices are silently stringified.+# Force these columns to double so neither can happen.+_EVENT_DOUBLE_FIELDS = (+ "price",+ "price_in_purchased_currency",+ "takehome_percentage",+ "tax_percentage",+ "commission_percentage",+ "discount_percentage",+ "discount_amount",+)++def _webhook_table_transformer(table: pa.Table) -> pa.Table:"""Unwrap RevenueCat's ``{"event": {...}, "api_version": "1.0"}`` envelope.@@ -68,7 +86,10 @@ def _webhook_table_transformer(table: pa.Table) -> pa.Table:We also derive a ``created_at`` field (Unix seconds) from RevenueCat's``event_timestamp_ms`` so this table can share the same datetime partitionconvention as the API endpoints. The original ``event_timestamp_ms`` is- preserved unchanged for callers that need sub-second precision.+ preserved unchanged for callers that need sub-second precision. Columns+ documented as doubles are forced to float64 so whole-valued or all-null+ batches can't pin them to an integer or string type (see+ ``_EVENT_DOUBLE_FIELDS``)."""if "event" not in table.column_names:return table_from_py_list([])@@ -92,7 +113,23 @@ def _webhook_table_transformer(table: pa.Table) -> pa.Table:row["created_at"] = event_ts_ms // 1000rows.append(row)- return table_from_py_list(rows)+ result = table_from_py_list(rows)++ # Cast at the table level rather than per value: an all-null column carries no values+ # to coerce, yet still needs the float64 type or it infers `null` (stored as string).+ for field_name in _EVENT_DOUBLE_FIELDS:+ if field_name not in result.column_names:+ continue+ field_index = result.schema.get_field_index(field_name)+ column_type = result.schema.field(field_index).type+ if pa.types.is_null(column_type) or pa.types.is_integer(column_type):+ result = result.set_column(+ field_index,+ pa.field(field_name, pa.float64()),+ result.column(field_name).cast(pa.float64()),+ )++ return result@SourceRegistry.register@@ -215,6 +252,12 @@ class RevenueCatSource("404 Client Error: Not Found": ("RevenueCat could not find the project. Double-check the project id and that the API key belongs to it."),+ "Source column type changed": (+ "A column in this table started receiving values that don't fit the type stored from "+ "earlier syncs (for example a price column created from whole-number values now "+ "receiving a decimal price). We can't widen an existing column in place — reset and "+ "fully re-sync this table to adopt the new type."+ ),}def validate_credentials(diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/revenuecat/tests/test_revenuecat_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/revenuecat/tests/test_revenuecat_source.pyindex fe46c5fd1745..b534412ed765 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/revenuecat/tests/test_revenuecat_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/revenuecat/tests/test_revenuecat_source.py@@ -381,6 +381,72 @@ class TestRevenueCatWebhookTableTransformer:assert rows[0]["event_timestamp_ms"] == 1658726374000assert rows[0]["created_at"] == 1658726374+ def test_coerces_whole_valued_double_fields_to_float(self):+ # RevenueCat documents these fields as doubles, but whole values arrive as JSON+ # ints. If every row in the batch that creates the Delta table is whole (e.g. $0+ # trials), the column would be locked to int64 and the first fractional price+ # (19.99) would fail every later sync with an Arrow truncation error.+ table = table_from_py_list(+ [+ {+ "api_version": "1.0",+ "event": {+ "id": "evt-1",+ "type": "INITIAL_PURCHASE",+ "price": 0,+ "price_in_purchased_currency": 0,+ "takehome_percentage": 1,+ "tax_percentage": 0,+ "commission_percentage": 0,+ "discount_percentage": 10,+ "discount_amount": 0,+ "renewal_number": 1,+ "event_timestamp_ms": 1658726374000,+ },+ },+ {+ "api_version": "1.0",+ "event": {"id": "evt-2", "type": "TRANSFER", "price": None},+ },+ ]+ )++ result = _webhook_table_transformer(table)++ for field in (+ "price",+ "price_in_purchased_currency",+ "takehome_percentage",+ "tax_percentage",+ "commission_percentage",+ "discount_percentage",+ "discount_amount",+ ):+ assert result.schema.field(field).type == pa.float64(), field+ # Only the documented double fields are coerced — integer fields stay integers.+ assert result.schema.field("renewal_number").type == pa.int64()+ assert result.schema.field("event_timestamp_ms").type == pa.int64()++ rows = result.to_pylist()+ assert rows[0]["price"] == 0.0+ assert rows[1]["price"] is None++ def test_all_null_double_fields_are_still_typed_as_float(self):+ # A first batch where a double field is null on every row (e.g. TRANSFER events)+ # would otherwise infer a `null` column, which the delta write path stores as+ # string — silently stringifying every later price instead of erroring.+ table = table_from_py_list(+ [+ {"api_version": "1.0", "event": {"id": "evt-1", "type": "TRANSFER", "price": None}},+ {"api_version": "1.0", "event": {"id": "evt-2", "type": "TRANSFER", "price": None}},+ ]+ )++ result = _webhook_table_transformer(table)++ assert result.schema.field("price").type == pa.float64()+ assert result.column("price").to_pylist() == [None, None]+def test_skips_created_at_derivation_when_event_timestamp_ms_missing(self):# Older RevenueCat events or test deliveries may omit the timestamp# entirely. Don't synthesize a fake `created_at` value — the partition