: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): defensive pre-write Delta compaction (#66659)
Daniel RC52be8b1b1c48
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/extract.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/extract.pyindex c106f13b6465..f993baf90bc5 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/extract.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/extract.py@@ -399,3 +399,30 @@ async def cdp_producer_clear_chunks(cdp_producer: CDPProducer):async def write_chunk_for_cdp_producer(cdp_producer: CDPProducer, index: int, pa_table: pa.Table):if await cdp_producer.should_produce_table():await cdp_producer.write_chunk_for_cdp_producer(chunk=index, table=pa_table)+++async def run_pre_write_defensive_compact(+ delta_table_helper: DeltaTableHelper,+ schema: "ExternalDataSchema",+ resource: SourceResponse,+ logger: FilteringBoundLogger,+) -> None:+ """Best-effort pre-write compact + vacuum at the start of a sync run.++ Triggers `DeltaTableHelper.compact_if_fragmented` so a sync that arrived at a+ fragmented Delta target (e.g. because earlier attempts failed before reaching+ `_post_run_operations`) cleans up before adding more small files — keeping the+ subsequent per-partition merge scans cheap. Wrapped in try/except so a+ compaction failure never blocks the actual sync; the original error path is+ unaffected.++ Used by both `PipelineNonDLT.run` (v2) and `PipelineV3.run` to keep the+ behaviour identical across pipelines without each having to know how to look+ up `partition_count` or how to swallow compaction errors.+ """+ try:+ partition_count_for_compact = schema.partition_count or resource.partition_count+ await delta_table_helper.compact_if_fragmented(partition_count=partition_count_for_compact)+ except Exception as e:+ capture_exception(e)+ await logger.aexception(f"Pre-write compaction failed: {e}", exc_info=e)diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/test/test_extract.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/test/test_extract.pynew file mode 100644index 000000000000..f2176a7c7d29--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/test/test_extract.py@@ -0,0 +1,52 @@+import pytest+from unittest.mock import AsyncMock, MagicMock, patch++from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.pipelines.common.extract import (+ run_pre_write_defensive_compact,+)++_EXTRACT_MODULE = "products.warehouse_sources.backend.temporal.data_imports.pipelines.common.extract"+++class TestRunPreWriteDefensiveCompact:+ @parameterized.expand(+ [+ # (schema_partition_count, resource_partition_count, expected_passed_to_compact)+ ("schema_value_wins", 10, 72, 10),+ ("falls_back_to_resource", None, 72, 72),+ ("both_none_passes_none", None, None, None),+ ]+ )+ @pytest.mark.asyncio+ async def test_resolves_partition_count_schema_over_resource(+ self, _name: str, schema_count: int | None, resource_count: int | None, expected: int | None+ ):+ compact = AsyncMock(return_value=False)+ helper = MagicMock(compact_if_fragmented=compact)++ await run_pre_write_defensive_compact(+ helper,+ MagicMock(partition_count=schema_count),+ MagicMock(partition_count=resource_count),+ MagicMock(aexception=AsyncMock()),+ )++ compact.assert_awaited_once_with(partition_count=expected)++ @pytest.mark.asyncio+ async def test_swallows_compaction_failure(self):+ # The whole point of the wrapper: a compaction error must never propagate and+ # block the sync — it's captured and logged instead.+ compact = AsyncMock(side_effect=RuntimeError("compaction blew up"))+ helper = MagicMock(compact_if_fragmented=compact)+ logger = MagicMock(aexception=AsyncMock())++ with patch(f"{_EXTRACT_MODULE}.capture_exception") as mock_capture:+ await run_pre_write_defensive_compact(+ helper, MagicMock(partition_count=5), MagicMock(partition_count=None), logger+ )++ mock_capture.assert_called_once()+ logger.aexception.assert_awaited_once()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 5f0e317627de..67102c01e232 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@@ -26,6 +26,28 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipelinepyarrow_schema_from_arrow_exportable,)+# A pre-write defensive compact fires when EITHER threshold is exceeded.+#+# Calibrated against the production file-count distribution (delta merge stats across+# all teams): total files per table sit at p50≈60, p90≈470, p95≈850, with a long tail+# (p99≈12k → ~14s merges; an observed pathological case hit ~82k files → ~45s merges).+# Merge planning time tracks TOTAL files, not files-per-partition — delta still+# enumerates every file's metadata even when partition pruning skips reading them — so+# we gate on both:+#+# - files-per-partition: bounds per-partition fragmentation and rescues partitioned+# (esp. md5) tables, where a merge touches every partition. 200 sits well above the+# healthy steady state (compaction runs at the end of each successful sync) yet+# triggers long before a table reaches the slow tail.+# - total files: a partition-count-independent backstop so a table with a high+# partition_count can't accumulate tens of thousands of files (each adding to merge+# planning time) while staying under the per-partition bar. 5,000 is above p95 (~850)+# — so healthy tables never trip it — and well below the p99/pathological tail.+#+# Tune further once the admin fragmentation view gives per-customer distributions.+DEFAULT_COMPACT_FILES_PER_PARTITION_THRESHOLD = 200+DEFAULT_COMPACT_TOTAL_FILES_THRESHOLD = 5000+def _write_deltalake(table_or_uri: str | deltalake.DeltaTable,@@ -636,3 +658,46 @@ class DeltaTableHelper:await self._logger.adebug(json.dumps(vacuum_stats))await self._logger.adebug("Compacting and vacuuming complete")++ async def compact_if_fragmented(+ self,+ partition_count: int | None,+ threshold: int = DEFAULT_COMPACT_FILES_PER_PARTITION_THRESHOLD,+ total_threshold: int = DEFAULT_COMPACT_TOTAL_FILES_THRESHOLD,+ ) -> bool:+ """Run compact + vacuum if the table is fragmented past either threshold.++ Fragmented = files-per-partition > `threshold` OR total files > `total_threshold`.+ The total-files backstop matters because delta enumerates every file's metadata+ during a merge even when partition pruning skips reading them, so merge planning+ time tracks total files — a high partition_count must not let a table accumulate+ tens of thousands of files while staying under the per-partition bar.++ Returns True if compaction ran, False if it was skipped. Cheap when the table is+ healthy: one S3 LIST via `get_file_uris`. Intended for pre-write defensive cleanup+ so a sync that arrived at a fragmented state (e.g. an earlier attempt that failed+ before reaching `_post_run_operations`) cleans up before adding to the pile.+ """+ table = await self.get_delta_table()+ if table is None:+ return False++ file_uris = await self.get_file_uris()+ total_files = len(file_uris)+ # Treat unpartitioned tables as one "partition" for the threshold math.+ effective_partitions = max(partition_count or 1, 1)+ files_per_partition = total_files / effective_partitions++ fragmented = files_per_partition > threshold or total_files > total_threshold+ stats = (+ f"total_files={total_files}, partitions={effective_partitions}, "+ f"files_per_partition={files_per_partition:.1f}, threshold={threshold}, "+ f"total_threshold={total_threshold}"+ )+ if not fragmented:+ await self._logger.adebug(f"compact_if_fragmented: skipping ({stats})")+ return False++ await self._logger.ainfo(f"compact_if_fragmented: triggering compact ({stats})")+ await self.compact_table()+ return Truediff --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 6c39b61984b5..d603800ce4d6 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@@ -26,6 +26,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.common.efinalize_desc_sort_incremental_value,handle_reset_or_full_refresh,reset_rows_synced_if_needed,+ run_pre_write_defensive_compact,setup_row_tracking_with_billing_check,should_check_shutdown,update_incremental_field_values,@@ -222,6 +223,16 @@ class PipelineNonDLT(Generic[ResumableData]):# If the schema has no DWH table, it's a first ever syncis_first_ever_sync: bool = self._table is None+ # Defensive pre-write compaction so a sync that arrived at a fragmented+ # Delta target (e.g. earlier attempts that failed before reaching+ # `_post_run_operations`) cleans up before adding more small files. Skipped+ # cheaply when the table is healthy. Shared implementation lives in+ # `extract.run_pre_write_defensive_compact` so the v3 pipeline matches.+ if not is_first_ever_sync:+ await run_pre_write_defensive_compact(+ self._delta_table_helper, self._schema, self._resource, self._logger+ )+async for item in async_iterate(self._resource.items()):py_table = Nonediff --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 7a9cbde87fad..282acee45004 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@@ -180,6 +180,64 @@ class TestHasBatchBeenCommitted:m.assert_called_once_with({"run_uuid": run_uuid, "batch_index": str(batch_index)})+class TestCompactIfFragmented:+ """Pre-write defensive compaction fires on files-per-partition OR total-files threshold."""++ @pytest.mark.asyncio+ async def test_skips_when_no_delta_table(self, helper: DeltaTableHelper):+ with patch.object(helper, "get_delta_table", AsyncMock(return_value=None)):+ ran = await helper.compact_if_fragmented(partition_count=10)+ assert ran is False++ # (case_name, file_count, partition_count, threshold_kw, expected_ran)+ # threshold_kw=None means "use default threshold" — exercises the prod path.+ _THRESHOLD_CASES: list[tuple[str, int, int | None, int | None, bool]] = [+ # 100 / 10 = 10 fpp, well below default 200 -> skip+ ("below_default_threshold", 100, 10, None, False),+ # 5,000 / 10 = 500 fpp, well above default 200 -> fire+ ("above_default_threshold", 5_000, 10, None, True),+ # partition_count=None treated as 1; 250 fpp >> default 200 -> fire+ ("unpartitioned_above_default", 250, None, None, True),+ # Custom threshold: 100 / 10 = 10 fpp, threshold=5 -> fire+ ("custom_threshold_fires", 100, 10, 5, True),+ # Boundary: exactly at threshold -> `>` not `>=`, so skip+ ("exactly_at_default_threshold", 2_000, 10, None, False),+ # Total-files backstop: 6,000 / 100 = 60 fpp (under the per-partition bar) but+ # total 6,000 > 5,000 default total threshold -> fire. Guards high-partition tables.+ ("total_cap_fires_under_per_partition", 6_000, 100, None, True),+ # Under both bars: 4,000 / 100 = 40 fpp and total 4,000 < 5,000 -> skip.+ ("below_both_thresholds", 4_000, 100, None, False),+ ]++ @parameterized.expand(_THRESHOLD_CASES)+ @pytest.mark.asyncio+ async def test_threshold(+ self,+ _name: str,+ file_count: int,+ partition_count: int | None,+ threshold_kw: int | None,+ expected_ran: bool,+ ):+ helper = DeltaTableHelper(resource_name="t", job=MagicMock(), logger=_make_logger())+ mock_delta = MagicMock()+ with (+ patch.object(helper, "get_delta_table", AsyncMock(return_value=mock_delta)),+ patch.object(helper, "get_file_uris", AsyncMock(return_value=[f"f{i}" for i in range(file_count)])),+ patch.object(helper, "compact_table", AsyncMock()) as mock_compact,+ ):+ kwargs: dict = {"partition_count": partition_count}+ if threshold_kw is not None:+ kwargs["threshold"] = threshold_kw+ ran = await helper.compact_if_fragmented(**kwargs)++ assert ran is expected_ran+ if expected_ran:+ mock_compact.assert_called_once()+ else:+ mock_compact.assert_not_called()++class TestWriteToDeltalakeCommitMetadataPassThrough:"""Covers that commit_metadata is forwarded to deltalake.write_deltalake as CommitProperties."""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.pyindex 812c31c57731..f6fd82963d08 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@@ -27,6 +27,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.common.efinalize_desc_sort_incremental_value,handle_reset_or_full_refresh,reset_rows_synced_if_needed,+ run_pre_write_defensive_compact,setup_row_tracking_with_billing_check,should_check_shutdown,update_incremental_field_values,@@ -261,6 +262,14 @@ class PipelineV3(Generic[ResumableData]):if is_fresh_sync:self._pg_producer.is_first_ever_sync = True+ # Defensive pre-write compaction. See `extract.run_pre_write_defensive_compact`+ # for rationale; shared with the v2 pipeline so the threshold + error handling+ # stay in lockstep.+ if not is_fresh_sync:+ await run_pre_write_defensive_compact(+ self._delta_table_helper, self._schema, self._resource, self._logger+ )+async for item in async_iterate(self._resource.items()):py_table = None