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-warehouse): serialize dict columns before arrow conversion to avoid quadratic batching (#70478)

Tom Owers9100d2e02020
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.py
index 7061dfdaa24d..60aa82014fa2 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
@@ -7,6 +7,7 @@ from typing import Any, cast
import pytest
from unittest.mock import AsyncMock, MagicMock, patch
+import orjson
import pyarrow as pa
import deltalake
import structlog
@@ -131,6 +132,40 @@ def test_table_from_py_list_inconsistent_types_with_str_and_dict():
)
+# A source may declare a non-string type for a column that arrives as dicts; the serialized
+# column must coerce the schema field to string or from_pydict fails.
+_STRING_DATA_FIELDS: list[pa.Field] = [pa.field("id", pa.int64()), pa.field("data", pa.string())]
+_STRUCT_DATA_FIELDS: list[pa.Field] = [
+ pa.field("id", pa.int64()),
+ pa.field("data", pa.struct([pa.field("a", pa.int64())])),
+]
+
+
+ "schema",
+ [
+ None,
+ pa.schema(_STRING_DATA_FIELDS),
+ pa.schema(_STRUCT_DATA_FIELDS),
+ ],
+)
+def test_table_from_py_list_dict_column_preserves_original_documents(schema):
+ # Heterogeneous nested documents (each row's structure differs, as in a MongoDB collection).
+ # Routing these through a unified pyarrow struct made conversion superlinear in batch size
+ # and injected null-filled union fields from other rows into every serialized document.
+ docs = [
+ {"a": 1, "nested": {"x": [{"k": 1, "verbs": ["led"]}]}},
+ {"b": "two", "nested": {"y": {"deep": True}}, "extra": [1, 2]},
+ None,
+ {"c": [{"only": "here"}]},
+ ]
+ table = table_from_py_list([{"id": i, "data": doc} for i, doc in enumerate(docs)], schema)
+
+ assert table.schema.field("data").type == pa.string()
+ stored = [None if v is None else orjson.loads(v) for v in table.column("data").to_pylist()]
+ assert stored == docs
+
+
@pytest.mark.parametrize(
"rows,expected",
[
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.py
index 94a59bfa3c0f..83c0b1364503 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
@@ -862,7 +862,54 @@ def _to_list_array(column_data: pa.Array | pa.ChunkedArray | np.ndarray[Any, np.
return column_data.tolist()
+def _serialize_dict_columns(table_data: list[dict]) -> tuple[list[dict], set[str]]:
+ """JSON-serialize columns whose non-None values are all dicts, before any Arrow work.
+
+ Such a column ends up stored as a JSON string either way, but letting it reach `pa.array()`
+ first builds a unified struct type whose field count is the union of every row's key paths.
+ For heterogeneous nested documents (e.g. a MongoDB collection where each document's structure
+ varies) that union grows with the batch, making conversion superlinear in rows — batches of a
+ few hundred documents can take minutes and starve activity heartbeats. The struct round-trip
+ also injects the union's null-filled fields into every serialized row, bloating the stored
+ JSON with keys the original document never had. Serializing the source dicts up front keeps
+ conversion linear and preserves each document exactly.
+
+ The caller's rows are left untouched — rows needing serialization are shallow-copied — so
+ reusing or retrying with the same batch stays safe. Returns the (possibly new) row list and
+ the serialized column names so a provided schema can be coerced to string for them.
+ """
+ dict_columns: set[str] = set()
+ non_dict_columns: set[str] = set()
+ for row in table_data:
+ for key, value in row.items():
+ if value is None or key in non_dict_columns:
+ continue
+ if isinstance(value, dict):
+ dict_columns.add(key)
+ else:
+ non_dict_columns.add(key)
+ dict_columns.discard(key)
+
+ if not dict_columns:
+ return table_data, dict_columns
+
+ serialized_rows: list[dict] = []
+ for row in table_data:
+ replaced: Optional[dict] = None
+ for key in dict_columns:
+ value = row.get(key)
+ if value is not None:
+ if replaced is None:
+ replaced = dict(row)
+ replaced[key] = _json_dumps(value)
+ serialized_rows.append(replaced if replaced is not None else row)
+
+ return serialized_rows, dict_columns
+
+
def _process_batch(table_data: list[dict], schema: Optional[pa.Schema] = None) -> pa.Table:
+ table_data, serialized_dict_columns = _serialize_dict_columns(table_data)
+
# Support both given schemas and inferred schemas
if schema is None or len(schema.names) == 0:
try:
@@ -919,6 +966,16 @@ def _process_batch(table_data: list[dict], schema: Optional[pa.Schema] = None) -
field = arrow_schema.field_by_name(str(field_name))
field_index = arrow_schema.get_field_index(str(field_name))
+ # A serialized dict column holds JSON strings now; a provided schema may still declare
+ # the source's original non-string type for it, which from_pydict would fail to cast.
+ if (
+ field_name in serialized_dict_columns
+ and not pa.types.is_string(field.type)
+ and not pa.types.is_large_string(field.type)
+ ):
+ arrow_schema = arrow_schema.set(field_index, field.with_type(pa.string()))
+ field = arrow_schema.field_by_name(str(field_name))
+
# cast double / float ndarrays to decimals if type mismatch, looks like decimals and floats are often mixed up in dialects
if pa.types.is_decimal(field.type) and (float in unique_types_in_column or str in unique_types_in_column):
float_array = pa.array(columnar_table_data[field_name], type=pa.float64())