: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): stop futile compactions and leaking vacuums (#111499)
Tom Owers56da4a54034e
diff --git a/posthog/settings/data_warehouse.py b/posthog/settings/data_warehouse.pyindex e4b323e1a4c0..8bb07c758ac3 100644--- a/posthog/settings/data_warehouse.py+++ b/posthog/settings/data_warehouse.py@@ -114,6 +114,17 @@ DATA_WAREHOUSE_COARSEN_BLOCK_MERGE_PEAK_BYTES = get_from_env(# merge success so tables that OOM their merge still get their tombstones cleared (the compact-after-merge# 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)+# A lite vacuum also runs once this many hours have passed since the last vacuum, whatever the commit+# count. A checkpoint drops tombstones older than delta's 7-day `deletedFileRetentionDuration`, and a lite+# vacuum cannot find a dead file without its tombstone. This interval plus the 24-hour vacuum retention+# must stay below 7 days, so a table that commits slowly does not leak its dead files.+DATA_WAREHOUSE_VACUUM_MAX_INTERVAL_HOURS = get_from_env("DATA_WAREHOUSE_VACUUM_MAX_INTERVAL_HOURS", 120, type_cast=int)+# A full vacuum lists the whole table and deletes the files that the log does not name, with the same+# 24-hour retention. It collects the files that a lite vacuum never finds: files that a crashed writer+# left, and files whose tombstone a checkpoint dropped.+DATA_WAREHOUSE_FULL_VACUUM_INTERVAL_HOURS = get_from_env(+ "DATA_WAREHOUSE_FULL_VACUUM_INTERVAL_HOURS", 168, 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-rsdiff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/load.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/load.pyindex fba22fb48aec..50eb937fc30d 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@@ -288,9 +288,10 @@ 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).+ # to compact, and an unconditional compact still lists and plans every file. Vacuum when the+ # commit or time cadence is due, then compact when compaction can remove files; 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(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.pyindex 4e760b0c2d2b..e5e1621ace8a 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@@ -5,14 +5,17 @@ import asyncioimport datetime as dtimport resourcefrom collections import defaultdict-from collections.abc import Iterable-from typing import TYPE_CHECKING, Any+from collections.abc import Callable, Iterable, Mapping+from typing import TYPE_CHECKING, Any, castfrom django.conf import settingsimport deltalake+import pyarrow.fs as pa_fs+import pyarrow.parquet as pqimport posthoganalyticsimport deltalake.exceptions+from deltalake.fs import DeltaStorageHandlerfrom posthog.dataclasses import frozenfrom posthog.exceptions_capture import capture_exception@@ -56,6 +59,10 @@ if TYPE_CHECKING:# 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.#+# Either count only starts a compaction when compaction can remove enough files (see+# `_count_trigger_can_compact`). A table with one file in each of many partitions stays over the+# total-files bar after any compaction.+## Tune further once the admin fragmentation view gives per-customer distributions.DEFAULT_COMPACT_FILES_PER_PARTITION_THRESHOLD = 200DEFAULT_COMPACT_TOTAL_FILES_THRESHOLD = 5000@@ -81,7 +88,8 @@ COMPACT_OFFSET_OVERFLOW_RETRIES = 3# bin of highly compressible text (JSON documents, say) can decode to many times its target size.# Keep one bin's decoded bytes at half the 2 GiB Arrow offset limit, and inside the load slot the# compaction runs in. A running task holds its bin's decoded batches plus the writer's buffers for-# the file it produces, so it is budgeted at twice the decoded bin.+# the file it produces, so it is budgeted at twice the decoded bin. delta-rs also leaves every file larger+# than the target out of the bins, so the target bounds the largest file that a compaction decodes.COMPACT_MAX_DECODED_BIN_BYTES = 1024 * 1024 * 1024COMPACT_MIN_TARGET_SIZE_BYTES = 8 * 1024 * 1024_COMPACT_TASK_MEMORY_FACTOR = 2@@ -137,22 +145,24 @@ def plan_compaction(compression_ratio: float | None, slot_budget_mb: float | Nondef _sample_compression_ratio(table: deltalake.DeltaTable) -> float | None:- """Decoded bytes per stored byte, from the footers of the table's largest files, or None if unreadable."""+ """Decoded bytes per stored byte, from the footers of the table's largest files, or None if unreadable.++ Reads the sampled footers directly. `to_pyarrow_dataset` builds a fragment for every live file+ first, which costs seconds and a gigabyte of memory on a table with ten thousand files.+ """sizes = table._table.get_add_file_sizes()- by_size = sorted(sizes.items(), key=lambda item: -(item[1] or 0))[:_COMPACT_RATIO_SAMPLE_FILES]- largest = {path.rpartition("/")[2] for path, _ in by_size}- decoded = stored = sampled = 0- for fragment in table.to_pyarrow_dataset().get_fragments():- if sampled >= _COMPACT_RATIO_SAMPLE_FILES:- break- if fragment.path.rpartition("/")[2] not in largest:- continue- metadata = fragment.metadata+ largest = dict(sorted(sizes.items(), key=lambda item: -(item[1] or 0))[:_COMPACT_RATIO_SAMPLE_FILES])+ if not largest:+ return None+ handler = DeltaStorageHandler.from_table(table._table, table._storage_options, largest)+ filesystem = pa_fs.PyFileSystem(cast(pa_fs.FileSystemHandler, handler))+ decoded = stored = 0+ for path in largest:+ metadata = pq.read_metadata(path, filesystem=filesystem)for index in range(metadata.num_row_groups):row_group = metadata.row_group(index)decoded += row_group.total_byte_sizestored += sum(row_group.column(column).total_compressed_size for column in range(row_group.num_columns))- sampled += 1return decoded / stored if stored else None@@ -166,6 +176,12 @@ def _peak_rss_mb() -> float:# warehouse-parent reader, which derives its bound from this value.VACUUM_RETENTION = dt.timedelta(hours=24)+# A checkpoint drops tombstones older than `delta.deletedFileRetentionDuration` (delta's default,+# which these tables keep). A lite vacuum finds dead files only through tombstones, so a file whose+# tombstone was dropped before a vacuum ran is never deleted. A vacuum must run within this window,+# less the retention, after each tombstone.+DELTA_DELETED_FILE_RETENTION = dt.timedelta(days=7)+def removable_file_count(file_sizes: Iterable[int], target_size: int = DEFAULT_COMPACT_TARGET_SIZE_BYTES) -> int:"""The fewest files a compaction is sure to remove from one partition, given the sizes of its files.@@ -239,6 +255,141 @@ def _small_file_fragmentation()+def _count_trigger_can_compact(small_files: _SmallFileFragmentation) -> bool:+ # The count triggers exist to lower the file count, so they need a compaction that removes files+ # in quantity. The table-wide count always applies here: the table is already over a count bar.+ return (+ small_files.max_removable >= DEFAULT_COMPACT_REMOVABLE_FILES_PER_PARTITION_THRESHOLD+ or small_files.total_removable >= DEFAULT_COMPACT_REMOVABLE_FILES_THRESHOLD+ )+++@frozen+class VacuumCadence:+ commit_threshold: int+ max_interval: dt.timedelta+ full_interval: dt.timedelta++ @classmethod+ def from_settings(cls) -> "VacuumCadence":+ return cls(+ commit_threshold=settings.DATA_WAREHOUSE_VACUUM_COMMIT_THRESHOLD,+ max_interval=dt.timedelta(hours=settings.DATA_WAREHOUSE_VACUUM_MAX_INTERVAL_HOURS),+ full_interval=dt.timedelta(hours=settings.DATA_WAREHOUSE_FULL_VACUUM_INTERVAL_HOURS),+ )+++@frozen+class _VacuumConfigKeys:+ version: str+ vacuumed_at: str+ full_vacuumed_at: str+++@frozen+class VacuumWatermarks:+ """The vacuum cadence state of one Delta table, persisted in the schema's `sync_type_config`.++ One schema can back two Delta tables (the snapshot and its `_cdc` companion). Their versions are+ unrelated numbers, so each table keeps its own keys.+ """++ version: int | None+ vacuumed_at: dt.datetime | None+ full_vacuumed_at: dt.datetime | None++ @staticmethod+ def _keys(is_cdc_companion: bool) -> _VacuumConfigKeys:+ suffix = "_cdc" if is_cdc_companion else ""+ return _VacuumConfigKeys(+ version=f"last_vacuum_version{suffix}",+ vacuumed_at=f"last_vacuum_at{suffix}",+ full_vacuumed_at=f"last_full_vacuum_at{suffix}",+ )++ @classmethod+ def from_config(cls, config: Mapping[str, Any] | None, is_cdc_companion: bool) -> "VacuumWatermarks":+ keys = cls._keys(is_cdc_companion)+ config = config or {}+ return cls(+ version=config.get(keys.version),+ vacuumed_at=_parse_timestamp(config.get(keys.vacuumed_at)),+ full_vacuumed_at=_parse_timestamp(config.get(keys.full_vacuumed_at)),+ )++ def config_updates(self, previous: "VacuumWatermarks", is_cdc_companion: bool) -> dict[str, Any]:+ keys = self._keys(is_cdc_companion)+ updates: dict[str, Any] = {}+ if self.version is not None and self.version != previous.version:+ updates[keys.version] = self.version+ if self.vacuumed_at is not None and self.vacuumed_at != previous.vacuumed_at:+ updates[keys.vacuumed_at] = self.vacuumed_at.isoformat()+ if self.full_vacuumed_at is not None and self.full_vacuumed_at != previous.full_vacuumed_at:+ updates[keys.full_vacuumed_at] = self.full_vacuumed_at.isoformat()+ return updates+++def _parse_timestamp(value: Any) -> dt.datetime | None:+ if not isinstance(value, str):+ return None+ try:+ parsed = dt.datetime.fromisoformat(value)+ except ValueError:+ return None+ return parsed if parsed.tzinfo is not None else parsed.replace(tzinfo=dt.UTC)+++@frozen+class VacuumDecision:+ # None when no vacuum is due. Otherwise "full", "commits" or "time".+ reason: str | None+ commits_since_vacuum: int+ # The watermarks with every missing or stale value seeded, whether a vacuum runs or not.+ watermarks: VacuumWatermarks++ @property+ def full(self) -> bool:+ return self.reason == "full"+++def decide_vacuum(+ watermarks: VacuumWatermarks, cadence: VacuumCadence, version: int, now: dt.datetime+) -> VacuumDecision:+ """Which vacuum, if any, this pass runs.++ A missing watermark is seeded without a vacuum, so the tables that existed before a watermark do+ not all vacuum at the same time after a deploy. A version above the table's current version means+ the table was recreated (delta versions are monotonic within one incarnation), and no reset path+ clears the persisted watermark. Left alone, it would block the commit cadence until the new table+ out-versioned the old one, so it is seeded again.++ The commit cadence alone lets a table that commits slowly go past the tombstone window (see+ `DELTA_DELETED_FILE_RETENTION`), so a lite vacuum also runs when `max_interval` has passed. A lite+ vacuum never finds files that no tombstone names: files a crashed writer left, or files whose+ tombstone was dropped. A full vacuum lists the table instead, and runs once each `full_interval`.+ A full vacuum also deletes everything that a lite vacuum deletes, so it replaces a lite one.+ """+ version_stale = watermarks.version is None or version < watermarks.version+ seeded = VacuumWatermarks(+ version=version if version_stale else watermarks.version,+ vacuumed_at=watermarks.vacuumed_at or now,+ full_vacuumed_at=watermarks.full_vacuumed_at or now,+ )+ reason = None+ if watermarks.full_vacuumed_at is not None and now - watermarks.full_vacuumed_at >= cadence.full_interval:+ reason = "full"+ elif watermarks.version is not None and not version_stale:+ if version - watermarks.version >= cadence.commit_threshold:+ reason = "commits"+ if reason is None and watermarks.vacuumed_at is not None and now - watermarks.vacuumed_at >= cadence.max_interval:+ reason = "time"+ return VacuumDecision(reason=reason, commits_since_vacuum=version - (seeded.version or 0), watermarks=seeded)+++def _utc_now() -> dt.datetime:+ return dt.datetime.now(dt.UTC)++class DeltaMaintenance:"""Compaction, vacuuming, and the vacuum-watermark cadence for one schema's Delta table.@@ -248,13 +399,14 @@ class DeltaMaintenance:cleans up before adding to the pile) and the post-load pass."""- def __init__(self, table: "DeltaTableRef") -> None:+ def __init__(self, table: "DeltaTableRef", *, clock: Callable[[], dt.datetime] = _utc_now) -> None:self._table = tableself._logger = table.logger+ self._clock = clock@recorded_phase("vacuum")- async def _vacuum(self, table: deltalake.DeltaTable) -> None:- await self._logger.adebug("Vacuuming table...")+ async def _vacuum(self, table: deltalake.DeltaTable, *, full: bool = False) -> int:+ await self._logger.adebug("Vacuuming table...", vacuum_full=full)# vacuum() commits a REMOVE of tombstoned files, so it's just as subject to delta-rs's# conflict checker as merge/optimize.compact — see execute_with_conflict_retry.vacuum_stats = await execute_with_conflict_retry(@@ -263,12 +415,14 @@ class DeltaMaintenance:retention_hours=int(VACUUM_RETENTION.total_seconds() // 3600),enforce_retention_duration=False,dry_run=False,+ full=full,),"vacuum_table",self._logger,)note_post_load_phase(files_deleted=len(vacuum_stats) if isinstance(vacuum_stats, list) else None)await self._logger.adebug(json.dumps(vacuum_stats))+ return len(vacuum_stats) if isinstance(vacuum_stats, list) else 0async def _plan_compaction(self, table: deltalake.DeltaTable) -> CompactionPlan:try:@@ -342,50 +496,31 @@ class DeltaMaintenance:await self._logger.adebug(json.dumps(compact_stats))return True- 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.+ async def vacuum_if_due(self, watermarks: VacuumWatermarks, cadence: VacuumCadence) -> VacuumDecision | None:+ """Vacuum when the cadence says so (see `decide_vacuum`), and return the decision.Decoupled from merge success (called pre-write) so a table that OOMs its merge every run still- gets cleaned — the post-load compaction never runs for it, which is how tables reach ~99% dead- files. Vacuum only deletes dead files (an S3 LIST + delete), so unlike `compact_if_fragmented`'s- `optimize.compact` (which rewrites partitions) it is memory-safe even on an oversized table.-- Uses the delta version (commit count) as a cheap proxy for tombstone accumulation — no S3 LIST to- decide. Returns the current version to persist as the new watermark when it vacuumed, on first- encounter, or when the table was recreated (both reseed the watermark without vacuuming);- None when nothing changed.+ gets cleaned. Vacuum only deletes dead files (an S3 LIST + delete), so unlike+ `compact_if_fragmented`'s `optimize.compact` (which rewrites partitions) it is memory-safe even+ on an oversized table. The cadence needs no S3 request to decide. The returned watermarks are+ the ones to persist; None means the table does not exist."""table = await self._table.get_delta_table()if table is None:return Noneversion = await asyncio.to_thread(table.version)- if last_vacuum_version is None or version < last_vacuum_version:- # First encounter: seed the watermark without vacuuming so existing tables clean up gradually- # over the next `commit_threshold` commits rather than all vacuuming at once on deploy.- # A version below the watermark means the table was reset/recreated (delta versions are- # monotonic within one incarnation) and no reset path clears the persisted watermark —- # left alone it would block the cadence until the new table out-versioned the old one.- return version-- commits_since = version - last_vacuum_version- if commits_since < commit_threshold:- await self._logger.adebug(- f"vacuum_if_stale: skipping, {commits_since} commits since last vacuum (< {commit_threshold})"- )- return None+ now = self._clock()+ decision = decide_vacuum(watermarks, cadence, version, now)+ if decision.reason is None:+ await self._logger.adebug(f"vacuum: not due, {decision.commits_since_vacuum} commits since the last vacuum")+ return decision- await self._logger.ainfo(- f"vacuum_if_stale: {commits_since} commits since last vacuum (>= {commit_threshold}), vacuuming"- )- await self._vacuum(table)+ await self._logger.ainfo(f"vacuum: due ({decision.reason}), vacuuming", vacuum_full=decision.full)+ started = time.monotonic()+ files_deleted = await self._vacuum(table, full=decision.full)+ # Vacuum commits its own start and end entries, which must not count towards the next cadence.+ version_after = await asyncio.to_thread(table.version)try:# Observability for the maintenance path — how often tables vacuum and how much log churn# accrued between vacuums. Best-effort: telemetry must never break the sync.@@ -397,13 +532,25 @@ class DeltaMaintenance:"schema_id": str(self._table.job.schema_id),"source_id": str(self._table.job.pipeline_id),"resource_name": self._table.resource_name,- "commits_since_last_vacuum": commits_since,+ "commits_since_last_vacuum": decision.commits_since_vacuum,"delta_version": version,+ "vacuum_reason": decision.reason,+ "vacuum_full": decision.full,+ "files_deleted": files_deleted,+ "duration_s": round(time.monotonic() - started, 2),},)except Exception as e:capture_exception(e)- return version+ return VacuumDecision(+ reason=decision.reason,+ commits_since_vacuum=decision.commits_since_vacuum,+ watermarks=VacuumWatermarks(+ version=version_after,+ vacuumed_at=now,+ full_vacuumed_at=now if decision.full else decision.watermarks.full_vacuumed_at,+ ),+ )async def compact_if_fragmented(self,@@ -413,13 +560,16 @@ class DeltaMaintenance:compact_small_files: bool = False,table_wide_small_files: bool = False,) -> bool:- """Run compact + vacuum if the table is fragmented past either threshold.+ """Compact if the table is fragmented past either count threshold, or has small files to merge.- Fragmented = files-per-partition > `threshold` OR total files > `total_threshold`.+ Count-fragmented = files-per-partition > `threshold` OR total files > `total_threshold`.The total-files backstop matters because delta enumerates every file's metadataduring a merge even when partition pruning skips reading them, so merge planningtime 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.+ tens of thousands of files while staying under the per-partition bar. A count trigger+ compacts only when compaction can remove enough files (see `_count_trigger_can_compact`):+ a table with one file in each of ten thousand partitions stays over the bar after a+ compaction, and would otherwise plan and commit a compaction on every pass.`compact_small_files` adds the removable-file triggers (see`DEFAULT_COMPACT_REMOVABLE_FILES_PER_PARTITION_THRESHOLD`), plus a trigger for any@@ -427,17 +577,19 @@ class DeltaMaintenance:post-load pass sets it. The pre-write pass is a backstop for a table that arrivedfragmented, and a CDC final lands every tick, so these triggers would compact a CDC tableevery few ticks. `table_wide_small_files` also enables the table-wide removable-file- trigger, which `run_maintenance` sets only when the vacuum is due.+ trigger, which `run_scheduled` sets only when a vacuum is due or ran earlier in the same sync.When `partition_count` is None it is derived from the table's actual layout (thedistinct file directories in the delta log, no extra I/O) — only md5 partitioningpersists a count on the schema, so datetime/numerical-partitioned tables alwaysarrive here with None.- Returns True if compaction ran, False if it was skipped. Cheap when the table is- healthy: one S3 LIST via `table.file_uris`. Runs pre-write, so a sync that arrived at a- fragmented state (e.g. an earlier attempt that failed before reaching post-load) cleans up- before adding to the pile, and again post-load once the sync's own files have landed.+ Returns True if compaction ran, False if it was skipped. The decision reads only the+ Delta log. Runs pre-write, so a sync that arrived at a fragmented state (e.g. an earlier+ attempt that failed before reaching post-load) cleans up before adding to the pile, and+ again post-load once the sync's own files have landed. Compaction does not vacuum: the+ files it removes are younger than `VACUUM_RETENTION`, so a vacuum right after it could not+ delete them, and the vacuum cadence collects them later."""table = await self._table.get_delta_table()if table is None:@@ -456,44 +608,44 @@ class DeltaMaintenance:files_per_partition = total_files / effective_partitionscount_fragmented = files_per_partition > threshold or total_files > total_threshold- fragmented = count_fragmentedstats = (f"total_files={total_files}, partitions={effective_partitions}, "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)- # 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.- small_file_stats = _small_file_fragmentation(partitions, table_wide_small_files)- fragmented = small_file_stats.fragmented- stats += (- f", max_removable_files_per_partition={small_file_stats.max_removable}, "- f"removable_files={small_file_stats.total_removable}, "- f"compactable_over_budget={small_file_stats.compactable_over_budget}"- )- if not fragmented:+ if not count_fragmented and not compact_small_files:await self._logger.adebug(f"compact_if_fragmented: skipping ({stats})")return False- if count_fragmented:- await self._logger.ainfo(f"compact_if_fragmented: triggering compact ({stats})")- if not await self._compact(table):- return False- await self._vacuum(table)- return True+ def triggered(small_file_stats: _SmallFileFragmentation) -> bool:+ return (count_fragmented and _count_trigger_can_compact(small_file_stats)) or (+ compact_small_files and small_file_stats.fragmented+ )++ partitions = await asyncio.to_thread(_partition_file_stats, table, DEFAULT_COMPACT_TARGET_SIZE_BYTES)+ # 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.+ small_file_stats = _small_file_fragmentation(partitions, table_wide_small_files)+ stats += (+ f", count_fragmented={count_fragmented}, "+ f"max_removable_files_per_partition={small_file_stats.max_removable}, "+ f"removable_files={small_file_stats.total_removable}, "+ f"compactable_over_budget={small_file_stats.compactable_over_budget}"+ )+ if not triggered(small_file_stats):+ await self._logger.adebug(f"compact_if_fragmented: skipping ({stats})")+ return Falseplan = await self._plan_compaction(table)if plan.target_size is None:await self._compact(table, plan)return False- if compact_small_files:+ if plan.target_size != DEFAULT_COMPACT_TARGET_SIZE_BYTES:+ # A smaller bin can merge fewer of the files, so the trigger must hold at the planned size too.partitions = await asyncio.to_thread(_partition_file_stats, table, plan.target_size)- fragmented = _small_file_fragmentation(partitions, table_wide_small_files).fragmented- if not fragmented:+ if not triggered(_small_file_fragmentation(partitions, table_wide_small_files)):await self._logger.adebug(f"compact_if_fragmented: skipping; no files are removable at planned target_size="f"{plan.target_size} ({stats})"@@ -501,41 +653,17 @@ class DeltaMaintenance:return Falseawait self._logger.ainfo(f"compact_if_fragmented: triggering compact ({stats})")- if not await self._compact(table, plan):- return False- await self._vacuum(table)- return True+ return await self._compact(table, plan)- async def run_maintenance(- self,- 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.-- The two triggers are orthogonal — fragmentation (active file count) vs. commit cadence (tombstone- accrual) — but they share one outcome, the vacuum watermark. `compact_if_fragmented` already- vacuums as part of compaction, so when it runs it supersedes the cadence vacuum (no double vacuum- in one run) and the watermark advances to the post-compaction version. When nothing was fragmented,- 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,- 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:- return None- # Compaction (which vacuumed) added a commit, advancing the version; reset the cadence- # watermark to it so the next vacuum is measured from this cleanup, not the old baseline.- return await asyncio.to_thread(table.version)- return await self.vacuum_if_stale(last_vacuum_version, commit_threshold)+ def _vacuumed_during_job(self, watermarks: VacuumWatermarks) -> bool:+ # The pre-write pass vacuums before it writes, and it never checks small files. The post-load+ # pass of the same sync then sees no vacuum due, but must still run the table-wide check.+ job_started_at = getattr(self._table.job, "created_at", None)+ if watermarks.vacuumed_at is None or not isinstance(job_started_at, dt.datetime):+ return False+ if job_started_at.tzinfo is None:+ job_started_at = job_started_at.replace(tzinfo=dt.UTC)+ return watermarks.vacuumed_at >= job_started_atasync def run_scheduled(self,@@ -547,12 +675,17 @@ class DeltaMaintenance:) -> None:"""Best-effort threshold maintenance owning the vacuum-watermark lifecycle for `schema`.- Reads the right watermark, runs `run_maintenance`, and persists the returned watermark via- `update_sync_type_config_keys` (row-locked merge) — both call sites (the pre-write defensive- pass and the post-load pass) share this, so the watermark can't drift between them.+ Vacuums when the cadence is due (see `decide_vacuum`), persists the watermarks via+ `update_sync_type_config_keys` (row-locked merge), and then compacts if fragmented. Both call+ sites (the pre-write defensive pass and the post-load pass) share this, so the watermarks+ can't drift between them. The persisted keys are also merged into the in-memory schema, so+ the post-load pass of the same sync sees the vacuum that the pre-write pass ran.++ The vacuum runs and persists before the compaction, so a compaction that fails on every+ sync does not stop the vacuum cadence.One schema can back two delta tables (snapshot + `_cdc` companion) whose delta versions are- unrelated numbers, so each table's vacuum cadence gets its own watermark key — sharing one+ unrelated numbers, so each table's vacuum cadence gets its own watermark keys — sharing themwould corrupt both cadences. The companion also ignores `schema.partition_count` (itdescribes the snapshot table); `compact_if_fragmented` derives the companion's count fromits actual layout instead.@@ -567,29 +700,29 @@ class DeltaMaintenance:so a refused pass leaves every live row queryable and costs the table nothing but a delayedcleanup. It is a policy condition on our own bucket rather than a maintenance defect, so areport per sync would say the same thing repeatedly about something no code change fixes.- The watermark is not persisted either, so the cadence re-attempts the vacuum on the next pass- instead of waiting another `commit_threshold` commits for a cleanup that never ran.+ The watermarks are not persisted either, so the cadence re-attempts the vacuum on the next+ pass instead of waiting for a cleanup that never ran."""try:- if is_cdc_companion:- partition_count = None- watermark_key = "last_vacuum_version_cdc"- last_vacuum_version = schema.last_vacuum_version_cdc- else:- partition_count = schema.partition_count or partition_count_fallback- watermark_key = "last_vacuum_version"- last_vacuum_version = schema.last_vacuum_version-- new_version = await self.run_maintenance(+ partition_count = None if is_cdc_companion else (schema.partition_count or partition_count_fallback)+ watermarks = VacuumWatermarks.from_config(schema.sync_type_config, is_cdc_companion)++ decision = await self.vacuum_if_due(watermarks, VacuumCadence.from_settings())+ if decision is None:+ return+ updates = decision.watermarks.config_updates(watermarks, is_cdc_companion)+ if updates:+ await database_sync_to_async_pool(update_sync_type_config_keys)(+ schema.id, schema.team_id, updates=updates+ )+ schema.sync_type_config = {**(schema.sync_type_config or {}), **updates}++ await self.compact_if_fragmented(partition_count=partition_count,- last_vacuum_version=last_vacuum_version,- commit_threshold=settings.DATA_WAREHOUSE_VACUUM_COMMIT_THRESHOLD,compact_small_files=compact_small_files,+ table_wide_small_files=compact_small_files+ and (decision.reason is not None or self._vacuumed_during_job(watermarks)),)- if new_version is not None and new_version != last_vacuum_version:- await database_sync_to_async_pool(update_sync_type_config_keys)(- schema.id, schema.team_id, updates={watermark_key: new_version}- )except ObjectStorePermissionDeniedError:await self._logger.awarning("Delta maintenance skipped: the object store denied the operation")returndiff --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.pyindex 31e517d264b8..d7afcbf1fb66 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,21 +1,33 @@import os+import json+import time+import datetime as dtimport tempfile+from pathlib import Pathimport pytestfrom unittest.mock import AsyncMock, MagicMock, patch+from django.conf import settingsfrom django.test import override_settingsimport pyarrow as paimport deltalake+import pyarrow.parquet as pqfrom parameterized import parameterizedfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.maintenance import (+ _COMPACT_RATIO_SAMPLE_FILES,COMPACT_OFFSET_OVERFLOW_RETRIES,DEFAULT_COMPACT_TARGET_SIZE_BYTES,+ DELTA_DELETED_FILE_RETENTION,+ VACUUM_RETENTION,CompactionPlan,DeltaMaintenance,+ VacuumCadence,+ VacuumWatermarks,_sample_compression_ratio,+ decide_vacuum,plan_compaction,)from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.ops import (@@ -27,6 +39,11 @@ _MAINTENANCE_MODULE = "products.warehouse_sources.backend.temporal.data_imports._MB = 1024 * 1024# Small enough that a local table can hold files above the compaction target._SMALL_TARGET = 100_000+_NOW = dt.datetime(2026, 6, 1, 12, 0, tzinfo=dt.UTC)+_DEFAULT_PLAN = CompactionPlan(+ target_size=DEFAULT_COMPACT_TARGET_SIZE_BYTES, max_concurrent_tasks=1, compression_ratio=1.0, slot_budget_mb=1356.8+)+_CADENCE = VacuumCadence(commit_threshold=100, max_interval=dt.timedelta(days=5), full_interval=dt.timedelta(days=7))def _append_file(path: str, row_id: int, payload_bytes: int) -> None:@@ -35,11 +52,31 @@ def _append_file(path: str, row_id: int, payload_bytes: int) -> None:deltalake.write_deltalake(path, pa.table({"id": [row_id], "blob": [blob]}), mode="append")-def _make_maintenance(delta_table: deltalake.DeltaTable | MagicMock | None) -> DeltaMaintenance:+def _make_maintenance(+ delta_table: deltalake.DeltaTable | MagicMock | None, *, now: dt.datetime = _NOW+) -> DeltaMaintenance:table_ref = MagicMock()table_ref.logger = make_logger()table_ref.get_delta_table = AsyncMock(return_value=delta_table)- return DeltaMaintenance(table_ref)+ table_ref.job.created_at = now - dt.timedelta(minutes=30)+ return DeltaMaintenance(table_ref, clock=lambda: now)+++def _mock_table(file_sizes: dict[str, int], version: int = 150) -> MagicMock:+ table = MagicMock()+ table.file_uris = MagicMock(return_value=[f"s3://bucket/table/{path}" for path in file_sizes])+ table._table.get_add_file_sizes = MagicMock(return_value=file_sizes)+ table.version = MagicMock(return_value=version)+ return table+++def _layout(groups: list[tuple[int, list[int]]]) -> dict[str, int]:+ return {+ f"_ph_partition_key={group}-{partition}/f{i}.parquet": size+ for group, (partitions, sizes) in enumerate(groups)+ for partition in range(partitions)+ for i, size in enumerate(sizes)+ }def _passthrough_pool(fn):@@ -49,31 +86,33 @@ def _passthrough_pool(fn):return _call-class TestCompactIfFragmented:- """Defensive compaction fires on files-per-partition OR total-files threshold."""+def _parquet_files(root: str) -> set[str]:+ return {str(path.relative_to(root)) for path in Path(root).rglob("*.parquet") if "_delta_log" not in path.parts}++def _dead_files(root: str) -> set[str]:+ live = set(deltalake.DeltaTable(root)._table.get_add_file_sizes())+ return _parquet_files(root) - live+++class TestCompactIfFragmented:@pytest.mark.asyncioasync def test_skips_when_no_delta_table(self):ran = await _make_maintenance(None).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.+ # (case_name, file_count, partition_count, threshold_kw, expected_ran). Every file is small, so a+ # count trigger can always remove files here._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 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),# 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-files backstop: 60 fpp is under the per-partition bar, but 6,000 files is over 5,000.("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),]@@ -87,12 +126,11 @@ class TestCompactIfFragmented:threshold_kw: int | None,expected_ran: bool,):- file_uris = [f"s3://bucket/table/f{i}.parquet" for i in range(file_count)]- mock_delta = MagicMock()- mock_delta.file_uris = MagicMock(return_value=file_uris)+ mock_delta = _mock_table({f"f{i}.parquet": _MB for i in range(file_count)})maintenance = _make_maintenance(mock_delta)with (- patch.object(maintenance, "_compact", AsyncMock()) as mock_compact,+ patch.object(maintenance, "_plan_compaction", AsyncMock(return_value=_DEFAULT_PLAN)),+ patch.object(maintenance, "_compact", AsyncMock(return_value=True)) as mock_compact,patch.object(maintenance, "_vacuum", AsyncMock()) as mock_vacuum,):kwargs: dict = {"partition_count": partition_count}@@ -101,12 +139,46 @@ class TestCompactIfFragmented:ran = await maintenance.compact_if_fragmented(**kwargs)assert ran is expected_ran- if expected_ran:- mock_compact.assert_called_once_with(mock_delta)- mock_vacuum.assert_called_once_with(mock_delta)- else:- mock_compact.assert_not_called()- mock_vacuum.assert_not_called()+ assert mock_compact.await_count == (1 if expected_ran else 0)+ # Compaction tombstones are younger than the vacuum retention, so a vacuum right after it is wasted.+ mock_vacuum.assert_not_called()++ # (case_name, file layout, partition_count, expected_ran)+ _COUNT_TRIGGER_CASES: list[tuple[str, list[tuple[int, list[int]]], int | None, bool]] = [+ # An hourly-partitioned table: one file in each of 13,215 partitions, and a few partitions+ # with a second file. It stays over the total-files bar after any compaction, so a count+ # trigger that ignores removable files compacts and commits on every pass.+ ("one_file_per_partition_never_compacts", [(13_215, [300_000]), (6, [300_000, 300_000])], None, False),+ # The same table once many partitions hold a second small file: compaction removes thousands.+ ("many_partitions_with_two_small_files_compacts", [(6_000, [300_000, 300_000])], None, True),+ # One partition far over the per-partition bar, with files compaction cannot merge.+ ("over_per_partition_bar_with_large_files_skips", [(1, [60 * _MB] * 250)], None, False),+ ("over_per_partition_bar_with_small_files_compacts", [(1, [_MB] * 250)], None, True),+ # md5 buckets each hold many small files: the persisted count gives files per partition.+ ("md5_buckets_fragmented_compacts", [(16, [_MB] * 300)], 16, True),+ # md5 buckets over the total bar, but each bucket already compacted to large files.+ ("md5_buckets_compacted_skips", [(150, [60 * _MB] * 40)], 150, False),+ # Below the removable thresholds in every partition and in total, though over the total bar.+ ("few_removable_files_skips", [(5_100, [300_000]), (50, [300_000, 300_000])], None, False),+ ]++ @parameterized.expand(_COUNT_TRIGGER_CASES)+ @pytest.mark.asyncio+ async def test_count_trigger_needs_removable_files(+ self, _name: str, layout: list[tuple[int, list[int]]], partition_count: int | None, expected_ran: bool+ ):+ mock_delta = _mock_table(_layout(layout))+ maintenance = _make_maintenance(mock_delta)+ with (+ patch.object(maintenance, "_compact", AsyncMock(return_value=True)) as mock_compact,+ patch.object(maintenance, "_plan_compaction", AsyncMock(return_value=_DEFAULT_PLAN)) as plan,+ ):+ ran = await maintenance.compact_if_fragmented(partition_count=partition_count)++ assert ran is expected_ran+ assert mock_compact.await_count == (1 if expected_ran else 0)+ # The decision reads the Delta log only. Planning reads parquet footers, so a skip must not plan.+ assert plan.await_count == (1 if expected_ran else 0)# (case_name, files_per_dir, dir_count, expected_ran)_DERIVATION_CASES: list[tuple[str, int, int, bool]] = [@@ -114,7 +186,6 @@ class TestCompactIfFragmented:# 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),]@@ -126,27 +197,16 @@ class TestCompactIfFragmented:# 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.- 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)- ]- mock_delta = MagicMock()- mock_delta.file_uris = MagicMock(return_value=file_uris)+ mock_delta = _mock_table(_layout([(dir_count, [_MB] * files_per_dir)]))maintenance = _make_maintenance(mock_delta)with (- patch.object(maintenance, "_compact", AsyncMock()) as mock_compact,- patch.object(maintenance, "_vacuum", AsyncMock()) as mock_vacuum,+ patch.object(maintenance, "_plan_compaction", AsyncMock(return_value=_DEFAULT_PLAN)),+ patch.object(maintenance, "_compact", AsyncMock(return_value=True)) as mock_compact,):ran = await maintenance.compact_if_fragmented(partition_count=None)assert ran is expected_ran- if expected_ran:- mock_compact.assert_called_once_with(mock_delta)- mock_vacuum.assert_called_once_with(mock_delta)- else:- mock_compact.assert_not_called()- mock_vacuum.assert_not_called()+ assert mock_compact.await_count == (1 if expected_ran else 0)# (case_name, layout as [(partitions, file sizes in each)], compact_small_files, table_wide_small_files,# expected_ran)@@ -166,6 +226,7 @@ class TestCompactIfFragmented:# 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),+ ("every_partition_grows_table_wide_check_fires", [(150, [20 * _MB, _MB])], True, True, True),# 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),@@ -182,32 +243,12 @@ class TestCompactIfFragmented: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)+ mock_delta = _mock_table(_layout(layout))maintenance = _make_maintenance(mock_delta)with (override_settings(DATA_WAREHOUSE_TARGET_PARTITION_BYTES=500 * _MB),- patch.object(- maintenance,- "_plan_compaction",- AsyncMock(- return_value=CompactionPlan(- target_size=DEFAULT_COMPACT_TARGET_SIZE_BYTES,- max_concurrent_tasks=1,- compression_ratio=1.0,- slot_budget_mb=1356.8,- )- ),- ),- patch.object(maintenance, "_compact", AsyncMock()) as mock_compact,- patch.object(maintenance, "_vacuum", AsyncMock()),+ patch.object(maintenance, "_plan_compaction", AsyncMock(return_value=_DEFAULT_PLAN)),+ patch.object(maintenance, "_compact", AsyncMock(return_value=True)) as mock_compact,):ran = await maintenance.compact_if_fragmented(partition_count=None,@@ -247,6 +288,38 @@ class TestCompactIfFragmented:assert (files_after < files_before) is expected_ranassert table.to_pyarrow_table().num_rows == rows_before+ @parameterized.expand(+ [+ # One file in each partition, as an hourly incremental table holds them: a no-op that adds no commit.+ ("one_file_per_partition", 30, 1, False, 0),+ # Thirty small files in one partition: one compaction commit, and no vacuum commits after it.+ ("fragmented_partition", 1, 30, True, 1),+ ]+ )+ @pytest.mark.asyncio+ async def test_count_trigger_on_a_real_table(+ self, _name: str, partitions: int, files_per_partition: int, expected_ran: bool, expected_commits: int+ ):+ with tempfile.TemporaryDirectory() as path:+ for part in range(partitions):+ for i in range(files_per_partition):+ deltalake.write_deltalake(+ path,+ pa.table({"p": [f"h{part:03d}"], "id": [part * 1000 + i]}),+ mode="append",+ partition_by=["p"],+ )+ table = deltalake.DeltaTable(path)+ version_before = table.version()+ rows_before = table.to_pyarrow_table().num_rows++ ran = await _make_maintenance(table).compact_if_fragmented(partition_count=None, total_threshold=10)++ assert ran is expected_ran+ table.update_incremental()+ assert table.version() - version_before == expected_commits+ assert table.to_pyarrow_table().num_rows == rows_before+class TestCompactConflictRetry:@pytest.mark.asyncio@@ -255,8 +328,7 @@ class TestCompactConflictRetry:# commit-conflict shape as a merge (see test_ops.TestExecuteWithConflictRetry). Regression# coverage for a CommitFailedError propagating straight out on the first conflict instead of# retrying with a refreshed table, like the write merges do.- mock_delta = MagicMock()- mock_delta.file_uris = MagicMock(return_value=[f"s3://t/{i}.parquet" for i in range(3)])+ mock_delta = _mock_table({f"{i}.parquet": _MB for i in range(12)})mock_delta.optimize.compact = MagicMock(side_effect=[deltalake.exceptions.CommitFailedError(@@ -265,26 +337,15 @@ class TestCompactConflictRetry:{"numFilesAdded": 1},])- mock_delta.vacuum = MagicMock(return_value=[])maintenance = _make_maintenance(mock_delta)- with patch.object(- maintenance,- "_plan_compaction",- AsyncMock(- return_value=CompactionPlan(- target_size=DEFAULT_COMPACT_TARGET_SIZE_BYTES,- max_concurrent_tasks=1,- compression_ratio=1.0,- slot_budget_mb=1356.8,- )- ),- ):+ with patch.object(maintenance, "_plan_compaction", AsyncMock(return_value=_DEFAULT_PLAN)):compacted = await maintenance.compact_if_fragmented(partition_count=1, threshold=1)assert compacted is Trueassert mock_delta.optimize.compact.call_count == 2mock_delta.update_incremental.assert_called_once()+ mock_delta.vacuum.assert_not_called()class TestCompactOffsetOverflow:@@ -345,7 +406,8 @@ class TestCompactionMemoryBounds:("incompressible", 1.0, 1356.8, DEFAULT_COMPACT_TARGET_SIZE_BYTES, 6),("modest_ratio", 2.0, 1356.8, DEFAULT_COMPACT_TARGET_SIZE_BYTES, 3),# Wide JSON documents: 100 MB on disk decodes past the 2 GiB offset limit, so the bin shrinks- # until it decodes to half the slot and only one bin runs at a time.+ # until it decodes to half the slot and only one bin runs at a time. delta-rs leaves files+ # larger than the bin alone, so the bin also caps the largest file that a compaction decodes.("wide_json", 25.0, 1356.8, int(1356.8 * _MB / 2 / 25), 1),("extreme_ratio_skips", 500.0, 1356.8, None, None),("zero_budget_skips", 1.0, 0.0, None, None),@@ -375,9 +437,7 @@ class TestCompactionMemoryBounds:@pytest.mark.asyncioasync def test_small_file_trigger_rechecks_removals_at_planned_target(self) -> None:file_sizes = {f"f{i}.parquet": 30 * _MB for i in range(30)}- mock_delta = MagicMock()- mock_delta.file_uris.return_value = [f"s3://bucket/table/{path}" for path in file_sizes]- mock_delta._table.get_add_file_sizes.return_value = file_sizes+ mock_delta = _mock_table(file_sizes)maintenance = _make_maintenance(mock_delta)plan = CompactionPlan(target_size=27 * _MB,@@ -388,29 +448,73 @@ class TestCompactionMemoryBounds:with (patch.object(maintenance, "_plan_compaction", AsyncMock(return_value=plan)),patch.object(maintenance, "_compact", AsyncMock()) as compact,- patch.object(maintenance, "_vacuum", AsyncMock()) as vacuum,):ran = await maintenance.compact_if_fragmented(partition_count=1, compact_small_files=True)assert ran is Falsecompact.assert_not_awaited()- vacuum.assert_not_awaited()- @parameterized.expand([("compressible_json", True), ("random", False)])- def test_samples_the_compression_ratio_from_parquet_footers(self, _name: str, compressible: bool) -> None:+ @parameterized.expand(+ [+ ("compressible_json", True, 1),+ ("random", False, 1),+ # Several row groups per file: the footer sums every row group.+ ("many_row_groups", True, 4),+ ]+ )+ def test_samples_the_compression_ratio_from_footers_only(+ self, _name: str, compressible: bool, row_groups: int+ ) -> None:with tempfile.TemporaryDirectory() as path:- for row_id in range(3):- payload = ('{"field": "value", "n": 1}' * 4000) if compressible else os.urandom(50_000).hex()- deltalake.write_deltalake(path, pa.table({"id": [row_id], "data": [payload]}), mode="append")-- ratio = _sample_compression_ratio(deltalake.DeltaTable(path))+ for file_index in range(5):+ rows = 4 + file_index+ payloads = [+ (json.dumps({"row": row}) + '{"field": "value", "n": 1}' * 4000)+ if compressible+ else os.urandom(50_000).hex()+ for row in range(rows)+ ]+ deltalake.write_deltalake(+ path,+ pa.table({"id": list(range(rows)), "data": payloads}),+ mode="append",+ writer_properties=deltalake.WriterProperties(+ compression="SNAPPY", max_row_group_size=max(1, rows // row_groups)+ ),+ )+ table = deltalake.DeltaTable(path)+ with (+ patch.object(deltalake.DeltaTable, "to_pyarrow_dataset", side_effect=AssertionError("full dataset")),+ patch(f"{_MAINTENANCE_MODULE}.pq.read_metadata", wraps=pq.read_metadata) as read_metadata,+ ):+ ratio = _sample_compression_ratio(table)++ # The same footers through the dataset, the way the sampling worked before.+ by_size = sorted(table._table.get_add_file_sizes().items(), key=lambda item: -item[1])+ largest = {path.rpartition("/")[2] for path, _ in by_size[:_COMPACT_RATIO_SAMPLE_FILES]}+ decoded = stored = 0+ for fragment in table.to_pyarrow_dataset().get_fragments():+ if fragment.path.rpartition("/")[2] in largest:+ metadata = fragment.metadata+ for index in range(metadata.num_row_groups):+ row_group = metadata.row_group(index)+ decoded += row_group.total_byte_size+ stored += sum(row_group.column(c).total_compressed_size for c in range(row_group.num_columns))++ assert read_metadata.call_count == _COMPACT_RATIO_SAMPLE_FILESassert ratio is not None+ assert ratio == pytest.approx(decoded / stored, rel=1e-9)if compressible:assert ratio > 10else:assert ratio < 3+ def test_samples_nothing_from_an_empty_table(self) -> None:+ table = MagicMock()+ table._table.get_add_file_sizes.return_value = {}+ assert _sample_compression_ratio(table) is None+@pytest.mark.asyncioasync def test_compact_runs_with_the_planned_bin_size_and_parallelism(self) -> None:mock_delta = MagicMock()@@ -473,108 +577,155 @@ class TestVacuum:assert mock_delta.vacuum.call_count == 2mock_delta.update_incremental.assert_called_once()+ @parameterized.expand([("lite", False), ("full", True)])+ @pytest.mark.asyncio+ async def test_lite_and_full_share_the_retention(self, _name: str, full: bool):+ mock_delta = MagicMock()+ mock_delta.vacuum = MagicMock(return_value=["a.parquet", "b.parquet"])++ deleted = await _make_maintenance(mock_delta)._vacuum(mock_delta, full=full)++ assert deleted == 2+ mock_delta.vacuum.assert_called_once_with(+ retention_hours=24, enforce_retention_duration=False, dry_run=False, full=full+ )+++def _watermarks(version: int | None, vacuumed_days_ago: float | None, full_days_ago: float | None) -> VacuumWatermarks:+ def at(days: float | None) -> dt.datetime | None:+ return None if days is None else _NOW - dt.timedelta(days=days)-class TestVacuumIfStale:+ return VacuumWatermarks(version=version, vacuumed_at=at(vacuumed_days_ago), full_vacuumed_at=at(full_days_ago))+++class TestDecideVacuum:@parameterized.expand([- # (last_vacuum_version, expect_vacuum, expected_return) — current version=150, threshold=100.- # First encounter must seed the watermark WITHOUT vacuuming (else every existing table vacuums- # at once on deploy); below threshold must skip (else vacuum runs every sync); at/above threshold- # must vacuum (else tombstones accumulate forever on tables that never reach post-load compaction).- ("first_encounter_seeds_no_vacuum", None, False, 150),- ("below_threshold_skips", 100, False, None),- ("at_threshold_vacuums", 50, True, 150),- ("above_threshold_vacuums", 40, True, 150),- # A watermark above the current version means the table was reset/recreated (delta- # versions are monotonic within one incarnation) and no reset path clears the persisted- # watermark — it must reseed, not block the cadence until the version catches up.- ("stale_watermark_from_recreated_table_reseeds", 999, False, 150),+ # (name, version watermark, days since vacuum, days since full vacuum, expected reason,+ # expected seeded version) at version 150, a 100-commit cadence, 5-day and 7-day intervals.+ # A first encounter seeds every watermark without vacuuming, so existing tables do not all+ # vacuum at once on deploy.+ ("first_encounter_seeds", None, None, None, None, 150),+ ("existing_table_seeds_timestamps", 100, None, None, None, 100),+ ("below_every_cadence_skips", 100, 1, 1, None, 100),+ ("commit_cadence_due", 50, 1, 1, "commits", 50),+ ("above_commit_cadence_due", 40, 1, 1, "commits", 40),+ # A table that commits slowly vacuums on time, before a checkpoint drops its tombstones.+ ("time_cadence_due", 149, 5, 1, "time", 149),+ ("time_cadence_just_under_skips", 149, 5 - 1 / 86400, 1, None, 149),+ ("full_vacuum_weekly", 149, 1, 7, "full", 149),+ # A full vacuum deletes everything a lite one does, so it replaces a due lite vacuum.+ ("full_replaces_commit_vacuum", 10, 6, 8, "full", 10),+ # A watermark above the current version means the table was recreated. It must reseed, not+ # block the commit cadence until the new table catches up.+ ("recreated_table_reseeds", 999, 1, 1, None, 150),+ ("recreated_table_still_vacuums_on_time", 999, 6, 1, "time", 150),+ # A watermark in the future (clock skew) is never due.+ ("future_watermarks_skip", 149, -1, -1, None, 149),])- @pytest.mark.asyncio- async def test_vacuum_cadence(- self, _name: str, last_version: int | None, expect_vacuum: bool, expected_return: int | None+ def test_cadence(+ self,+ _name: str,+ version: int | None,+ vacuumed_days_ago: float | None,+ full_days_ago: float | None,+ expected_reason: str | None,+ expected_version: int,):- table = MagicMock()- table.version = MagicMock(return_value=150)- maintenance = _make_maintenance(table)- with (- patch.object(maintenance, "_vacuum", new=AsyncMock()) as vacuum,- patch(f"{_MAINTENANCE_MODULE}.posthoganalytics") as ph,- ):- result = await maintenance.vacuum_if_stale(last_version, 100)+ watermarks = _watermarks(version, vacuumed_days_ago, full_days_ago)- assert result == expected_return- assert vacuum.await_count == (1 if expect_vacuum else 0)- if expect_vacuum:- vacuum.assert_awaited_once_with(table)- # The observability event fires exactly when a vacuum runs — not on seed/skip — so the cadence is measurable.- assert ph.capture.call_count == (1 if expect_vacuum else 0)- if expect_vacuum:- assert ph.capture.call_args.kwargs["event"] == "warehouse_delta_vacuumed"+ decision = decide_vacuum(watermarks, _CADENCE, 150, _NOW)+ assert decision.reason == expected_reason+ assert decision.full is (expected_reason == "full")+ assert decision.watermarks.version == expected_version+ assert decision.watermarks.vacuumed_at == (watermarks.vacuumed_at or _NOW)+ assert decision.watermarks.full_vacuumed_at == (watermarks.full_vacuumed_at or _NOW)-class TestRunMaintenance:- """run_maintenance is the single threshold-maintenance step: compaction supersedes the cadence vacuum."""+ def test_time_cadence_vacuums_before_a_checkpoint_can_drop_a_tombstone(self):+ cadence = VacuumCadence.from_settings()+ # A tombstone ages past the retention, then a vacuum is due at most `max_interval` later.+ assert cadence.max_interval + VACUUM_RETENTION < DELTA_DELETED_FILE_RETENTION+ assert cadence.commit_threshold == settings.DATA_WAREHOUSE_VACUUM_COMMIT_THRESHOLD+ assert cadence.full_interval >= cadence.max_interval- @pytest.mark.asyncio- async def test_compaction_supersedes_vacuum_and_advances_watermark(self):- # Fragmented table: compact runs (and vacuums as part of it), so the cadence vacuum is skipped —- # no double vacuum in one run — and the watermark advances to the post-compaction version.- table = MagicMock(version=MagicMock(return_value=200))- maintenance = _make_maintenance(table)- with (- patch.object(maintenance, "compact_if_fragmented", new=AsyncMock(return_value=True)),- patch.object(maintenance, "vacuum_if_stale", new=AsyncMock()) as vacuum_if_stale,- ):- result = await maintenance.run_maintenance(partition_count=10, last_vacuum_version=50, commit_threshold=100)- assert result == 200- vacuum_if_stale.assert_not_awaited()+class TestVacuumWatermarks:+ @parameterized.expand(+ [+ ("snapshot", False, "last_vacuum_version", "last_vacuum_at", "last_full_vacuum_at"),+ # The _cdc companion is another delta table with unrelated versions, so it keeps its own keys.+ ("companion", True, "last_vacuum_version_cdc", "last_vacuum_at_cdc", "last_full_vacuum_at_cdc"),+ ]+ )+ def test_round_trips_through_sync_type_config(+ self, _name: str, is_cdc_companion: bool, version_key: str, vacuumed_key: str, full_key: str+ ):+ watermarks = _watermarks(42, 1, 3)+ config = watermarks.config_updates(+ VacuumWatermarks(version=None, vacuumed_at=None, full_vacuumed_at=None), is_cdc_companion+ )- @pytest.mark.asyncio- async def test_falls_through_to_vacuum_when_not_fragmented(self):- # Not fragmented → no compaction; fall through to the commit-cadence vacuum and return its watermark.- maintenance = _make_maintenance(MagicMock())- with (- patch.object(maintenance, "compact_if_fragmented", new=AsyncMock(return_value=False)),- patch.object(maintenance, "vacuum_if_stale", new=AsyncMock(return_value=150)) as vacuum_if_stale,- ):- result = await maintenance.run_maintenance(partition_count=10, last_vacuum_version=40, commit_threshold=100)+ assert set(config) == {version_key, vacuumed_key, full_key}+ assert VacuumWatermarks.from_config(config, is_cdc_companion) == watermarks+ assert VacuumWatermarks.from_config(config, not is_cdc_companion) == VacuumWatermarks(+ version=None, vacuumed_at=None, full_vacuumed_at=None+ )++ @parameterized.expand([("not_a_string", 12), ("not_a_timestamp", "yesterday")])+ def test_unreadable_timestamp_reads_as_missing(self, _name: str, value: object):+ watermarks = VacuumWatermarks.from_config({"last_vacuum_at": value}, False)+ assert watermarks.vacuumed_at is None- assert result == 150- vacuum_if_stale.assert_awaited_once_with(40, 100)+ def test_unchanged_values_are_not_rewritten(self):+ watermarks = _watermarks(42, 1, 3)+ assert watermarks.config_updates(watermarks, False) == {}++class TestVacuumIfDue:@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),+ # (name, watermarks, expected reason)+ ("not_due", _watermarks(100, 1, 1), None),+ ("commits", _watermarks(40, 1, 1), "commits"),+ ("time", _watermarks(149, 6, 1), "time"),+ ("full", _watermarks(149, 1, 8), "full"),])@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)))+ async def test_vacuums_when_due(self, _name: str, watermarks: VacuumWatermarks, expected_reason: str | None):+ table = MagicMock()+ # Vacuum commits its own start and end entries.+ table.version = MagicMock(side_effect=[150, 152])+ maintenance = _make_maintenance(table)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)),+ patch.object(maintenance, "_vacuum", new=AsyncMock(return_value=3)) as vacuum,+ patch(f"{_MAINTENANCE_MODULE}.posthoganalytics") as ph,):- await maintenance.run_maintenance(- partition_count=10,- last_vacuum_version=last_vacuum_version,- commit_threshold=100,- compact_small_files=compact_small_files,- )+ decision = await maintenance.vacuum_if_due(watermarks, _CADENCE)++ assert decision is not None+ assert decision.reason == expected_reason+ if expected_reason is None:+ vacuum.assert_not_awaited()+ ph.capture.assert_not_called()+ assert decision.watermarks == watermarks+ return+ vacuum.assert_awaited_once_with(table, full=expected_reason == "full")+ assert decision.watermarks.version == 152+ assert decision.watermarks.vacuumed_at == _NOW+ assert decision.watermarks.full_vacuumed_at == (+ _NOW if expected_reason == "full" else watermarks.full_vacuumed_at+ )+ properties = ph.capture.call_args.kwargs["properties"]+ assert ph.capture.call_args.kwargs["event"] == "warehouse_delta_vacuumed"+ assert properties["vacuum_reason"] == expected_reason+ assert properties["files_deleted"] == 3- 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+ @pytest.mark.asyncio+ async def test_no_table(self):+ assert await _make_maintenance(None).vacuum_if_due(_watermarks(1, 1, 1), _CADENCE) is Noneclass TestRunScheduled:@@ -582,11 +733,21 @@ class TestRunScheduled:pass and post-load), so watermark-key selection, persistence gating, and the never-raisecontract all live here."""- def _schema(self) -> MagicMock:+ def _schema(self, config: dict | None = None) -> MagicMock:schema = MagicMock()schema.partition_count = 10- schema.last_vacuum_version = 41- schema.last_vacuum_version_cdc = 7+ schema.sync_type_config = (+ config+ if config is not None+ else {+ "last_vacuum_version": 41,+ "last_vacuum_at": (_NOW - dt.timedelta(days=1)).isoformat(),+ "last_full_vacuum_at": (_NOW - dt.timedelta(days=1)).isoformat(),+ "last_vacuum_version_cdc": 7,+ "last_vacuum_at_cdc": (_NOW - dt.timedelta(days=1)).isoformat(),+ "last_full_vacuum_at_cdc": (_NOW - dt.timedelta(days=1)).isoformat(),+ }+ )return schemaasync def _run(@@ -594,18 +755,18 @@ class TestRunScheduled:maintenance: DeltaMaintenance,schema: MagicMock,*,- 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)- if isinstance(run_maintenance_result, Exception)- else AsyncMock(return_value=run_maintenance_result)- )+ compact: AsyncMock | None = None,+ vacuum: AsyncMock | None = None,+ ) -> tuple[AsyncMock, AsyncMock, MagicMock, MagicMock]:+ compact = compact or AsyncMock(return_value=False)+ vacuum = vacuum or AsyncMock(return_value=0)with (- patch.object(maintenance, "run_maintenance", run_maintenance),+ patch.object(maintenance, "compact_if_fragmented", compact),+ patch.object(maintenance, "_vacuum", vacuum),+ patch(f"{_MAINTENANCE_MODULE}.posthoganalytics"),patch(f"{_MAINTENANCE_MODULE}.database_sync_to_async_pool", _passthrough_pool),patch(f"{_MAINTENANCE_MODULE}.update_sync_type_config_keys") as update_config,patch(f"{_MAINTENANCE_MODULE}.capture_exception") as capture,@@ -616,32 +777,20 @@ class TestRunScheduled: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+ return compact, vacuum, update_config, capture@parameterized.expand([- # (name, is_cdc_companion, schema_partition_count, fallback, expected_count, expected_last, expected_key)+ # (name, is_cdc_companion, schema_partition_count, fallback, expected_count, expected_key)# The schema's persisted count wins over the source's fallback.- ("main_schema_count_wins", False, 10, 72, 10, 41, "last_vacuum_version"),+ ("main_schema_count_wins", False, 10, 72, 10, "last_vacuum_version"),# md5-less schemas persist no count; the source-provided fallback applies.- ("main_falls_back_to_source_count", False, None, 72, 72, 41, "last_vacuum_version"),- ("main_both_none_derives_downstream", False, None, None, None, 41, "last_vacuum_version"),+ ("main_falls_back_to_source_count", False, None, 72, 72, "last_vacuum_version"),+ ("main_both_none_derives_downstream", False, None, None, None, "last_vacuum_version"),# The snapshot and _cdc companion are different delta tables with unrelated versions, so- # the companion must use last_vacuum_version_cdc — sharing a key corrupts both cadences —- # and must ignore schema.partition_count, which describes the snapshot table's layout.- ("companion_own_key_and_layout", True, 10, 72, None, 7, "last_vacuum_version_cdc"),+ # the companion must use its own keys — sharing a key corrupts both cadences — and must+ # ignore schema.partition_count, which describes the snapshot table's layout.+ ("companion_own_key_and_layout", True, 10, 72, None, "last_vacuum_version_cdc"),])@pytest.mark.asyncio@@ -652,46 +801,138 @@ class TestRunScheduled:schema_count: int | None,fallback: int | None,expected_count: int | None,- expected_last: int,expected_key: str,):schema = self._schema()schema.partition_count = schema_count- run_maintenance, update_config, _ = await self._run(- _make_maintenance(MagicMock()),- schema,- run_maintenance_result=99,- is_cdc_companion=is_cdc_companion,- partition_count_fallback=fallback,+ # 150 - 41 and 150 - 7 are both past the 100-commit cadence.+ table = MagicMock(version=MagicMock(side_effect=[150, 152]))+ compact, vacuum, update_config, _ = await self._run(+ _make_maintenance(table), schema, is_cdc_companion=is_cdc_companion, partition_count_fallback=fallback)- assert run_maintenance.await_args is not None- assert run_maintenance.await_args.kwargs["partition_count"] == expected_count- assert run_maintenance.await_args.kwargs["last_vacuum_version"] == expected_last- update_config.assert_called_once_with(schema.id, schema.team_id, updates={expected_key: 99})+ assert compact.await_args is not None+ assert compact.await_args.kwargs["partition_count"] == expected_count+ vacuum.assert_awaited_once()+ suffix = "_cdc" if is_cdc_companion else ""+ expected_updates = {expected_key: 152, f"last_vacuum_at{suffix}": _NOW.isoformat()}+ update_config.assert_called_once_with(schema.id, schema.team_id, updates=expected_updates)+ assert schema.sync_type_config[expected_key] == 152@parameterized.expand([- # run_maintenance returning a version must persist it — a lost watermark means- # vacuum_if_stale re-seeds forever and the table never vacuums.- ("new_version_persists", 55, True),- ("no_change_skips_write", None, False),- ("same_version_skips_write", 41, False),+ ("first_encounter_seeds_without_vacuum", {}, True, False),+ (+ "nothing_due_writes_nothing",+ {+ "last_vacuum_version": 100,+ "last_vacuum_at": (_NOW - dt.timedelta(days=1)).isoformat(),+ "last_full_vacuum_at": (_NOW - dt.timedelta(days=1)).isoformat(),+ },+ False,+ False,+ ),+ (+ "due_vacuum_persists",+ {+ "last_vacuum_version": 10,+ "last_vacuum_at": (_NOW - dt.timedelta(days=1)).isoformat(),+ "last_full_vacuum_at": (_NOW - dt.timedelta(days=1)).isoformat(),+ },+ True,+ True,+ ),])@pytest.mark.asyncio- async def test_watermark_persistence_gating(self, _name: str, returned_version: int | None, expect_write: bool):+ async def test_watermark_persistence_gating(+ self, _name: str, config: dict, expect_write: bool, expect_vacuum: bool+ ):+ schema = self._schema(config)+ table = MagicMock(version=MagicMock(return_value=150))+ _, vacuum, update_config, _ = await self._run(_make_maintenance(table), schema)++ assert update_config.called is expect_write+ assert vacuum.await_count == (1 if expect_vacuum else 0)++ @pytest.mark.asyncio+ async def test_compaction_does_not_vacuum_unless_due(self):+ table = MagicMock(version=MagicMock(return_value=50))+ compact = AsyncMock(return_value=True)+ _, vacuum, update_config, _ = await self._run(_make_maintenance(table), self._schema(), compact=compact)++ compact.assert_awaited_once()+ vacuum.assert_not_awaited()+ update_config.assert_not_called()++ @pytest.mark.asyncio+ async def test_a_failing_compaction_keeps_the_vacuum_cadence(self):+ # A compaction that fails on every sync must not stop the vacuum, or its table leaks dead files.schema = self._schema()- _, update_config, _ = await self._run(- _make_maintenance(MagicMock()), schema, run_maintenance_result=returned_version+ table = MagicMock(version=MagicMock(side_effect=[150, 152]))+ compact = AsyncMock(side_effect=RuntimeError("compaction blew up"))+ _, vacuum, update_config, capture = await self._run(_make_maintenance(table), schema, compact=compact)++ vacuum.assert_awaited_once()+ update_config.assert_called_once()+ capture.assert_called_once()++ @pytest.mark.asyncio+ async def test_pre_write_and_post_load_passes_vacuum_once(self):+ # Both passes of one sync share the schema object. The post-load pass must see the vacuum that+ # the pre-write pass persisted, and still run the table-wide small-file check that it skipped.+ schema = self._schema({"last_vacuum_version": 10})+ schema.sync_type_config.update(+ last_vacuum_at=(_NOW - dt.timedelta(days=1)).isoformat(),+ last_full_vacuum_at=(_NOW - dt.timedelta(days=1)).isoformat(),)+ table = MagicMock(version=MagicMock(side_effect=[150, 152, 155]))+ maintenance = _make_maintenance(table)+ vacuum = AsyncMock(return_value=0)+ pre_compact, _, pre_update, _ = await self._run(maintenance, schema, vacuum=vacuum)+ post_compact, _, post_update, _ = await self._run(maintenance, schema, compact_small_files=True, vacuum=vacuum)- if expect_write:- update_config.assert_called_once_with(- schema.id, schema.team_id, updates={"last_vacuum_version": returned_version}- )- else:- update_config.assert_not_called()+ vacuum.assert_awaited_once()+ pre_update.assert_called_once()+ post_update.assert_not_called()+ assert pre_compact.await_args is not None and post_compact.await_args is not None+ assert pre_compact.await_args.kwargs["table_wide_small_files"] is False+ assert post_compact.await_args.kwargs["table_wide_small_files"] is True++ @parameterized.expand(+ [+ # (name, compact_small_files, version watermark, days since vacuum, expected_table_wide) at+ # version 150 with a 100-commit cadence.+ ("vacuum_due", True, 40, 1, True),+ ("vacuum_not_due", True, 100, 1, False),+ ("vacuumed_earlier_in_this_job", True, 149, 0.01, True),+ ("watermark_not_seeded", True, None, None, False),+ ("small_file_triggers_off", False, 40, 1, False),+ ]+ )+ @pytest.mark.asyncio+ async def test_table_wide_small_file_trigger_follows_the_vacuum_cadence(+ self,+ _name: str,+ compact_small_files: bool,+ version: int | None,+ vacuumed_days_ago: float | None,+ expected_table_wide: bool,+ ):+ config: dict = {}+ if version is not None:+ config["last_vacuum_version"] = version+ if vacuumed_days_ago is not None:+ config["last_vacuum_at"] = (_NOW - dt.timedelta(days=vacuumed_days_ago)).isoformat()+ config["last_full_vacuum_at"] = (_NOW - dt.timedelta(days=1)).isoformat()+ table = MagicMock(version=MagicMock(side_effect=[150, 152]))+ compact, _, _, _ = await self._run(+ _make_maintenance(table), self._schema(config), 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@parameterized.expand([@@ -715,20 +956,19 @@ class TestRunScheduled:# A refused read/write/delete on our own bucket is a policy condition rather than a# maintenance defect, and no code change fixes it, so reporting it once per sync says# the same thing repeatedly. The watermark assertion below is what keeps the cadence- # re-attempting the vacuum instead of waiting another commit_threshold commits for a- # cleanup that never ran.+ # re-attempting the vacuum instead of waiting for a cleanup that never ran.("object_store_refusal_warned_only", ObjectStorePermissionDeniedError("denied"), False),])@pytest.mark.asyncioasync def test_never_raises(self, _name: str, error: Exception, expect_capture: bool):+ maintenance = _make_maintenance(MagicMock(version=MagicMock(return_value=150)))logger = make_logger()- table_ref = MagicMock()- table_ref.logger = logger- table_ref.get_delta_table = AsyncMock(return_value=MagicMock())- maintenance = DeltaMaintenance(table_ref)+ maintenance._logger = logger- _, update_config, capture = await self._run(maintenance, self._schema(), run_maintenance_result=error)+ _, _, update_config, capture = await self._run(+ maintenance, self._schema({"last_vacuum_version": 10}), vacuum=AsyncMock(side_effect=error)+ )assert capture.called is expect_captureupdate_config.assert_not_called()@@ -736,3 +976,103 @@ class TestRunScheduled:logger.aexception.assert_awaited_once()else:logger.awarning.assert_awaited_once()+++class TestVacuumOnARealTable:+ """Lite vacuum finds dead files only through tombstones, and a checkpoint drops tombstones older+ than `delta.deletedFileRetentionDuration`. These tests shorten that window to one second."""++ def _table_with_dropped_tombstones(self, root: str) -> None:+ config = {"delta.checkpointInterval": "5", "delta.deletedFileRetentionDuration": "interval 1 seconds"}+ deltalake.write_deltalake(+ root, pa.table({"p": ["a"] * 3, "x": [1, 2, 3]}), partition_by=["p"], configuration=config+ )+ for _ in range(3):+ deltalake.write_deltalake(+ root, pa.table({"p": ["a"] * 3, "x": [1, 2, 3]}), partition_by=["p"], mode="overwrite"+ )+ assert len(_dead_files(root)) == 3+ # The tombstones must age past the window before the next checkpoint drops them.+ time.sleep(1.1)+ for i in range(6):+ deltalake.write_deltalake(root, pa.table({"p": ["b"], "x": [i]}), partition_by=["p"], mode="append")++ @pytest.mark.asyncio+ async def test_periodic_full_vacuum_collects_files_lite_vacuum_misses(self):+ with tempfile.TemporaryDirectory() as root, patch(f"{_MAINTENANCE_MODULE}.VACUUM_RETENTION", dt.timedelta(0)):+ self._table_with_dropped_tombstones(root)+ table = deltalake.DeltaTable(root)+ rows = table.to_pyarrow_table().num_rows++ # The leak: the tombstones are gone from the checkpoint, so a lite vacuum deletes nothing.+ maintenance = _make_maintenance(table)+ await maintenance._vacuum(table)+ assert len(_dead_files(root)) == 3++ # The weekly full vacuum lists the table and deletes them.+ watermarks = VacuumWatermarks(+ version=table.version(), vacuumed_at=_NOW, full_vacuumed_at=_NOW - dt.timedelta(days=7)+ )+ with patch(f"{_MAINTENANCE_MODULE}.posthoganalytics"):+ decision = await maintenance.vacuum_if_due(watermarks, _CADENCE)++ assert decision is not None and decision.reason == "full"+ assert decision.watermarks.full_vacuumed_at == _NOW+ assert _dead_files(root) == set()+ assert deltalake.DeltaTable(root).to_pyarrow_table().num_rows == rows++ @pytest.mark.asyncio+ async def test_time_cadence_vacuums_a_slow_table_before_its_tombstones_drop(self):+ with tempfile.TemporaryDirectory() as root, patch(f"{_MAINTENANCE_MODULE}.VACUUM_RETENTION", dt.timedelta(0)):+ deltalake.write_deltalake(root, pa.table({"x": [1, 2, 3]}))+ for _ in range(3):+ deltalake.write_deltalake(root, pa.table({"x": [1, 2, 3]}), mode="overwrite")+ table = deltalake.DeltaTable(root)+ assert len(_dead_files(root)) == 3++ # Three commits since the last vacuum: the commit cadence is far from due, the time cadence is due.+ watermarks = VacuumWatermarks(+ version=table.version() - 3,+ vacuumed_at=_NOW - dt.timedelta(days=5),+ full_vacuumed_at=_NOW - dt.timedelta(days=1),+ )+ with patch(f"{_MAINTENANCE_MODULE}.posthoganalytics"):+ decision = await _make_maintenance(table).vacuum_if_due(watermarks, _CADENCE)++ assert decision is not None and decision.reason == "time"+ assert _dead_files(root) == set()++ @pytest.mark.asyncio+ async def test_full_vacuum_keeps_recent_tombstones_new_files_and_sibling_folders(self):+ # A full vacuum keeps the same 24-hour retention as a lite one: a reader pinned to a recent+ # version still needs a file that was tombstoned within it, however old the file is.+ with tempfile.TemporaryDirectory() as parent:+ root = os.path.join(parent, "table")+ deltalake.write_deltalake(root, pa.table({"x": [1, 2, 3]}))+ old = time.time() - 3 * 86400+ for name in _parquet_files(root):+ os.utime(os.path.join(root, name), (old, old))+ deltalake.write_deltalake(root, pa.table({"x": [4]}), mode="overwrite")+ recently_tombstoned = _dead_files(root)+ assert len(recently_tombstoned) == 1++ stale_orphan = os.path.join(root, "stale-orphan.parquet")+ new_orphan = os.path.join(root, "new-orphan.parquet")+ for path in (stale_orphan, new_orphan):+ pq.write_table(pa.table({"x": [0]}), path)+ os.utime(stale_orphan, (old, old))+ # The queryable folder copy sits next to the table, under a name that the table name prefixes.+ sibling = os.path.join(parent, "table__query", "copy.parquet")+ os.makedirs(os.path.dirname(sibling))+ pq.write_table(pa.table({"x": [0]}), sibling)+ os.utime(sibling, (old, old))++ table = deltalake.DeltaTable(root)+ deleted = await _make_maintenance(table)._vacuum(table, full=True)++ assert deleted == 1+ assert not os.path.exists(stale_orphan)+ assert os.path.exists(new_orphan)+ assert os.path.exists(sibling)+ assert recently_tombstoned <= _parquet_files(root)+ assert deltalake.DeltaTable(root).to_pyarrow_table().num_rows == 1diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/test/test_writer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/test/test_writer.pyindex 3690033480e5..ba2c1d1567d7 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/test/test_writer.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/test/test_writer.py@@ -701,7 +701,9 @@ class TestSchemaEvolutionNullability:status_field = next(f for f in result.schema().fields if f.name == "status")assert status_field.nullable is True- assert await DeltaMaintenance(helper).compact_if_fragmented(partition_count=None, threshold=0) is True+ table = await helper.get_delta_table()+ assert table is not None+ assert await DeltaMaintenance(helper)._compact(table) is Truefinal = result.to_pyarrow_table()by_id = dict(zip(final.column("id").to_pylist(), final.column("status").to_pylist()))diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/compute_table_statistics.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/compute_table_statistics.pyindex a4c10e7d64be..db77645f8391 100644--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/compute_table_statistics.py+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/compute_table_statistics.py@@ -548,7 +548,7 @@ def compute_table_statistics_sync(team_id: int, schema_id: uuid.UUID) -> dict[stdelta_version = delta_table.version()stored_version = _most_recent_computed_version(existing, columns)- # Delta versions are only monotonic within one incarnation (see vacuum_if_stale's identical+ # Delta versions are only monotonic within one incarnation (see decide_vacuum's identical# caveat): reset_table() purges the log and restarts numbering at 0 for full-refresh/reset tables,# so a stored version ahead of the table's current one means the table was recreated since the# last computation. Treat that stored version as stale rather than a match, or a table whose