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): coalesce Arrow tables in the batcher so chunk caps apply (#80690)

estefaniae20c91c3a086
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/batcher.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/batcher.py
index 30b9f207b723..a33b18f31762 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/batcher.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/batcher.py
@@ -64,6 +64,11 @@ def _split_table(table: pa.Table, *, offset_limit: int, bytes_limit: int) -> lis
class Batcher:
_buffer: list[Any]
_buffer_size_bytes: int
+ _table_buffer: list[pa.Table]
+ _table_buffer_rows: int
+ _table_buffer_bytes: int
+ _table_buffer_schema: Optional[pa.Schema]
+ _coalesce_tables: bool
_ready: deque[pa.Table]
_logger: FilteringBoundLogger
_chunk_size: int
@@ -84,6 +89,7 @@ class Batcher:
source_type: Optional[str] = None,
team_id: Optional[int] = None,
schema_name: Optional[str] = None,
+ coalesce_tables: bool = False,
) -> None:
self._logger = logger
@@ -97,9 +103,19 @@ class Batcher:
self._source_type = source_type
self._team_id = team_id
self._schema_name = schema_name
+ # Off by default because coalescing delays when a yielded table becomes a durable batch:
+ # sources that checkpoint resume state or delete upstream staging right after yielding
+ # (ResumableSource implementations, the webhook S3 path) rely on yield => persisted and
+ # would lose data across a crash if their tables sat in this buffer. Only enable for
+ # sources with no such dependency.
+ self._coalesce_tables = coalesce_tables
self._buffer = []
self._buffer_size_bytes = 0
+ self._table_buffer = []
+ self._table_buffer_rows = 0
+ self._table_buffer_bytes = 0
+ self._table_buffer_schema = None
self._ready = deque()
def _set_ready(self, table: pa.Table) -> None:
@@ -117,7 +133,9 @@ class Batcher:
report_buffer_bytes(payload_bytes)
if self._source_type is not None:
# The materialised table is the true in-memory peak (an unbounded source yields one giant
- # list -> one giant table here, before the split into bounded chunks).
+ # list -> one giant table here, before the split into bounded chunks). With table
+ # coalescing this is the whole coalesced batch, not one source yield; the buffered input
+ # tables it was concatenated from share its buffers, so it still measures the real peak.
record_table_stats(
source_type=self._source_type,
stage="batcher",
@@ -137,6 +155,89 @@ class Batcher:
)
self._ready = deque(chunks)
+ def _batch_table(self, table: pa.Table) -> None:
+ """Buffer `table` and flush the accumulated buffer once `_chunk_size` / `_chunk_size_bytes`
+ is reached, so a source's per-yield fetch size doesn't dictate batch granularity (a driver
+ fetching 10k rows per Arrow table would otherwise emit one queue batch per fetch).
+
+ Bytes are counted as each table arrives, and a table that would push the buffer past
+ `_chunk_size_bytes` flushes the buffer *before* joining it, so buffered payload never
+ exceeds the byte cap unless a single table does on its own. With the default caps
+ (200 MiB chunk vs 256 MiB max table) the flushed batch stays under `_max_table_bytes`,
+ so `_split_table` doesn't undo the coalescing, and accumulation memory stays bounded on
+ pods where memory is the constraint.
+ """
+ table_bytes = table_payload_bytes(table)
+
+ if not self._table_buffer:
+ self._start_table_buffer(table, table_bytes)
+ self._flush_table_buffer_if_full()
+ return
+
+ unified_schema = self._unify_schema_or_none(table.schema)
+ would_overflow = (
+ self._table_buffer_rows + table.num_rows > self._chunk_size
+ or self._table_buffer_bytes + table_bytes > self._chunk_size_bytes
+ )
+ if unified_schema is None or would_overflow:
+ if unified_schema is None:
+ self._logger.info(
+ "batcher_flush_on_schema_drift",
+ buffered_rows=self._table_buffer_rows,
+ incoming_rows=table.num_rows,
+ )
+ # `_set_ready` replaces `_ready` wholesale, so only one flush can happen per
+ # `batch()` call; the incoming table waits in a fresh buffer until the next
+ # call (or `get_table` at end of stream) flushes it.
+ self._flush_table_buffer()
+ self._start_table_buffer(table, table_bytes)
+ return
+
+ self._table_buffer.append(table)
+ self._table_buffer_rows += table.num_rows
+ self._table_buffer_bytes += table_bytes
+ self._table_buffer_schema = unified_schema
+ self._flush_table_buffer_if_full()
+
+ def _unify_schema_or_none(self, schema: pa.Schema) -> Optional[pa.Schema]:
+ """Permissively unify `schema` with the buffered schema, or None if they can't be merged.
+
+ Permissive promotion (nullability, new columns, numeric widening) matches how
+ `S3BatchWriter.write_batch` already unifies schemas across batches, so coalescing doesn't
+ reject drift the writer would have accepted. Non-promotable drift (e.g. int64 vs string)
+ returns None and the caller flushes, yielding the same per-table failure surface the
+ writer had.
+ """
+ assert self._table_buffer_schema is not None
+ try:
+ return pa.unify_schemas([self._table_buffer_schema, schema], promote_options="permissive")
+ except (pa.ArrowInvalid, pa.ArrowTypeError):
+ return None
+
+ def _start_table_buffer(self, table: pa.Table, table_bytes: int) -> None:
+ self._table_buffer = [table]
+ self._table_buffer_rows = table.num_rows
+ self._table_buffer_bytes = table_bytes
+ self._table_buffer_schema = table.schema
+
+ def _flush_table_buffer_if_full(self) -> None:
+ if self._table_buffer_rows >= self._chunk_size or self._table_buffer_bytes >= self._chunk_size_bytes:
+ self._flush_table_buffer()
+
+ def _flush_table_buffer(self) -> None:
+ if len(self._table_buffer) == 1:
+ table = self._table_buffer[0]
+ else:
+ # Zero-copy for matching schemas (the output table references the buffered chunks);
+ # only columns needing promotion are cast, so the flush doesn't double peak memory
+ # in the common no-drift case.
+ table = pa.concat_tables(self._table_buffer, promote_options="permissive")
+ self._table_buffer = []
+ self._table_buffer_rows = 0
+ self._table_buffer_bytes = 0
+ self._table_buffer_schema = None
+ self._set_ready(table)
+
def _estimate_size(self, obj: Any) -> int:
if isinstance(obj, dict):
return sys.getsizeof(obj) + sum(self._estimate_size(k) + self._estimate_size(v) for k, v in obj.items())
@@ -149,6 +250,11 @@ class Batcher:
if self._ready:
raise Exception("Batcher already has a table ready to yield. Call get_table() before batching more items.")
+ # Mirror of the pa.Table guard below: buffered tables and buffered rows can't be merged
+ # into one batch, so mixing them would silently reorder or drop data on flush.
+ if self._table_buffer and not isinstance(item, pa.Table):
+ raise Exception("Cannot batch list/dict rows while pa.Tables are buffered; call get_table() first")
+
if isinstance(item, list):
if len(self._buffer) > 0:
self._buffer.extend(item)
@@ -176,12 +282,15 @@ class Batcher:
self._logger.debug(f"Processing buffer (dict). Length of buffer = {len(self._buffer)}")
self._set_ready(table_from_py_list(self._buffer))
elif isinstance(item, pa.Table):
- # A pa.Table is self-contained and bypasses the buffer. Clearing the buffer
+ # A pa.Table never joins the list/dict buffer. Clearing the buffer
# below would silently drop any rows accumulated from earlier list/dict
# items, so treat a non-empty buffer here as a programming error rather than
# losing data. (In practice sources emit only one item type, never a mix.)
if self._buffer:
raise Exception("Cannot batch a pa.Table while list/dict rows are buffered; call get_table() first")
+ if self._coalesce_tables:
+ self._batch_table(item)
+ return
self._set_ready(item)
else:
raise Exception(f"Unhandled item type: {item.__class__.__name__}")
@@ -194,7 +303,7 @@ class Batcher:
def should_yield(self, include_incomplete_chunk: bool = False) -> bool:
if include_incomplete_chunk:
- return len(self._ready) > 0 or len(self._buffer) > 0
+ return len(self._ready) > 0 or len(self._buffer) > 0 or len(self._table_buffer) > 0
return len(self._ready) > 0
@@ -205,6 +314,12 @@ class Batcher:
self._buffer = []
self._buffer_size_bytes = 0
+ # End-of-stream flush of a partial Arrow buffer, matching the list/dict path above;
+ # dropping it would lose every row batched since the last full chunk.
+ if not self._ready and len(self._table_buffer) > 0:
+ self._logger.debug(f"Processing leftover table buffer. Buffered tables = {len(self._table_buffer)}")
+ self._flush_table_buffer()
+
if self._ready:
return self._ready.popleft()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_batcher.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_batcher.py
index 94fbc54211a2..8d184e77f932 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_batcher.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_batcher.py
@@ -316,6 +316,122 @@ def test_batcher_does_not_split_small_table_under_byte_cap():
assert drained[0].equals(table)
+def test_coalescing_pa_tables_accumulates_to_row_cap():
+ batcher = Batcher(logger=mock.MagicMock(), chunk_size=10, coalesce_tables=True)
+
+ tables = [pa.table({"id": [i * 2, i * 2 + 1]}) for i in range(6)]
+ yielded = []
+ for table in tables:
+ batcher.batch(table)
+ while batcher.should_yield():
+ yielded.append(batcher.get_table())
+
+ # 5 x 2-row tables buffer silently; the 5th reaches the 10-row cap and flushes as one batch.
+ assert len(yielded) == 1
+ assert yielded[0].num_rows == 10
+ while batcher.should_yield(include_incomplete_chunk=True):
+ yielded.append(batcher.get_table())
+ combined = pa.concat_tables(yielded)
+ assert combined.column("id").to_pylist() == list(range(12))
+
+
+def test_coalescing_disabled_by_default_keeps_one_yield_one_batch():
+ batcher = Batcher(logger=mock.MagicMock(), chunk_size=1_000)
+ table = pa.table({"id": [1, 2]})
+
+ batcher.batch(table)
+
+ assert batcher.should_yield() is True
+ assert batcher.get_table().equals(table)
+
+
+def test_coalescing_flushes_buffer_before_byte_cap_is_exceeded():
+ table = pa.table({"id": [1, 2], "val": ["aa", "bb"]})
+ per_table = table_payload_bytes(table)
+ # Cap fits 2 tables but not 3, so the 3rd must flush the buffer *without* joining it.
+ cap = per_table * 2 + per_table // 2
+ batcher = Batcher(logger=mock.MagicMock(), chunk_size_bytes=cap, coalesce_tables=True)
+
+ batcher.batch(table)
+ batcher.batch(table)
+ assert batcher.should_yield() is False
+
+ # The flushed batch stays within chunk_size_bytes (which keeps it under max_table_bytes,
+ # so _split_table doesn't undo the coalescing) and the 3rd table starts the next buffer.
+ batcher.batch(table)
+ assert batcher.should_yield() is True
+ flushed = batcher.get_table()
+ assert flushed.num_rows == 4
+ assert table_payload_bytes(flushed) <= cap
+
+ assert batcher.should_yield(include_incomplete_chunk=True) is True
+ assert batcher.get_table().equals(table)
+
+
+def test_coalescing_oversized_single_table_flushes_alone_without_waiting():
+ table = pa.table({"id": [1, 2], "val": ["aa", "bb"]})
+ batcher = Batcher(logger=mock.MagicMock(), chunk_size_bytes=1, coalesce_tables=True)
+
+ batcher.batch(table)
+
+ assert batcher.should_yield() is True
+ assert batcher.get_table().equals(table)
+
+
+def test_coalescing_promotes_compatible_schema_drift():
+ batcher = Batcher(logger=mock.MagicMock(), chunk_size=4, coalesce_tables=True)
+
+ batcher.batch(pa.table({"a": pa.array([1, 2], pa.int64()), "b": ["x", "y"]}))
+ batcher.batch(pa.table({"a": pa.array([1.5, 2.5], pa.float64())}))
+
+ assert batcher.should_yield() is True
+ flushed = batcher.get_table()
+ assert flushed.num_rows == 4
+ assert flushed.schema.field("a").type == pa.float64()
+ assert flushed.column("b").to_pylist() == ["x", "y", None, None]
+
+
+def test_coalescing_flushes_on_non_promotable_schema_drift():
+ batcher = Batcher(logger=mock.MagicMock(), chunk_size=1_000, coalesce_tables=True)
+ int_table = pa.table({"a": pa.array([1, 2], pa.int64())})
+ str_table = pa.table({"a": pa.array(["x", "y"], pa.string())})
+
+ batcher.batch(int_table)
+ assert batcher.should_yield() is False
+
+ # int64 -> string can't be promoted, so the buffered table flushes as-is and the
+ # incompatible one starts a new buffer instead of crashing pa.concat_tables.
+ batcher.batch(str_table)
+ assert batcher.should_yield() is True
+ assert batcher.get_table().equals(int_table)
+
+ assert batcher.should_yield(include_incomplete_chunk=True) is True
+ assert batcher.get_table().equals(str_table)
+
+
+def test_coalescing_partial_buffer_flushes_at_end_of_stream():
+ batcher = Batcher(logger=mock.MagicMock(), chunk_size=1_000, coalesce_tables=True)
+
+ batcher.batch(pa.table({"id": [1, 2]}))
+ batcher.batch(pa.table({"id": [3]}))
+
+ # Below the caps nothing is ready, but the end-of-stream drain must still see and
+ # flush the buffered tables; dropping them would silently lose the sync's tail.
+ assert batcher.should_yield() is False
+ assert batcher.should_yield(include_incomplete_chunk=True) is True
+ assert batcher.get_table().column("id").to_pylist() == [1, 2, 3]
+ assert batcher.should_yield(include_incomplete_chunk=True) is False
+
+
+def test_batching_list_while_tables_buffered_raises():
+ batcher = Batcher(logger=mock.MagicMock(), chunk_size=1_000, coalesce_tables=True)
+
+ batcher.batch(pa.table({"id": [1]}))
+
+ with pytest.raises(Exception, match="Cannot batch list/dict rows while pa.Tables are buffered"):
+ batcher.batch([{"id": 2}])
+
+
def test_batching_should_not_yield_when_buffer_not_full():
batcher = Batcher(logger=mock.MagicMock(), chunk_size=5, chunk_size_bytes=1000)
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 06bbd2a1f377..1d5d714c4473 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
@@ -212,6 +212,11 @@ class PipelineV3(Generic[ResumableData]):
self._resumable_source_manager = resumable_source_manager
# A source can shrink the batcher chunk (e.g. document sources with large rows) so the
# source->Arrow conversion doesn't materialise an oversized table; None falls back to defaults.
+ # Arrow coalescing keeps a driver's fetch size (e.g. a SQL cursor's 10k-row Arrow tables)
+ # from becoming the queue's batch granularity, but it delays when a yielded table is
+ # persisted, so it must stay off for sources that treat yield as durable: resumable
+ # sources checkpoint resume state right after yielding, and the webhook path deletes its
+ # staged S3 files right after yielding.
self._batcher = Batcher(
self._logger,
chunk_size=source_response.chunk_size,
@@ -219,6 +224,7 @@ class PipelineV3(Generic[ResumableData]):
source_type=self._source.source_type if self._source else None,
team_id=self._job.team_id,
schema_name=self._schema.name,
+ coalesce_tables=resumable_source_manager is None and not self._schema.is_webhook,
)
self._internal_schema = HogQLSchema()
self._sinks = build_pipeline_sinks(
diff --git a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_end_to_end.py b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_end_to_end.py
index 384e815f8bc3..0a765c9f9abc 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_end_to_end.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_end_to_end.py
@@ -1722,6 +1722,11 @@ async def test_delta_no_merging_on_first_sync(team, postgres_config, postgres_co
mock.patch(
"products.warehouse_sources.backend.temporal.data_imports.sources.postgres.postgres._get_table_chunk_size"
) as mock_chunk_size,
+ # The pipeline batcher coalesces the source's 1-row Arrow tables back into one batch
+ # unless its own row cap is pinned to 1; this test needs two batches to reach the loader.
+ mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.core.batcher.DEFAULT_CHUNK_SIZE", 1
+ ),
mock.patch.object(DeltaTable, "merge") as mock_merge,
mock.patch.object(deltalake, "write_deltalake") as mock_write,
mock.patch.object(PipelineNonDLT, "_post_run_operations") as mock_post_run_operations,
@@ -1915,6 +1920,11 @@ async def test_delta_no_merging_on_first_sync_after_reset(team, postgres_config,
mock.patch(
"products.warehouse_sources.backend.temporal.data_imports.sources.postgres.postgres._get_table_chunk_size"
) as mock_chunk_size,
+ # The pipeline batcher coalesces the source's 1-row Arrow tables back into one batch
+ # unless its own row cap is pinned to 1; this test needs two batches to reach the loader.
+ mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.core.batcher.DEFAULT_CHUNK_SIZE", 1
+ ),
mock.patch.object(DeltaTable, "merge") as mock_merge,
mock.patch.object(deltalake, "write_deltalake") as mock_write,
mock.patch.object(PipelineNonDLT, "_post_run_operations") as mock_post_run_operations,