:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): compact delta tables with deltalite behind a setting (#111504)
Tom Owersf1aed0e96850
diff --git a/posthog/settings/data_warehouse.py b/posthog/settings/data_warehouse.pyindex 8bb07c758ac3..c5ae57e1e6dc 100644--- a/posthog/settings/data_warehouse.py+++ b/posthog/settings/data_warehouse.py@@ -125,6 +125,10 @@ DATA_WAREHOUSE_VACUUM_MAX_INTERVAL_HOURS = get_from_env("DATA_WAREHOUSE_VACUUM_MDATA_WAREHOUSE_FULL_VACUUM_INTERVAL_HOURS = get_from_env("DATA_WAREHOUSE_FULL_VACUUM_INTERVAL_HOURS", 168, type_cast=int)+# Compact Delta tables with deltalite's native `DeltaLiteTable.compact` instead of delta-rs+# `optimize.compact`. deltalite streams each bin under the load slot's memory budget. A deltalite build+# without `compact`, a table that deltalite refuses, or a deltalite failure falls back to delta-rs.+DATA_WAREHOUSE_DELTALITE_COMPACTION = get_from_env("DATA_WAREHOUSE_DELTALITE_COMPACTION", False, type_cast=str_to_bool)# 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/core/delta/maintenance.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/maintenance.pyindex e5e1621ace8a..52342674ee7e 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@@ -23,15 +23,24 @@ from posthog.sync import database_sync_to_async_poolfrom posthog.utils import get_machine_idfrom products.warehouse_sources.backend.models.external_data_schema import update_sync_type_config_keys+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.deltalite_handles import (+ get_handle_cache,+)from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.errors import (+ TransientObjectStoreError,is_offset_overflow_compaction_error,is_transient_maintenance_error,+ is_transient_object_store_error,)from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.memory_governor import get_governorfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.ops import (+ OBJECT_STORE_PERMISSION_DENIED_MESSAGE,+ OBJECT_STORE_TRANSIENT_MESSAGE,ObjectStorePermissionDeniedError,execute_with_conflict_retry,+ is_object_store_permission_denied,)+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.writer import _delta_table_identityfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.core.post_load_phases import (note_post_load_phase,recorded_phase,@@ -448,6 +457,7 @@ class DeltaMaintenance:started = time.monotonic()await self._logger.ainfo("Compacting table...",+ compact_engine="delta-rs",compact_target_size=target_size,compact_max_concurrent_tasks=max_concurrent_tasks,compact_compression_ratio=plan.compression_ratio,@@ -484,6 +494,7 @@ class DeltaMaintenance:)await self._logger.ainfo("compact: done",+ compact_engine="delta-rs",compact_duration_s=round(time.monotonic() - started, 1),compact_files_added=compact_stats.get("numFilesAdded"),compact_files_removed=compact_stats.get("numFilesRemoved"),@@ -496,6 +507,111 @@ class DeltaMaintenance:await self._logger.adebug(json.dumps(compact_stats))return True+ async def _compact_with_deltalite(self, table: deltalake.DeltaTable) -> bool | None:+ """Compact through deltalite's native compaction. None means delta-rs must compact instead.++ deltalite streams each bin under byte budgets and caps every output file by its decoded size,+ so it needs no compression-ratio sample and no offset-overflow retry ladder. It also retries its+ own commit conflicts, and keeps each bin whose input files are still live.+ """+ try:+ import deltalite # noqa: PLC0415 - keeps deltalite off the import path while the setting is off+ except ImportError:+ await self._log_compact_fallback("deltalite_not_installed")+ return None+ if not hasattr(deltalite.DeltaLiteTable, "compact"):+ await self._log_compact_fallback("deltalite_compact_unavailable")+ return None++ uri = await self._table.get_table_uri()+ storage_options = self._table.get_storage_options()+ identity = _delta_table_identity(table, self._table)+ slot_budget_mb = get_governor().slot_budget_mb()+ compact_kwargs: dict[str, Any] = {+ "target_file_size": DEFAULT_COMPACT_TARGET_SIZE_BYTES,+ # deltalite lowers this until the bins in flight fit the slot budget.+ "max_parallel_bins": os.cpu_count() or 1,+ "slot_budget_bytes": int(slot_budget_mb * 1024 * 1024) if slot_budget_mb else None,+ # These keys must never include the loader's `run_uuid`/`batch_index` tags, because+ # `has_batch_been_committed` would then read a compaction as a committed batch.+ "commit_metadata": {"compact_engine": "deltalite", "job_id": str(self._table.job.id)},+ "min_partition_removable_files": 1,+ }++ def _run() -> dict[str, Any]:+ if identity is None:+ return deltalite.DeltaLiteTable.open(uri, storage_options).compact(**compact_kwargs)+ table_id, table_version = identity+ with get_handle_cache().lease(+ uri, storage_options=storage_options, table_id=table_id, table_version=table_version+ ) as handle:+ return handle.compact(**compact_kwargs)++ pod_mb_before = get_governor().pod.current_mb()+ started = time.monotonic()+ await self._logger.ainfo(+ "Compacting table...",+ compact_engine="deltalite",+ compact_target_size=DEFAULT_COMPACT_TARGET_SIZE_BYTES,+ compact_max_parallel_bins=compact_kwargs["max_parallel_bins"],+ compact_slot_budget_mb=round(slot_budget_mb, 1) if slot_budget_mb is not None else None,+ pod_memory_mb=pod_mb_before,+ peak_rss_mb=_peak_rss_mb(),+ )+ try:+ compact_stats = await asyncio.to_thread(_run)+ except deltalite.DeltaLiteUnsupportedTableError:+ await self._log_compact_fallback("unsupported_table")+ return None+ except deltalite.DeltaLiteCommitConflictError:+ # The retries ran out, or a concurrent writer changed the schema or the partitioning.+ # Nothing was committed, and the next maintenance pass compacts the table again.+ await self._logger.awarning("compact: deltalite lost to a concurrent commit, not reporting")+ return False+ except Exception as e:+ # The object-store classifiers match the error text, but accept only OS and delta-rs errors.+ as_os_error = OSError(str(e))+ if is_object_store_permission_denied(as_os_error):+ await self._logger.awarning(f"compact: the object store denied the operation ({type(e).__name__})")+ raise ObjectStorePermissionDeniedError(OBJECT_STORE_PERMISSION_DENIED_MESSAGE) from e+ if is_transient_object_store_error(as_os_error):+ await self._logger.awarning("compact: transient object-store error, not reporting")+ raise TransientObjectStoreError(OBJECT_STORE_TRANSIENT_MESSAGE) from e+ # A failed deltalite compaction commits nothing and deletes its output files, so delta-rs+ # can compact the same table safely.+ capture_exception(e)+ await self._log_compact_fallback("deltalite_error")+ return None++ commits = compact_stats.get("commits")+ if isinstance(commits, int) and commits > 0:+ # The delta-rs handle is now behind the log. Marking it stale makes the next reader refresh it.+ version = compact_stats.get("version")+ self._table.note_deltalite_commit(version if isinstance(version, int) else None)+ await self._logger.ainfo(+ "compact: done",+ compact_engine="deltalite",+ compact_duration_s=round(time.monotonic() - started, 1),+ compact_files_added=compact_stats.get("numFilesAdded"),+ compact_files_removed=compact_stats.get("numFilesRemoved"),+ compact_commits=commits,+ compact_commit_retries=compact_stats.get("commit_retries"),+ compact_bins=compact_stats.get("bins"),+ compact_bins_dropped=compact_stats.get("bins_dropped"),+ compact_parallel_bins=compact_stats.get("parallel_bins"),+ pod_memory_mb=get_governor().pod.current_mb(),+ peak_rss_mb=_peak_rss_mb(),+ )+ await self._logger.adebug(json.dumps(compact_stats))+ return True++ async def _log_compact_fallback(self, reason: str) -> None:+ await self._logger.ainfo(+ "compact: falling back to delta-rs",+ compact_engine="delta-rs",+ compact_fallback_reason=reason,+ )+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.@@ -637,6 +753,12 @@ class DeltaMaintenance:await self._logger.adebug(f"compact_if_fragmented: skipping ({stats})")return False+ if settings.DATA_WAREHOUSE_DELTALITE_COMPACTION:+ await self._logger.ainfo(f"compact_if_fragmented: triggering compact ({stats})")+ compacted = await self._compact_with_deltalite(table)+ if compacted is not None:+ return compacted+plan = await self._plan_compaction(table)if plan.target_size is None:await self._compact(table, plan)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.pyindex d7afcbf1fb66..85b767c20752 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@@ -4,6 +4,7 @@ import timeimport datetime as dtimport tempfilefrom pathlib import Path+from typing import Anyimport pytestfrom unittest.mock import AsyncMock, MagicMock, patch@@ -13,9 +14,16 @@ from django.test import override_settingsimport pyarrow as paimport deltalake+import deltaliteimport pyarrow.parquet as pqfrom parameterized import parameterized+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.deltalite_handles import (+ DeltaLiteHandleCache,+)+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.errors import (+ TransientObjectStoreError,+)from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.maintenance import (_COMPACT_RATIO_SAMPLE_FILES,COMPACT_OFFSET_OVERFLOW_RETRIES,@@ -555,6 +563,184 @@ class TestCompactionMemoryBounds:assert second == {"target_size": first["target_size"] // 2, "max_concurrent_tasks": 1}+class TestDeltaliteCompaction:+ _URI = "s3://bucket/table"+ _SLOT_MB = 1356.8++ def _setup(self, compact: MagicMock | None, *, table_id: object = "table-id") -> tuple[DeltaMaintenance, Any, Any]:+ # 300 small files in one partition trip the per-partition count trigger.+ delta_table = _mock_table({f"f{i}.parquet": _MB for i in range(300)})+ delta_table.metadata.return_value.id = table_id+ table_ref = MagicMock()+ table_ref.logger = make_logger()+ table_ref.get_delta_table = AsyncMock(return_value=delta_table)+ table_ref.get_table_uri = AsyncMock(return_value=self._URI)+ table_ref.get_storage_options = MagicMock(return_value={"AWS_REGION": "us-east-1"})+ table_ref.latest_known_version = MagicMock(return_value=150)+ table_ref.note_deltalite_commit = MagicMock()+ table_ref.job.id = "job-1"++ handle = MagicMock()+ handle.version.return_value = 151+ attributes: dict[str, Any] = {"open": staticmethod(MagicMock(return_value=handle))}+ if compact is not None:+ handle.compact = compact+ attributes["compact"] = compact+ fake_class = type("FakeDeltaLiteTable", (), attributes)+ return DeltaMaintenance(table_ref, clock=lambda: _NOW), table_ref, fake_class++ async def _run(+ self, maintenance: DeltaMaintenance, fake_class: Any, *, enabled: bool = True+ ) -> tuple[bool, AsyncMock, AsyncMock, MagicMock]:+ cache = DeltaLiteHandleCache(maxsize=2, opener=fake_class.open)+ with (+ override_settings(DATA_WAREHOUSE_DELTALITE_COMPACTION=enabled),+ patch.object(deltalite, "DeltaLiteTable", fake_class),+ patch(f"{_MAINTENANCE_MODULE}.get_handle_cache", return_value=cache),+ patch(f"{_MAINTENANCE_MODULE}.get_governor") as governor,+ patch(f"{_MAINTENANCE_MODULE}.os.cpu_count", return_value=7),+ patch(f"{_MAINTENANCE_MODULE}.capture_exception") as capture,+ patch.object(maintenance, "_plan_compaction", AsyncMock(return_value=_DEFAULT_PLAN)) as plan,+ patch.object(maintenance, "_compact", AsyncMock(return_value=True)) as delta_rs_compact,+ ):+ governor.return_value.slot_budget_mb.return_value = self._SLOT_MB+ governor.return_value.pod.current_mb.return_value = 4096.0+ ran = await maintenance.compact_if_fragmented(partition_count=1)+ return ran, delta_rs_compact, plan, capture++ @staticmethod+ def _info_calls(table_ref: Any, message: str) -> list[dict[str, Any]]:+ return [call.kwargs for call in table_ref.logger.ainfo.call_args_list if call.args[:1] == (message,)]++ @parameterized.expand(+ [+ ("committed", 1, 152, [152]),+ ("nothing_to_rewrite", 0, 150, []),+ ]+ )+ @pytest.mark.asyncio+ async def test_compacts_through_a_leased_deltalite_handle(+ self, _name: str, commits: int, version: int, expected_noted: list[int]+ ) -> None:+ compact = MagicMock(+ return_value={"commits": commits, "version": version, "numFilesAdded": 3, "numFilesRemoved": 300}+ )+ maintenance, table_ref, fake_class = self._setup(compact)++ with patch(f"{_MAINTENANCE_MODULE}._sample_compression_ratio", side_effect=AssertionError("sampled")):+ ran, delta_rs_compact, plan, capture = await self._run(maintenance, fake_class)++ assert ran is True+ delta_rs_compact.assert_not_awaited()+ plan.assert_not_awaited()+ capture.assert_not_called()+ fake_class.open.assert_called_once_with(self._URI, {"AWS_REGION": "us-east-1"})+ compact.assert_called_once_with(+ target_file_size=DEFAULT_COMPACT_TARGET_SIZE_BYTES,+ max_parallel_bins=7,+ slot_budget_bytes=int(self._SLOT_MB * _MB),+ commit_metadata={"compact_engine": "deltalite", "job_id": "job-1"},+ min_partition_removable_files=1,+ )+ assert [call.args[0] for call in table_ref.note_deltalite_commit.call_args_list] == expected_noted+ [done] = self._info_calls(table_ref, "compact: done")+ assert done["compact_engine"] == "deltalite"+ assert (done["compact_files_added"], done["compact_files_removed"]) == (3, 300)++ @pytest.mark.asyncio+ async def test_opens_a_fresh_handle_when_the_table_identity_is_unknown(self) -> None:+ compact = MagicMock(return_value={"commits": 1, "version": 151})+ maintenance, _, fake_class = self._setup(compact, table_id=None)++ with patch.object(DeltaLiteHandleCache, "lease") as lease:+ ran, _, _, _ = await self._run(maintenance, fake_class)++ assert ran is True+ lease.assert_not_called()+ compact.assert_called_once()++ @parameterized.expand(+ [+ ("setting_off", False, True, None, None, False),+ ("wheel_without_compact", True, False, None, "deltalite_compact_unavailable", False),+ (+ "unsupported_table",+ True,+ True,+ deltalite.DeltaLiteUnsupportedTableError("deletion vectors are not supported"),+ "unsupported_table",+ False,+ ),+ (+ "unexpected_deltalite_error",+ True,+ True,+ deltalite.DeltaLiteError("parquet decode failed"),+ "deltalite_error",+ True,+ ),+ ]+ )+ @pytest.mark.asyncio+ async def test_falls_back_to_delta_rs(+ self,+ _name: str,+ enabled: bool,+ has_compact: bool,+ error: Exception | None,+ expected_reason: str | None,+ expect_capture: bool,+ ) -> None:+ compact = MagicMock(side_effect=error) if has_compact else None+ maintenance, table_ref, fake_class = self._setup(compact)++ ran, delta_rs_compact, _, capture = await self._run(maintenance, fake_class, enabled=enabled)++ assert ran is True+ delta_rs_compact.assert_awaited_once_with(table_ref.get_delta_table.return_value, _DEFAULT_PLAN)+ fallbacks = self._info_calls(table_ref, "compact: falling back to delta-rs")+ assert [call["compact_fallback_reason"] for call in fallbacks] == ([expected_reason] if expected_reason else [])+ assert capture.called is expect_capture+ if not enabled and compact is not None:+ compact.assert_not_called()++ @pytest.mark.asyncio+ async def test_commit_conflict_skips_the_pass_without_reporting(self) -> None:+ compact = MagicMock(side_effect=deltalite.DeltaLiteCommitConflictError("schema changed"))+ maintenance, table_ref, fake_class = self._setup(compact)++ ran, delta_rs_compact, _, capture = await self._run(maintenance, fake_class)++ assert ran is False+ delta_rs_compact.assert_not_awaited()+ capture.assert_not_called()+ table_ref.note_deltalite_commit.assert_not_called()++ @parameterized.expand(+ [+ (+ "permission_denied",+ "Generic S3 error: Access Denied for _delta_log/00001.json",+ ObjectStorePermissionDeniedError,+ ),+ ("transient", "Generic S3 error: Please reduce your request rate", TransientObjectStoreError),+ ]+ )+ @pytest.mark.asyncio+ async def test_object_store_errors_use_the_existing_classifiers(+ self, _name: str, message: str, expected: type[Exception]+ ) -> None:+ compact = MagicMock(side_effect=deltalite.DeltaLiteError(message))+ maintenance, table_ref, fake_class = self._setup(compact)++ with pytest.raises(expected) as raised:+ await self._run(maintenance, fake_class)++ assert "_delta_log" not in str(raised.value)+ assert "_delta_log" not in str(table_ref.logger.method_calls)+ assert isinstance(raised.value.__cause__, deltalite.DeltaLiteError)++class TestVacuum:@pytest.mark.asyncioasync def test_retries_on_commit_conflict_then_succeeds(self):