: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): split oversized batches to avoid delta offset overflow (#60698)
Tom Owers906e0971290f
diff --git a/posthog/temporal/data_imports/pipelines/pipeline/batcher.py b/posthog/temporal/data_imports/pipelines/pipeline/batcher.pyindex 1813fc55878a..977d7ea1ecd2 100644--- a/posthog/temporal/data_imports/pipelines/pipeline/batcher.py+++ b/posthog/temporal/data_imports/pipelines/pipeline/batcher.py@@ -1,7 +1,9 @@import sys+from collections import dequefrom typing import Any, Optionalimport pyarrow as pa+import pyarrow.compute as pcfrom structlog.types import FilteringBoundLoggerfrom posthog.temporal.data_imports.pipelines.pipeline.utils import table_from_py_list@@ -9,26 +11,85 @@ from posthog.temporal.data_imports.pipelines.pipeline.utils import table_from_pyDEFAULT_CHUNK_SIZE_BYTES: int = 200 * 1024 * 1024 # 200 MiBDEFAULT_CHUNK_SIZE: int = 5000+# pyarrow `string`/`binary`/`list` columns use 32-bit offsets, so a single column in+# one batch overflows once its offsets cross 2^31 (~2.1e9). delta-rs concatenates a+# merge source's chunks into one contiguous array, which is where this surfaces in+# prod as "Offset overflow error: <bytes>". Casting the source to large_string does+# NOT help — delta-rs coerces back to the target's 32-bit `string` during the merge —+# so the only reliable fix is to keep each yielded table's worst column under the+# limit, splitting by rows when needed. The margin below 2^31 leaves room for the+# offset buffer itself and any target-side rows pulled into a matched-update merge.+DEFAULT_MAX_COLUMN_OFFSET_BYTES: int = 1_500_000_000 # ~1.4 GiB+++def _column_offset_pressure(col: pa.ChunkedArray) -> int:+ """Return the 32-bit-offset quantity that would overflow for this column.++ For `string`/`binary` it's the total value bytes (the final offset). For `list`+ it's the total child element count (the final list offset). 64-bit (`large_*`)+ variants can't overflow, so they contribute nothing. Computed via `pc.sum` over+ per-row lengths, which is slice-accurate (unlike `Array.nbytes`, which reports the+ full shared buffer for a zero-copy slice and would break the recursion below).+ """+ t = col.type+ if pa.types.is_string(t) or pa.types.is_binary(t):+ total = pc.sum(pc.binary_length(col)).as_py()+ return int(total or 0)+ if pa.types.is_list(t):+ total = pc.sum(pc.list_value_length(col)).as_py()+ return int(total or 0)+ return 0+++def _max_offset_pressure(table: pa.Table) -> int:+ return max((_column_offset_pressure(table.column(name)) for name in table.column_names), default=0)+++def _split_to_offset_limit(table: pa.Table, limit: int) -> list[pa.Table]:+ """Recursively row-halve `table` until every slice's worst column is under `limit`.++ Slices are zero-copy views, so this doesn't duplicate the data. A single row can+ never overflow (a string value can't itself exceed 2^31), so the `num_rows <= 1`+ base case guarantees termination.+ """+ if table.num_rows <= 1 or _max_offset_pressure(table) <= limit:+ return [table]++ mid = table.num_rows // 2+ left = table.slice(0, mid)+ right = table.slice(mid, table.num_rows - mid)+ return _split_to_offset_limit(left, limit) + _split_to_offset_limit(right, limit)+class Batcher:_buffer: list[Any]_buffer_size_bytes: int- _py_table: pa.Table | None = None+ _ready: deque[pa.Table]_logger: FilteringBoundLogger_chunk_size: int_chunk_size_bytes: int+ _max_column_offset_bytes: intdef __init__(- self, logger: FilteringBoundLogger, chunk_size: Optional[int] = None, chunk_size_bytes: Optional[int] = None+ self,+ logger: FilteringBoundLogger,+ chunk_size: Optional[int] = None,+ chunk_size_bytes: Optional[int] = None,+ max_column_offset_bytes: Optional[int] = None,) -> None:self._logger = loggerself._chunk_size = chunk_size or DEFAULT_CHUNK_SIZEself._chunk_size_bytes = chunk_size_bytes or DEFAULT_CHUNK_SIZE_BYTES+ self._max_column_offset_bytes = max_column_offset_bytes or DEFAULT_MAX_COLUMN_OFFSET_BYTESself._buffer = []self._buffer_size_bytes = 0- self._py_table = None+ self._ready = deque()++ def _set_ready(self, table: pa.Table) -> None:+ """Split `table` so no yielded chunk can overflow a 32-bit offset column."""+ self._ready = deque(_split_to_offset_limit(table, self._max_column_offset_bytes))def _estimate_size(self, obj: Any) -> int:if isinstance(obj, dict):@@ -39,7 +100,7 @@ class Batcher:return sys.getsizeof(obj)def batch(self, item: list[Any] | dict | pa.Table) -> None:- if self._py_table is not None:+ if self._ready:raise Exception("Batcher already has a table ready to yield. Call get_table() before batching more items.")if isinstance(item, list):@@ -49,14 +110,14 @@ class Batcher:if self._buffer_size_bytes >= self._chunk_size_bytes or len(self._buffer) >= self._chunk_size:self._logger.debug(f"Processing buffer (list). Length of buffer = {len(self._buffer)}")- self._py_table = table_from_py_list(self._buffer)+ self._set_ready(table_from_py_list(self._buffer))else: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._logger.debug(f"Processing item (list). Length of item = {len(item)}")- self._py_table = table_from_py_list(item)+ self._set_ready(table_from_py_list(item))else:self._buffer.extend(item)return@@ -67,34 +128,38 @@ class Batcher:returnself._logger.debug(f"Processing buffer (dict). Length of buffer = {len(self._buffer)}")- self._py_table = table_from_py_list(self._buffer)+ self._set_ready(table_from_py_list(self._buffer))elif isinstance(item, pa.Table):- self._py_table = item+ # A pa.Table is self-contained and bypasses the 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")+ self._set_ready(item)else:raise Exception(f"Unhandled item type: {item.__class__.__name__}")+ # 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+def should_yield(self, include_incomplete_chunk: bool = False) -> bool:if include_incomplete_chunk:- return self._py_table is not None or len(self._buffer) > 0+ return len(self._ready) > 0 or len(self._buffer) > 0- return self._py_table is not None+ return len(self._ready) > 0def get_table(self) -> pa.Table:- if self._py_table is not None:- table = self._py_table-- self._py_table = None- self._buffer = []- self._buffer_size_bytes = 0- return table-- if len(self._buffer) > 0:+ if not self._ready and len(self._buffer) > 0:self._logger.debug(f"Processing leftover buffer. Length of buffer = {len(self._buffer)}")- table = table_from_py_list(self._buffer)-+ self._set_ready(table_from_py_list(self._buffer))self._buffer = []self._buffer_size_bytes = 0- return table+ if self._ready:+ return self._ready.popleft()raise Exception("No chunks available to yield")diff --git a/posthog/temporal/data_imports/pipelines/pipeline/pipeline.py b/posthog/temporal/data_imports/pipelines/pipeline/pipeline.pyindex 35dc314bab8f..f17cd2a7e886 100644--- a/posthog/temporal/data_imports/pipelines/pipeline/pipeline.py+++ b/posthog/temporal/data_imports/pipelines/pipeline/pipeline.py@@ -217,30 +217,31 @@ class PipelineNonDLT(Generic[ResumableData]):py_table = Noneself._batcher.batch(item)- if not self._batcher.should_yield():- continue- py_table = self._batcher.get_table()+ # A single batched table may be split into several when a string/binary/list+ # column would otherwise overflow a 32-bit offset, so drain every ready chunk.+ while self._batcher.should_yield():+ py_table = self._batcher.get_table()- row_count += py_table.num_rows+ row_count += py_table.num_rows- await self._process_pa_table(- pa_table=py_table,- index=chunk_index,- resuming_sync=should_resume,- row_count=row_count,- is_first_ever_sync=is_first_ever_sync,- )+ await self._process_pa_table(+ pa_table=py_table,+ index=chunk_index,+ resuming_sync=should_resume,+ row_count=row_count,+ is_first_ever_sync=is_first_ever_sync,+ )- chunk_index += 1+ chunk_index += 1- cleanup_memory(pa_memory_pool, py_table)- py_table = None+ cleanup_memory(pa_memory_pool, py_table)+ py_table = Noneif should_check_shutdown(self._schema, self._resource, self._reset_pipeline, source_is_resumable):self._shutdown_monitor.raise_if_is_worker_shutdown()- if self._batcher.should_yield(include_incomplete_chunk=True):+ while self._batcher.should_yield(include_incomplete_chunk=True):py_table = self._batcher.get_table()row_count += py_table.num_rowsawait self._process_pa_table(@@ -250,6 +251,7 @@ class PipelineNonDLT(Generic[ResumableData]):row_count=row_count,is_first_ever_sync=is_first_ever_sync,)+ chunk_index += 1await self._post_run_operations(row_count=row_count)diff --git a/posthog/temporal/data_imports/pipelines/pipeline/test/test_batcher.py b/posthog/temporal/data_imports/pipelines/pipeline/test/test_batcher.pyindex 4fd07e6e5ca7..75498f539c1f 100644--- a/posthog/temporal/data_imports/pipelines/pipeline/test/test_batcher.py+++ b/posthog/temporal/data_imports/pipelines/pipeline/test/test_batcher.py@@ -2,8 +2,21 @@ import pytestfrom unittest import mockimport pyarrow as pa+from parameterized import parameterized-from posthog.temporal.data_imports.pipelines.pipeline.batcher import Batcher+from posthog.temporal.data_imports.pipelines.pipeline.batcher import (+ Batcher,+ _column_offset_pressure,+ _max_offset_pressure,+ _split_to_offset_limit,+)+++def _drain(batcher: Batcher) -> list[pa.Table]:+ tables = []+ while batcher.should_yield(include_incomplete_chunk=True):+ tables.append(batcher.get_table())+ return tablesdef test_batching_pa_table_should_yield():@@ -80,6 +93,100 @@ def test_batching_lists_should_yield_after_chunk_size_bytes_threshold():assert result_table.equals(expected_table)+ [+ ("string", pa.array(["aa", "bb", "cc", "dd"], type=pa.string()), 8),+ ("binary", pa.array([b"aa", b"bb"], type=pa.binary()), 4),+ ("list", pa.array([[1, 2], [3], [4, 5, 6]], type=pa.list_(pa.int64())), 6),+ ("large_string_is_safe", pa.array(["aa", "bb"], type=pa.large_string()), 0),+ ("int_is_safe", pa.array([1, 2, 3], type=pa.int64()), 0),+ ("nulls_counted_as_zero", pa.array([None, "abc", None], type=pa.string()), 3),+ ]+)+def test_column_offset_pressure(_name: str, array: pa.Array, expected: int):+ assert _column_offset_pressure(pa.chunked_array([array])) == expected+++def test_max_offset_pressure_picks_worst_column():+ table = pa.table(+ {+ "small": pa.array(["a", "b"], type=pa.string()),+ "big": pa.array(["aaaa", "bbbb"], type=pa.string()),+ "ints": pa.array([1, 2], type=pa.int64()),+ }+ )++ assert _max_offset_pressure(table) == 8+++def test_split_to_offset_limit_under_limit_is_noop():+ table = pa.table({"a": ["x", "y", "z"]})++ result = _split_to_offset_limit(table, limit=1_000)++ assert len(result) == 1+ assert result[0].equals(table)+++def test_split_to_offset_limit_splits_and_preserves_data_and_order():+ table = pa.table({"id": [0, 1, 2, 3], "val": ["aa", "bb", "cc", "dd"]})++ # Total "val" bytes = 8; limit 3 forces splitting until each slice is <= 3 bytes.+ result = _split_to_offset_limit(table, limit=3)++ assert len(result) > 1+ for slice_table in result:+ assert _max_offset_pressure(slice_table) <= 3+ # Concatenating the slices reproduces the original table in order.+ assert pa.concat_tables(result).equals(table)+++def test_split_to_offset_limit_single_row_never_splits():+ # A single row can't be split further even if it exceeds the limit.+ table = pa.table({"val": ["a-very-long-value"]})++ result = _split_to_offset_limit(table, limit=1)++ assert len(result) == 1+ assert result[0].equals(table)+++def test_batcher_splits_oversized_pa_table_on_yield():+ batcher = Batcher(logger=mock.MagicMock(), max_column_offset_bytes=3)+ table = pa.table({"id": [0, 1, 2, 3], "val": ["aa", "bb", "cc", "dd"]})++ batcher.batch(table)++ drained = _drain(batcher)++ assert len(drained) > 1+ assert pa.concat_tables(drained).equals(table)+++def test_batcher_does_not_split_when_under_limit():+ batcher = Batcher(logger=mock.MagicMock(), max_column_offset_bytes=1_000_000)+ table = pa.table({"id": [0, 1, 2, 3], "val": ["aa", "bb", "cc", "dd"]})++ batcher.batch(table)++ drained = _drain(batcher)++ assert len(drained) == 1+ assert drained[0].equals(table)+++def test_batcher_splits_buffered_list_items():+ batcher = Batcher(logger=mock.MagicMock(), chunk_size=4, max_column_offset_bytes=3)++ batcher.batch([{"val": "aa"}, {"val": "bb"}, {"val": "cc"}, {"val": "dd"}])++ drained = _drain(batcher)++ assert len(drained) > 1+ combined = pa.concat_tables(drained)+ assert combined.column("val").to_pylist() == ["aa", "bb", "cc", "dd"]++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/posthog/temporal/data_imports/pipelines/pipeline_v3/pipeline.py b/posthog/temporal/data_imports/pipelines/pipeline_v3/pipeline.pyindex ee3675cdebb0..4ff1475872ee 100644--- a/posthog/temporal/data_imports/pipelines/pipeline_v3/pipeline.py+++ b/posthog/temporal/data_imports/pipelines/pipeline_v3/pipeline.py@@ -227,31 +227,32 @@ class PipelineV3(Generic[ResumableData]):py_table = Noneself._batcher.batch(item)- if not self._batcher.should_yield():- continue- py_table = self._batcher.get_table()- row_count += py_table.num_rows+ # A single batched table may be split into several when a string/binary/list+ # column would otherwise overflow a 32-bit offset, so drain every ready chunk.+ while self._batcher.should_yield():+ py_table = self._batcher.get_table()+ row_count += py_table.num_rows- await self._process_batch(- pa_table=py_table,- batch_index=chunk_index,- row_count=row_count,- )+ await self._process_batch(+ pa_table=py_table,+ batch_index=chunk_index,+ row_count=row_count,+ )- if activity.in_activity():- get_rows_extracted_metric(team_id_str, schema_id_str, source_type).add(py_table.num_rows)- get_batches_produced_metric(team_id_str, schema_id_str).add(1)+ if activity.in_activity():+ get_rows_extracted_metric(team_id_str, schema_id_str, source_type).add(py_table.num_rows)+ get_batches_produced_metric(team_id_str, schema_id_str).add(1)- chunk_index += 1+ chunk_index += 1- cleanup_memory(pa_memory_pool, py_table)- py_table = None+ cleanup_memory(pa_memory_pool, py_table)+ py_table = Noneif should_check_shutdown(self._schema, self._resource, self._reset_pipeline, source_is_resumable):self._shutdown_monitor.raise_if_is_worker_shutdown()- if self._batcher.should_yield(include_incomplete_chunk=True):+ while self._batcher.should_yield(include_incomplete_chunk=True):py_table = self._batcher.get_table()row_count += py_table.num_rowsawait self._process_batch(@@ -264,6 +265,8 @@ class PipelineV3(Generic[ResumableData]):get_rows_extracted_metric(team_id_str, schema_id_str, source_type).add(py_table.num_rows)get_batches_produced_metric(team_id_str, schema_id_str).add(1)+ chunk_index += 1+await self._finalize(row_count=row_count)return {