: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
feat(data-warehouse): spill delta merges to disk to avoid OOMs (#72934)
Tom Owers891298e6888f
diff --git a/posthog/settings/data_warehouse.py b/posthog/settings/data_warehouse.pyindex 5cbdfc22ee76..88a3780f88d8 100644--- a/posthog/settings/data_warehouse.py+++ b/posthog/settings/data_warehouse.py@@ -50,6 +50,26 @@ DATA_WAREHOUSE_REPARTITION_OOM_WINDOW_DAYS = get_from_env(# path never runs for them). Vacuum only deletes dead files, so it's memory-safe even on oversized tables.DATA_WAREHOUSE_VACUUM_COMMIT_THRESHOLD = get_from_env("DATA_WAREHOUSE_VACUUM_COMMIT_THRESHOLD", 100, type_cast=int)+# delta-rs merge spill-to-disk. A merge decompresses the target partition into an Arrow working set that+# can exceed the 29 GB pod limit and OOM — killing every co-tenant activity on the pod. When set, delta-rs+# hands DataFusion a bounded memory pool: once the merge's in-memory bytes cross MAX_SPILL_SIZE it spills+# the overflow to its temp directory (the process TMPDIR) instead of allocating unbounded. Left as None,+# DataFusion runs with its unbounded default (today's behavior) — so this is a no-op until BOTH the byte+# budget and a scratch disk are provisioned (the temporal-worker-data-warehouse / warehouse-sources-load+# pods mount an ephemeral volume at /tmp and set these env vars).+#+# Sizing interacts with concurrency: each merge gets its own DataFusion pool, so N concurrent merges on a+# pod can hold up to N * MAX_SPILL_SIZE in memory and N * MAX_TEMP_DIRECTORY_SIZE on the shared disk. Keep+# MAX_SPILL_SIZE below the designed per-partition working set (~10 GB) so genuinely-large merges spill+# before the multi-tenant OOM, while typical small merges stay in memory (spilling is slow). Keep+# MAX_TEMP_DIRECTORY_SIZE small enough that a few concurrent spills fit the mounted disk.+DATA_WAREHOUSE_DELTA_MERGE_MAX_SPILL_SIZE_BYTES: int | None = get_from_env(+ "DATA_WAREHOUSE_DELTA_MERGE_MAX_SPILL_SIZE_BYTES", None, optional=True, type_cast=int+)+DATA_WAREHOUSE_DELTA_MERGE_MAX_TEMP_DIRECTORY_SIZE_BYTES: int | None = get_from_env(+ "DATA_WAREHOUSE_DELTA_MERGE_MAX_TEMP_DIRECTORY_SIZE_BYTES", None, optional=True, type_cast=int+)+GOOGLE_ADS_SERVICE_ACCOUNT_CLIENT_EMAIL: str | None = os.getenv("GOOGLE_ADS_SERVICE_ACCOUNT_CLIENT_EMAIL")GOOGLE_ADS_SERVICE_ACCOUNT_PRIVATE_KEY: str | None = os.getenv("GOOGLE_ADS_SERVICE_ACCOUNT_PRIVATE_KEY")GOOGLE_ADS_SERVICE_ACCOUNT_PRIVATE_KEY_ID: str | None = os.getenv("GOOGLE_ADS_SERVICE_ACCOUNT_PRIVATE_KEY_ID")diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/delta_table_helper.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/delta_table_helper.pyindex 413d17448232..06d00e6c90a8 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/delta_table_helper.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/delta_table_helper.py@@ -51,6 +51,24 @@ DEFAULT_COMPACT_FILES_PER_PARTITION_THRESHOLD = 200DEFAULT_COMPACT_TOTAL_FILES_THRESHOLD = 5000+def _delta_merge_spill_kwargs() -> dict[str, int]:+ """delta-rs `merge` kwargs that let DataFusion spill to disk instead of OOMing on large merges.++ A merge decompresses the target partition into an Arrow working set that can exceed the pod's+ memory limit and take down every co-tenant activity. When the byte budgets are configured (and the+ worker mounts a scratch disk at its TMPDIR), delta-rs bounds DataFusion's memory pool: bytes past+ `max_spill_size` spill to disk, capped at `max_temp_directory_size`. Unset → omit the kwargs so+ DataFusion keeps its unbounded default (today's behavior), which also keeps this compatible with+ deltalake versions predating the parameters.+ """+ kwargs: dict[str, int] = {}+ if settings.DATA_WAREHOUSE_DELTA_MERGE_MAX_SPILL_SIZE_BYTES is not None:+ kwargs["max_spill_size"] = settings.DATA_WAREHOUSE_DELTA_MERGE_MAX_SPILL_SIZE_BYTES+ if settings.DATA_WAREHOUSE_DELTA_MERGE_MAX_TEMP_DIRECTORY_SIZE_BYTES is not None:+ kwargs["max_temp_directory_size"] = settings.DATA_WAREHOUSE_DELTA_MERGE_MAX_TEMP_DIRECTORY_SIZE_BYTES+ return kwargs++async def _purge_s3_prefix(s3: Any, uri: str) -> None:"""Delete every object under `uri`, resilient to S3 recursive-delete gaps.@@ -455,6 +473,7 @@ class DeltaTableHelper:predicate=predicate,streamed_exec=True,commit_properties=merge_commit_properties,+ **_delta_merge_spill_kwargs(),).when_matched_update_all().when_not_matched_insert_all()@@ -478,6 +497,7 @@ class DeltaTableHelper:predicate=" AND ".join(predicate_ops),streamed_exec=False,commit_properties=commit_properties,+ **_delta_merge_spill_kwargs(),).when_matched_update_all().when_not_matched_insert_all()@@ -624,6 +644,7 @@ class DeltaTableHelper:target_alias="target",predicate=predicate,streamed_exec=False,+ **_delta_merge_spill_kwargs(),).when_matched_update(updates={"valid_to": "source.valid_from"}).execute()diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/test/test_delta_table_helper.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/test/test_delta_table_helper.pyindex df7bd67d56c2..c568e4f2c369 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/test/test_delta_table_helper.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/test/test_delta_table_helper.py@@ -17,6 +17,7 @@ from parameterized import parameterizedfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.consts import PARTITION_KEYfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.delta_table_helper import (DeltaTableHelper,+ _delta_merge_spill_kwargs,_first_per_pk_table,_realign_decimal_buffers,)@@ -163,6 +164,32 @@ class TestStorageOptionsCommitSafety:assert ("AWS_S3_ALLOW_UNSAFE_RENAME" in options) is allow_unsafe+class TestDeltaMergeSpillKwargs:+ # Guards the wiring from settings → delta-rs merge kwargs. A silent break here (renamed setting,+ # dropped forwarding, or emitting a None kwarg) stops merges spilling to disk and OOMs return.+ @parameterized.expand(+ [+ ("both_unset", None, None, {}),+ ("only_spill", 6_442_450_944, None, {"max_spill_size": 6_442_450_944}),+ ("only_temp_dir", None, 51_539_607_552, {"max_temp_directory_size": 51_539_607_552}),+ (+ "both_set",+ 6_442_450_944,+ 51_539_607_552,+ {"max_spill_size": 6_442_450_944, "max_temp_directory_size": 51_539_607_552},+ ),+ ]+ )+ def test_kwargs_from_settings(+ self, _case: str, spill: int | None, temp_dir: int | None, expected: dict[str, int]+ ) -> None:+ with override_settings(+ DATA_WAREHOUSE_DELTA_MERGE_MAX_SPILL_SIZE_BYTES=spill,+ DATA_WAREHOUSE_DELTA_MERGE_MAX_TEMP_DIRECTORY_SIZE_BYTES=temp_dir,+ ):+ assert _delta_merge_spill_kwargs() == expected++class TestHasCommitWithMetadata:@pytest.mark.asyncioasync def test_returns_false_when_no_delta_table(self, helper: DeltaTableHelper):