: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): size Mongo extraction chunk to document size to avoid OOM (#68236)
Tom Owers1cbfdef62355
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/pipeline.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/pipeline.pyindex d603800ce4d6..ecddf16bf08f 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/pipeline.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/pipeline.py@@ -177,7 +177,13 @@ class PipelineNonDLT(Generic[ResumableData]):self._delta_table_helper = DeltaTableHelper(self._resource_name, self._job, self._logger)self._resumable_source_manager = resumable_source_manager- self._batcher = Batcher(self._logger)+ # 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.+ self._batcher = Batcher(+ self._logger,+ chunk_size=source_response.chunk_size,+ chunk_size_bytes=source_response.chunk_size_bytes,+ )self._internal_schema = HogQLSchema()self._cdp_producer = CDPProducer(team_id=self._job.team_id, schema_id=self._schema.id, job_id=job_id, logger=self._loggerdiff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/typings.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/typings.pyindex b3410a8fb1db..bb21fc187781 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/typings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/typings.py@@ -61,6 +61,12 @@ class SourceResponse:rows_to_sync: Optional[int] = Nonehas_duplicate_primary_keys: Optional[bool] = None"""Whether incremental tables have non-unique primary keys"""+ chunk_size: Optional[int] = None+ """Override the batcher's rows-per-chunk (defaults to DEFAULT_CHUNK_SIZE)."""+ chunk_size_bytes: Optional[int] = None+ """Override the batcher's per-chunk byte cap (defaults to DEFAULT_CHUNK_SIZE_BYTES). Lower it for+ sources whose rows are large (e.g. whole documents) so the source->Arrow conversion doesn't+ materialise an oversized table and OOM the worker."""xmin_ceiling_xid: Optional[int] = None"""xmin syncs: bare 32-bit ceiling captured this run, persisted as the next run's lower bound."""xmin_ceiling_xid8: Optional[int] = Nonediff --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.pyindex f6fd82963d08..4b727f079145 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@@ -190,7 +190,13 @@ class PipelineV3(Generic[ResumableData]):)self._resumable_source_manager = resumable_source_manager- self._batcher = Batcher(self._logger)+ # 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.+ self._batcher = Batcher(+ self._logger,+ chunk_size=source_response.chunk_size,+ chunk_size_bytes=source_response.chunk_size_bytes,+ )self._internal_schema = HogQLSchema()self._cdp_producer = CDPProducer(team_id=self._job.team_id, schema_id=self._schema.id, job_id=job_id, logger=self._loggerdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mongodb/mongo.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mongodb/mongo.pyindex ac70a0efede8..c364205da735 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mongodb/mongo.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mongodb/mongo.py@@ -37,6 +37,30 @@ from products.warehouse_sources.backend.types import IncrementalFieldType, PartiSCHEMA_INFERENCE_LIMIT = 10_000 # First 10k documentsSCHEMA_INFERENCE_TIMEOUT_MS = 45_000 # 45 seconds+# Mongo yields whole documents (the full doc rides along under `data`), so a collection of large+# documents can OOM the worker when a chunk is materialised into a PyArrow table — before any Delta+# merge. Size the extraction chunk to a fixed byte budget: rows-per-chunk are derived from the average+# document size and clamped, and a chunk flushes at whichever of the byte/row limit is hit first.+MONGO_CHUNK_SIZE_BYTES = 100 * 1024 * 1024 # 100 MiB+MONGO_MIN_CHUNK_ROWS = 100+# Ceiling reuses the pipeline default so tiny documents keep the large, efficient chunk. The 100 MiB+# byte budget is the real OOM guard; this only caps row count when documents are small enough that+# many fit in that budget.+MONGO_MAX_CHUNK_ROWS = DEFAULT_CHUNK_SIZE+++def _adaptive_chunk_size(avg_obj_size: int | None) -> int:+ """Rows per extraction chunk, sized so one chunk holds roughly MONGO_CHUNK_SIZE_BYTES of documents.++ Small documents keep the default (large, efficient) chunk; large documents get a small chunk so the+ conversion of a chunk into a PyArrow table stays bounded. Falls back to the default when the average+ document size is unknown.+ """+ if not avg_obj_size or avg_obj_size <= 0:+ return DEFAULT_CHUNK_SIZE+ rows = MONGO_CHUNK_SIZE_BYTES // avg_obj_size+ return max(MONGO_MIN_CHUNK_ROWS, min(MONGO_MAX_CHUNK_ROWS, rows))+def _convert_binary(value: Binary) -> str:"""Convert a bson.Binary to a safe string representation.@@ -493,6 +517,21 @@ def _get_primary_keys(collection: Collection, collection_name: str) -> list[str]return ["_id"]+def _get_avg_document_size(collection: Collection, logger: FilteringBoundLogger) -> int | None:+ """Average BSON document size in bytes from collStats, used to size the extraction chunk.++ Returns None if unavailable (permissions, sharded stats, etc.) — the caller falls back to the+ default chunk size. Never raises: chunk sizing is best-effort tuning, not correctness.+ """+ try:+ stats = collection.database.command("collStats", collection.name)+ avg_obj_size = stats.get("avgObjSize")+ return int(avg_obj_size) if avg_obj_size else None+ except Exception as e:+ logger.debug(f"MongoDB: could not read collStats avgObjSize ({e}); using default chunk size")+ return None++def _get_rows_to_sync(collection: Collection, query: dict[str, Any], logger: FilteringBoundLogger) -> int:try:rows_to_sync = collection.count_documents(query)@@ -547,6 +586,12 @@ def mongo_source(_get_partition_settings(collection, collection_name) if should_use_incremental_field else None)rows_to_sync = _get_rows_to_sync(collection, query, logger)+ avg_obj_size = _get_avg_document_size(collection, logger)++ # Bound the extraction chunk to the collection's document size so large documents don't OOM the+ # source->Arrow conversion (the merge is never reached for such collections).+ chunk_size = _adaptive_chunk_size(avg_obj_size)+ logger.debug(f"MongoDB: chunk_size={chunk_size} rows (avg_obj_size={avg_obj_size}, rows_to_sync={rows_to_sync})")def get_rows() -> Iterator[dict[str, Any]]:# New connection for data reading@@ -561,7 +606,7 @@ def mongo_source(db_incremental_field_last_value,)- cursor = read_collection.find(query, batch_size=DEFAULT_CHUNK_SIZE)+ cursor = read_collection.find(query, batch_size=chunk_size)for doc in cursor:# Convert BSON types (ObjectId, Binary, UUID, DatetimeMS) to SQL-safe@@ -595,4 +640,6 @@ def mongo_source(partition_count=partition_settings.partition_count if partition_settings else None,partition_size=partition_settings.partition_size if partition_settings else None,rows_to_sync=rows_to_sync,+ chunk_size=chunk_size,+ chunk_size_bytes=MONGO_CHUNK_SIZE_BYTES,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mongodb/test_mongo.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mongodb/test_mongo.pyindex 190fa80fb3fb..1fd8e5551187 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mongodb/test_mongo.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mongodb/test_mongo.py@@ -12,7 +12,11 @@ from parameterized import parameterizedfrom pymongo.errors import ServerSelectionTimeoutErrorfrom pymongo.server_description import ServerDescription+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.consts import DEFAULT_CHUNK_SIZEfrom products.warehouse_sources.backend.temporal.data_imports.sources.mongodb.mongo import (+ MONGO_MAX_CHUNK_ROWS,+ MONGO_MIN_CHUNK_ROWS,+ _adaptive_chunk_size,_build_query,_get_rows_to_sync,_list_importable_collection_names,@@ -502,3 +506,21 @@ class TestListImportableCollectionNames(SimpleTestCase):db.list_collection_names.return_value = ["system_events", "billing.system", "systematic"]assert _list_importable_collection_names(db) == ["system_events", "billing.system", "systematic"]+++class TestAdaptiveChunkSize(SimpleTestCase):+ @parameterized.expand(+ [+ ("unknown_size", None, DEFAULT_CHUNK_SIZE),+ ("zero_size", 0, DEFAULT_CHUNK_SIZE),+ ("negative_size", -10, DEFAULT_CHUNK_SIZE),+ # 5 MiB docs -> 100MiB/5MiB = 20 rows, clamped up to the floor so we don't thrash on tiny chunks+ ("huge_docs_clamped_to_min", 5 * 1024 * 1024, MONGO_MIN_CHUNK_ROWS),+ # 1 KiB docs -> 100k rows, clamped down to the ceiling (the OOM guard for large collections)+ ("tiny_docs_clamped_to_max", 1024, MONGO_MAX_CHUNK_ROWS),+ # 256 KiB docs -> 100MiB/256KiB = 400 rows, between the floor and ceiling+ ("mid_size_computed", 256 * 1024, 400),+ ]+ )+ def test_adaptive_chunk_size(self, _name, avg_obj_size, expected):+ assert _adaptive_chunk_size(avg_obj_size) == expected