Skip to content

: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.

fix(data-warehouse): compact small files after syncs and before splits (#109148)

Daniel RC4d259e95c538
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/load.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/load.py
index 6fdc7625e869..6e2cef13e0fb 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/load.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/load.py
@@ -285,10 +285,14 @@ async def _run_delta_maintenance(
# Threshold maintenance for every sync type: most final batches leave the table with nothing
# to compact, and an unconditional compact still lists and plans every file. Compact when
# fragmented, otherwise vacuum once enough commits have accrued; see DeltaMaintenance.run_scheduled.
+ # A non-CDC sync also compacts once its small merge files add up (see compact_if_fragmented).
logger.debug("Running threshold-based delta maintenance")
with POST_LOAD_DURATION_SECONDS.labels(operation="maintenance").time():
await DeltaMaintenance(delta_table_ref).run_scheduled(
- schema, is_cdc_companion=is_cdc_companion, partition_count_fallback=partition_count_fallback
+ schema,
+ is_cdc_companion=is_cdc_companion,
+ partition_count_fallback=partition_count_fallback,
+ compact_small_files=not schema.is_cdc,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/test/test_load.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/test/test_load.py
index 17b7b0ab85b4..76ef738d4de0 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/test/test_load.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/test/test_load.py
@@ -113,18 +113,22 @@ class TestRunPostLoadDeltaMaintenance:
"""Post-load routes every schema kind through threshold maintenance; the threshold/watermark
mechanics themselves are covered in core/delta/test/test_maintenance.py."""
- @parameterized.expand([("cdc", True, "incremental"), ("non_cdc", False, None)])
+ @parameterized.expand([("cdc", True, "incremental", False), ("non_cdc", False, None, True)])
@pytest.mark.asyncio
async def test_uses_threshold_maintenance_not_unconditional_compact(
- self, _name: str, is_cdc: bool, cdc_write_mode: str | None
+ self, _name: str, is_cdc: bool, cdc_write_mode: str | None, compact_small_files: bool
) -> None:
# CDC finals land every tick, and a non-CDC final batch usually leaves nothing to compact,
# so an unconditional compact+vacuum here paid a full file listing and rewrite plan per sync.
+ # A non-CDC table still needs its small merge files compacted: without that they pile up in
+ # the newest partition, reads slow down, and the inflated partition trips a false repartition.
schema = _make_schema(is_cdc=is_cdc, sync_type_config={"last_vacuum_version": 41})
run_scheduled, _ = await _run_post_load(schema, _make_helper(), cdc_write_mode=cdc_write_mode)
- run_scheduled.assert_awaited_once_with(schema, is_cdc_companion=False, partition_count_fallback=None)
+ run_scheduled.assert_awaited_once_with(
+ schema, is_cdc_companion=False, partition_count_fallback=None, compact_small_files=compact_small_files
+ )
@pytest.mark.asyncio
async def test_forwards_resource_partition_count_as_fallback(self) -> None:
@@ -135,7 +139,9 @@ class TestRunPostLoadDeltaMaintenance:
run_scheduled, _ = await _run_post_load(schema, _make_helper(), resource=resource)
- run_scheduled.assert_awaited_once_with(schema, is_cdc_companion=False, partition_count_fallback=12)
+ run_scheduled.assert_awaited_once_with(
+ schema, is_cdc_companion=False, partition_count_fallback=12, compact_small_files=True
+ )
@pytest.mark.asyncio
async def test_cdc_companion_write_runs_companion_maintenance(self):
@@ -146,7 +152,9 @@ class TestRunPostLoadDeltaMaintenance:
run_scheduled, _ = await _run_post_load(schema, _make_helper(), cdc_write_mode="scd2_append")
- run_scheduled.assert_awaited_once_with(schema, is_cdc_companion=True, partition_count_fallback=None)
+ run_scheduled.assert_awaited_once_with(
+ schema, is_cdc_companion=True, partition_count_fallback=None, compact_small_files=False
+ )
@parameterized.expand([("non_cdc", False), ("cdc", True)])
@pytest.mark.asyncio
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/maintenance.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/maintenance.py
index 2c0e81aa7b6b..79a5a204ee17 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/maintenance.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/maintenance.py
@@ -1,6 +1,8 @@
import json
import asyncio
import datetime as dt
+from collections import defaultdict
+from collections.abc import Iterable
from typing import TYPE_CHECKING, Any
from django.conf import settings
@@ -9,6 +11,7 @@ import deltalake
import posthoganalytics
import deltalake.exceptions
+from posthog.dataclasses import frozen
from posthog.exceptions_capture import capture_exception
from posthog.sync import database_sync_to_async_pool
from posthog.utils import get_machine_id
@@ -49,6 +52,14 @@ if TYPE_CHECKING:
DEFAULT_COMPACT_FILES_PER_PARTITION_THRESHOLD = 200
DEFAULT_COMPACT_TOTAL_FILES_THRESHOLD = 5000
+# Post-load triggers on the files a compaction would remove (see `removable_file_count`). The
+# averages above cannot see an incremental table's newest partition, because its older partitions
+# keep the average near one file each. The table-wide trigger covers partitions that each keep a few,
+# and only runs when the vacuum is due: an md5 table gets a small file in every bucket on each sync,
+# so a table-wide count checked on every sync would compact the whole table every time.
+DEFAULT_COMPACT_REMOVABLE_FILES_PER_PARTITION_THRESHOLD = 8
+DEFAULT_COMPACT_REMOVABLE_FILES_THRESHOLD = 100
+
# delta-rs's own default target size for a compaction rewrite bin when none is given (see
# `delta.targetFileSize`, or 100MB absent that table property). Starting the retry ladder here
# instead of passing None keeps every attempt's size explicit and halvable.
@@ -64,6 +75,42 @@ COMPACT_OFFSET_OVERFLOW_RETRIES = 3
VACUUM_RETENTION = dt.timedelta(hours=24)
+def removable_file_count(file_sizes: Iterable[int]) -> int:
+ """The fewest files a compaction is sure to remove from one partition, given the sizes of its files.
+
+ delta-rs keeps a partition's files in their original order and packs neighbours into bins up to the
+ target size. A file at or above the target splits the run around it, and a bin with one file is
+ skipped. The log's file sizes do not show that order, so this assumes the worst case: every file of
+ at least half the target separates the small files around it. A compaction usually writes files of
+ that size, so they must not count as small. Inside a run, every bin but the last is more than half
+ full, because the next small file did not fit. A count above zero therefore always means a
+ compaction that removes files, and a layout that compaction cannot improve never starts one.
+ """
+ sizes = list(file_sizes)
+ small = [size for size in sizes if size < DEFAULT_COMPACT_TARGET_SIZE_BYTES // 2]
+ runs = len(sizes) - len(small) + 1
+ output_files = runs + 2 * sum(small) // DEFAULT_COMPACT_TARGET_SIZE_BYTES
+ return max(0, len(small) - output_files)
+
+
+@frozen
+class _PartitionFileStats:
+ size_bytes: int
+ removable_files: int
+
+
+def _partition_file_stats(table: deltalake.DeltaTable) -> list[_PartitionFileStats]:
+ """Stats for each partition, read from the Delta log with no S3 request."""
+ # Each partition value is one directory, and an unpartitioned table keeps its files at the root.
+ sizes: defaultdict[str, list[int]] = defaultdict(list)
+ for path, size in table._table.get_add_file_sizes().items():
+ sizes[path.rpartition("/")[0]].append(size or 0)
+ return [
+ _PartitionFileStats(size_bytes=sum(partition_sizes), removable_files=removable_file_count(partition_sizes))
+ for partition_sizes in sizes.values()
+ ]
+
+
class DeltaMaintenance:
"""Compaction, vacuuming, and the vacuum-watermark cadence for one schema's Delta table.
@@ -121,6 +168,13 @@ class DeltaMaintenance:
)
await self._logger.adebug(json.dumps(compact_stats))
+ async def _vacuum_due(self, last_vacuum_version: int | None, commit_threshold: int) -> bool:
+ # The same cadence `vacuum_if_stale` applies. An unseeded watermark is never due.
+ table = await self._table.get_delta_table()
+ if table is None or last_vacuum_version is None:
+ return False
+ return await asyncio.to_thread(table.version) - last_vacuum_version >= commit_threshold
+
async def vacuum_if_stale(self, last_vacuum_version: int | None, commit_threshold: int) -> int | None:
"""Vacuum tombstoned files once enough commits have accrued since the last vacuum.
@@ -182,6 +236,8 @@ class DeltaMaintenance:
partition_count: int | None,
threshold: int = DEFAULT_COMPACT_FILES_PER_PARTITION_THRESHOLD,
total_threshold: int = DEFAULT_COMPACT_TOTAL_FILES_THRESHOLD,
+ compact_small_files: bool = False,
+ table_wide_small_files: bool = False,
) -> bool:
"""Run compact + vacuum if the table is fragmented past either threshold.
@@ -191,6 +247,14 @@ class DeltaMaintenance:
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.
+ `compact_small_files` adds the removable-file triggers (see
+ `DEFAULT_COMPACT_REMOVABLE_FILES_PER_PARTITION_THRESHOLD`), plus a trigger for any
+ partition over the repartition budget that compaction can shrink. Only the non-CDC
+ post-load pass sets it. The pre-write pass is a backstop for a table that arrived
+ fragmented, and a CDC final lands every tick, so these triggers would compact a CDC table
+ every few ticks. `table_wide_small_files` also enables the table-wide removable-file
+ trigger, which `run_maintenance` sets only when the vacuum is due.
+
When `partition_count` is None it is derived from the table's actual layout (the
distinct file directories in the delta log, no extra I/O) — only md5 partitioning
persists a count on the schema, so datetime/numerical-partitioned tables always
@@ -222,6 +286,26 @@ class DeltaMaintenance:
f"files_per_partition={files_per_partition:.1f}, threshold={threshold}, "
f"total_threshold={total_threshold}"
)
+ if compact_small_files and not fragmented:
+ partitions = await asyncio.to_thread(_partition_file_stats, table)
+ max_removable = max((partition.removable_files for partition in partitions), default=0)
+ total_removable = sum(partition.removable_files for partition in partitions)
+ # Repartition detection runs after this pass and compares partition bytes to its budget.
+ # Small files take more bytes at rest than the same rows after compaction, so an
+ # over-budget partition that compaction can shrink must be compacted before it is measured.
+ budget = settings.DATA_WAREHOUSE_TARGET_PARTITION_BYTES
+ compactable_over_budget = any(
+ partition.size_bytes > budget and partition.removable_files > 0 for partition in partitions
+ )
+ fragmented = (
+ max_removable >= DEFAULT_COMPACT_REMOVABLE_FILES_PER_PARTITION_THRESHOLD
+ or (table_wide_small_files and total_removable >= DEFAULT_COMPACT_REMOVABLE_FILES_THRESHOLD)
+ or compactable_over_budget
+ )
+ stats += (
+ f", max_removable_files_per_partition={max_removable}, removable_files={total_removable}, "
+ f"compactable_over_budget={compactable_over_budget}"
+ )
if not fragmented:
await self._logger.adebug(f"compact_if_fragmented: skipping ({stats})")
return False
@@ -236,6 +320,7 @@ class DeltaMaintenance:
partition_count: int | None,
last_vacuum_version: int | None,
commit_threshold: int,
+ compact_small_files: bool = False,
) -> int | None:
"""Single threshold-maintenance step: compact if fragmented, else vacuum on commit cadence.
@@ -246,7 +331,12 @@ class DeltaMaintenance:
fall through to `vacuum_if_stale`. Returns the single delta version to persist as the new
`last_vacuum_version` watermark, or None when nothing changed — `run_scheduled` persists it.
"""
- compacted = await self.compact_if_fragmented(partition_count=partition_count)
+ compacted = await self.compact_if_fragmented(
+ partition_count=partition_count,
+ compact_small_files=compact_small_files,
+ table_wide_small_files=compact_small_files
+ and await self._vacuum_due(last_vacuum_version, commit_threshold),
+ )
if compacted:
table = await self._table.get_delta_table()
if table is None:
@@ -262,6 +352,7 @@ class DeltaMaintenance:
*,
is_cdc_companion: bool = False,
partition_count_fallback: int | None = None,
+ compact_small_files: bool = False,
) -> None:
"""Best-effort threshold maintenance owning the vacuum-watermark lifecycle for `schema`.
@@ -302,6 +393,7 @@ class DeltaMaintenance:
partition_count=partition_count,
last_vacuum_version=last_vacuum_version,
commit_threshold=settings.DATA_WAREHOUSE_VACUUM_COMMIT_THRESHOLD,
+ compact_small_files=compact_small_files,
)
if new_version is not None and new_version != last_vacuum_version:
await database_sync_to_async_pool(update_sync_type_config_keys)(
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/test/test_maintenance.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/test/test_maintenance.py
index e0e4430ce526..8d7f24ccb833 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/test/test_maintenance.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/test/test_maintenance.py
@@ -1,6 +1,12 @@
+import os
+import tempfile
+
import pytest
from unittest.mock import AsyncMock, MagicMock, patch
+from django.test import override_settings
+
+import pyarrow as pa
import deltalake
from parameterized import parameterized
@@ -14,9 +20,18 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.del
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.test.helpers import make_logger
_MAINTENANCE_MODULE = "products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.maintenance"
+_MB = 1024 * 1024
+# Small enough that a local table can hold files above the compaction target.
+_SMALL_TARGET = 100_000
+
+def _append_file(path: str, row_id: int, payload_bytes: int) -> None:
+ # Random hex keeps each file about as large as its payload, because parquet cannot compress it much.
+ blob = os.urandom(payload_bytes).hex()[:payload_bytes]
+ deltalake.write_deltalake(path, pa.table({"id": [row_id], "blob": [blob]}), mode="append")
-def _make_maintenance(delta_table: MagicMock | None) -> DeltaMaintenance:
+
+def _make_maintenance(delta_table: deltalake.DeltaTable | MagicMock | None) -> DeltaMaintenance:
table_ref = MagicMock()
table_ref.logger = make_logger()
table_ref.get_delta_table = AsyncMock(return_value=delta_table)
@@ -129,6 +144,93 @@ class TestCompactIfFragmented:
mock_compact.assert_not_called()
mock_vacuum.assert_not_called()
+ # (case_name, layout as [(partitions, file sizes in each)], compact_small_files, table_wide_small_files,
+ # expected_ran)
+ _SMALL_FILE_CASES: list[tuple[str, list[tuple[int, list[int]]], bool, bool, bool]] = [
+ # An incremental datetime table: every sync lands in the newest partition, and 600 cold
+ # partitions hold the average near one file per partition, so the averages never fire.
+ ("hot_partition_fires", [(600, [60 * _MB]), (1, [_MB] * 9)], True, False, True),
+ # The pre-write pass and CDC tables keep the average-only thresholds.
+ ("hot_partition_ignored_without_small_file_triggers", [(600, [60 * _MB]), (1, [_MB] * 9)], False, False, False),
+ ("hot_partition_below_threshold_skips", [(600, [60 * _MB]), (1, [_MB] * 8)], True, False, False),
+ # Compaction writes files between half and the whole target, and delta-rs cannot pair two of
+ # them into one bin. Counting them would start a compaction that does nothing on every sync.
+ ("compaction_output_never_counts", [(600, [60 * _MB]), (1, [60 * _MB] * 20)], True, True, False),
+ # A cold tail of partitions with a few small files each, which no single partition reveals.
+ ("cold_tail_fires", [(100, [_MB] * 2)], True, True, True),
+ ("cold_tail_below_threshold_skips", [(99, [_MB] * 2)], True, True, False),
+ # md5 hashes new rows into every bucket, so each sync adds a small file to each one. Checked on
+ # every sync, the table-wide count would compact the whole table every time.
+ ("every_partition_grows_waits_for_table_wide_check", [(150, [20 * _MB, _MB])], True, False, False),
+ # Repartition detection measures right after this pass, so a partition that its small files
+ # push over the budget must compact even below the removable thresholds, or it gets split.
+ ("over_budget_partition_fires", [(1, [90 * _MB] * 6 + [_MB] * 10)], True, False, True),
+ ("same_files_under_budget_skip", [(1, [90 * _MB] * 4 + [_MB] * 10)], True, False, False),
+ ]
+
+ @parameterized.expand(_SMALL_FILE_CASES)
+ @pytest.mark.asyncio
+ async def test_small_file_threshold(
+ self,
+ _name: str,
+ layout: list[tuple[int, list[int]]],
+ compact_small_files: bool,
+ table_wide_small_files: bool,
+ expected_ran: bool,
+ ):
+ file_sizes = {
+ f"_ph_partition_key={group}-{partition}/f{i}.parquet": size
+ for group, (partitions, sizes) in enumerate(layout)
+ for partition in range(partitions)
+ for i, size in enumerate(sizes)
+ }
+ mock_delta = MagicMock()
+ mock_delta.file_uris = MagicMock(return_value=[f"s3://bucket/table/{path}" for path in file_sizes])
+ mock_delta._table.get_add_file_sizes = MagicMock(return_value=file_sizes)
+ maintenance = _make_maintenance(mock_delta)
+ with (
+ override_settings(DATA_WAREHOUSE_TARGET_PARTITION_BYTES=500 * _MB),
+ patch.object(maintenance, "_compact", AsyncMock()) as mock_compact,
+ patch.object(maintenance, "_vacuum", AsyncMock()),
+ ):
+ ran = await maintenance.compact_if_fragmented(
+ partition_count=None,
+ compact_small_files=compact_small_files,
+ table_wide_small_files=table_wide_small_files,
+ )
+
+ assert ran is expected_ran
+ assert mock_compact.await_count == (1 if expected_ran else 0)
+
+ @parameterized.expand(
+ [
+ ("adjacent_small_files_compact", False, True),
+ # delta-rs merges only neighbouring files, and a file over the target splits them. A trigger
+ # that counted these small files would start a compaction that removes nothing on every sync.
+ ("small_files_between_oversized_files_skip", True, False),
+ ]
+ )
+ @pytest.mark.asyncio
+ async def test_small_file_trigger_on_a_real_table(self, _name: str, interleave_oversized: bool, expected_ran: bool):
+ with (
+ tempfile.TemporaryDirectory() as path,
+ patch(f"{_MAINTENANCE_MODULE}.DEFAULT_COMPACT_TARGET_SIZE_BYTES", _SMALL_TARGET),
+ ):
+ for i in range(12):
+ _append_file(path, i, payload_bytes=500)
+ if interleave_oversized:
+ _append_file(path, 100 + i, payload_bytes=2 * _SMALL_TARGET)
+ table = deltalake.DeltaTable(path)
+ files_before = len(table.file_uris())
+ rows_before = table.to_pyarrow_table().num_rows
+
+ ran = await _make_maintenance(table).compact_if_fragmented(partition_count=None, compact_small_files=True)
+
+ assert ran is expected_ran
+ files_after = len(table.file_uris())
+ assert (files_after < files_before) is expected_ran
+ assert table.to_pyarrow_table().num_rows == rows_before
+
class TestCompactConflictRetry:
@pytest.mark.asyncio
@@ -301,6 +403,37 @@ class TestRunMaintenance:
assert result == 150
vacuum_if_stale.assert_awaited_once_with(40, 100)
+ @parameterized.expand(
+ [
+ # (name, compact_small_files, last_vacuum_version, expected_table_wide) at version 200 with a
+ # 100-commit cadence. 150 commits since the last vacuum is due, 50 is not, and a watermark that
+ # was never seeded is never due.
+ ("vacuum_due", True, 50, True),
+ ("vacuum_not_due", True, 150, False),
+ ("watermark_not_seeded", True, None, False),
+ ("small_file_triggers_off", False, 50, False),
+ ]
+ )
+ @pytest.mark.asyncio
+ async def test_table_wide_small_file_trigger_follows_the_vacuum_cadence(
+ self, _name: str, compact_small_files: bool, last_vacuum_version: int | None, expected_table_wide: bool
+ ):
+ maintenance = _make_maintenance(MagicMock(version=MagicMock(return_value=200)))
+ with (
+ patch.object(maintenance, "compact_if_fragmented", new=AsyncMock(return_value=False)) as compact,
+ patch.object(maintenance, "vacuum_if_stale", new=AsyncMock(return_value=None)),
+ ):
+ await maintenance.run_maintenance(
+ partition_count=10,
+ last_vacuum_version=last_vacuum_version,
+ commit_threshold=100,
+ compact_small_files=compact_small_files,
+ )
+
+ assert compact.await_args is not None
+ assert compact.await_args.kwargs["compact_small_files"] is compact_small_files
+ assert compact.await_args.kwargs["table_wide_small_files"] is expected_table_wide
+
class TestRunScheduled:
"""run_scheduled owns the vacuum-watermark lifecycle for both call sites (pre-write defensive
@@ -322,6 +455,7 @@ class TestRunScheduled:
run_maintenance_result: int | None | Exception = None,
is_cdc_companion: bool = False,
partition_count_fallback: int | None = None,
+ compact_small_files: bool = False,
) -> tuple[AsyncMock, MagicMock, MagicMock]:
run_maintenance = (
AsyncMock(side_effect=run_maintenance_result)
@@ -335,10 +469,25 @@ class TestRunScheduled:
patch(f"{_MAINTENANCE_MODULE}.capture_exception") as capture,
):
await maintenance.run_scheduled(
- schema, is_cdc_companion=is_cdc_companion, partition_count_fallback=partition_count_fallback
+ schema,
+ is_cdc_companion=is_cdc_companion,
+ partition_count_fallback=partition_count_fallback,
+ compact_small_files=compact_small_files,
)
return run_maintenance, update_config, capture
+ @parameterized.expand([("on", True), ("off", False)])
+ @pytest.mark.asyncio
+ async def test_forwards_small_file_triggers(self, _name: str, compact_small_files: bool):
+ # Only the non-CDC post-load pass turns these triggers on, so a dropped pass-through here turns
+ # them off for every table while every caller-side test stays green.
+ run_maintenance, _, _ = await self._run(
+ _make_maintenance(MagicMock()), self._schema(), compact_small_files=compact_small_files
+ )
+
+ assert run_maintenance.await_args is not None
+ assert run_maintenance.await_args.kwargs["compact_small_files"] is compact_small_files
+
@parameterized.expand(
[
# (name, is_cdc_companion, schema_partition_count, fallback, expected_count, expected_last, expected_key)