: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): bound the batcher by cells, not just rows and bytes (#106800)
Tom Owers72005a21e363
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.pyindex dbb2a12916ec..6291c33eb414 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@@ -1,5 +1,6 @@import sysfrom collections import deque+from collections.abc import Iterable, Mappingfrom typing import Any, Optionalimport pyarrow as pa@@ -28,6 +29,13 @@ DEFAULT_MAX_COLUMN_OFFSET_BYTES: int = 1_500_000_000 # ~1.4 GiB, safely under t# table from a few thousand rows, which becomes the loader's per-batch merge memory and OOMs the pod.DEFAULT_MAX_TABLE_BYTES: int = 256 * 1024 * 1024 # 256 MiB of Arrow payload+# Cap rows x distinct keys in the row buffer. `table_from_py_list` unions every key in the batch+# into columns, so its cost follows cells rather than rows. When a source carries sparse top-level+# keys, keys grow with rows and that cost turns quadratic, while the row and byte caps see nothing+# because the rows themselves stay small. A 20-column source already reaches 10M cells at+# DEFAULT_CHUNK_SIZE, so an ordinary batch keeps flushing exactly where it did.+DEFAULT_MAX_BUFFER_CELLS: int = 10_000_000+def _column_offset_pressure(col: pa.ChunkedArray) -> int:"""32-bit-offset pressure: value bytes (string/binary) or child element count (list); 0 otherwise.@@ -68,6 +76,7 @@ def _split_table(table: pa.Table, *, offset_limit: int, bytes_limit: int) -> lisclass Batcher:_buffer: list[Any]_buffer_size_bytes: int+ _buffer_keys: set[str]_table_buffer: list[pa.Table]_table_buffer_rows: int_table_buffer_bytes: int@@ -80,6 +89,7 @@ class Batcher:_chunk_size_bytes: int_max_column_offset_bytes: int_max_table_bytes: int+ _max_buffer_cells: int_source_type: Optional[str]_team_id: Optional[int]_schema_name: Optional[str]@@ -98,6 +108,7 @@ class Batcher:schema_name: Optional[str] = None,coalesce_tables: bool = False,primary_keys: Optional[list[str]] = None,+ max_buffer_cells: Optional[int] = None,) -> None:self._logger = loggerself._primary_keys = primary_keys@@ -107,6 +118,7 @@ class Batcher:self._chunk_size_bytes = chunk_size_bytes or DEFAULT_CHUNK_SIZE_BYTESself._max_column_offset_bytes = max_column_offset_bytes or DEFAULT_MAX_COLUMN_OFFSET_BYTESself._max_table_bytes = max_table_bytes or DEFAULT_MAX_TABLE_BYTES+ self._max_buffer_cells = max_buffer_cells or DEFAULT_MAX_BUFFER_CELLS# When set, each materialised table is measured under `stage="batcher"`. Left None by# source-internal batchers (e.g. apify), whose output is measured when it reaches the# pipeline's own batcher — so this only records once, with the real source_type.@@ -121,6 +133,7 @@ class Batcher:self._buffer = []self._buffer_size_bytes = 0+ self._buffer_keys: set[str] = set()self._table_buffer = []self._table_buffer_rows = 0self._table_buffer_bytes = 0@@ -253,6 +266,35 @@ class Batcher:self._table_buffer_schema = Noneself._set_ready(table)+ def _track_buffer_keys(self, rows: Iterable[Any]) -> None:+ """Accumulate the distinct keys the buffered rows carry, which is the batch's column count."""+ for row in rows:+ if isinstance(row, Mapping):+ self._buffer_keys.update(row.keys())++ def _buffer_is_full(self, row_count: int) -> bool:+ if row_count >= self._chunk_size or self._buffer_size_bytes >= self._chunk_size_bytes:+ return True++ if row_count * len(self._buffer_keys) < self._max_buffer_cells:+ return False++ # Nothing else in the run identifies a source whose key set grows with its rows, and the+ # durable fix belongs in that source's row shape.+ self._logger.info(+ "batcher_flush_on_cell_cap",+ row_count=row_count,+ column_count=len(self._buffer_keys),+ cell_cap=self._max_buffer_cells,+ buffer_bytes=self._buffer_size_bytes,+ )+ return True++ def _reset_buffer(self) -> None:+ self._buffer = []+ self._buffer_size_bytes = 0+ self._buffer_keys = set()+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())@@ -284,7 +326,8 @@ class Batcher:if len(self._buffer) > 0:self._buffer.extend(item)self._buffer_size_bytes += self._estimate_size(item)- if self._buffer_size_bytes >= self._chunk_size_bytes or len(self._buffer) >= self._chunk_size:+ self._track_buffer_keys(item)+ if self._buffer_is_full(len(self._buffer)):self._logger.debug(f"Processing buffer (list). Length of buffer = {len(self._buffer)}")self._set_ready(self._rows_to_table(self._buffer))@@ -292,7 +335,8 @@ class Batcher:returnelse:self._buffer_size_bytes += self._estimate_size(item)- if self._buffer_size_bytes >= self._chunk_size_bytes or len(item) >= self._chunk_size:+ self._track_buffer_keys(item)+ if self._buffer_is_full(len(item)):self._logger.debug(f"Processing item (list). Length of item = {len(item)}")self._set_ready(self._rows_to_table(item))else:@@ -301,7 +345,8 @@ class Batcher:elif isinstance(item, dict):self._buffer.append(item)self._buffer_size_bytes += self._estimate_size(item)- if self._buffer_size_bytes < self._chunk_size_bytes and len(self._buffer) < self._chunk_size:+ self._track_buffer_keys((item,))+ if not self._buffer_is_full(len(self._buffer)):returnself._logger.debug(f"Processing buffer (dict). Length of buffer = {len(self._buffer)}")@@ -326,8 +371,7 @@ class Batcher:# The list/dict branches above materialized the buffer into `_ready`, and the# pa.Table branch is guaranteed empty by the guard — so the buffer is now spent.# Reset it (and its byte counter) so the next batching cycle starts fresh.- self._buffer = []- self._buffer_size_bytes = 0+ self._reset_buffer()def should_yield(self, include_incomplete_chunk: bool = False) -> bool:if include_incomplete_chunk:@@ -339,8 +383,7 @@ class Batcher:if not self._ready and len(self._buffer) > 0:self._logger.debug(f"Processing leftover buffer. Length of buffer = {len(self._buffer)}")self._set_ready(self._rows_to_table(self._buffer))- self._buffer = []- self._buffer_size_bytes = 0+ self._reset_buffer()# 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.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.pyindex 598820bbb18c..c45099cf59ad 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@@ -505,3 +505,87 @@ def test_batching_pa_table_converts_primary_key_binary_column_to_hex():assert result_table.column("sk_load").to_pylist() == ["bdd640", None]assert result_table.schema.field("sk_load").type == pa.string()assert result_table.column("payload").to_pylist() == [b"\x01", b"\x02"]+++def _sparse_key_rows(count: int, start: int = 0) -> list[dict]:+ """Rows shaped like a source that merges per-row custom properties into the row itself."""+ return [{"id": str(i), f"trait_{i}": "x"} for i in range(start, start + count)]+++def _feed_until_yield(batcher: Batcher, rows: list[dict]) -> int:+ """Batch rows one at a time, stopping at the first yield. Returns how many were taken."""+ for taken, row in enumerate(rows, start=1):+ batcher.batch(row)+ if batcher.should_yield():+ return taken+ return len(rows)+++def _sparse_key_batcher(logger: object, max_buffer_cells: int = 400) -> Batcher:+ """Row and byte caps held far out of reach, so only the cell cap can fire."""+ return Batcher(+ logger=logger, # type: ignore[arg-type]+ chunk_size=100_000,+ chunk_size_bytes=2**40,+ max_buffer_cells=max_buffer_cells,+ )+++def test_batcher_flushes_sparse_key_rows_before_the_row_and_byte_caps():+ batcher = _sparse_key_batcher(mock.MagicMock())++ # 20 rows carry 21 keys, the first point at which the product crosses 400.+ assert _feed_until_yield(batcher, _sparse_key_rows(40)) == 20+ assert batcher.get_table().num_rows == 20+++def test_batcher_keeps_dense_rows_on_the_row_cap():+ # The cell cap must not shrink an ordinary batch, whose key set does not grow with its rows.+ batcher = Batcher(logger=mock.MagicMock(), chunk_size=50, chunk_size_bytes=2**40, max_buffer_cells=400)++ for i in range(49):+ batcher.batch({"id": str(i), "name": "n"})++ assert batcher.should_yield() is False++ batcher.batch({"id": "49", "name": "n"})++ assert batcher.should_yield() is True+ assert batcher.get_table().num_rows == 50+++def test_batcher_cell_cap_resets_between_batches():+ # The key set is per-buffer. Carrying it across flushes would trip the cap on every later row.+ batcher = _sparse_key_batcher(mock.MagicMock())++ _feed_until_yield(batcher, _sparse_key_rows(40))+ assert batcher.get_table().num_rows == 20++ assert _feed_until_yield(batcher, _sparse_key_rows(40, start=100)) == 20+ assert batcher.get_table().num_rows == 20+++def test_batcher_logs_the_shape_when_the_cell_cap_flushes():+ # The log is the only signal that names which source has the quadratic row shape.+ logger = mock.MagicMock()+ batcher = _sparse_key_batcher(logger)++ _feed_until_yield(batcher, _sparse_key_rows(40))++ logger.info.assert_called_once()+ assert logger.info.call_args.args[0] == "batcher_flush_on_cell_cap"+ assert logger.info.call_args.kwargs["row_count"] == 20+ assert logger.info.call_args.kwargs["column_count"] == 21+++def test_batcher_cell_cap_applies_to_list_items():+ # A source that yields pages, not single rows, reaches the cap through the list branch.+ batcher = _sparse_key_batcher(mock.MagicMock())++ batcher.batch(_sparse_key_rows(10))+ assert batcher.should_yield() is False++ batcher.batch(_sparse_key_rows(10, start=10))++ assert batcher.should_yield() is True+ assert batcher.get_table().num_rows == 20