: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): stabilize CDC column types across micro-batches (#66202)
Daniel RCec99d552d050
diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.pyindex 6b71234e31b6..be7d63fe18dc 100644--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.py+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.py@@ -50,6 +50,7 @@ from products.warehouse_sources.backend.temporal.data_imports.cdc.batcher importfrom products.warehouse_sources.backend.temporal.data_imports.cdc.errors import (MAX_FRIENDLY_MESSAGE_LENGTH,CDCErrorInfo,+ CDCSchemaMergeError,classify_cdc_error,)from products.warehouse_sources.backend.temporal.data_imports.cdc.types import ChangeEvent@@ -591,7 +592,16 @@ class CDCExtractActivity:key_columns,schema,)- batch_result = tracker.s3_writer.write_batch(write_table, batch_index=tracker.batch_index)+ try:+ batch_result = tracker.s3_writer.write_batch(write_table, batch_index=tracker.batch_index)+ except pa.ArrowTypeError as e:+ # The per-batch table is built consistently (typed columns + safe fallback),+ # so an Arrow type error here is a cross-batch merge conflict — a column whose+ # type genuinely drifted mid-stream. Replaying re-fails identically, so surface+ # it as non-retryable instead of looping the schedule.+ raise CDCSchemaMergeError(+ f"Incompatible column types across CDC batches for {write_resource_name}"+ ) from etracker.batch_results.append(batch_result)tracker.batch_index += 1tracker.total_rows += write_table.num_rows@@ -782,6 +792,7 @@ class CDCExtractActivity:position_serialized=event.position_serialized,timestamp=event.timestamp,columns=filtered,+ column_types=event.column_types,)def _qualified_table_name(self, schema: ExternalDataSchema) -> str:diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/batcher.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/batcher.pyindex 89b246ed642a..e44df3b008e4 100644--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/batcher.py+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/batcher.py@@ -336,6 +336,10 @@ def _events_to_table(events: list[ChangeEvent]) -> pa.Table:all_columns[col_name] = Nonecolumn_names = list(all_columns.keys())+ # Authoritative Arrow type per column from the source schema (same for every event+ # of a relation). Lets all-null micro-batches keep the column's real type.+ column_types = next((e.column_types for e in events if e.column_types), None) or {}+# Build column arrayssource_data: dict[str, list] = {col: [] for col in column_names}cdc_ops: list[str] = []@@ -362,12 +366,18 @@ def _events_to_table(events: list[ChangeEvent]) -> pa.Table:arrays: list[pa.Array] = []fields: list[pa.Field] = []for col_name in column_names:- try:- arr = pa.array(source_data[col_name])- except (pa.ArrowInvalid, pa.ArrowTypeError):- arr = pa.array([str(v) if v is not None else None for v in source_data[col_name]], type=pa.string())- if arr.type == pa.null():- arr = arr.cast(pa.string())+ target_type = column_types.get(col_name)+ if target_type is not None:+ # _safe_pa_array falls back to inference, then string, if the values+ # don't fit the declared type (e.g. a mid-WAL type change).+ arr = _safe_pa_array(source_data[col_name], target_type)+ else:+ try:+ arr = pa.array(source_data[col_name])+ except (pa.ArrowInvalid, pa.ArrowTypeError):+ arr = pa.array([str(v) if v is not None else None for v in source_data[col_name]], type=pa.string())+ if arr.type == pa.null():+ arr = arr.cast(pa.string())arrays.append(arr)fields.append(pa.field(col_name, arr.type))diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/errors.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/errors.pyindex 354d81d959df..2e15c949a395 100644--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/errors.py+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/errors.py@@ -31,6 +31,7 @@ class CDCErrorCategory(enum.StrEnum):SLOT_IN_USE = "slot_in_use"WAL_DECODE_ERROR = "wal_decode_error"TRANSACTION_TOO_LARGE = "transaction_too_large"+ SCHEMA_MERGE_INCOMPATIBLE = "schema_merge_incompatible"UNKNOWN = "unknown"@@ -50,6 +51,16 @@ class CDCTransactionTooLargeError(Exception):"""+class CDCSchemaMergeError(Exception):+ """A column's values can't be reconciled into one Parquet type across micro-batches.++ Non-retryable: the conflicting batches replay identically, so re-running re-fails. The+ activity raises this when an Arrow schema merge rejects the data (e.g. a source column+ that genuinely changed type mid-stream — int in one batch, text in another). Defined+ here so the shared classifier owns the mapping to ``SCHEMA_MERGE_INCOMPATIBLE``.+ """++# (friendly_message, retryable) per category. Messages are STATIC templates — they never# interpolate host/user/password or raw exception text, so stored copy can't leak credentials._CATEGORY_DEFAULTS: dict[CDCErrorCategory, tuple[str, bool]] = {@@ -92,6 +103,12 @@ _CATEGORY_DEFAULTS: dict[CDCErrorCategory, tuple[str, bool]] = {"once. Reduce the size of bulk operations on the source, then re-sync.",False,),+ CDCErrorCategory.SCHEMA_MERGE_INCOMPATIBLE: (+ "A source column changed type partway through the change stream (for example, numbers and text "+ "in the same column), so the changes can no longer be combined into one table. Disable and "+ "re-enable change data capture to re-sync from a fresh snapshot.",+ False,+ ),CDCErrorCategory.UNKNOWN: ("Change data capture hit an unexpected error. PostHog will retry automatically — if it ""persists, check the source's sync logs or contact support.",@@ -126,6 +143,8 @@ def classify_cdc_error(exc: BaseException, adapter: CDCSourceAdapter | None) ->for err in _iter_cause_chain(exc):if isinstance(err, CDCTransactionTooLargeError):return cdc_error_info(CDCErrorCategory.TRANSACTION_TOO_LARGE)+ if isinstance(err, CDCSchemaMergeError):+ return cdc_error_info(CDCErrorCategory.SCHEMA_MERGE_INCOMPATIBLE)if adapter is not None:info = adapter.classify_error(err)if info is not None:diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_batcher.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_batcher.pyindex 838b0623a3f6..1ea388af0543 100644--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_batcher.py+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_batcher.py@@ -1,4 +1,5 @@import decimal+from collections.abc import Mappingfrom datetime import UTC, datetimefrom typing import Literal@@ -26,6 +27,7 @@ def _make_event(position: str = "0/100",columns: dict | None = None,timestamp: datetime | None = None,+ column_types: Mapping[str, pa.DataType] | None = None,) -> ChangeEvent:return ChangeEvent(operation=op,@@ -33,6 +35,7 @@ def _make_event(position_serialized=position,timestamp=timestamp or datetime(2025, 6, 15, 12, 0, 0, tzinfo=UTC),columns=columns or {"id": 1, "name": "Alice"},+ column_types=column_types,)@@ -212,6 +215,45 @@ class TestEventsToTableEdgeCases:table = tables["users"]assert table.column("val").type == pa.string()+ def test_source_type_overrides_all_null_inference(self):+ # A column that is all-null in a micro-batch must keep its declared source type+ # rather than being inferred as null/string.+ types = {"id": pa.int64(), "seats": pa.int64()}+ batcher = ChangeEventBatcher()+ batcher.add(_make_event(op="D", columns={"id": 1, "seats": None}, column_types=types))+ batcher.add(_make_event(op="D", columns={"id": 2, "seats": None}, column_types=types))++ table = batcher.flush()["users"]+ assert table.column("seats").type == pa.int64()++ def test_all_null_and_concrete_flushes_merge(self):+ # Reproduces the prod crash: one flush sees `seats` all-null, a later flush sees+ # concrete ints. Without a declared source type the first is string and the+ # second int64, and S3BatchWriter's unify_schemas raises int64-vs-string.+ types = {"id": pa.int64(), "seats": pa.int64()}++ b1 = ChangeEventBatcher()+ b1.add(_make_event(op="D", columns={"id": 1, "seats": None}, column_types=types))+ flush1 = b1.flush()["users"]++ b2 = ChangeEventBatcher()+ b2.add(_make_event(op="I", columns={"id": 2, "seats": 5}, column_types=types))+ flush2 = b2.flush()["users"]++ # Both Parquet schemas agree, so the cross-flush merge succeeds.+ merged = pa.unify_schemas([flush1.schema, flush2.schema])+ assert merged.field("seats").type == pa.int64()++ def test_source_type_falls_back_when_value_does_not_fit(self):+ # If a value can't be cast to the declared type (e.g. a mid-WAL type change),+ # the batch must still build rather than raise.+ types = {"id": pa.int64(), "seats": pa.int64()}+ batcher = ChangeEventBatcher()+ batcher.add(_make_event(op="I", columns={"id": 1, "seats": "not-a-number"}, column_types=types))++ table = batcher.flush()["users"]+ assert table.column("seats").type == pa.string()+class TestDeduplicateTable:def _make_raw_table(self, events):diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_errors.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_errors.pyindex c2c1c90d4d9c..b4f629ba22f1 100644--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_errors.py+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_errors.py@@ -5,6 +5,7 @@ from products.warehouse_sources.backend.temporal.data_imports.cdc.errors importMAX_FRIENDLY_MESSAGE_LENGTH,CDCErrorCategory,CDCErrorInfo,+ CDCSchemaMergeError,CDCTransactionTooLargeError,cdc_error_info,classify_cdc_error,@@ -36,6 +37,7 @@ class TestCDCErrorInfo:(CDCErrorCategory.SLOT_IN_USE, True),(CDCErrorCategory.WAL_DECODE_ERROR, False),(CDCErrorCategory.TRANSACTION_TOO_LARGE, False),+ (CDCErrorCategory.SCHEMA_MERGE_INCOMPATIBLE, False),(CDCErrorCategory.UNKNOWN, True),])@@ -81,6 +83,16 @@ class TestClassifyCDCError:assert info.category is CDCErrorCategory.TRANSACTION_TOO_LARGEassert info.retryable is False+ def test_schema_merge_error_is_non_retryable_via_cause_chain(self):+ # The activity wraps the Arrow type error as CDCSchemaMergeError; classification must+ # find it through the cause chain and mark the run non-retryable so it stops looping.+ cause = CDCSchemaMergeError("Incompatible column types across CDC batches for orders")+ wrapper = RuntimeError("flush failed")+ wrapper.__cause__ = cause+ info = classify_cdc_error(wrapper, None)+ assert info.category is CDCErrorCategory.SCHEMA_MERGE_INCOMPATIBLE+ assert info.retryable is False+def test_non_psycopg_exception_with_slot_message_is_not_classified(self):# A non-psycopg exception whose message happens to contain slot/auth patterns must not be# misclassified as non-retryable — only psycopg exceptions carry these patterns meaningfully.diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_extract_activity.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_extract_activity.pyindex e50ce402f8ed..4d4442ae4835 100644--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_extract_activity.py+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_extract_activity.py@@ -6,6 +6,7 @@ from typing import Literalimport pytestfrom unittest.mock import MagicMock, patch+import pyarrow as paimport psycopg.errorsfrom products.warehouse_sources.backend.temporal.data_imports.cdc.activities import (@@ -870,6 +871,61 @@ class TestCDCExtractActivity:# Slot should NOT have been advancedmock_reader.confirm_position.assert_not_called()+ @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.activity")+ @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.PostgresProducer")+ @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.S3BatchWriter")+ @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.get_cdc_adapter")+ @patch.object(CDCExtractActivity, "_get_cdc_schemas")+ @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.ExternalDataSource")+ @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.ExternalDataJob")+ @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.close_old_connections")+ def test_unmergeable_schema_fails_non_retryably(+ self,+ mock_close_conns,+ MockJob,+ MockSourceModel,+ mock_get_schemas,+ mock_get_adapter,+ MockS3Writer,+ MockProducer,+ mock_activity,+ ):+ source = _make_source()+ schema = _make_schema("users", cdc_mode="streaming", source=source)+ events = [_make_event(op="I", table="users", position="0/100")]++ mock_reader, mock_s3, mock_producer, mock_job = _setup_mocks(+ mock_activity,+ MockProducer,+ MockS3Writer,+ mock_get_adapter,+ mock_get_schemas,+ MockSourceModel,+ MockJob,+ mock_close_conns,+ source,+ [schema],+ events,+ )++ # A cross-batch Arrow merge conflict (a column that drifted type mid-stream) surfaces+ # from write_batch as ArrowTypeError. Replaying re-fails identically, so the run must+ # stop rather than loop the schedule.+ mock_s3.write_batch.side_effect = pa.ArrowTypeError(+ "Unable to merge: Field seats has incompatible types: int64 vs string"+ )++ inputs = CDCExtractInput(team_id=1, source_id=source.id)++ with pytest.raises(NonRetryableException):+ cdc_extract_activity(inputs)++ assert schema.status == "Failed"+ assert schema.latest_error == cdc_error_info(CDCErrorCategory.SCHEMA_MERGE_INCOMPATIBLE).friendly_message+ # The raw column/type detail never reaches the user-facing message.+ assert "int64" not in schema.latest_error+ mock_reader.confirm_position.assert_not_called()+@patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.activity")@patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.PostgresProducer")@patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.S3BatchWriter")diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/types.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/types.pyindex d52aca967441..eb21db18da95 100644--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/types.py+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/types.py@@ -1,10 +1,12 @@from __future__ import annotations-from collections.abc import Iterator+from collections.abc import Iterator, Mappingfrom dataclasses import dataclassfrom datetime import datetimefrom typing import Any, Literal, Protocol, Self+import pyarrow as pa+ManagementMode = Literal["posthog", "self_managed"]@@ -48,6 +50,12 @@ class ChangeEvent:position_serialized: strtimestamp: datetimecolumns: dict[str, Any]+ # Authoritative Arrow type per source column, from the engine's schema metadata+ # (e.g. Postgres relation OIDs). Lets the batcher type a column the same way in+ # every micro-batch even when one flush sees it all-null — without it, an all-null+ # flush is inferred as string while a concrete flush is int64, and the two Parquet+ # schemas fail to merge. Shared across all events of one relation; None when unknown.+ column_types: Mapping[str, pa.DataType] | None = Noneclass CDCStreamReader(Protocol):diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/decoder.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/decoder.pyindex 5e884ff4ce63..13ac424f07b4 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/decoder.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/decoder.py@@ -30,6 +30,8 @@ from dataclasses import (from datetime import UTC, datetimefrom typing import Any+import pyarrow as pa+from products.warehouse_sources.backend.temporal.data_imports.cdc.types import ChangeEventfrom products.warehouse_sources.backend.temporal.data_imports.sources.postgres.cdc.position import PgLSN@@ -73,6 +75,9 @@ class Relation:table_name: strreplica_identity: int # 0=default, 1=nothing, 2=full, 3=indexcolumns: list[RelationColumn] = field(default_factory=list)+ # Arrow type per column, derived once from the column OIDs. Stamped onto every+ # ChangeEvent so the batcher types all-null micro-batches consistently.+ column_arrow_types: dict[str, pa.DataType] = field(default_factory=dict)@propertydef qualified_name(self) -> str:@@ -221,6 +226,7 @@ class PgOutputDecoder:table_name=table_name,replica_identity=replica_identity,columns=columns,+ column_arrow_types={col.name: _arrow_type_for_oid(col.type_oid) for col in columns},)def _handle_insert(self, payload: bytes, lsn: str) -> None:@@ -242,6 +248,7 @@ class PgOutputDecoder:position_serialized=lsn,timestamp=self._tx_timestamp or datetime.now(tz=UTC),columns=columns,+ column_types=relation.column_arrow_types,))@@ -279,6 +286,7 @@ class PgOutputDecoder:position_serialized=lsn,timestamp=self._tx_timestamp or datetime.now(tz=UTC),columns=columns,+ column_types=relation.column_arrow_types,))@@ -309,6 +317,7 @@ class PgOutputDecoder:position_serialized=lsn,timestamp=self._tx_timestamp or datetime.now(tz=UTC),columns=columns,+ column_types=relation.column_arrow_types,))@@ -417,6 +426,24 @@ def _skip_tuple(data: bytes, offset: int, relation: Relation) -> tuple[dict[str,return columns, offset+def _arrow_type_for_oid(type_oid: int) -> pa.DataType:+ """Arrow type matching the Python value ``_cast_text_value`` produces for this OID.++ Must stay in lockstep with ``_cast_text_value``: bool→bool_, integers→int64,+ floats→float64, everything else (numeric, json, text, …) stays string. Used to+ type a column the same way in every micro-batch, so an all-null flush is not+ inferred as string and then rejected when merged with a concrete int64 flush.+ """+ if type_oid == _OID_BOOL:+ return pa.bool_()+ elif type_oid in (_OID_INT2, _OID_INT4, _OID_INT8):+ return pa.int64()+ elif type_oid in (_OID_FLOAT4, _OID_FLOAT8):+ return pa.float64()+ else:+ return pa.string()++def _cast_text_value(text: str, type_oid: int) -> Any:"""Cast a pgoutput text-format value to a Python type based on OID.diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/tests/test_decoder.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/tests/test_decoder.pyindex b1802af51f9b..3a8eacbc92ba 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/tests/test_decoder.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/tests/test_decoder.py@@ -1,6 +1,7 @@import structfrom datetime import UTC, datetime+import pyarrow as pafrom parameterized import parameterizedfrom products.warehouse_sources.backend.temporal.data_imports.sources.postgres.cdc.decoder import (@@ -250,6 +251,35 @@ class TestPgOutputDecoder:assert events[0].columns["name"] is Noneassert events[0].columns["email"] == "[email protected]"+ def test_event_carries_column_arrow_types(self):+ # Events expose the Arrow type per column from the relation OIDs, so the batcher+ # can type a column the same way even in a micro-batch where it's all-null.+ decoder = self._setup_decoder_with_relation(+ columns=[+ ("id", _OID_INT8, -1),+ ("seats", _OID_INT4, -1),+ ("price", _OID_FLOAT8, -1),+ ("active", _OID_BOOL, -1),+ ("payload", _OID_JSONB, -1),+ ("name", _OID_TEXT, -1),+ ]+ )++ decoder.decode_message(_make_begin(), "0/100")+ decoder.decode_message(+ _make_insert(1, [("t", "1"), ("t", "5"), ("t", "9.5"), ("t", "t"), ("t", "{}"), ("t", "x")]), "0/150"+ )+ events = decoder.decode_message(_make_commit(), "0/200")++ assert events[0].column_types == {+ "id": pa.int64(),+ "seats": pa.int64(),+ "price": pa.float64(),+ "active": pa.bool_(),+ "payload": pa.string(),+ "name": pa.string(),+ }+def test_unchanged_toast_column(self):decoder = self._setup_decoder_with_relation(columns=[("id", _OID_INT4, -1), ("big_text", _OID_TEXT, -1)])