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-imports): stabilize column types across extract batches (#75819)

posthog[bot]e1d7c96de0bd
diff --git a/products/warehouse_sources/backend/temporal/data_imports/external_data_job.py b/products/warehouse_sources/backend/temporal/data_imports/external_data_job.py
index 8f820e49dfb3..2f4c16d4884b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/external_data_job.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/external_data_job.py
@@ -326,6 +326,8 @@ async def update_external_data_job_model(inputs: UpdateExternalDataJobStatusInpu
else:
job_id = inputs.job_id
+ source: ExternalDataSource | None = None
+ has_non_retryable_error = False
if inputs.internal_error:
logger.exception(
f"External data job failed for external data schema {inputs.schema_id} on job {inputs.job_id} with error: {inputs.internal_error}"
@@ -333,9 +335,7 @@ async def update_external_data_job_model(inputs: UpdateExternalDataJobStatusInpu
internal_error_normalized = re.sub("[\n\r\t]", " ", inputs.internal_error)
- source: ExternalDataSource = await database_sync_to_async_pool(ExternalDataSource.objects.get)(
- pk=inputs.source_id
- )
+ source = await database_sync_to_async_pool(ExternalDataSource.objects.get)(pk=inputs.source_id)
source_cls = SourceRegistry.get_source(ExternalDataSourceType(source.source_type))
non_retryable_errors = source_cls.get_non_retryable_errors()
@@ -355,19 +355,8 @@ async def update_external_data_job_model(inputs: UpdateExternalDataJobStatusInpu
has_non_retryable_error = not platform_failure and error_message_matches(
internal_error_normalized, non_retryable_errors.keys()
)
+
if has_non_retryable_error:
- posthoganalytics.capture(
- distinct_id=get_machine_id(),
- event="schema non-retryable error",
- properties={
- "schemaId": inputs.schema_id,
- "sourceId": inputs.source_id,
- "sourceType": source.source_type,
- "jobId": inputs.job_id,
- "teamId": inputs.team_id,
- "error": inputs.internal_error,
- },
- )
friendly_errors = [
friendly_error
for error, friendly_error in non_retryable_errors.items()
@@ -397,6 +386,29 @@ async def update_external_data_job_model(inputs: UpdateExternalDataJobStatusInpu
team_id=inputs.team_id,
)
+ if inputs.internal_error and source is not None:
+ # This activity runs once the workflow has given up, so every error reaching here has
+ # already exhausted its retries — including the ones no source classified. Those used to
+ # leave a schema in error state with no event behind it, which is why whole classes of
+ # failure only ever surfaced through support tickets. Emit for both outcomes and
+ # distinguish them with a property. The capture comes after the DB writes because this
+ # activity retries without limit: emitting first would duplicate the event on every
+ # attempt a transient DB failure causes. The error text is uncurated exception output,
+ # so cap what flows into analytics.
+ posthoganalytics.capture(
+ distinct_id=get_machine_id(),
+ event="schema non-retryable error" if has_non_retryable_error else "schema unclassified error",
+ properties={
+ "schemaId": inputs.schema_id,
+ "sourceId": inputs.source_id,
+ "sourceType": source.source_type,
+ "jobId": inputs.job_id,
+ "teamId": inputs.team_id,
+ "error": inputs.internal_error[:1000],
+ "classified": has_non_retryable_error,
+ },
+ )
+
logger.info(
f"Updated external data job with for external data source {job_id} to status {inputs.status}",
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/arrow_utils.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/arrow_utils.py
index 94b349b1973b..7bb2ce546ed5 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/arrow_utils.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/arrow_utils.py
@@ -5,7 +5,7 @@ import math
import uuid
import decimal
import datetime
-from collections.abc import Callable, Iterable, Iterator, Sequence
+from collections.abc import Callable, Collection, Iterable, Iterator, Sequence
from functools import _make_key, wraps
from ipaddress import IPv4Address, IPv6Address
from typing import TYPE_CHECKING, Any, Literal, Optional, cast
@@ -787,6 +787,224 @@ def restrict_schema_to_columns(schema: pa.Schema, column_names: Sequence[str]) -
return pa.schema([field for field in schema if field.name in present])
+def _stringify_column(column: pa.ChunkedArray | pa.Array) -> pa.ChunkedArray | pa.Array:
+ """Render a column as text.
+
+ Prefer Arrow's own cast: it is vectorized and renders values the same way as sibling
+ batches that were cast (rather than stringified) into the same string column. Only what
+ Arrow can't cast takes the per-value pass — nested values as JSON, bytes decoded.
+ """
+ casted = _cast_column_to(column, pa.string())
+ if casted is not None:
+ return casted
+
+ def _render(value: object) -> str | None:
+ if value is None:
+ return None
+ if isinstance(value, dict | list):
+ return _json_dumps(value)
+ if isinstance(value, bytes | bytearray):
+ return bytes(value).decode("utf-8", errors="replace")
+ return str(value)
+
+ return pa.array([_render(value) for value in _to_list_array(column)], type=pa.string())
+
+
+def _cast_column_to(column: pa.ChunkedArray | pa.Array, target: pa.DataType) -> pa.ChunkedArray | pa.Array | None:
+ """Safe-cast a column, returning None when the values don't fit the target type."""
+ try:
+ return pc.cast(column, target)
+ except (pa.ArrowInvalid, pa.ArrowNotImplementedError, pa.ArrowTypeError):
+ return None
+
+
+def _common_type(left: pa.DataType, right: pa.DataType) -> pa.DataType | None:
+ """The type Arrow will promote `left` and `right` to, or None if it won't promote them."""
+ try:
+ unified = pa.unify_schemas(
+ [pa.schema([pa.field("f", left)]), pa.schema([pa.field("f", right)])], promote_options="permissive"
+ )
+ except (pa.ArrowInvalid, pa.ArrowTypeError, pa.ArrowNotImplementedError):
+ return None
+ return unified.field("f").type
+
+
+def _cast_is_faithful(source: pa.DataType, target: pa.DataType) -> bool:
+ """Whether a successful `pc.cast(source → target)` converts values rather than reinterpreting them.
+
+ Arrow "casts" int64 → timestamp by reading the ints as the target's epoch unit, numeric → bool
+ by truthiness, and struct → struct by dropping unmatched fields and null-filling the rest —
+ silent corruption, not conversion, so those pairs must fall through to the text fallback
+ instead. String targets render faithfully, string sources parse (raising on values that don't
+ fit), and pairs Arrow itself promotes (numeric widening, decimal rescaling, temporal unit
+ changes) convert.
+ """
+ if pa.types.is_nested(source) or pa.types.is_nested(target):
+ return False
+ if pa.types.is_string(target) or pa.types.is_large_string(target):
+ return True
+ if pa.types.is_string(source) or pa.types.is_large_string(source):
+ return True
+ return _common_type(source, target) is not None
+
+
+def reconcile_batch_to_accumulated_schema(
+ pa_table: pa.Table,
+ accumulated_schema: pa.Schema | None,
+ logger: FilteringBoundLogger | None = None,
+ protected_columns: Collection[str] = (),
+) -> tuple[pa.Table, pa.Schema]:
+ """Make a batch's schema consistent with the batches already written in this run.
+
+ Extraction infers each batch's Arrow types independently, so a source that returns the same
+ field as an int on some rows and a string on others produces parquet parts that disagree —
+ which then fails when the parts' schemas are merged, with the whole sync landing in error.
+ That is not fixable per-field per-source: a workspace can put arbitrary values in a custom
+ attribute, so the set of flip-prone fields is unbounded.
+
+ Reconciling here converges every batch onto one type for the run, preferring in order:
+ the type earlier batches already wrote (nothing to rewrite), Arrow's own promotion (e.g.
+ int64 + double → double), and finally text, which holds anything. Casts are only taken when
+ they convert values; pairs Arrow would reinterpret (int ↔ timestamp, numeric → bool, nested
+ shapes) go straight to text.
+
+ Also backfills columns that earlier batches had and this one doesn't, so a column that only
+ appears in some batches still lands with a stable type.
+
+ Convergence is per run: parts written before a mid-run flip keep their original type, and a
+ new Delta table adopts the first part's type at load. A column whose values genuinely cannot
+ cast between the flipped types therefore still fails the run — at the load stage, classified
+ as a column type change — rather than being silently rewritten. What this removes is the
+ extract-time merge crash and the per-source field allowlists.
+
+ `protected_columns` (the incremental cursor) must never converge to text: a lexicographic
+ watermark silently corrupts incremental progress, so an unresolvable flip there raises
+ instead.
+ """
+ if accumulated_schema is None:
+ return pa_table, pa_table.schema
+
+ protected = frozenset(protected_columns)
+
+ for accumulated_field in accumulated_schema:
+ name = accumulated_field.name
+ index = pa_table.schema.get_field_index(name)
+ if index == -1:
+ pa_table = pa_table.append_column(
+ accumulated_field, pa.nulls(pa_table.num_rows, type=accumulated_field.type)
+ )
+ continue
+
+ incoming_type = pa_table.field(index).type
+ if incoming_type == accumulated_field.type:
+ continue
+
+ column = pa_table.column(name)
+
+ if name in protected:
+ # The cursor may widen numerically or parse numeric text back toward the accumulated
+ # type, but must never become text: `max()` over a string cursor orders
+ # lexicographically and silently corrupts the persisted watermark.
+ casted = None
+ resolved_type = accumulated_field.type
+ resolution = "cast_to_accumulated"
+ if not pa.types.is_string(accumulated_field.type) and not pa.types.is_large_string(accumulated_field.type):
+ casted = (
+ _cast_column_to(column, accumulated_field.type)
+ if _cast_is_faithful(incoming_type, accumulated_field.type)
+ else None
+ )
+ if casted is None:
+ promoted = _common_type(accumulated_field.type, incoming_type)
+ if promoted is not None and _cast_is_faithful(incoming_type, promoted):
+ casted = _cast_column_to(column, promoted)
+ resolved_type = promoted
+ resolution = "promoted"
+ if casted is None:
+ raise ValueError(
+ f"Incremental cursor column '{name}' changed type across batches "
+ f"({accumulated_field.type} vs {incoming_type}) and cannot be safely converged"
+ )
+ else:
+ casted = (
+ _cast_column_to(column, accumulated_field.type)
+ if _cast_is_faithful(incoming_type, accumulated_field.type)
+ else None
+ )
+ resolved_type = accumulated_field.type
+ resolution = "cast_to_accumulated"
+
+ if casted is None:
+ promoted = _common_type(accumulated_field.type, incoming_type)
+ if promoted is not None and _cast_is_faithful(incoming_type, promoted):
+ casted = _cast_column_to(column, promoted)
+ if casted is not None:
+ resolved_type = promoted
+ resolution = "promoted"
+ else:
+ casted = _stringify_column(column)
+ resolved_type = pa.string()
+ resolution = "stringified"
+
+ if logger is not None:
+ logger.warning(
+ "Reconciled a batch column type against the run's accumulated schema",
+ column=name,
+ incoming_type=str(incoming_type),
+ accumulated_type=str(accumulated_field.type),
+ resolved_type=str(resolved_type),
+ resolution=resolution,
+ )
+
+ resolved_field = accumulated_field.with_type(resolved_type).with_nullable(True)
+ pa_table = pa_table.set_column(index, resolved_field, casted)
+ if resolved_type != accumulated_field.type:
+ accumulated_schema = accumulated_schema.set(accumulated_schema.get_field_index(name), resolved_field)
+
+ for field in pa_table.schema:
+ if field.name not in accumulated_schema.names:
+ accumulated_schema = accumulated_schema.append(field)
+
+ return pa_table, accumulated_schema
+
+
+def unify_schemas_with_text_fallback(schemas: list[pa.Schema], logger: FilteringBoundLogger | None = None) -> pa.Schema:
+ """Merge batch schemas, resolving any field Arrow refuses to merge to text.
+
+ `reconcile_batch_to_accumulated_schema` converges a run onto one type per column, but batches
+ written before the conflicting one keep the type they were written with, so the merged view of
+ a run can still hold two types for a field. The merged schema is descriptive metadata — the
+ load stage casts each part toward the Delta table on its own — so it's better to describe such
+ a column as text than to fail the extraction over it.
+ """
+ try:
+ return pa.unify_schemas(schemas, promote_options="permissive")
+ except (pa.ArrowInvalid, pa.ArrowTypeError, pa.ArrowNotImplementedError):
+ pass
+
+ merged: dict[str, pa.Field] = {}
+ for schema in schemas:
+ for field in schema:
+ existing = merged.get(field.name)
+ if existing is None:
+ merged[field.name] = field
+ continue
+ if existing.type == field.type:
+ continue
+ resolved = _common_type(existing.type, field.type) or pa.string()
+ if logger is not None:
+ logger.warning(
+ "Batch schemas disagree on a column type; describing it in the merged schema",
+ column=field.name,
+ first_type=str(existing.type),
+ second_type=str(field.type),
+ resolved_type=str(resolved),
+ )
+ merged[field.name] = existing.with_type(resolved).with_nullable(True)
+
+ return pa.schema(list(merged.values()))
+
+
def build_pyarrow_decimal_type(precision: int, scale: int) -> pa.Decimal128Type | pa.Decimal256Type:
if precision <= 38:
return pa.decimal128(precision, scale)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_utils.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_utils.py
index 22df271244a2..44711705b6ac 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_utils.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_utils.py
@@ -35,10 +35,12 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arr
observe_and_project_table,
observed_schema_metadata_columns,
raise_on_nullability_drift,
+ reconcile_batch_to_accumulated_schema,
relax_batch_nullability,
restrict_schema_to_columns,
source_uses_delta_write_column_selection,
table_from_py_list,
+ unify_schemas_with_text_fallback,
)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.consts import PARTITION_KEY
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.partitioning import (
@@ -1904,3 +1906,181 @@ class TestConditionalLruCacheAsyncCachePop:
assert fetch.cache_pop("a") == "value-a"
# Popped, not just read — a second pop finds nothing left to remove.
assert fetch.cache_pop("a") is None
+
+
+class TestReconcileBatchToAccumulatedSchema:
+ def test_first_batch_seeds_the_accumulated_schema(self):
+ batch = pa.table({"owner_id": [1, 2]})
+
+ result, accumulated = reconcile_batch_to_accumulated_schema(batch, None)
+
+ assert result.equals(batch)
+ assert accumulated == batch.schema
+
+ @pytest.mark.parametrize(
+ "first,second,expected_type,expected_values",
+ [
+ # An epoch field arriving as numeric text after a numeric batch — the shape that
+ # kept breaking Intercom syncs — folds back into the type already written.
+ (pa.table({"f": [1700000000]}), pa.table({"f": ["1700000001"]}), pa.int64(), [1700000001]),
+ (pa.table({"f": ["a"]}), pa.table({"f": [7]}), pa.string(), ["7"]),
+ # Arrow's own promotion wins over stringifying when the types are compatible.
+ (pa.table({"f": [1]}), pa.table({"f": [1.5]}), pa.float64(), [1.5]),
+ # A column that was all-null in the first batch adopts the real type later.
+ (pa.table({"f": [None]}), pa.table({"f": [3]}), pa.int64(), [3]),
+ # Nothing else holds both, so text does.
+ (pa.table({"f": [1]}), pa.table({"f": ["nope"]}), pa.string(), ["nope"]),
+ # Pairs Arrow would "cast" by reinterpretation must degrade to text instead: ints
+ # read as the accumulated timestamp's epoch unit would turn 2023 data into 1970
+ # dates, and numeric ↔ bool casts truthify.
+ (
+ pa.table({"f": pa.array([datetime.datetime(2023, 11, 14)], type=pa.timestamp("us"))}),
+ pa.table({"f": [1700000000]}),
+ pa.string(),
+ ["1700000000"],
+ ),
+ (pa.table({"f": [True]}), pa.table({"f": [7]}), pa.string(), ["7"]),
+ (pa.table({"f": [1]}), pa.table({"f": [True]}), pa.string(), ["true"]),
+ ],
+ )
+ def test_conflicting_column_types_converge(
+ self, first: pa.Table, second: pa.Table, expected_type: pa.DataType, expected_values: list[Any]
+ ):
+ _, accumulated = reconcile_batch_to_accumulated_schema(first, None)
+
+ result, accumulated = reconcile_batch_to_accumulated_schema(second, accumulated)
+
+ assert result.schema.field("f").type == expected_type
+ assert accumulated.field("f").type == expected_type
+ assert result.column("f").to_pylist() == expected_values
+
+ def test_columns_missing_from_a_batch_are_backfilled(self):
+ _, accumulated = reconcile_batch_to_accumulated_schema(pa.table({"a": [1], "b": ["x"]}), None)
+
+ result, accumulated = reconcile_batch_to_accumulated_schema(pa.table({"a": [2]}), accumulated)
+
+ assert result.column("b").to_pylist() == [None]
+ assert result.schema.field("b").type == pa.string()
+
+ def test_columns_new_to_a_batch_join_the_accumulated_schema(self):
+ _, accumulated = reconcile_batch_to_accumulated_schema(pa.table({"a": [1]}), None)
+
+ _, accumulated = reconcile_batch_to_accumulated_schema(pa.table({"a": [2], "b": ["x"]}), accumulated)
+
+ assert accumulated.names == ["a", "b"]
+
+ def test_nested_shapes_degrade_to_json_text_not_reshaped_structs(self):
+ # pc.cast(struct → struct) "succeeds" by dropping unmatched fields and null-filling the
+ # rest, silently emptying the column. A nested column whose shape changes between
+ # batches must render as JSON text instead — with nulls staying null, not becoming text.
+ _, accumulated = reconcile_batch_to_accumulated_schema(pa.table({"f": [{"a": 1}]}), None)
+
+ result, accumulated = reconcile_batch_to_accumulated_schema(pa.table({"f": [{"b": "x"}, None]}), accumulated)
+
+ assert result.schema.field("f").type == pa.string()
+ rendered, null_value = result.column("f").to_pylist()
+ assert rendered is not None
+ assert orjson.loads(rendered) == {"b": "x"}
+ assert null_value is None
+ assert accumulated.field("f").type == pa.string()
+
+ def test_stringified_bytes_decode_as_text_and_nulls_stay_null(self):
+ # A binary flip against a non-string accumulated type has no Arrow promotion, so it
+ # degrades to text through the per-value renderer: bytes must decode (replacing invalid
+ # sequences) rather than render as Python reprs, and nulls must stay null.
+ _, accumulated = reconcile_batch_to_accumulated_schema(pa.table({"f": [1]}), None)
+
+ result, _ = reconcile_batch_to_accumulated_schema(
+ pa.table({"f": pa.array([b"caf\xc3\xa9", b"\xff", None], type=pa.binary())}), accumulated
+ )
+
+ assert result.schema.field("f").type == pa.string()
+ assert result.column("f").to_pylist() == ["café", "�", None]
+
+ def test_protected_cursor_column_still_converges_castable_flips(self):
+ # The known Intercom shape on the cursor itself: numeric text parses back to the
+ # accumulated numeric type, so incremental syncs keep working.
+ _, accumulated = reconcile_batch_to_accumulated_schema(pa.table({"updated_at": [1700000000]}), None)
+
+ result, _ = reconcile_batch_to_accumulated_schema(
+ pa.table({"updated_at": ["1700000001"]}), accumulated, protected_columns={"updated_at"}
+ )
+
+ assert result.column("updated_at").to_pylist() == [1700000001]
+
+ def test_protected_cursor_column_widens_numerically_instead_of_raising(self):
+ # A cursor that outgrows the narrow integer type its first batch inferred must widen
+ # via Arrow's own promotion — and log the coercion — rather than fail the run.
+ logger = MagicMock()
+ _, accumulated = reconcile_batch_to_accumulated_schema(
+ pa.table({"updated_at": pa.array([1000], type=pa.int32())}), None
+ )
+
+ result, accumulated = reconcile_batch_to_accumulated_schema(
+ pa.table({"updated_at": pa.array([2**40], type=pa.int64())}),
+ accumulated,
+ logger=logger,
+ protected_columns={"updated_at"},
+ )
+
+ assert result.schema.field("updated_at").type == pa.int64()
+ assert result.column("updated_at").to_pylist() == [2**40]
+ assert accumulated.field("updated_at").type == pa.int64()
+ assert logger.warning.call_args.kwargs["resolution"] == "promoted"
+
+ @pytest.mark.parametrize(
+ "first,second",
+ [
+ # True text in the cursor: a string watermark would compare lexicographically and
+ # silently corrupt incremental progress, so refuse loudly.
+ (pa.table({"updated_at": [1700000000]}), pa.table({"updated_at": ["not-a-number"]})),
+ # A cursor that accumulated as text must not quietly absorb numbers either.
+ (pa.table({"updated_at": ["2024-01-01T00:00:00"]}), pa.table({"updated_at": [1700000000]})),
+ ],
+ )
+ def test_protected_cursor_column_refuses_text_convergence(self, first: pa.Table, second: pa.Table):
+ _, accumulated = reconcile_batch_to_accumulated_schema(first, None)
+
+ with pytest.raises(ValueError, match="cursor column"):
+ reconcile_batch_to_accumulated_schema(second, accumulated, protected_columns={"updated_at"})
+
+ def test_batches_of_source_rows_that_flip_type_stay_mergeable(self):
+ # The prod failure: a source returns the same field as an int on some rows and a string
+ # on others, each batch infers its own type, and merging the run's parquet schemas dies
+ # with "Unable to merge: Field ... has incompatible types: int64 vs string".
+ accumulated = None
+ schemas = []
+ for row in ({"id": "1", "waiting_since": 1700000000}, {"id": "2", "waiting_since": "1700000001"}):
+ batch = evolve_pyarrow_schema(table_from_py_list([row]), None)
+ batch, accumulated = reconcile_batch_to_accumulated_schema(batch, accumulated)
+ schemas.append(batch.schema)
+
+ assert unify_schemas_with_text_fallback(schemas).field("waiting_since").type == pa.int64()
+
+
+class TestUnifySchemasWithTextFallback:
+ def test_unmergeable_field_resolves_to_text(self):
+ # Batches written before a conflict keep their original type on disk, so the run's
+ # merged schema still sees both. Describing it as text beats failing the extraction —
+ # while columns the schemas agree on pass through untouched, with only the conflict
+ # resolved and logged.
+ logger = MagicMock()
+ struct = pa.struct([pa.field("x", pa.int64())])
+ merged = unify_schemas_with_text_fallback(
+ [
+ pa.schema([pa.field("f", pa.int64()), pa.field("s", struct)]),
+ pa.schema([pa.field("f", pa.string()), pa.field("s", struct)]),
+ ],
+ logger=logger,
+ )
+
+ assert merged.field("f").type == pa.string()
+ assert merged.field("s").type == struct
+ assert logger.warning.call_count == 1
+
+ def test_mergeable_schemas_are_unchanged(self):
+ merged = unify_schemas_with_text_fallback(
+ [pa.schema([pa.field("a", pa.int64())]), pa.schema([pa.field("b", pa.string())])]
+ )
+
+ assert merged.names == ["a", "b"]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/pipeline.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/pipeline.py
index 7a345054177d..3574fbe42fa3 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/pipeline.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/pipeline.py
@@ -45,8 +45,10 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arr
_handle_null_columns_with_definitions,
evolve_pyarrow_schema,
merge_observed_columns_into_schema_metadata,
+ normalize_column_name,
normalize_table_column_names,
observe_and_project_table,
+ reconcile_batch_to_accumulated_schema,
source_uses_delta_write_column_selection,
)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.async_iterate import async_iterate
@@ -459,12 +461,17 @@ class PipelineV3(Generic[ResumableData]):
pa_table = evolve_pyarrow_schema(pa_table, None)
pa_table = _handle_null_columns_with_definitions(pa_table, self._resource)
- # Add missing columns from previous batches for schema consistency
- if self._accumulated_pa_schema is not None:
- for field in self._accumulated_pa_schema:
- if field.name not in pa_table.schema.names:
- null_column = pa.array([None] * pa_table.num_rows, type=field.type)
- pa_table = pa_table.append_column(field, null_column)
+ # Converge this batch onto the column types earlier batches in this run already used,
+ # and backfill columns they had that this one doesn't. The cursor column is named both
+ # raw and normalized because `normalize_table_column_names` above may have renamed it.
+ cursor_columns = (
+ {self._schema.incremental_field, normalize_column_name(self._schema.incremental_field)}
+ if self._schema.incremental_field
+ else set()
+ )
+ pa_table, self._accumulated_pa_schema = reconcile_batch_to_accumulated_schema(
+ pa_table, self._accumulated_pa_schema, self._logger, protected_columns=cursor_columns
+ )
batch_result = await asyncio.to_thread(self._s3_batch_writer.write_batch, pa_table, batch_index)
self._batch_results.append(batch_result)
@@ -475,14 +482,6 @@ class PipelineV3(Generic[ResumableData]):
await self._sinks.stage_chunk(batch_index, pa_table)
- # Update accumulated schema with any new columns from this batch
- if self._accumulated_pa_schema is None:
- self._accumulated_pa_schema = pa_table.schema
- else:
- for field in pa_table.schema:
- if field.name not in self._accumulated_pa_schema.names:
- self._accumulated_pa_schema = self._accumulated_pa_schema.append(field)
-
incremental_values = await update_incremental_field_values(
self._schema,
pa_table,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/s3/test_writer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/s3/test_writer.py
index a420c89f5d25..6783680408a4 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/s3/test_writer.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/s3/test_writer.py
@@ -106,3 +106,29 @@ class TestSchemaAccumulation:
schema = writer.get_schema()
assert schema is not None
assert schema.field("consumed_quantity").type == pa.float64()
+
+ @patch(
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.s3.writer._write_parquet_to_s3"
+ )
+ @patch("products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.s3.writer.ensure_bucket")
+ @patch("products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.s3.writer.get_s3_client")
+ def test_conflicting_column_types_across_batches_fall_back_to_text(
+ self, mock_get_s3_client, _mock_ensure_bucket, _mock_write
+ ) -> None:
+ # A vendor sending the same id as int in one page and string in the next used to abort
+ # the whole table's sync with ArrowTypeError when the batch schemas were folded together.
+ mock_get_s3_client.return_value.info.return_value = {"Size": 1}
+
+ job = MagicMock()
+ job.team_id = 1
+ job.created_at = datetime(2026, 8, 5, tzinfo=UTC)
+ job.workflow_run_id = "run-1"
+
+ writer = S3BatchWriter(MagicMock(), job, schema_id="schema-1", run_uuid="run-1")
+
+ writer.write_batch(pa.table({"owner_id": pa.array([1], type=pa.int64())}), 0)
+ writer.write_batch(pa.table({"owner_id": pa.array(["2"], type=pa.string())}), 1)
+
+ schema = writer.get_schema()
+ assert schema is not None
+ assert schema.field("owner_id").type == pa.string()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/s3/writer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/s3/writer.py
index 2f3cabb4ac8a..8db1cf45b341 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/s3/writer.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/s3/writer.py
@@ -12,6 +12,9 @@ from tenacity import retry, retry_if_exception, stop_after_attempt, wait_exponen
from products.data_warehouse.backend.facade.api import get_s3_client
from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrow_utils import (
+ unify_schemas_with_text_fallback,
+)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.metrics import (
get_s3_write_duration_metric,
get_s3_write_errors_metric,
@@ -144,8 +147,9 @@ class S3BatchWriter:
else:
# Batches infer their own types, so one run's column can land int64 in an early batch and
# double in a later one (whole vs fractional values). Permissive promotion widens to the
- # common type instead of raising ArrowTypeError; the default only unifies identical types.
- self._schema = pa.unify_schemas([self._schema, pa_table.schema], promote_options="permissive")
+ # common type; flips promotion can't reconcile (string vs int64) fall back to text
+ # instead of raising ArrowTypeError.
+ self._schema = unify_schemas_with_text_fallback([self._schema, pa_table.schema], self._logger)
self._logger.debug(
f"Batch {batch_index} written successfully",
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/row_transforms.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/row_transforms.py
deleted file mode 100644
index a2762bab2713..000000000000
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/row_transforms.py
+++ /dev/null
@@ -1,21 +0,0 @@
-"""Shared per-item row transforms usable as REST-source `data_map` callables.
-
-Sources supply their own `data_map` transforms, but some transforms recur across
-sources. Centralize those here so a source doesn't re-implement the same loop.
-"""
-
-from collections.abc import Iterable
-from typing import Any
-
-
-def coerce_fields_to_str(item: dict[str, Any], fields: Iterable[str]) -> dict[str, Any]:
- """Stringify the named fields in place, so a field whose JSON type varies across
- records (int in some, string in others) infers one stable type when the pipeline
- builds Arrow batches. `None` is left as-is to preserve nullability. Mutates and
- returns `item` so it can be used directly as a `data_map`.
- """
- for field in fields:
- value = item.get(field)
- if value is not None:
- item[field] = str(value)
- return item
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/test_row_transforms.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/test_row_transforms.py
deleted file mode 100644
index b0715ab253c9..000000000000
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/test_row_transforms.py
+++ /dev/null
@@ -1,25 +0,0 @@
-from typing import Any
-
-import pytest
-
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.row_transforms import coerce_fields_to_str
-
-
-class TestCoerceFieldsToStr:
- @pytest.mark.parametrize(
- "item,fields,expected",
- [
- # int -> str: the type flip that breaks Arrow batch merging.
- ({"owner_id": 42}, ["owner_id"], {"owner_id": "42"}),
- # An already-string value is unchanged.
- ({"owner_id": "42"}, ["owner_id"], {"owner_id": "42"}),
- # None is preserved so the column stays nullable.
- ({"owner_id": None}, ["owner_id"], {"owner_id": None}),
- # A missing field is a no-op.
- ({"name": "x"}, ["owner_id"], {"name": "x"}),
- # Only named fields are touched.
- ({"owner_id": 1, "count": 2}, ["owner_id"], {"owner_id": "1", "count": 2}),
- ],
- )
- def test_coerce_fields_to_str(self, item: dict[str, Any], fields: list[str], expected: dict[str, Any]):
- assert coerce_fields_to_str(item, fields) == expected
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/intercom/intercom.py b/products/warehouse_sources/backend/temporal/data_imports/sources/intercom/intercom.py
index 99b56d9b7a27..483ba7394b7a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/intercom/intercom.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/intercom/intercom.py
@@ -26,7 +26,6 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.res
Endpoint,
EndpointResource,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.row_transforms import coerce_fields_to_str
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.intercom.settings import (
INTERCOM_ENDPOINTS,
@@ -304,10 +303,6 @@ def get_resource(
"table_format": "delta",
}
- if cfg.coerce_string_fields:
- coerce_fields = cfg.coerce_string_fields
- resource["data_map"] = lambda item: coerce_fields_to_str(item, coerce_fields)
-
return resource
@@ -590,18 +585,10 @@ def _substream_items(
# walk every conversation. `updated_at` is the only declared
# cursor, so default to it for the parent search filter.
incremental_field = "updated_at"
- base = _conversation_parts_generator(session, incremental_field, db_incremental_field_last_value)
- elif endpoint == "company_segments":
- base = _company_segments_generator(session)
- else:
- raise ValueError(f"Unknown Intercom substream endpoint: {endpoint}")
-
- # Substreams bypass the REST framework's `data_map`, so coerce type-flip
- # fields here to keep every Arrow batch's schema consistent (see get_resource).
- coerce_fields = INTERCOM_ENDPOINTS[endpoint].coerce_string_fields
- if not coerce_fields:
- return base
- return (coerce_fields_to_str(item, coerce_fields) for item in base)
+ return _conversation_parts_generator(session, incremental_field, db_incremental_field_last_value)
+ if endpoint == "company_segments":
+ return _company_segments_generator(session)
+ raise ValueError(f"Unknown Intercom substream endpoint: {endpoint}")
def validate_credentials(
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/intercom/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/intercom/settings.py
index 128f6f8e0504..19332e21003d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/intercom/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/intercom/settings.py
@@ -1,6 +1,8 @@
-from dataclasses import dataclass, field
+from dataclasses import field
from typing import Literal
+from posthog.dataclasses import frozen
+
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import PartitionFormat
from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
@@ -10,7 +12,7 @@ HttpMethod = Literal["GET", "POST"]
SortMode = Literal["asc", "desc"]
-@dataclass
+@frozen
class IntercomEndpointConfig:
name: str
path: str
@@ -31,9 +33,6 @@ class IntercomEndpointConfig:
incremental_query_param: str | None = None
# Substream wiring — when set, this endpoint is fetched per-row of `parent_endpoint`.
parent_endpoint: str | None = None
- # Fields whose Intercom JSON type is inconsistent across records (int vs string);
- # coerced to string at the source so every Arrow batch infers one stable type.
- coerce_string_fields: list[str] = field(default_factory=list)
# Endpoint contracts validated against the live Intercom REST API (version 2.13).
@@ -102,19 +101,6 @@ INTERCOM_ENDPOINTS: dict[str, IntercomEndpointConfig] = {
paginator_kind="search",
method="POST",
partition_key="created_at",
- # owner_id flips int/string per row; the nullable epoch attributes flip the
- # same way (each observed failing prod syncs), so the whole family is pinned.
- coerce_string_fields=[
- "owner_id",
- "last_seen_at",
- "last_replied_at",
- "last_contacted_at",
- "last_email_opened_at",
- "last_email_clicked_at",
- "ios_last_seen_at",
- "android_last_seen_at",
- "signed_up_at",
- ],
),
"conversations": IntercomEndpointConfig(
name="conversations",
@@ -123,7 +109,6 @@ INTERCOM_ENDPOINTS: dict[str, IntercomEndpointConfig] = {
paginator_kind="search",
method="POST",
partition_key="created_at",
- coerce_string_fields=["admin_assignee_id", "team_assignee_id", "waiting_since", "snoozed_until"],
),
"tickets": IntercomEndpointConfig(
# `POST /tickets/search` mirrors contacts/conversations: it accepts
@@ -135,7 +120,6 @@ INTERCOM_ENDPOINTS: dict[str, IntercomEndpointConfig] = {
paginator_kind="search",
method="POST",
partition_key="created_at",
- coerce_string_fields=["admin_assignee_id", "team_assignee_id"],
),
"articles": IntercomEndpointConfig(
name="articles",
@@ -193,7 +177,6 @@ INTERCOM_ENDPOINTS: dict[str, IntercomEndpointConfig] = {
paginator_kind="substream",
parent_endpoint="conversations",
partition_key="created_at",
- coerce_string_fields=["waiting_since"],
),
"help_centers": IntercomEndpointConfig(
# `GET /help_center/help_centers` — one row per Help Center site. A workspace
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/intercom/tests/test_intercom.py b/products/warehouse_sources/backend/temporal/data_imports/sources/intercom/tests/test_intercom.py
index 915875f0c9e3..8b4e0aed625c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/intercom/tests/test_intercom.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/intercom/tests/test_intercom.py
@@ -362,90 +362,19 @@ class TestGetResource:
assert resource["table_format"] == "delta"
-class TestCoerceStringFields:
- def test_contacts_data_map_coerces_owner_id(self):
- # REST-path wiring: contacts declares owner_id in coerce_string_fields, so
- # get_resource must attach a data_map that stringifies it before rows hit Arrow.
- resource = get_resource(
- "contacts", should_use_incremental_field=False, incremental_field=None, db_incremental_field_last_value=None
- )
- data_map = resource.get("data_map")
- assert data_map is not None
- assert data_map({"owner_id": 7, "id": "c1"}) == {"owner_id": "7", "id": "c1"}
+class TestNoSourceLevelTypeCoercion:
+ # Type flips (Intercom returning a field as an int on some rows and a string on others)
+ # are stabilized generically when batches are built, not by naming fields per endpoint.
+ # These guard against a per-field allowlist creeping back in.
- @pytest.mark.parametrize(
- "field",
- [
- "last_seen_at",
- "last_replied_at",
- "last_contacted_at",
- "last_email_opened_at",
- "last_email_clicked_at",
- "ios_last_seen_at",
- "android_last_seen_at",
- "signed_up_at",
- ],
- )
- def test_contacts_data_map_coerces_epoch_attributes(self, field: str):
- # Intercom returns each nullable epoch attribute as an int on some rows and a
- # string on others, so every one must be pinned to string before rows hit Arrow.
- resource = get_resource(
- "contacts", should_use_incremental_field=False, incremental_field=None, db_incremental_field_last_value=None
- )
- data_map = resource.get("data_map")
- assert data_map is not None
- assert data_map({"id": "c1", field: 1700000000}) == {"id": "c1", field: "1700000000"}
- assert data_map({"id": "c2", field: None}) == {"id": "c2", field: None}
-
- @pytest.mark.parametrize("name", ["conversations", "tickets"])
- def test_assignee_ids_data_map_coerces_to_str(self, name: str):
- # REST-path wiring for both streams carrying flat assignee ids: Intercom returns
- # team_assignee_id as an int on some rows and a string on others, which produced
- # int64-vs-string parquet batches that pa.unify_schemas refused to merge. An
- # unassigned id stays None so the column remains nullable.
+ @pytest.mark.parametrize("name", NON_SUBSTREAM_ENDPOINTS)
+ def test_no_endpoint_declares_a_data_map(self, name: str):
resource = get_resource(
name, should_use_incremental_field=False, incremental_field=None, db_incremental_field_last_value=None
)
- data_map = resource.get("data_map")
- assert data_map is not None
- assert data_map({"id": "1", "admin_assignee_id": 12345, "team_assignee_id": 678}) == {
- "id": "1",
- "admin_assignee_id": "12345",
- "team_assignee_id": "678",
- }
- assert data_map({"id": "2", "admin_assignee_id": None, "team_assignee_id": "678"}) == {
- "id": "2",
- "admin_assignee_id": None,
- "team_assignee_id": "678",
- }
-
- @pytest.mark.parametrize("field", ["waiting_since", "snoozed_until"])
- def test_conversations_data_map_coerces_epoch_attributes(self, field: str):
- # The parent conversations stream carries its own top-level epoch attributes with
- # the same int-or-string flip as the conversation_parts substream. Coercing only
- # the substream left conversations syncs failing on int64-vs-string merges.
- resource = get_resource(
- "conversations",
- should_use_incremental_field=False,
- incremental_field=None,
- db_incremental_field_last_value=None,
- )
- data_map = resource.get("data_map")
- assert data_map is not None
- assert data_map({"id": "1", field: 1700000000}) == {"id": "1", field: "1700000000"}
- assert data_map({"id": "2", field: None}) == {"id": "2", field: None}
-
- def test_endpoint_without_coerce_fields_has_no_data_map(self):
- # Only endpoints declaring coerce_string_fields get a data_map — others stay untouched.
- resource = get_resource(
- "admins", should_use_incremental_field=False, incremental_field=None, db_incremental_field_last_value=None
- )
assert "data_map" not in resource
- def test_conversation_parts_substream_coerces_waiting_since(self):
- # Substream-path wiring: conversation_parts bypasses the framework's data_map,
- # so _substream_items must coerce waiting_since itself. Mixed int/str/None across
- # parts previously produced int64-vs-string Arrow batches that failed to merge.
+ def test_substream_rows_pass_through_untouched(self):
mock_session = mock.MagicMock()
mock_session.post.side_effect = [
_make_response({"conversations": [{"id": "c1"}], "pages": {}}),
@@ -466,22 +395,7 @@ class TestCoerceStringFields:
parts = list(_substream_items(mock_session, "conversation_parts", "updated_at", None))
- assert [p["waiting_since"] for p in parts] == ["1700000000", "1700000001", None]
-
- def test_substream_without_coerce_fields_passes_rows_through_untouched(self):
- # company_segments declares no coerce_string_fields, so _substream_items must
- # return its rows unchanged — a numeric field stays an int, not stringified.
- # Guards the refactor against coercing endpoints that opted out.
- mock_session = mock.MagicMock()
- mock_session.get.side_effect = [
- _make_response({"data": [{"id": "co1"}], "scroll_param": "s1"}),
- _make_response({"data": []}),
- _make_response({"data": [{"id": "seg1", "count": 5}]}),
- ]
-
- segments = list(_substream_items(mock_session, "company_segments", None, None))
-
- assert segments == [{"id": "seg1", "count": 5, "company_id": "co1"}]
+ assert [p["waiting_since"] for p in parts] == [1700000000, "1700000001", None]
def test_unknown_substream_endpoint_raises(self):
# Adding a substream endpoint config without wiring it into _substream_items