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): derive partition count in compact threshold check (#70549)

Daniel RC7333cfa6de22
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.py
index f9c21df0002d..8e69fecf45c4 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
@@ -803,6 +803,11 @@ class DeltaTableHelper:
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.
+ 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
+ arrive here with None.
+
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
@@ -814,6 +819,11 @@ class DeltaTableHelper:
file_uris = await self.get_file_uris()
total_files = len(file_uris)
+ if partition_count is None:
+ # One directory per partition value; unpartitioned tables collapse to the single
+ # table root. Without this, a partitioned table with no persisted count reads as
+ # one giant partition and trips the per-partition threshold on every run.
+ partition_count = len({uri.rsplit("/", 1)[0] for uri in 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
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.py
index 424ca9520f85..24c15ce62fdb 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
@@ -228,7 +228,7 @@ class TestCompactIfFragmented:
("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
+ # partition_count=None on an unpartitioned layout derives 1 partition; 250 fpp >> 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),
@@ -253,9 +253,10 @@ class TestCompactIfFragmented:
):
helper = DeltaTableHelper(resource_name="t", job=MagicMock(), logger=_make_logger())
mock_delta = MagicMock()
+ file_uris = [f"s3://bucket/table/f{i}.parquet" for i in range(file_count)]
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, "get_file_uris", AsyncMock(return_value=file_uris)),
patch.object(helper, "compact_table", AsyncMock()) as mock_compact,
):
kwargs: dict = {"partition_count": partition_count}
@@ -269,6 +270,43 @@ class TestCompactIfFragmented:
else:
mock_compact.assert_not_called()
+ # (case_name, files_per_dir, dir_count, expected_ran)
+ _DERIVATION_CASES: list[tuple[str, int, int, bool]] = [
+ # 300 files / 3 derived partitions = 100 fpp < 200 and total < 5,000 -> skip.
+ # Before derivation, None meant 1 partition (300 fpp) and this healthy table
+ # compacted on every run.
+ ("healthy_partitioned_table_skips", 100, 3, False),
+ # Genuinely fragmented per partition: 750/3 = 250 fpp > 200 -> still fires.
+ ("fragmented_partitioned_table_fires", 250, 3, True),
+ ]
+
+ @parameterized.expand(_DERIVATION_CASES)
+ @pytest.mark.asyncio
+ async def test_partition_count_derived_from_layout(
+ self, _name: str, files_per_dir: int, dir_count: int, expected_ran: bool
+ ):
+ # Only md5 partitioning persists a partition_count; datetime/numerical schemas pass
+ # None. The count must come from the layout or every >200-file partitioned table
+ # would defensively compact at the start of every sync run.
+ helper = DeltaTableHelper(resource_name="t", job=MagicMock(), logger=_make_logger())
+ file_uris = [
+ f"s3://bucket/table/_ph_partition_key={d}/f{i}.parquet"
+ for d in range(dir_count)
+ for i in range(files_per_dir)
+ ]
+ with (
+ patch.object(helper, "get_delta_table", AsyncMock(return_value=MagicMock())),
+ patch.object(helper, "get_file_uris", AsyncMock(return_value=file_uris)),
+ patch.object(helper, "compact_table", AsyncMock()) as mock_compact,
+ ):
+ ran = await helper.compact_if_fragmented(partition_count=None)
+
+ assert ran is expected_ran
+ if expected_ran:
+ mock_compact.assert_called_once()
+ else:
+ mock_compact.assert_not_called()
+
class TestGetDeltaTableUnrecoverableErrors:
# (case_name, error_message, expect_heal) — heal = wipe the table and fall back to first-sync mode