: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): threshold-based compact and vacuum for CDC tables (#70499)
Daniel RCb778ad3f47b1
diff --git a/products/warehouse_sources/backend/models/external_data_schema.py b/products/warehouse_sources/backend/models/external_data_schema.pyindex bddb314823e9..376d24b64299 100644--- a/products/warehouse_sources/backend/models/external_data_schema.py+++ b/products/warehouse_sources/backend/models/external_data_schema.py@@ -260,6 +260,23 @@ class ExternalDataSchema(ModelActivityMixin, CreatedMetaFields, UpdatedMetaFieldreturn None+ @property+ def last_vacuum_version(self) -> int | None:+ # Delta version of the schema's snapshot table at its last vacuum (cadence watermark).+ if self.sync_type_config:+ return self.sync_type_config.get("last_vacuum_version", None)++ return None++ @property+ def last_vacuum_version_cdc(self) -> int | None:+ # Same watermark for the _cdc companion table — a separate delta table whose versions+ # are unrelated to the snapshot's, so it can't share last_vacuum_version.+ if self.sync_type_config:+ return self.sync_type_config.get("last_vacuum_version_cdc", None)++ return None+@propertydef partition_count_override(self) -> int | None:# Operator-pinned partition_count set via the admin repartition action. Unlikediff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/extract.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/extract.pyindex 51b5fdf5172d..ecf33bf8cfe7 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/extract.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/extract.py@@ -589,8 +589,9 @@ async def run_pre_write_defensive_compact(reaching `_post_run_operations` — keeping the subsequent per-partition merge scanscheap) and otherwise vacuums on a commit-count cadence so a table that OOMs its mergeevery run and never reaches post-load compaction still sheds tombstones (the- ~99%-dead-file tables). The helper returns the single vacuum watermark to persist, so- this function is the sole writer of `last_vacuum_version`. Wrapped in try/except so a+ ~99%-dead-file tables). The helper returns the single vacuum watermark to persist;+ the CDC post-load path in `common/load.py` writes the same watermark, and both merge+ via `update_sync_type_config_keys` under a row lock. Wrapped in try/except so amaintenance failure never blocks the actual sync; the original error path is unaffected.Used by both `PipelineNonDLT.run` (v2) and `PipelineV3.run` to keep the behaviour@@ -603,8 +604,8 @@ async def run_pre_write_defensive_compact()partition_count_for_compact = schema.partition_count or resource.partition_count- last_vacuum_version = (schema.sync_type_config or {}).get("last_vacuum_version")- commit_threshold = int(getattr(settings, "DATA_WAREHOUSE_VACUUM_COMMIT_THRESHOLD", 100))+ last_vacuum_version = schema.last_vacuum_version+ commit_threshold = settings.DATA_WAREHOUSE_VACUUM_COMMIT_THRESHOLDnew_version = await delta_table_helper.run_maintenance(partition_count=partition_count_for_compact,last_vacuum_version=last_vacuum_version,diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/load.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/load.pyindex 5e94e0642d20..f87ac6754531 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@@ -1,5 +1,6 @@from typing import TYPE_CHECKING, Any, Literal, Optional+from django.conf import settingsfrom django.db.models import Fimport pyarrow as pa@@ -12,7 +13,11 @@ from posthog.sync import database_sync_to_async_poolfrom posthog.temporal.common.logger import get_loggerfrom products.warehouse_sources.backend.models.external_data_job import ExternalDataJob-from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema, process_incremental_value+from products.warehouse_sources.backend.models.external_data_schema import (+ ExternalDataSchema,+ process_incremental_value,+ update_sync_type_config_keys,+)from products.warehouse_sources.backend.models.table import DataWarehouseTablefrom products.warehouse_sources.backend.temporal.data_imports.pipelines.helpers import (sync_engineering_analytics_views,@@ -287,13 +292,49 @@ async def run_post_load_operations(# table independently, otherwise we overwrite the snapshot queryable_folder with the SCD2 path.is_cdc_companion = cdc_write_mode == "scd2_append"- logger.debug("Triggering compaction and vacuuming on delta table")- try:- with POST_LOAD_DURATION_SECONDS.labels(operation="compact").time():- await delta_table_helper.compact_table()- except Exception as e:- capture_exception(e)- logger.exception(f"Compaction failed: {e}", exc_info=e)+ if schema.is_cdc:+ # CDC finals land once per tick per changed schema, so unconditional compaction would run+ # near-continuously after mostly-tiny merges. Use threshold/cadence maintenance instead:+ # compact when fragmented, otherwise vacuum once enough commits have accrued.+ logger.debug("Running threshold-based delta maintenance")+ try:+ with POST_LOAD_DURATION_SECONDS.labels(operation="maintenance").time():+ # Only md5 partitioning persists a partition_count; datetime/numerical modes leave it+ # None, and the companion is a different table than the one schema.partition_count+ # describes. Without a count the threshold math treats the table as one partition and+ # any >200-file table compacts every tick, so derive it from the table's actual layout+ # (one directory per partition value in the delta log's file paths).+ partition_count = None if is_cdc_companion else schema.partition_count+ if partition_count is None:+ file_uris = await delta_table_helper.get_file_uris()+ partition_count = len({uri.rsplit("/", 1)[0] for uri in file_uris}) or None++ # 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 would corrupt both cadences.+ watermark_key = "last_vacuum_version_cdc" if is_cdc_companion else "last_vacuum_version"+ last_vacuum_version = schema.last_vacuum_version_cdc if is_cdc_companion else schema.last_vacuum_version+ commit_threshold = settings.DATA_WAREHOUSE_VACUUM_COMMIT_THRESHOLD+ new_version = await delta_table_helper.run_maintenance(+ partition_count=partition_count,+ last_vacuum_version=last_vacuum_version,+ commit_threshold=commit_threshold,+ )+ 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 Exception as e:+ capture_exception(e)+ logger.exception(f"Delta maintenance failed: {e}", exc_info=e)+ else:+ logger.debug("Triggering compaction and vacuuming on delta table")+ try:+ with POST_LOAD_DURATION_SECONDS.labels(operation="compact").time():+ await delta_table_helper.compact_table()+ except Exception as e:+ capture_exception(e)+ logger.exception(f"Compaction failed: {e}", exc_info=e)if is_cdc_companion:# Look up the existing companion table's queryable_folder (not the main schema.table).diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/test/test_load.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/test/test_load.pynew file mode 100644index 000000000000..d175c0e7e7e5--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/test/test_load.py@@ -0,0 +1,185 @@+import uuid++import pytest+from unittest.mock import AsyncMock, MagicMock, patch++from parameterized import parameterized++from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema+from products.warehouse_sources.backend.temporal.data_imports.pipelines.common.load import run_post_load_operations++_LOAD_MODULE = "products.warehouse_sources.backend.temporal.data_imports.pipelines.common.load"+_PIPELINE_SYNC_MODULE = "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_sync"+_REPARTITION_MODULE = (+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.repartition_controller"+)+++def _make_schema(*, is_cdc: bool, sync_type_config: dict | None = None, partition_count: int | None = 7) -> MagicMock:+ config = sync_type_config if sync_type_config is not None else {}+ schema = MagicMock()+ schema.id = uuid.uuid4()+ schema.team_id = 1+ schema.is_cdc = is_cdc+ schema.sync_type = ExternalDataSchema.SyncType.CDC if is_cdc else ExternalDataSchema.SyncType.INCREMENTAL+ schema.sync_type_config = config+ schema.last_vacuum_version = config.get("last_vacuum_version")+ schema.last_vacuum_version_cdc = config.get("last_vacuum_version_cdc")+ schema.partition_count = partition_count+ schema.cdc_table_mode = "consolidated"+ schema.initial_sync_complete = True+ return schema+++def _make_helper(*, run_maintenance_returns: int | None = None, file_uris: list[str] | None = None) -> MagicMock:+ return MagicMock(+ get_delta_table=AsyncMock(return_value=MagicMock()),+ get_file_uris=AsyncMock(return_value=file_uris or []),+ compact_table=AsyncMock(),+ run_maintenance=AsyncMock(return_value=run_maintenance_returns),+ )+++async def _run_post_load(+ schema: MagicMock,+ helper: MagicMock,+ *,+ cdc_write_mode: str | None = None,+) -> tuple[MagicMock, AsyncMock]:+ job = MagicMock()+ job.id = uuid.uuid4()+ job.team_id = schema.team_id+ logger = MagicMock(adebug=AsyncMock(), ainfo=AsyncMock())++ prepare_s3 = AsyncMock(return_value="orders__query_1")+ with (+ patch(f"{_LOAD_MODULE}.prepare_s3_files_for_querying", prepare_s3),+ patch(f"{_LOAD_MODULE}.notify_revenue_analytics_that_sync_has_completed", AsyncMock()),+ patch(f"{_LOAD_MODULE}.sync_revenue_analytics_views", MagicMock()),+ patch(f"{_LOAD_MODULE}.update_sync_type_config_keys", MagicMock()) as update_config,+ patch(f"{_LOAD_MODULE}.DataWarehouseTable", MagicMock()),+ patch(f"{_PIPELINE_SYNC_MODULE}.update_last_synced_at", AsyncMock()),+ patch(f"{_PIPELINE_SYNC_MODULE}.validate_schema_and_update_table", AsyncMock()),+ patch(f"{_PIPELINE_SYNC_MODULE}.register_cdc_companion_table", AsyncMock()),+ patch(f"{_REPARTITION_MODULE}.maybe_flag_for_repartition", AsyncMock()),+ ):+ await run_post_load_operations(+ job=job,+ schema=schema,+ source=MagicMock(),+ delta_table_helper=helper,+ row_count=10,+ file_uris=["s3://bucket/orders/1.parquet"],+ table_schema_dict={},+ resource_name="orders",+ logger=logger,+ cdc_write_mode=cdc_write_mode,+ )+ return update_config, prepare_s3+++class TestRunPostLoadDeltaMaintenance:+ @pytest.mark.asyncio+ async def test_cdc_schema_uses_threshold_maintenance_not_unconditional_compact(self):+ # The incident behavior this guards: CDC finals land every tick, so an unconditional+ # compact_table here means hundreds of compact+vacuum cycles per hour on a busy source.+ schema = _make_schema(is_cdc=True, sync_type_config={"last_vacuum_version": 41})+ helper = _make_helper()++ await _run_post_load(schema, helper, cdc_write_mode="incremental")++ helper.compact_table.assert_not_awaited()+ assert helper.run_maintenance.await_args is not None+ assert helper.run_maintenance.await_args.kwargs == {+ "partition_count": 7,+ "last_vacuum_version": 41,+ "commit_threshold": 100,+ }++ @pytest.mark.asyncio+ async def test_missing_partition_count_is_derived_from_table_layout(self):+ # datetime/numerical-partitioned schemas persist no partition_count. Passing None through+ # makes the threshold math treat the table as one partition, so any >200-file table would+ # compact every tick again — the exact behavior this change removes.+ schema = _make_schema(is_cdc=True, partition_count=None)+ helper = _make_helper(+ file_uris=[+ "s3://bucket/orders/_ph_partition_key=2026-01/a.parquet",+ "s3://bucket/orders/_ph_partition_key=2026-01/b.parquet",+ "s3://bucket/orders/_ph_partition_key=2026-02/c.parquet",+ ]+ )++ await _run_post_load(schema, helper, cdc_write_mode="incremental")++ assert helper.run_maintenance.await_args is not None+ assert helper.run_maintenance.await_args.kwargs["partition_count"] == 2++ @pytest.mark.asyncio+ async def test_non_cdc_schema_keeps_unconditional_compact(self):+ schema = _make_schema(is_cdc=False)+ helper = _make_helper()++ update_config, _ = await _run_post_load(schema, helper)++ helper.compact_table.assert_awaited_once()+ helper.run_maintenance.assert_not_awaited()+ update_config.assert_not_called()++ @pytest.mark.asyncio+ async def test_cdc_companion_uses_its_own_watermark_key(self):+ # The snapshot and _cdc companion are different delta tables with unrelated versions, so+ # the companion must run cadence maintenance against last_vacuum_version_cdc — reading or+ # writing the snapshot's last_vacuum_version would corrupt both cadences, and skipping+ # cadence maintenance entirely would let companion tombstones accumulate until the+ # file-count thresholds happen to trip. Partition count is derived from its own layout —+ # schema.partition_count describes the snapshot table.+ schema = _make_schema(is_cdc=True, sync_type_config={"last_vacuum_version": 41, "last_vacuum_version_cdc": 7})+ helper = _make_helper(run_maintenance_returns=9, file_uris=["s3://bucket/orders_cdc/a.parquet"])++ update_config, _ = await _run_post_load(schema, helper, cdc_write_mode="scd2_append")++ assert helper.run_maintenance.await_args is not None+ assert helper.run_maintenance.await_args.kwargs == {+ "partition_count": 1,+ "last_vacuum_version": 7,+ "commit_threshold": 100,+ }+ update_config.assert_called_once_with(schema.id, schema.team_id, updates={"last_vacuum_version_cdc": 9})++ @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),+ ]+ )+ @pytest.mark.asyncio+ async def test_watermark_persistence(self, _name: str, returned_version: int | None, expect_write: bool):+ schema = _make_schema(is_cdc=True, sync_type_config={"last_vacuum_version": 41})+ helper = _make_helper(run_maintenance_returns=returned_version)++ update_config, _ = await _run_post_load(schema, helper, cdc_write_mode="incremental")++ 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()++ @pytest.mark.asyncio+ async def test_maintenance_failure_does_not_fail_post_load(self):+ # A maintenance hiccup (S3 flake) must not fail the final batch — the rest of post-load+ # (queryable folder prep, table registration) still has to run or the job wedges.+ schema = _make_schema(is_cdc=True)+ helper = _make_helper()+ helper.run_maintenance = AsyncMock(side_effect=RuntimeError("maintenance blew up"))++ with patch(f"{_LOAD_MODULE}.capture_exception") as mock_capture:+ _, prepare_s3 = await _run_post_load(schema, helper, cdc_write_mode="incremental")++ mock_capture.assert_called_once()+ prepare_s3.assert_awaited_once()diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/delta_table_helper.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/delta_table_helper.pyindex 8e69fecf45c4..d45a5c331d04 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/delta_table_helper.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/delta_table_helper.py@@ -745,8 +745,8 @@ class DeltaTableHelper:`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, or on first- encounter (seeding the watermark without vacuuming, to avoid a synchronized vacuum wave on deploy);+ 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."""table = await self.get_delta_table()@@ -754,9 +754,12 @@ class DeltaTableHelper:return Noneversion = await asyncio.to_thread(table.version)- if last_vacuum_version is None:+ 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 versioncommits_since = version - last_vacuum_version@@ -855,8 +858,9 @@ class DeltaTableHelper:vacuums as part of compaction, so when it runs it supersedes the cadence vacuum (no double vacuumin 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; the caller is the sole writer of- the watermark so it lives in exactly one place.+ `last_vacuum_version` watermark, or None when nothing changed. Callers persist the watermark+ via `update_sync_type_config_keys` (row-locked merge): the pre-write defensive path in+ `common/extract.py` and the CDC post-load path in `common/load.py`."""compacted = await self.compact_if_fragmented(partition_count=partition_count)if compacted:diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/test/test_delta_table_helper.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/test/test_delta_table_helper.pyindex 24c15ce62fdb..46ebd6219db4 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/test/test_delta_table_helper.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/test/test_delta_table_helper.py@@ -838,6 +838,10 @@ class TestVacuumIfStale:("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),])@pytest.mark.asyncio