Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

perf(data-warehouse): cut repeated table opens and no-op work from v3 loads (#107402)

Tom Owers8e02df942a1b
diff --git a/products/warehouse_sources/backend/temporal/data_imports/external_data_job.py b/products/warehouse_sources/backend/temporal/data_imports/external_data_job.py
index 14cf8d8da889..4c5b93cd32af 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/external_data_job.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/external_data_job.py
@@ -876,6 +876,7 @@ class ExternalDataJobWorkflow(PostHogWorkflow):
person_property_sync_enabled = False
fast_return_eligible = False
scheduled_full_refresh = False
+ repartition_needed = True
else:
job_id = create_job_result.job_id
incremental_or_append = create_job_result.incremental_or_append
@@ -888,6 +889,7 @@ class ExternalDataJobWorkflow(PostHogWorkflow):
person_property_sync_enabled = create_job_result.person_property_sync_enabled
fast_return_eligible = create_job_result.fast_return_eligible
scheduled_full_refresh = create_job_result.scheduled_full_refresh
+ repartition_needed = create_job_result.repartition_needed
update_inputs.job_id = str(job_id) if job_id is not None else None
# Check billing limits
@@ -908,9 +910,10 @@ class ExternalDataJobWorkflow(PostHogWorkflow):
# Pre-extraction, in-place repartition of any table flagged on a prior run. Runs here — sole
# writer, lock held, before the merge — so the subsequent merge uses the memory-safe layout.
- # A no-op unless a repartition is pending; never fails the sync (errors are swallowed). A scheduled
- # full refresh deletes the table before extraction, so rewriting it first is wasted work.
- if job_id is not None and not scheduled_full_refresh:
+ # Never fails the sync (errors are swallowed). Skipped when the job-creation activity saw nothing
+ # queued and no on-disk measurement due, so the common sync pays no activity round trip. A
+ # scheduled full refresh deletes the table before extraction, so rewriting it first is wasted work.
+ if job_id is not None and not scheduled_full_refresh and repartition_needed:
try:
await workflow.execute_activity(
maybe_repartition_table_activity,
@@ -929,6 +932,17 @@ class ExternalDataJobWorkflow(PostHogWorkflow):
"Repartition activity failed; continuing with sync on existing layout",
extra={"schema_id": str(inputs.external_data_schema_id)},
)
+ elif job_id is not None:
+ # Logged so the Syncs UI/log stream still shows the repartition check ran for the
+ # common no-op case — the activity's own start/finish logs only fire when it's called.
+ workflow.logger.info(
+ "Repartition scheduling skipped",
+ extra={
+ "schema_id": str(inputs.external_data_schema_id),
+ "repartition_needed": repartition_needed,
+ "scheduled_full_refresh": scheduled_full_refresh,
+ },
+ )
job_inputs = ImportDataActivityInputs(
team_id=inputs.team_id,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/load.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/load.py
index 9d2c9ed4ac8e..bd13e5656585 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
@@ -270,36 +270,20 @@ async def _run_delta_maintenance(
delta_table_ref: "DeltaTableRef",
is_cdc_companion: bool,
logger: FilteringBoundLogger,
+ partition_count_fallback: int | None,
) -> None:
- from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.errors import ( # noqa: PLC0415 — keeps the heavy deltalake dep off this module's top-level import path
- is_transient_maintenance_error,
- )
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.maintenance import ( # noqa: PLC0415 — keeps the heavy deltalake dep off this module's top-level import path
DeltaMaintenance,
)
- maintenance = DeltaMaintenance(delta_table_ref)
- 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")
- with POST_LOAD_DURATION_SECONDS.labels(operation="maintenance").time():
- await maintenance.run_scheduled(schema, is_cdc_companion=is_cdc_companion)
- else:
- logger.debug("Triggering compaction and vacuuming on delta table")
- try:
- with POST_LOAD_DURATION_SECONDS.labels(operation="compact").time():
- await maintenance.compact_table()
- except Exception as e:
- if is_transient_maintenance_error(e):
- # A rate-limited or connectivity blip talking to our own S3 bucket (or a concurrent
- # maintenance pass losing a file race) isn't a bug - the next sync's maintenance pass
- # retries the same idempotent cleanup.
- logger.warning(f"Compaction skipped: transient infra error: {e}")
- else:
- capture_exception(e)
- logger.exception(f"Compaction failed: {e}", exc_info=e)
+ # 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.
+ logger.debug("Running threshold-based delta maintenance")
+ with POST_LOAD_DURATION_SECONDS.labels(operation="maintenance").time():
+ await DeltaMaintenance(delta_table_ref).run_scheduled(
+ schema, is_cdc_companion=is_cdc_companion, partition_count_fallback=partition_count_fallback
+ )
async def _publish_queryable_files(
@@ -604,7 +588,7 @@ async def run_post_load_operations(
) -> Optional[str]:
"""
Orchestrator that runs all post-load operations, in order:
- 1. Delta maintenance (threshold-based for CDC schemas, unconditional compaction otherwise)
+ 1. Delta maintenance (compact when fragmented, otherwise vacuum on commit cadence)
2. Prepare S3 files for querying
3. Sync bookkeeping (last_synced_at, initial_sync_complete, desc-sort incremental finalization)
4. Register the table (skipped for CDC companion writes and cdc_only initial loads)
@@ -660,7 +644,13 @@ async def run_post_load_operations(
await _run_post_load_steps(job, schema, source, delta_table_ref, is_cdc_companion, logger)
return None
- await _run_delta_maintenance(schema, delta_table_ref, is_cdc_companion, logger)
+ await _run_delta_maintenance(
+ schema,
+ delta_table_ref,
+ is_cdc_companion,
+ logger,
+ partition_count_fallback=resource.partition_count if resource is not None else None,
+ )
queryable_folder = await _publish_queryable_files(
job, schema, delta_table_ref, resource_name, is_cdc_companion, logger
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/test/test_load.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/test/test_load.py
index 9528e884b02d..d66e26104662 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/test/test_load.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/test/test_load.py
@@ -8,7 +8,6 @@ from unittest.mock import AsyncMock, MagicMock, patch
from django.db import OperationalError
import pyarrow as pa
-import deltalake.exceptions
from parameterized import parameterized
from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
@@ -69,8 +68,8 @@ async def _run_post_load(
helper: MagicMock,
*,
cdc_write_mode: str | None = None,
- compact_error: Exception | None = None,
-) -> tuple[AsyncMock, AsyncMock, AsyncMock]:
+ resource: Optional[MagicMock] = None,
+) -> tuple[AsyncMock, AsyncMock]:
job = MagicMock()
job.id = uuid.uuid4()
job.team_id = schema.team_id
@@ -78,7 +77,6 @@ async def _run_post_load(
prepare_s3 = AsyncMock(return_value="orders__query_1")
run_scheduled = AsyncMock()
- compact_table = AsyncMock(side_effect=compact_error)
with (
patch(f"{_LOAD_MODULE}.prepare_s3_files_for_querying", prepare_s3),
patch(f"{_LOAD_MODULE}.notify_revenue_analytics_that_sync_has_completed", AsyncMock()),
@@ -86,7 +84,6 @@ async def _run_post_load(
patch(f"{_LOAD_MODULE}.DataWarehouseTable", MagicMock()),
patch(f"{_LOAD_MODULE}.set_initial_sync_complete", AsyncMock()),
patch.object(DeltaMaintenance, "run_scheduled", run_scheduled),
- patch.object(DeltaMaintenance, "compact_table", compact_table),
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()),
@@ -101,34 +98,39 @@ async def _run_post_load(
table_schema_dict={},
resource_name="orders",
logger=logger,
+ resource=resource,
cdc_write_mode=cdc_write_mode,
)
- return run_scheduled, compact_table, prepare_s3
+ return run_scheduled, prepare_s3
class TestRunPostLoadDeltaMaintenance:
- """Post-load picks the right maintenance flavor per schema kind; the threshold/watermark
+ """Post-load routes every schema kind through threshold maintenance; the threshold/watermark
mechanics themselves are covered in core/delta/test/test_maintenance.py."""
+ @parameterized.expand([("cdc", True, "incremental"), ("non_cdc", False, None)])
@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})
+ async def test_uses_threshold_maintenance_not_unconditional_compact(
+ self, _name: str, is_cdc: bool, cdc_write_mode: str | None
+ ) -> None:
+ # CDC finals land every tick, and a non-CDC final batch usually leaves nothing to compact,
+ # so an unconditional compact+vacuum here paid a full file listing and rewrite plan per sync.
+ schema = _make_schema(is_cdc=is_cdc, sync_type_config={"last_vacuum_version": 41})
- run_scheduled, compact_table, _ = await _run_post_load(schema, _make_helper(), cdc_write_mode="incremental")
+ run_scheduled, _ = await _run_post_load(schema, _make_helper(), cdc_write_mode=cdc_write_mode)
- compact_table.assert_not_awaited()
- run_scheduled.assert_awaited_once_with(schema, is_cdc_companion=False)
+ run_scheduled.assert_awaited_once_with(schema, is_cdc_companion=False, partition_count_fallback=None)
@pytest.mark.asyncio
- async def test_non_cdc_schema_keeps_unconditional_compact(self):
- schema = _make_schema(is_cdc=False)
+ async def test_forwards_resource_partition_count_as_fallback(self) -> None:
+ # A first sync has no schema.partition_count persisted yet; the fallback comes from the
+ # synced resource instead, so this must actually reach run_scheduled and not silently drop.
+ schema = _make_schema(is_cdc=False, sync_type_config={"last_vacuum_version": 41}, partition_count=None)
+ resource = MagicMock(partition_count=12)
- run_scheduled, compact_table, _ = await _run_post_load(schema, _make_helper())
+ run_scheduled, _ = await _run_post_load(schema, _make_helper(), resource=resource)
- compact_table.assert_awaited_once()
- run_scheduled.assert_not_awaited()
+ run_scheduled.assert_awaited_once_with(schema, is_cdc_companion=False, partition_count_fallback=12)
@pytest.mark.asyncio
async def test_cdc_companion_write_runs_companion_maintenance(self):
@@ -137,9 +139,9 @@ class TestRunPostLoadDeltaMaintenance:
# watermark key and layout instead of the snapshot's (see test_maintenance.TestRunScheduled).
schema = _make_schema(is_cdc=True, sync_type_config={"last_vacuum_version": 41, "last_vacuum_version_cdc": 7})
- run_scheduled, _, _ = await _run_post_load(schema, _make_helper(), cdc_write_mode="scd2_append")
+ run_scheduled, _ = await _run_post_load(schema, _make_helper(), cdc_write_mode="scd2_append")
- run_scheduled.assert_awaited_once_with(schema, is_cdc_companion=True)
+ run_scheduled.assert_awaited_once_with(schema, is_cdc_companion=True, partition_count_fallback=None)
@parameterized.expand([("non_cdc", False), ("cdc", True)])
@pytest.mark.asyncio
@@ -151,43 +153,12 @@ class TestRunPostLoadDeltaMaintenance:
post_maintenance_uris = ["s3://bucket/orders/compacted.parquet"]
helper = _make_helper(file_uris=post_maintenance_uris)
- _, _, prepare_s3 = await _run_post_load(schema, helper, cdc_write_mode="incremental" if is_cdc else None)
+ _, prepare_s3 = await _run_post_load(schema, helper, cdc_write_mode="incremental" if is_cdc else None)
prepare_s3.assert_awaited_once()
assert prepare_s3.await_args is not None
assert prepare_s3.await_args.args[2] == post_maintenance_uris
- @parameterized.expand(
- [
- # A genuine compaction bug must still be captured for visibility.
- ("genuine_bug", RuntimeError("compaction blew up"), True),
- # A transient S3 rate-limit/connectivity blip is already non-fatal here (the next
- # sync's maintenance retries the same idempotent cleanup) and must not be promoted
- # into a fresh error-tracking issue — the regression this guards.
- ("transient_s3_slowdown", OSError("Generic S3 error: Please reduce your request rate."), False),
- # Likewise for a concurrent-maintenance race: a full_refresh `reset_table` purging
- # `_delta_log` out from under this same compact/vacuum pass is self-healing, not a defect.
- (
- "transient_delta_maintenance_race",
- deltalake.exceptions.DeltaError(
- "Generic error: Kernel error: File not found: table/_delta_log/00000000000000000001.json"
- ),
- False,
- ),
- ]
- )
- @pytest.mark.asyncio
- async def test_compact_failure_handling(self, _name: str, error: Exception, expect_capture: bool):
- # A compaction hiccup 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=False)
-
- with patch(f"{_LOAD_MODULE}.capture_exception") as mock_capture:
- _, _, prepare_s3 = await _run_post_load(schema, _make_helper(), compact_error=error)
-
- assert mock_capture.called is expect_capture
- prepare_s3.assert_awaited_once()
-
class TestZeroRowSkip:
@parameterized.expand(
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/arrow_utils.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/arrow_utils.py
index d92043c2333e..84dd16ac8d74 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/arrow_utils.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/arrow_utils.py
@@ -6,8 +6,7 @@ import math
import uuid
import decimal
import datetime
-from collections.abc import Callable, Collection, Iterable, Iterator, Mapping, Sequence
-from functools import _make_key, wraps
+from collections.abc import Collection, Iterable, Iterator, Mapping, Sequence
from ipaddress import IPv4Address, IPv6Address
from typing import TYPE_CHECKING, Any, Literal, Optional, cast
@@ -17,7 +16,6 @@ import pyarrow as pa
import deltalake as deltalake
import pyarrow.compute as pc
from arro3.core.types import ArrowSchemaExportable
-from circular_dict import CircularDict
from dateutil import parser
from dlt.common.libs.deltalake import ensure_delta_compatible_arrow_schema
from psycopg.types.multirange import Multirange
@@ -1858,53 +1856,6 @@ def _process_batch(
return pa.Table.from_pydict(columnar_table_data, schema=arrow_schema)
-# from `conditional-cache`, but changed to be made async
-def conditional_lru_cache_async(
- maxsize: int = 128, typed: bool = False, condition: Callable[[Any], bool] = lambda x: True
-):
- cache = CircularDict(maxlen=maxsize)
-
- def decorator(func):
- @wraps(func)
- async def wrapper(*args, **kwargs):
- key = _make_key(args, kwargs, typed)
-
- if key in cache:
- return cache[key]
-
- result = await func(*args, **kwargs)
-
- if condition(result):
- cache[key] = result
-
- return result
-
- def cache_remove(*args, **kwargs):
- key = _make_key(args, kwargs, typed)
- cache.pop(key, None)
-
- def cache_pop(*args, **kwargs) -> Any:
- """Remove and return a cached value without ever invoking `func` — unlike calling
- `wrapper` itself, a cache miss returns `None` instead of computing and storing a
- fresh result. For callers that only want to release an already-cached resource.
-
- Checks membership before popping: CircularDict.pop(key, None) treats a `None`
- default as "no default" and raises KeyError on a miss instead of returning it.
- """
- key = _make_key(args, kwargs, typed)
- if key not in cache:
- return None
- return cache.pop(key)
-
- cast(Any, wrapper).cache_remove = cache_remove
- cast(Any, wrapper).cache_clear = lambda: cache.clear()
- cast(Any, wrapper).cache_pop = cache_pop
-
- return wrapper
-
- return decorator
-
-
def realign_decimal_buffers(table: pa.Table) -> pa.Table:
"""Re-materialize any Decimal128/256 column whose values buffer isn't 16-byte aligned.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/maintenance.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/maintenance.py
index 127e88a81257..2c0e81aa7b6b 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
@@ -70,8 +70,7 @@ class DeltaMaintenance:
Stateless over a `DeltaTableRef`, which holds the cached table handle — construct one at the
call site whenever maintenance is needed. `run_scheduled` is the policy entry point shared by
the pre-write defensive pass (both pipelines, so a sync that arrived at a fragmented table
- cleans up before adding to the pile) and the CDC post-load pass; `compact_table` is the
- unconditional post-load compaction for non-CDC syncs.
+ cleans up before adding to the pile) and the post-load pass.
"""
def __init__(self, table: "DeltaTableRef") -> None:
@@ -107,7 +106,7 @@ class DeltaMaintenance:
compact_stats = await execute_with_conflict_retry(
table,
_compact_op,
- "compact_table",
+ "compact",
self._logger,
)
break
@@ -117,41 +116,17 @@ class DeltaMaintenance:
attempt += 1
target_size //= 2
await self._logger.awarning(
- f"compact_table: byte array offset overflow, retrying with smaller "
+ f"compact: byte array offset overflow, retrying with smaller "
f"target_size={target_size} (attempt {attempt}/{COMPACT_OFFSET_OVERFLOW_RETRIES})"
)
await self._logger.adebug(json.dumps(compact_stats))
- async def compact_table(self) -> None:
- """Compact and vacuum unconditionally, after a non-CDC sync has loaded its rows.
-
- An object-store refusal (see `run_scheduled` for why it does not fail the sync) is logged
- and swallowed. Every other failure propagates to the caller, which decides how to report it.
- """
- table = await self._table.get_delta_table()
- if table is None:
- raise Exception("Deltatable not found")
-
- try:
- await self._compact(table)
- # Reuse the table already resolved above instead of re-fetching it: `get_delta_table`
- # is cached only opportunistically, so a re-fetch here can race a concurrent sync of a
- # different table evicting this table's cache entry and spuriously report it missing.
- await self._vacuum(table)
- except ObjectStorePermissionDeniedError:
- await self._logger.awarning(
- "Delta maintenance skipped: the object store denied the operation. The table's rows "
- "are unaffected and the next maintenance pass retries the same cleanup."
- )
- return
- await self._logger.adebug("Compacting and vacuuming complete")
-
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.
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_table`'s
+ 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
@@ -222,9 +197,9 @@ class DeltaMaintenance:
arrive 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`. Intended for pre-write defensive cleanup
- so a sync that arrived at a fragmented state (e.g. an earlier attempt that failed
- before reaching post-load compaction) cleans up before adding to the pile.
+ 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.
"""
table = await self._table.get_delta_table()
if table is None:
@@ -292,7 +267,7 @@ class DeltaMaintenance:
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 CDC post-load pass) share this, so the watermark can't drift between them.
+ pass and the post-load pass) share this, so the watermark can't drift between them.
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
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/ops.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/ops.py
index 3d09a66a4f95..03dac2860db3 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/ops.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/ops.py
@@ -1,6 +1,6 @@
import asyncio
from collections.abc import Callable
-from typing import TypeVar
+from typing import TypedDict, TypeVar
from django.conf import settings
@@ -8,7 +8,12 @@ import deltalake
import deltalake.exceptions
from structlog.types import FilteringBoundLogger
-from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.errors import is_invalid_version_race
+from posthog.exceptions_capture import capture_exception
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.errors import (
+ is_invalid_version_race,
+ is_transient_maintenance_error,
+)
T = TypeVar("T")
@@ -56,7 +61,12 @@ def is_object_store_permission_denied(error: BaseException) -> bool:
)
-def delta_merge_spill_kwargs() -> dict[str, int]:
+class DeltaMergeSpillKwargs(TypedDict, total=False):
+ max_spill_size: int
+ max_temp_directory_size: int
+
+
+def delta_merge_spill_kwargs() -> DeltaMergeSpillKwargs:
"""delta-rs `merge` kwargs that let DataFusion spill to disk instead of OOMing on large merges.
A merge decompresses the target partition into an Arrow working set that can exceed the pod's
@@ -66,7 +76,7 @@ def delta_merge_spill_kwargs() -> dict[str, int]:
DataFusion keeps its unbounded default (today's behavior), which also keeps this compatible with
deltalake versions predating the parameters.
"""
- kwargs: dict[str, int] = {}
+ kwargs: DeltaMergeSpillKwargs = {}
if settings.DATA_WAREHOUSE_DELTA_MERGE_MAX_SPILL_SIZE_BYTES is not None:
kwargs["max_spill_size"] = settings.DATA_WAREHOUSE_DELTA_MERGE_MAX_SPILL_SIZE_BYTES
if settings.DATA_WAREHOUSE_DELTA_MERGE_MAX_TEMP_DIRECTORY_SIZE_BYTES is not None:
@@ -124,3 +134,51 @@ async def execute_with_conflict_retry(
f"(attempt {attempt}/{DELTA_MERGE_CONFLICT_RETRIES})"
)
await asyncio.to_thread(table.update_incremental)
+
+
+# delta-rs replays every commit after the latest checkpoint when it opens a table, and it reads that
+# uncheckpointed tail twice. Its default checkpoints every 100 commits, so a table that takes many
+# small commits pays a long replay on every open. A checkpoint write itself is O(live file count),
+# not O(commits since last checkpoint) — it serializes the table's whole current add-action listing —
+# so dropping the interval too far raises checkpoint-write frequency on exactly the large/hot tables
+# (hundreds to tens of thousands of files, see maintenance.py's documented p90/p99/pathological file
+# counts) where that rewrite is most expensive. 25 shortens the uncheckpointed tail well below the
+# default without quadrupling checkpoint-write frequency the way 10 would. deltalite reads the same
+# property when it commits, so both writers checkpoint on the same cadence.
+DELTA_TABLE_PROPERTIES: dict[str, str] = {"delta.checkpointInterval": "25"}
+
+
+async def ensure_table_properties(table: deltalake.DeltaTable, logger: FilteringBoundLogger) -> bool:
+ """Apply DELTA_TABLE_PROPERTIES to a table that was created without them.
+
+ A metadata-only commit, made once per table: the check reads the handle's own snapshot, and
+ `set_table_properties` refreshes that snapshot, so a table that already carries the values costs
+ nothing here. Never raises, because the data write has already committed and a property that
+ fails to land only waits for the next write. Returns True when it committed.
+ """
+ try:
+ # The metadata read is in the same best-effort boundary as the write below: it touches the
+ # same table handle (and, on a lazily-loaded snapshot, can hit the same object store), and
+ # the data commit has already landed either way, so a failure here must not propagate either.
+ current = table.metadata().configuration or {}
+ missing = {key: value for key, value in DELTA_TABLE_PROPERTIES.items() if current.get(key) != value}
+ if not missing:
+ return False
+ await execute_with_conflict_retry(
+ table, lambda: table.alter.set_table_properties(missing), "set_table_properties", logger
+ )
+ except ObjectStorePermissionDeniedError as e:
+ await logger.awarning(
+ f"set_table_properties: could not apply table properties, will retry on the next write: {e}"
+ )
+ return False
+ except Exception as e: # noqa: BLE001 - best-effort; the data commit already landed
+ if not is_transient_maintenance_error(e):
+ # Not a known transient/permission case, so this commit can never succeed on its own —
+ # every write would otherwise retry it forever with nothing surfacing to error tracking.
+ capture_exception(e)
+ await logger.awarning(
+ f"set_table_properties: could not apply table properties, will retry on the next write: {e}"
+ )
+ return False
+ return True
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/scd2.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/scd2.py
index 8e457c7db91c..342abab957ea 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/scd2.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/scd2.py
@@ -14,7 +14,9 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arr
)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.evolution import evolve_delta_schema
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.ops import (
+ DELTA_TABLE_PROPERTIES,
delta_merge_spill_kwargs,
+ ensure_table_properties,
execute_with_conflict_retry,
)
@@ -126,6 +128,7 @@ class Scd2DeltaWriter:
table_uri=delta_uri,
schema=data.schema,
storage_options=storage_options,
+ configuration=DELTA_TABLE_PROPERTIES,
)
await asyncio.to_thread(
@@ -139,4 +142,6 @@ class Scd2DeltaWriter:
delta_table = await self._table.get_delta_table()
assert delta_table is not None
+
+ await ensure_table_properties(delta_table, self._logger)
return delta_table
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/table.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/table.py
index d7c16ee9336a..633c891cf130 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/table.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/table.py
@@ -13,9 +13,6 @@ from posthog.sync import database_sync_to_async_pool
from products.data_warehouse.backend.facade.api import aget_s3_client, delta_proxy_storage_options, ensure_bucket_exists
from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob
from products.warehouse_sources.backend.temporal.data_imports.naming_convention import NamingConvention
-from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrow_utils import (
- conditional_lru_cache_async,
-)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.errors import (
TransientObjectStoreError,
is_transient_delta_maintenance_error,
@@ -163,6 +160,7 @@ class DeltaTableRef:
_job: ExternalDataJob
_logger: FilteringBoundLogger
_is_first_sync: bool
+ _cached_table: deltalake.DeltaTable | None
def __init__(
self, resource_name: str, job: ExternalDataJob, logger: FilteringBoundLogger, is_first_sync: bool = False
@@ -171,6 +169,7 @@ class DeltaTableRef:
self._job = job
self._logger = logger
self._is_first_sync = is_first_sync
+ self._cached_table = None
@property
def is_first_sync(self) -> bool:
@@ -239,8 +238,32 @@ class DeltaTableRef:
raise TransientObjectStoreError(str(e)) from e
capture_exception(e)
- @conditional_lru_cache_async(maxsize=1, condition=lambda result: result is not None)
async def get_delta_table(self) -> deltalake.DeltaTable | None:
+ """Open the table once and hand back the same handle for the rest of this ref's life.
+
+ The cache is per instance on purpose. A process-wide slot lets any other table in flight on
+ the same worker evict this one's handle, and every re-open is a full Delta-log replay against
+ object storage. Writes through the handle keep it current, so it stays valid until this ref's
+ own `invalidate_cached_table` (reset, repartition swap) says otherwise. A missing table is
+ never cached, so a table created after the first probe is found by the next call.
+ """
+ if self._cached_table is not None:
+ return self._cached_table
+ table = await self._open_delta_table()
+ self._cached_table = table
+ return table
+
+ def invalidate_cached_table(self) -> None:
+ """Drop the cached handle so the next `get_delta_table` re-reads the live Delta log."""
+ self._cached_table = None
+
+ def pop_cached_table(self) -> deltalake.DeltaTable | None:
+ """Release the cached handle without opening the table, for end-of-run memory cleanup."""
+ table = self._cached_table
+ self._cached_table = None
+ return table
+
+ async def _open_delta_table(self) -> deltalake.DeltaTable | None:
delta_uri = await self._get_delta_table_uri()
storage_options = self._get_credentials()
@@ -335,7 +358,7 @@ class DeltaTableRef:
except FileNotFoundError:
pass
- self.get_delta_table.cache_clear()
+ self.invalidate_cached_table()
await self._logger.adebug("reset_table: _is_first_sync=True")
self._is_first_sync = True
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/test/helpers.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/test/helpers.py
index 4ce80377866c..79248e41f973 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/test/helpers.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/test/helpers.py
@@ -20,7 +20,6 @@ def make_local_table_ref(delta_uri: str) -> DeltaTableRef:
table_ref = DeltaTableRef(resource_name="test", job=MagicMock(), logger=make_logger())
patch.object(table_ref, "_get_delta_table_uri", new=AsyncMock(return_value=delta_uri)).start()
patch.object(table_ref, "_get_credentials", new=MagicMock(return_value={})).start()
- table_ref.get_delta_table.cache_clear()
return table_ref
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/test/test_maintenance.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/test/test_maintenance.py
index ee7be716f195..e0e4430ce526 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
@@ -130,54 +130,15 @@ class TestCompactIfFragmented:
mock_vacuum.assert_not_called()
-class TestCompactTable:
- @pytest.mark.asyncio
- async def test_does_not_refetch_table_for_the_vacuum_step(self):
- # Regression: compact_table used to finish its own compact, then call vacuum_table(),
- # which called get_delta_table() again instead of reusing the table already in hand.
- # get_delta_table() is cached only opportunistically (a concurrent sync of a different
- # table can evict this table's cache entry), so that second call could come back None
- # and raise "Deltatable not found" right after a successful compact. Asserting a single
- # get_delta_table() call locks in that the vacuum step reuses the resolved table instead
- # of re-deriving it.
- mock_delta = MagicMock()
- mock_delta.optimize.compact = MagicMock(return_value={})
- mock_delta.vacuum = MagicMock(return_value=[])
- maintenance = _make_maintenance(mock_delta)
-
- await maintenance.compact_table()
-
- maintenance._table.get_delta_table.assert_called_once()
- mock_delta.optimize.compact.assert_called_once()
- mock_delta.vacuum.assert_called_once()
-
- @pytest.mark.asyncio
- async def test_refused_vacuum_does_not_fail_the_sync(self):
- # Vacuum only reclaims files the load already tombstoned, so a bucket that refuses the delete
- # leaves every live row queryable. compact_table's caller reports anything it raises, which
- # turned a refused cleanup into a reported failure on a sync that had loaded its rows fine.
- mock_delta = MagicMock()
- mock_delta.optimize.compact = MagicMock(return_value={})
- mock_delta.vacuum = MagicMock(
- side_effect=OSError(
- "Kernel error -> The operation lacked the necessary privileges to complete for path "
- "warehouse/team_42_source_7/orders/part-00003.parquet"
- )
- )
- maintenance = _make_maintenance(mock_delta)
-
- await maintenance.compact_table()
-
- # One attempt only: a refusal must not be retried as though it were a commit conflict.
- mock_delta.vacuum.assert_called_once()
-
+class TestCompactConflictRetry:
@pytest.mark.asyncio
async def test_retries_compact_on_commit_conflict_then_succeeds(self):
- # compact_table's optimize.compact() commits a REMOVE+ADD when rewriting fragmented files —
- # the same commit-conflict shape as a merge (see test_ops.TestExecuteWithConflictRetry).
- # Regression coverage for a CommitFailedError propagating straight out of compact_table on
- # the first conflict instead of retrying with a refreshed table, like the write merges do.
+ # optimize.compact() commits a REMOVE+ADD when rewriting fragmented files — the same
+ # 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.optimize.compact = MagicMock(
side_effect=[
deltalake.exceptions.CommitFailedError(
@@ -188,8 +149,9 @@ class TestCompactTable:
)
mock_delta.vacuum = MagicMock(return_value=[])
- await _make_maintenance(mock_delta).compact_table()
+ compacted = await _make_maintenance(mock_delta).compact_if_fragmented(partition_count=1, threshold=1)
+ assert compacted is True
assert mock_delta.optimize.compact.call_count == 2
mock_delta.update_incremental.assert_called_once()
@@ -212,7 +174,7 @@ class TestCompactOffsetOverflow:
)
mock_delta.vacuum = MagicMock(return_value=[])
- await _make_maintenance(mock_delta).compact_table()
+ await _make_maintenance(mock_delta)._compact(mock_delta)
assert mock_delta.optimize.compact.call_count == 2
first_target_size = mock_delta.optimize.compact.call_args_list[0].kwargs["target_size"]
@@ -249,9 +211,9 @@ class TestVacuum:
@pytest.mark.asyncio
async def test_retries_on_commit_conflict_then_succeeds(self):
# vacuum() commits a REMOVE of tombstoned files — the same commit-conflict shape as
- # optimize.compact() (see TestCompactTable.test_retries_compact_on_commit_conflict_then_succeeds).
+ # optimize.compact() (see TestCompactConflictRetry.test_retries_compact_on_commit_conflict_then_succeeds).
# Regression coverage for a CommitFailedError propagating straight out of _vacuum on the first
- # conflict instead of retrying with a refreshed table, like compact_table already does.
+ # conflict instead of retrying with a refreshed table, like _compact already does.
mock_delta = MagicMock()
mock_delta.vacuum = MagicMock(
side_effect=[
@@ -342,7 +304,7 @@ class TestRunMaintenance:
class TestRunScheduled:
"""run_scheduled owns the vacuum-watermark lifecycle for both call sites (pre-write defensive
- pass and CDC post-load), so watermark-key selection, persistence gating, and the never-raise
+ pass and post-load), so watermark-key selection, persistence gating, and the never-raise
contract all live here."""
def _schema(self) -> MagicMock:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/test/test_ops.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/test/test_ops.py
index f0c675541bc3..749d8d4acdfc 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/test/test_ops.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/test/test_ops.py
@@ -47,7 +47,7 @@ class TestExecuteWithConflictRetry:
DELTA_MERGE_CONFLICT_RETRIES). Regression coverage for the sync dying on the first such
conflict instead of refreshing the table and re-running the operation, as the error's own
"must be rerun" message calls for. Shared by merges, overwrite/append writes, and
- `compact_table`'s optimize.compact."""
+ `compact_if_fragmented`'s optimize.compact."""
@pytest.mark.asyncio
async def test_succeeds_without_retry(self):
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/test/test_scd2.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/test/test_scd2.py
index 6d6d6b689579..8e2290cf328c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/test/test_scd2.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/test/test_scd2.py
@@ -24,6 +24,23 @@ def _make_writer(delta_uri: str) -> Scd2DeltaWriter:
class TestScd2Write:
+ @pytest.mark.asyncio
+ async def test_first_write_creates_the_table_with_a_short_checkpoint_interval(self, tmp_path: Path) -> None:
+ # The SCD2 writer has its own create path; a table it creates on delta-rs's default interval
+ # would replay a long uncheckpointed tail on every open.
+ delta_path = str(tmp_path / "scd2_table")
+ batch = pa.table(
+ {
+ "id": pa.array([1]),
+ "valid_from": pa.array([datetime(2026, 1, 1, tzinfo=UTC)], type=_TS_TYPE),
+ "valid_to": pa.array([None], type=_TS_TYPE),
+ }
+ )
+
+ await _make_writer(delta_path).write(data=batch, primary_keys=["id"])
+
+ assert deltalake.DeltaTable(delta_path).metadata().configuration.get("delta.checkpointInterval") == "25"
+
@pytest.mark.asyncio
async def test_write_misaligned_decimal_to_local_delta(self, tmp_path: Path) -> None:
# The SCD2 write carries its own realignment guard; without it the
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/test/test_table.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/test/test_table.py
index 9b818c6ef735..f171df459c30 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/test/test_table.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/test/test_table.py
@@ -26,6 +26,65 @@ def table_ref():
return DeltaTableRef(resource_name="test_resource", job=MagicMock(), logger=make_logger())
+def _openable_table_ref(delta_uri: str) -> DeltaTableRef:
+ ref = DeltaTableRef(resource_name="t", job=MagicMock(), logger=make_logger())
+ patch.object(ref, "_get_delta_table_uri", AsyncMock(return_value=delta_uri)).start()
+ patch.object(ref, "_get_credentials", MagicMock(return_value={})).start()
+ return ref
+
+
+class TestGetDeltaTableCache:
+ _MODULE = "products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.table"
+
+ @pytest.mark.asyncio
+ async def test_one_ref_cannot_evict_another_refs_handle(self):
+ # A loader process has several tables in flight. When they shared one cache slot, every
+ # interleaved call re-opened its table (a full Delta-log replay against object storage).
+ first = _openable_table_ref("s3://bucket/team/job/first")
+ second = _openable_table_ref("s3://bucket/team/job/second")
+
+ with patch(f"{self._MODULE}.deltalake.DeltaTable") as mock_delta_table:
+ mock_delta_table.is_deltatable.return_value = True
+ mock_delta_table.side_effect = lambda table_uri, storage_options: MagicMock(uri=table_uri)
+
+ first_handle = await first.get_delta_table()
+ await second.get_delta_table()
+ assert await first.get_delta_table() is first_handle
+ assert await second.get_delta_table() is not first_handle
+
+ assert mock_delta_table.call_count == 2
+
+ @parameterized.expand([("invalidate", "invalidate_cached_table"), ("pop", "pop_cached_table")])
+ @pytest.mark.asyncio
+ async def test_dropping_the_handle_forces_a_fresh_open(self, _name: str, method: str):
+ # Reset and repartition rewrite the files under the table, so a caller that drops the handle
+ # must get the live log on its next read rather than the pre-swap snapshot.
+ ref = _openable_table_ref("s3://bucket/team/job/t")
+
+ with patch(f"{self._MODULE}.deltalake.DeltaTable") as mock_delta_table:
+ mock_delta_table.is_deltatable.return_value = True
+ mock_delta_table.side_effect = lambda table_uri, storage_options: MagicMock()
+
+ stale = await ref.get_delta_table()
+ getattr(ref, method)()
+ fresh = await ref.get_delta_table()
+
+ assert fresh is not stale
+ assert mock_delta_table.call_count == 2
+
+ @pytest.mark.asyncio
+ async def test_pop_never_opens_the_table(self):
+ # End-of-run cleanup pops the handle. If the table was never fetched, a pop that opened it
+ # would make an object-storage call whose failure could mask the import error being handled.
+ ref = _openable_table_ref("s3://bucket/team/job/t")
+
+ with patch(f"{self._MODULE}.deltalake.DeltaTable") as mock_delta_table:
+ assert ref.pop_cached_table() is None
+
+ mock_delta_table.is_deltatable.assert_not_called()
+ mock_delta_table.assert_not_called()
+
+
class TestStorageOptionsCommitSafety:
# Re-adding AWS_S3_ALLOW_UNSAFE_RENAME unconditionally would silently restore
# the legacy rename backend, which has no commit-conflict detection.
diff --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.py
index 59db8d733744..d46d659cb5a7 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
@@ -2,7 +2,7 @@ import json
from decimal import Decimal
from pathlib import Path
from types import SimpleNamespace
-from typing import Any, cast
+from typing import Any, Literal, cast
import pytest
from unittest.mock import AsyncMock, MagicMock, patch
@@ -11,6 +11,7 @@ import pyarrow as pa
import deltalake
import pyarrow.compute as pc
from parameterized import parameterized
+from pytest_mock import MockerFixture
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrow_utils import (
MissingPrimaryKeysException,
@@ -22,6 +23,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arr
)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.consts import PARTITION_KEY
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.maintenance import DeltaMaintenance
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.ops import ensure_table_properties
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.table import DeltaTableRef
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.test.helpers import (
decimal_array,
@@ -677,7 +679,7 @@ class TestSchemaEvolutionNullability:
status_field = next(f for f in result.schema().fields if f.name == "status")
assert status_field.nullable is True
- await DeltaMaintenance(helper).compact_table()
+ assert await DeltaMaintenance(helper).compact_if_fragmented(partition_count=None, threshold=0) is True
final = result.to_pyarrow_table()
by_id = dict(zip(final.column("id").to_pylist(), final.column("status").to_pylist()))
@@ -748,6 +750,91 @@ class TestIncrementalBatchDeduplication:
assert final.column("name").to_pylist() == ["second_copy"]
+def _commit_operations(delta_path: str) -> list[str]:
+ return [commit["operation"] for commit in deltalake.DeltaTable(delta_path).history()]
+
+
+class TestCheckpointIntervalProperty:
+ """Opening a table replays every commit after the last checkpoint, so a table left on delta-rs's
+ default interval pays a long replay on every open. Every table has to carry the short interval:
+ new ones from creation, existing ones from their next write."""
+
+ @pytest.mark.parametrize(
+ "write_type,primary_keys", [("incremental", ["id"]), ("append", None), ("full_refresh", None)]
+ )
+ @pytest.mark.asyncio
+ async def test_first_sync_creates_the_table_with_the_property(
+ self,
+ write_type: Literal["incremental", "append", "full_refresh"],
+ primary_keys: list[str] | None,
+ tmp_path: Path,
+ ) -> None:
+ delta_path = str(tmp_path / "table")
+
+ await DeltaWriter(make_local_table_ref(delta_path)).write(
+ data=pa.table({"id": [1, 2]}),
+ write_type=write_type,
+ should_overwrite_table=False,
+ primary_keys=primary_keys,
+ )
+
+ stored = deltalake.DeltaTable(delta_path)
+ assert stored.metadata().configuration.get("delta.checkpointInterval") == "25"
+ # Set at creation, so no separate metadata commit was needed.
+ assert "SET TBLPROPERTIES" not in _commit_operations(delta_path)
+
+ @pytest.mark.asyncio
+ async def test_existing_table_gets_the_property_once(self, tmp_path: Path) -> None:
+ # A table created before the property existed must pick it up, and a second write must not
+ # spend another commit on it: each metadata commit is one more entry in the tail every open replays.
+ delta_path = str(tmp_path / "table")
+ deltalake.write_deltalake(delta_path, pa.table({"id": [1]}))
+ table_ref = make_local_table_ref(delta_path)
+
+ for value in (2, 3):
+ await DeltaWriter(table_ref).write(
+ data=pa.table({"id": [value]}),
+ write_type="append",
+ should_overwrite_table=False,
+ primary_keys=None,
+ )
+
+ assert deltalake.DeltaTable(delta_path).metadata().configuration.get("delta.checkpointInterval") == "25"
+ assert _commit_operations(delta_path).count("SET TBLPROPERTIES") == 1
+
+ @pytest.mark.asyncio
+ async def test_a_persistently_failing_commit_is_swallowed_not_propagated(
+ self, tmp_path: Path, mocker: MockerFixture
+ ) -> None:
+ # The data write has already committed by the time this runs, so a property commit that can
+ # never succeed (an incompatible backend, an unexpected metadata shape, any bug in this path)
+ # must not fail the write call it's attached to.
+ delta_path = str(tmp_path / "table")
+ deltalake.write_deltalake(delta_path, pa.table({"id": [1]}))
+ table = deltalake.DeltaTable(delta_path)
+ mocker.patch.object(type(table.alter), "set_table_properties", side_effect=RuntimeError("boom"), create=True)
+
+ result = await ensure_table_properties(table, make_logger())
+
+ assert result is False
+
+ @pytest.mark.asyncio
+ async def test_a_metadata_read_failure_is_swallowed_not_propagated(
+ self, tmp_path: Path, mocker: MockerFixture
+ ) -> None:
+ # The metadata read that decides whether a commit is even needed is in the same best-effort
+ # boundary as the commit itself: the data write has already landed either way, so a failure
+ # reading metadata must not propagate any more than a failed property commit does above.
+ delta_path = str(tmp_path / "table")
+ deltalake.write_deltalake(delta_path, pa.table({"id": [1]}))
+ table = deltalake.DeltaTable(delta_path)
+ mocker.patch.object(type(table), "metadata", side_effect=RuntimeError("boom"))
+
+ result = await ensure_table_properties(table, make_logger())
+
+ assert result is False
+
+
class TestCreateRaceWithExistingTable:
"""DeltaTable.create() defaults to mode="error", raising "table already exists at that
location" whenever the destination is non-empty. get_delta_table() can report "no table
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/writer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/writer.py
index 98b329a2353a..0d41d6bede9b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/writer.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/writer.py
@@ -25,7 +25,9 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arr
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.consts import PARTITION_KEY
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.evolution import evolve_delta_schema
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.ops import (
+ DELTA_TABLE_PROPERTIES,
delta_merge_spill_kwargs,
+ ensure_table_properties,
execute_with_conflict_retry,
)
from products.warehouse_sources.backend.temporal.data_imports.workload_report import report_buffer_bytes, report_phase
@@ -483,6 +485,7 @@ class DeltaWriter:
storage_options=storage_options,
partition_by=PARTITION_KEY if use_partitioning else None,
mode="ignore",
+ configuration=DELTA_TABLE_PROPERTIES,
)
if mode == "append":
@@ -494,11 +497,13 @@ class DeltaWriter:
# column's type in place.
data = align_incoming_decimals_to_delta(data, delta_table.schema())
+ # Bound outside the lambdas: mypy does not carry the None narrowing into a closure.
+ overwrite_target = delta_table
try:
await execute_with_conflict_retry(
delta_table,
lambda: _write_deltalake(
- delta_table,
+ overwrite_target,
data,
partition_by=PARTITION_KEY if use_partitioning else None,
mode=mode,
@@ -515,7 +520,7 @@ class DeltaWriter:
await execute_with_conflict_retry(
delta_table,
lambda: _write_deltalake(
- delta_table,
+ overwrite_target,
data,
partition_by=None,
mode=mode,
@@ -537,6 +542,7 @@ class DeltaWriter:
storage_options=storage_options,
partition_by=PARTITION_KEY if use_partitioning else None,
mode="ignore",
+ configuration=DELTA_TABLE_PROPERTIES,
)
else:
# An append re-casts each source column to its stored type, same as a merge. A decimal
@@ -548,10 +554,11 @@ class DeltaWriter:
await self._logger.adebug(f"write: write_type = append")
+ append_target = delta_table
await execute_with_conflict_retry(
delta_table,
lambda: _write_deltalake(
- delta_table,
+ append_target,
data,
partition_by=PARTITION_KEY if use_partitioning else None,
mode="append",
@@ -565,6 +572,8 @@ class DeltaWriter:
delta_table = await self._table.get_delta_table()
assert delta_table is not None
+ await ensure_table_properties(delta_table, self._logger)
+
return delta_table
async def has_commit_with_metadata(self, match: dict[str, str], *, scan_limit: int = 50) -> bool:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/repartition.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/repartition.py
index 268cdaa053dc..3ba889528e45 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/repartition.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/repartition.py
@@ -1330,7 +1330,7 @@ async def repartition_table_in_place(
# interrupted write instead of re-streaming the whole table for a scheme it already has.
await ensure_claim()
await _persist_resolved_scheme(schema, staged_target, claim_token, logger)
- table_ref.get_delta_table.cache_clear()
+ table_ref.invalidate_cached_table()
await logger.ainfo(
f"repartition: recovered an unrecorded swap, saved scheme={_format_scheme(staged_target)} "
f"schema_id={schema.id}",
@@ -1543,7 +1543,7 @@ async def repartition_table_in_place(
await _persist_resolved_scheme(schema, resolved, claim_token, logger)
# The cached delta-table object points at the pre-swap files; drop it so callers re-read live.
- table_ref.get_delta_table.cache_clear()
+ table_ref.invalidate_cached_table()
await logger.ainfo(
f"repartition: completed schema_id={schema.id} rows={rows_written} "
@@ -1619,7 +1619,7 @@ async def _resume_swap_with_missing_live(
)
await _persist_resolved_scheme(schema, target, claim_token, logger)
- table_ref.get_delta_table.cache_clear()
+ table_ref.invalidate_cached_table()
await logger.ainfo(
f"repartition: recovered from interrupted swap schema_id={schema.id} rows={expected_rows}",
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/repartition_controller.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/repartition_controller.py
index bf49d70bf94d..086c107565f9 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/repartition_controller.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/repartition_controller.py
@@ -9,6 +9,7 @@ schema. The next run's pre-extraction activity performs the rewrite (see `repart
from __future__ import annotations
import asyncio
+from collections.abc import Mapping
from typing import TYPE_CHECKING, Any, Literal
from django.conf import settings
@@ -118,6 +119,78 @@ def is_auto_coarsen_enabled(schema: ExternalDataSchema) -> bool:
return is_schema_flag_enabled(schema, WAREHOUSE_AUTO_COARSEN_FLAG)
+def needs_pre_extraction_detection(schema: ExternalDataSchema, enabled: bool) -> bool:
+ """Whether to read the live on-disk partition sizes to decide if a repartition is needed.
+
+ We deliberately do NOT gate on the recorded `max_partition_bytes`. That value is only refreshed by
+ post-load detection, so for a table whose merge OOMs before post-load it goes stale and can sit far
+ below the true partition size — precisely the tables this path exists to rescue (e.g. a partition
+ that has since grown to many GB while the recorded value still reads a few hundred MB). Instead,
+ whenever the rollout flag is on (a targeted set of schemas) and the table isn't CDC-excluded, we
+ read the live partition sizes from the Delta log each run and let `maybe_flag_for_repartition` judge
+ against the real, current size. The cost is one metadata-only Delta-log read per sync, bounded to
+ flagged schemas; a disabled flag still short-circuits to a zero-I/O no-op.
+
+ A table nominated for coarsening is measured whether or not the rollout flag covers it, since the
+ nomination is the operator asking for exactly this measurement. CDC stays excluded either way.
+ """
+ if schema.sync_type == ExternalDataSchema.SyncType.CDC:
+ return False
+ if schema.coarsen_requested is not None:
+ return True
+ return enabled
+
+
+def is_pending_repartition_released_by_flag(
+ schema: ExternalDataSchema, pending: Mapping[str, object], *, enabled: bool | None = None
+) -> bool:
+ """Whether a queued rewrite's own rollout flag has since been disabled, releasing it as a no-op.
+
+ Mirrors `_maybe_repartition_table`'s 'release' branch in `repartition_table.py` exactly: each
+ auto-staged trigger family answers to the flag that staged it (the flag is the only lever support
+ has to release such a table), and any other reason fails open because operator-staged work (admin,
+ a staged swap) must never dead-end on a rollout flag. Shared so `repartition_activity_has_work`
+ agrees with the activity's own answer instead of scheduling a round trip the activity would just
+ skip.
+
+ `enabled` lets a caller that already evaluated `WAREHOUSE_AUTO_REPARTITION_FLAG` this run thread
+ the result through instead of paying for a second evaluation.
+ """
+ reason = pending.get("trigger_reason")
+ if reason in ("proactive_threshold", "oom_history"):
+ return not (enabled if enabled is not None else is_auto_repartition_enabled(schema))
+ if reason == "coarsening":
+ return not is_auto_coarsen_enabled(schema)
+ return False
+
+
+def repartition_activity_has_work(schema: ExternalDataSchema) -> bool:
+ """Whether the pre-extraction repartition activity would do more than log and return.
+
+ The workflow uses this to skip scheduling the activity, so it must say True whenever the activity
+ itself would go past its own fast no-op path: a queued rewrite or staged swap to drive, or a table
+ the rollout flag (or a coarsening nomination) wants measured on disk. A pending corruption revive
+ makes the activity stand down before any of that, so it is a no-op here too. The flag is only
+ evaluated when nothing is queued, which is the one case the activity's answer depends on it.
+
+ A queued rewrite whose own trigger flag has since been disabled is also a no-op: the activity's
+ fast path stands it down without doing any work (see `is_pending_repartition_released_by_flag`), so
+ scheduling the activity for it would just pay a full round trip to log and return.
+ """
+ if schema.delta_revive_required is not None:
+ return False
+ pending = schema.repartition_pending
+ swap = schema.repartition_swap
+ if swap is not None:
+ return True
+ if pending is not None:
+ enabled = is_auto_repartition_enabled(schema)
+ if is_pending_repartition_released_by_flag(schema, pending, enabled=enabled):
+ return needs_pre_extraction_detection(schema, enabled)
+ return True
+ return needs_pre_extraction_detection(schema, is_auto_repartition_enabled(schema))
+
+
def is_repartition_hold_enabled(schema: ExternalDataSchema) -> bool:
return is_schema_flag_enabled(schema, WAREHOUSE_REPARTITION_HOLD_FLAG)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_utils.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_utils.py
index 4db7b4a78ad5..2bffcf766b9e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_utils.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_utils.py
@@ -29,7 +29,6 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arr
_to_list_array,
align_incoming_decimals_to_delta,
apply_enabled_columns_projection,
- conditional_lru_cache_async,
evolve_pyarrow_schema,
hex_encode_id_binary_columns,
is_safe_numeric_widening,
@@ -1949,36 +1948,6 @@ def test_billing_limit_exception_is_non_reportable_error():
assert issubclass(BillingLimitsWillBeReachedException, NonReportableError)
-class TestConditionalLruCacheAsyncCachePop:
- @pytest.mark.asyncio
- async def test_pop_on_cache_miss_returns_none_without_calling_func(self):
- # A best-effort cleanup path (e.g. releasing an already-fetched delta table) must be able
- # to check the cache without ever triggering the wrapped function's own I/O — a miss here
- # used to mean "call the real function", which made cleanup do an unrelated object-storage
- # call and risk masking the real error with a fresh, spurious one.
- calls = []
-
- @conditional_lru_cache_async(maxsize=1)
- async def fetch(key: str) -> str:
- calls.append(key)
- return f"value-{key}"
-
- assert fetch.cache_pop("a") is None
- assert calls == []
-
- @pytest.mark.asyncio
- async def test_pop_on_cache_hit_returns_and_removes_cached_value(self):
- @conditional_lru_cache_async(maxsize=1)
- async def fetch(key: str) -> str:
- return f"value-{key}"
-
- assert await fetch("a") == "value-a"
-
- assert fetch.cache_pop("a") == "value-a"
- # Popped, not just read — a second pop finds nothing left to remove.
- assert fetch.cache_pop("a") is None
-
-
class TestReconcileBatchToAccumulatedSchema:
def test_first_batch_seeds_the_accumulated_schema(self):
batch = pa.table({"owner_id": [1, 2]})
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test_repartition.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test_repartition.py
index fd9c8f18f887..d03c27ce80f6 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test_repartition.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test_repartition.py
@@ -76,6 +76,7 @@ def _make_table_ref(**kwargs):
"get_table_uri": AsyncMock(return_value="s3://bucket/live"),
"get_storage_options": Mock(return_value={}),
"get_delta_table": AsyncMock(return_value=None),
+ "invalidate_cached_table": Mock(),
}
defaults.update(kwargs)
return SimpleNamespace(**defaults)
@@ -1223,6 +1224,36 @@ class TestResumeSwapWithMissingLive:
schema.clear_repartition_pending.assert_called_once()
assert result == {"outcome": "skipped", "reason": "no_delta_table"}
+ def test_recovery_finishes_swap_and_invalidates_cache(self) -> None:
+ # Live is gone but temp is intact and complete: the recovery finishes the swap from temp. The
+ # cached delta-table handle still points at the now-deleted live files, so it must be dropped
+ # or a subsequent read in the same run would keep serving the pre-swap listing.
+ table_ref = _make_table_ref()
+ schema = _schema(id="s1")
+ target = RepartitionTarget(partition_keys=["created_at"], trigger_reason="resume")
+
+ with (
+ patch.object(repartition_module, "_valid_delta_row_count", new=AsyncMock(return_value=2)),
+ patch.object(repartition_module, "_swap_temp_into_live", new=AsyncMock()) as swap,
+ patch.object(repartition_module, "_persist_resolved_scheme", new=AsyncMock()) as persist,
+ ):
+ result = asyncio.run(
+ repartition_module._resume_swap_with_missing_live(
+ table_ref=table_ref,
+ schema=schema,
+ target=target,
+ temp_uri="s3://bucket/live__repartitioned",
+ live_uri="s3://bucket/live",
+ storage_options={},
+ logger=logger,
+ )
+ )
+
+ swap.assert_awaited_once()
+ persist.assert_awaited_once()
+ table_ref.invalidate_cached_table.assert_called_once()
+ assert result == {"outcome": "completed", "row_count": 2, "recovered": True}
+
class TestLiveUnreadable:
"""`get_delta_table()` *raising* (a DeltaError/FileNotFoundError from an OOM-crashed merge or an
@@ -1757,6 +1788,9 @@ class TestSwapSchemeIsRecorded:
assert result["outcome"] == "completed"
assert finalize.call_args.kwargs["partition_format"] == "day"
+ # The cached delta-table handle still points at pre-swap files; a subsequent read must not
+ # reuse it, or an incremental merge scopes its predicate to a partition that no longer exists.
+ table_ref.invalidate_cached_table.assert_called_once()
def test_a_swap_that_already_landed_is_finished_without_rewriting_the_table(self, tmp_path):
# temp is gone because the swap deleted it — only the scheme write was lost. Live is on the
@@ -1782,6 +1816,7 @@ class TestSwapSchemeIsRecorded:
rewrite.assert_not_awaited()
swap.assert_not_awaited()
assert finalize.call_args.kwargs["partition_format"] == "day"
+ table_ref.invalidate_cached_table.assert_called_once()
def test_a_lost_scheme_write_raises_instead_of_reporting_success(self, tmp_path):
# The swap has already landed, so a database blip here is not the noise it looks like: every
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v2/pipeline.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v2/pipeline.py
index 6793e9aead51..24a4cb2804e9 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v2/pipeline.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v2/pipeline.py
@@ -322,7 +322,7 @@ class PipelineNonDLT(Generic[ResumableData]):
# captured, obscuring the real import error that's already driving retry
# classification and the user-facing message.
await self._logger.adebug("Cleaning up delta table helper")
- delta_table = self._delta_table_ref.get_delta_table.cache_pop(self._delta_table_ref)
+ delta_table = self._delta_table_ref.pop_cached_table()
if delta_table:
del delta_table
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v2/test/test_pipeline.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v2/test/test_pipeline.py
index f0af4b14427d..00c8f2edd07a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v2/test/test_pipeline.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v2/test/test_pipeline.py
@@ -38,7 +38,7 @@ async def test_run_cleanup_does_not_call_get_delta_table_and_does_not_mask_impor
pipeline._resumable_source_manager = None
pipeline._resource = cast(SourceResponse, object())
delta_table_ref = AsyncMock()
- delta_table_ref.get_delta_table.cache_pop.return_value = None
+ delta_table_ref.pop_cached_table.return_value = None
pipeline._delta_table_ref = delta_table_ref
class ImportError_(Exception):
@@ -52,7 +52,7 @@ async def test_run_cleanup_does_not_call_get_delta_table_and_does_not_mask_impor
# run()'s finally `del self._delta_table_ref`s afterward, so assert on the captured
# reference rather than re-reading it off `pipeline`.
delta_table_ref.get_delta_table.assert_not_called()
- delta_table_ref.get_delta_table.cache_pop.assert_called_once_with(delta_table_ref)
+ delta_table_ref.pop_cached_table.assert_called_once_with()
@pytest.mark.asyncio
@@ -178,7 +178,7 @@ def _runnable_pipeline(manager: ResumableSourceManager[_Cursor], items) -> Pipel
pipeline._is_incremental = False
pipeline._reset_pipeline = False
delta_table_ref = AsyncMock()
- delta_table_ref.get_delta_table.cache_pop.return_value = None
+ delta_table_ref.pop_cached_table.return_value = None
pipeline._delta_table_ref = delta_table_ref
pipeline._sinks = MagicMock(clear=AsyncMock())
pipeline._shutdown_monitor = MagicMock()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/s3/test_writer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/s3/test_writer.py
index 1f43f7ae2fe8..265f6c703151 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/s3/test_writer.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/s3/test_writer.py
@@ -80,6 +80,43 @@ class TestBuildSchemaDict:
assert build_schema_dict(schema)["fields"][0]["metadata"] is None
+class TestBatchByteSize:
+ @parameterized.expand(
+ [
+ # s3fs spells the key in lowercase; reading S3's `Size` here recorded 0 bytes on every queue row.
+ ("s3fs_lowercase_size", {"size": 2048}, 2048),
+ ("raw_s3_head_shape", {"Size": 512}, 512),
+ ("numeric_string", {"size": "64"}, 64),
+ ("no_size_key", {"type": "file"}, 0),
+ ("not_a_dict", None, 0),
+ ]
+ )
+ @patch(
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.s3.writer._write_parquet_to_s3"
+ )
+ @patch("products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.s3.writer.ensure_bucket")
+ @patch("products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.s3.writer.get_s3_client")
+ def test_byte_size_comes_from_the_written_object(
+ self,
+ _name: str,
+ file_info: dict | None,
+ expected: int,
+ mock_get_s3_client,
+ _mock_ensure_bucket,
+ _mock_write,
+ ) -> None:
+ mock_get_s3_client.return_value.info.return_value = file_info
+
+ job = MagicMock()
+ job.team_id = 1
+ job.created_at = datetime(2026, 8, 5, tzinfo=UTC)
+ writer = S3BatchWriter(MagicMock(), job, schema_id="schema-1", run_uuid="run-1")
+
+ result = writer.write_batch(pa.table({"id": [1]}), 0)
+
+ assert result.byte_size == expected
+
+
class TestSchemaAccumulation:
@parameterized.expand(
[
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/s3/writer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/s3/writer.py
index 8db1cf45b341..f03473f2be83 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/s3/writer.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/s3/writer.py
@@ -57,6 +57,22 @@ def build_schema_dict(schema: pa.Schema) -> dict:
}
+def _object_size(file_info: object) -> int:
+ # s3fs reports the object size under the lowercase `size` key. S3's own HeadObject shape
+ # uses `Size`, so both are accepted rather than trusting one client's spelling.
+ if not isinstance(file_info, dict):
+ return 0
+ for key in ("size", "Size"):
+ value = file_info.get(key)
+ if value is None:
+ continue
+ try:
+ return int(value)
+ except (TypeError, ValueError):
+ continue
+ return 0
+
+
def _is_transient_s3_write_error(exc: BaseException) -> bool:
# s3fs translates most S3-side write failures (IncompleteBody, InternalError,
# SlowDown/ServiceUnavailable, ...) into a plain OSError. PermissionError,
@@ -139,8 +155,7 @@ class S3BatchWriter:
if activity.in_activity():
get_s3_write_duration_metric().record(write_duration)
- file_info = self._s3.info(s3_path_without_protocol)
- byte_size = file_info.get("Size", 0) if isinstance(file_info, dict) else 0
+ byte_size = _object_size(self._s3.info(s3_path_without_protocol))
if self._schema is None:
self._schema = pa_table.schema
diff --git a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/conftest.py b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/conftest.py
index 2743f8b112b7..fcfd36840403 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/conftest.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/conftest.py
@@ -180,7 +180,7 @@ async def run_external_data_job_workflow(
DATAWAREHOUSE_LOCAL_BUCKET_REGION="us-east-1",
DATAWAREHOUSE_BUCKET_DOMAIN="objectstorage:19000",
),
- mock.patch.object(DeltaMaintenance, "compact_table") as mock_compact_table,
+ mock.patch.object(DeltaMaintenance, "run_scheduled") as mock_run_scheduled,
mock.patch(
"products.warehouse_sources.backend.temporal.data_imports.external_data_job.get_data_import_finished_metric"
) as mock_get_data_import_finished_metric,
@@ -222,7 +222,7 @@ async def run_external_data_job_workflow(
if expected_rows_synced is not None:
assert run.rows_synced == expected_rows_synced
- mock_compact_table.assert_called()
+ mock_run_scheduled.assert_called()
mock_get_data_import_finished_metric.assert_called_with(
source_type=external_data_source.source_type, status=ExternalDataJob.Status.COMPLETED.lower()
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_end_to_end.py b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_end_to_end.py
index 5e20c48248e2..ac1c8e2fa197 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_end_to_end.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_end_to_end.py
@@ -459,7 +459,7 @@ async def _run(
)
with (
- mock.patch.object(DeltaMaintenance, "compact_table") as mock_compact_table,
+ mock.patch.object(DeltaMaintenance, "run_scheduled") as mock_run_scheduled,
mock.patch(
"products.warehouse_sources.backend.temporal.data_imports.external_data_job.get_data_import_finished_metric"
) as mock_get_data_import_finished_metric,
@@ -497,7 +497,14 @@ async def _run(
# so that case only checks storage_delta_mib was computed at all, above.
assert run.storage_delta_mib != 0
- mock_compact_table.assert_called()
+ if existing_schema_id is not None:
+ # A genuine re-sync also runs the pre-write defensive maintenance pass (see
+ # DeltaMaintenance.run_scheduled's callers in pipeline_v2/pipeline_v3), so both that call
+ # and the post-load call must land — asserting only "called" would still pass if the
+ # post-load call were dropped, since the pre-write call alone satisfies it.
+ assert mock_run_scheduled.call_count == 2
+ else:
+ mock_run_scheduled.assert_called()
mock_get_data_import_finished_metric.assert_called_with(
source_type=source_type, status=ExternalDataJobStatus.COMPLETED.lower()
)
@@ -2351,6 +2358,13 @@ _COARSEN_FLAGS_ON = (
".is_auto_repartition_enabled",
"products.warehouse_sources.backend.temporal.data_imports.pipelines.core.repartition_controller"
".is_auto_coarsen_enabled",
+ # `repartition_activity_has_work` (used by job creation to decide whether to schedule the
+ # activity at all) calls the module-local `is_auto_repartition_enabled` binding inside
+ # `repartition_controller`, a separate name from the one `repartition_table` imported for its
+ # own use above. Patching only the latter leaves job creation seeing the real (disabled) flag,
+ # so organic pre-extraction detection never gets scheduled and coarsening never runs.
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.core.repartition_controller"
+ ".is_auto_repartition_enabled",
)
@@ -2444,7 +2458,11 @@ async def test_in_place_coarsening_merges_weekly_partitions_into_months(
assert len(ids_before) == len(timestamps)
# Coarsening evaluates on the next sync and, finding a layout that fits, rewrites in the same run.
- with mock.patch(_COARSEN_FLAGS_ON[0], return_value=True), mock.patch(_COARSEN_FLAGS_ON[1], return_value=True):
+ with (
+ mock.patch(_COARSEN_FLAGS_ON[0], return_value=True),
+ mock.patch(_COARSEN_FLAGS_ON[1], return_value=True),
+ mock.patch(_COARSEN_FLAGS_ON[2], return_value=True),
+ ):
await _execute_run(str(uuid.uuid4()), inputs, [])
await _replay_v3_consumer(team_id=team.pk, schema_id=inputs.external_data_schema_id)
@@ -2460,7 +2478,11 @@ async def test_in_place_coarsening_merges_weekly_partitions_into_months(
assert await _row_ids(team, "postgres_test_coarsen_week") == ids_before
# And it must settle: a table just coarsened must not be split straight back on the next sync.
- with mock.patch(_COARSEN_FLAGS_ON[0], return_value=True), mock.patch(_COARSEN_FLAGS_ON[1], return_value=True):
+ with (
+ mock.patch(_COARSEN_FLAGS_ON[0], return_value=True),
+ mock.patch(_COARSEN_FLAGS_ON[1], return_value=True),
+ mock.patch(_COARSEN_FLAGS_ON[2], return_value=True),
+ ):
await _execute_run(str(uuid.uuid4()), inputs, [])
await _replay_v3_consumer(team_id=team.pk, schema_id=inputs.external_data_schema_id)
@@ -2598,7 +2620,11 @@ async def test_in_place_coarsening_merges_hourly_partitions_up(
ids_before = await _row_ids(team, "postgres_test_coarsen_hour")
await _backdate_last_repartition(schema, days=8)
- with mock.patch(_COARSEN_FLAGS_ON[0], return_value=True), mock.patch(_COARSEN_FLAGS_ON[1], return_value=True):
+ with (
+ mock.patch(_COARSEN_FLAGS_ON[0], return_value=True),
+ mock.patch(_COARSEN_FLAGS_ON[1], return_value=True),
+ mock.patch(_COARSEN_FLAGS_ON[2], return_value=True),
+ ):
await _execute_run(str(uuid.uuid4()), inputs, [])
await _replay_v3_consumer(team_id=team.pk, schema_id=inputs.external_data_schema_id)
@@ -2684,7 +2710,11 @@ async def test_in_place_coarsening_for_hashed_and_numerical_modes(
assert len(ids_before) == 320
await _backdate_last_repartition(schema, days=8)
- with mock.patch(_COARSEN_FLAGS_ON[0], return_value=True), mock.patch(_COARSEN_FLAGS_ON[1], return_value=True):
+ with (
+ mock.patch(_COARSEN_FLAGS_ON[0], return_value=True),
+ mock.patch(_COARSEN_FLAGS_ON[1], return_value=True),
+ mock.patch(_COARSEN_FLAGS_ON[2], return_value=True),
+ ):
await _execute_run(str(uuid.uuid4()), inputs, [])
await _replay_v3_consumer(team_id=team.pk, schema_id=inputs.external_data_schema_id)
@@ -3274,7 +3304,7 @@ async def test_append_only_table(team, mock_stripe_client):
sync_type_config={"incremental_field": "created", "incremental_field_type": "integer"},
)
- with mock.patch.object(DeltaMaintenance, "compact_table"):
+ with mock.patch.object(DeltaMaintenance, "run_scheduled"):
await _execute_run(str(uuid.uuid4()), inputs, [])
run_for_replay = await sync_to_async(
@@ -4359,7 +4389,7 @@ async def test_stripe_webhook_s3_charges(team, stripe_charge, mock_stripe_client
assert len(files.get("Contents", [])) == 1
# Run the pipeline again to ingest the webhook parquet
- with mock.patch.object(DeltaMaintenance, "compact_table"):
+ with mock.patch.object(DeltaMaintenance, "run_scheduled"):
workflow_id = str(uuid.uuid4())
await _execute_run(workflow_id, inputs, stripe_charge["data"])
@@ -4550,7 +4580,7 @@ async def test_stripe_webhook_consumer_e2e(team, stripe_charge, mock_stripe_clie
consumer._consumer.commit.assert_called_once_with(asynchronous=False)
# 6. Run the import pipeline to ingest the parquet
- with mock.patch.object(DeltaMaintenance, "compact_table"):
+ with mock.patch.object(DeltaMaintenance, "run_scheduled"):
workflow_id = str(uuid.uuid4())
await _execute_run(workflow_id, inputs, stripe_charge["data"])
diff --git a/products/warehouse_sources/backend/temporal/data_imports/tests/test_post_import_fork.py b/products/warehouse_sources/backend/temporal/data_imports/tests/test_post_import_fork.py
index a21ea4eb2442..2bc248ba4155 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/tests/test_post_import_fork.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/tests/test_post_import_fork.py
@@ -66,6 +66,7 @@ def _stub_activities(
fast_return_eligible: bool = False,
source_has_new_data: bool = True,
scheduled_full_refresh: bool = False,
+ repartition_needed: bool = True,
) -> list:
@activity.defn(name="check_pipeline_version_activity")
async def check_pipeline_version(inputs: CheckPipelineVersionActivityInputs) -> CheckPipelineVersionActivityOutputs:
@@ -96,6 +97,7 @@ def _stub_activities(
person_property_sync_enabled=True,
fast_return_eligible=fast_return_eligible,
scheduled_full_refresh=scheduled_full_refresh,
+ repartition_needed=repartition_needed,
)
@activity.defn(name="check_billing_limits_activity")
@@ -158,6 +160,7 @@ async def _run_workflow(
fast_return_eligible: bool = False,
source_has_new_data: bool = True,
scheduled_full_refresh: bool = False,
+ repartition_needed: bool = True,
) -> tuple[list[str], list[str]]:
"""Run the workflow with stubbed activities; return (executed activities + child starts in
order, started child ids)."""
@@ -189,6 +192,7 @@ async def _run_workflow(
fast_return_eligible=fast_return_eligible,
source_has_new_data=source_has_new_data,
scheduled_full_refresh=scheduled_full_refresh,
+ repartition_needed=repartition_needed,
),
workflow_runner=UnsandboxedWorkflowRunner(),
activity_executor=ThreadPoolExecutor(max_workers=10),
@@ -307,6 +311,19 @@ async def test_the_import_learns_a_run_is_a_scheduled_full_refresh(scheduled_ful
assert ("maybe_repartition_table_activity" in executed) is not scheduled_full_refresh
[email protected]("repartition_needed", [True, False])
+async def test_repartition_activity_is_scheduled_only_when_job_creation_finds_work(repartition_needed: bool):
+ # The activity round trip is most of what a healthy sync paid for repartitioning; the
+ # job-creation activity already knows whether anything is queued or due for measurement.
+ executed, _ = await _run_workflow(
+ is_v3=False, consumer_manages_job_status=False, repartition_needed=repartition_needed
+ )
+
+ assert ("maybe_repartition_table_activity" in executed) is repartition_needed
+ assert "import_data_activity_sync" in executed
+
+
@pytest.mark.parametrize(
"search_attributes,expected",
[
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.py
index 2a2d05e4d7c9..22485d75b4d8 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
@@ -9,13 +9,15 @@ Stats come from the Delta transaction log's per-file statistics (`num_records`,
exact, whole-table, correct for full-refresh/append/incremental-upsert (live add-actions reflect the
current files), and scales to any table size. Results land in `WarehouseColumnStatistics`, fully
system-owned and overwritten on each run. To avoid re-profiling an hourly-syncing table every hour,
-a row computed within `MIN_RECOMPUTE_INTERVAL` is left alone.
+a row computed within `MIN_RECOMPUTE_INTERVAL` is left alone, and a table whose Delta version has not
+moved since the last computation is left alone until `MAX_RECOMPUTE_INTERVAL` has passed.
"""
import os
import json
import uuid
import dataclasses
+from collections.abc import Iterable
from datetime import timedelta
from typing import Any
@@ -51,6 +53,10 @@ STATISTICS_FEATURE_FLAG = "data-warehouse-column-statistics"
# Cap profiling to once a day per table — an hourly-syncing table doesn't need re-profiling every hour,
# and Delta-log stats only move materially over longer windows. Env-overridable for ops.
MIN_RECOMPUTE_INTERVAL = timedelta(hours=int(os.getenv("WAREHOUSE_STATS_MIN_RECOMPUTE_INTERVAL_HOURS", "24")))
+# Stats derive from the Delta log at one version, so an unchanged version means unchanged stats and the
+# Add-action scan (the expensive step) can be skipped. The cap still forces a recompute so a change in
+# the table's registered columns, or in how stats are derived, reaches every table eventually.
+MAX_RECOMPUTE_INTERVAL = timedelta(days=int(os.getenv("WAREHOUSE_STATS_MAX_RECOMPUTE_INTERVAL_DAYS", "7")))
# Product-analytics events — query these to track statistics volume, columns profiled, skips, and errors.
EVENT_STARTED = "data warehouse table statistics started"
@@ -162,9 +168,54 @@ def _aggregate_add_action_stats(add_actions: Any, columns: dict[str, Any]) -> tu
return row_count, result
-def _most_recent_computed_at(existing: dict[str, WarehouseColumnStatistics]) -> Any | None:
- times = [s.computed_at for s in existing.values() if s.computed_at is not None]
- return max(times) if times else None
+def _most_recent_computed_at(
+ existing: dict[str, WarehouseColumnStatistics], current_columns: Iterable[str]
+) -> Any | None:
+ """Oldest `computed_at` among currently-registered columns, not the newest.
+
+ `_upsert_statistics` writes one column at a time and only retries the whole batch on a transient
+ DB error (`OperationalError`/`InterfaceError`); any other failure partway through a run leaves some
+ columns stamped with a fresh `computed_at` while others still carry an earlier one. Taking the max
+ would read that mixed, partially-written state as "computed recently" and skip the columns that are
+ actually still stale; the min only reports fresh once every currently-registered column agrees.
+ Scoped to `current_columns` so a column dropped from the table doesn't hold a stale row open
+ forever and block this gate on a time that can never be reached again.
+ """
+ times = [s.computed_at for name, s in existing.items() if name in current_columns and s.computed_at is not None]
+ return min(times) if times else None
+
+
+def _most_recent_computed_version(
+ existing: dict[str, WarehouseColumnStatistics], current_columns: Iterable[str]
+) -> int | None:
+ """Oldest `computed_for_delta_version` among currently-registered columns, not the newest.
+
+ Same partial-write hazard as `_most_recent_computed_at`, and the same fix: a recompute that aborts
+ after updating only some columns must not read as "version unchanged" just because the columns it
+ did reach now carry the current version. Scoped to `current_columns` for the same reason — a column
+ dropped from the table keeps its old row, which the maximum used to rely on to avoid it; the
+ minimum has to exclude it explicitly instead, or a dropped column's stale version would hold this
+ gate open indefinitely.
+ """
+ versions = [
+ s.computed_for_delta_version
+ for name, s in existing.items()
+ if name in current_columns and s.computed_for_delta_version is not None
+ ]
+ return min(versions) if versions else None
+
+
+def _all_columns_have_stats(existing: dict[str, WarehouseColumnStatistics], current_columns: Iterable[str]) -> bool:
+ """Whether every currently-registered column has a statistics row at all.
+
+ The min-based staleness checks above only compare columns that already have a row; a column
+ whose very first computation never landed (its upsert failed before any row was written, not
+ just before its version caught up) is invisible to them entirely, so a table with such a gap
+ would read as fully fresh off the other columns' timestamps and versions alone. Both skip gates
+ require this to be true first, so a never-computed column always forces a recompute rather than
+ waiting out the interval.
+ """
+ return set(current_columns) <= existing.keys()
@retry_on_operational_error
@@ -215,12 +266,16 @@ def compute_table_statistics_sync(team_id: int, schema_id: uuid.UUID) -> dict[st
emit_completed("skipped", reason="no_table")
return {"status": "skipped", "reason": "no_table"}
event_props["table_id"] = str(table.id)
+ columns = table.columns or {}
existing = {
stat.column_name: stat for stat in WarehouseColumnStatistics.objects.for_team(team_id).filter(table_id=table.id)
}
- latest = _most_recent_computed_at(existing)
- if latest is not None and timezone.now() - latest < MIN_RECOMPUTE_INTERVAL:
+ latest = _most_recent_computed_at(existing, columns)
+ # Gates every skip below: a column missing a row entirely (see _all_columns_have_stats) is
+ # invisible to the min-based checks, so it must not let a table with such a gap read as fresh.
+ all_columns_have_stats = _all_columns_have_stats(existing, columns)
+ if latest is not None and all_columns_have_stats and timezone.now() - latest < MIN_RECOMPUTE_INTERVAL:
emit_completed("skipped", reason="computed_recently")
return {"status": "skipped", "reason": "computed_recently"}
@@ -246,16 +301,34 @@ def compute_table_statistics_sync(team_id: int, schema_id: uuid.UUID) -> dict[st
return {"status": "skipped", "reason": "no_delta_table"}
delta_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
+ # 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
+ # refresh always produces the same low version number would skip recomputation indefinitely.
+ version_is_stale = stored_version is not None and stored_version > delta_version
+ if (
+ latest is not None
+ and all_columns_have_stats
+ and not version_is_stale
+ and stored_version == delta_version
+ and timezone.now() - latest < MAX_RECOMPUTE_INTERVAL
+ ):
+ emit_completed("skipped", reason="version_unchanged", delta_version=delta_version)
+ return {"status": "skipped", "reason": "version_unchanged"}
+
+ # Checked before the Add-action scan: a table with no registered columns writes no rows, so
+ # nothing would stop the scan from repeating on every sync.
+ if not columns:
+ emit_completed("skipped", reason="no_columns")
+ return {"status": "skipped", "reason": "no_columns"}
+
add_actions = delta_table.get_add_actions(flatten=True)
if add_actions.num_rows == 0:
emit_completed("skipped", reason="no_files")
return {"status": "skipped", "reason": "no_files"}
- columns = table.columns or {}
- if not columns:
- emit_completed("skipped", reason="no_columns")
- return {"status": "skipped", "reason": "no_columns"}
-
row_count, stats_by_column = _aggregate_add_action_stats(add_actions, columns)
try:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/create_job_model.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/create_job_model.py
index c3e17930044a..39e18b141c58 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/create_job_model.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/create_job_model.py
@@ -41,6 +41,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.common.d
retry_on_operational_error,
)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.repartition_controller import (
+ repartition_activity_has_work,
repartition_import_hold_reason,
)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.sync_lock import (
@@ -326,6 +327,9 @@ class CreateExternalDataJobModelActivityOutputs:
# The workflow hands this to the import, which resets only while the schema is still due. Nothing is
# stored on the schema, so a run that stops before the wipe leaves no reset behind for later runs.
scheduled_full_refresh: bool = False
+ # True when the pre-extraction repartition activity has a rewrite, swap or on-disk measurement to
+ # do. Defaults True so a payload from a worker that predates the field still schedules it.
+ repartition_needed: bool = True
@activity.defn
@@ -443,6 +447,10 @@ def create_external_data_job_model_activity(
statistics_needed=statistics_needed,
)
+ # The repartition activity re-checks this itself; deciding here lets the workflow skip
+ # scheduling it at all, which for most syncs is its whole cost.
+ repartition_needed = repartition_activity_has_work(schema)
+
return CreateExternalDataJobModelActivityOutputs(
job_id=str(job.id),
incremental_or_append=schema.is_incremental or schema.is_append or schema.is_webhook,
@@ -457,6 +465,7 @@ def create_external_data_job_model_activity(
person_property_sync_enabled=person_property_sync_enabled,
fast_return_eligible=fast_return_eligible,
scheduled_full_refresh=scheduled_full_refresh,
+ repartition_needed=repartition_needed,
)
except V3PipelineLockLostError:
# The takeover race the guard handles, not a defect — skip the generic handler's
diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/repartition_table.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/repartition_table.py
index 7e7442dadaef..393eaa36f3d8 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/repartition_table.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/repartition_table.py
@@ -60,6 +60,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.rep
is_auto_coarsen_enabled,
is_auto_repartition_enabled,
maybe_flag_for_repartition,
+ needs_pre_extraction_detection,
target_partition_bytes,
)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.load.metrics import (
@@ -203,28 +204,6 @@ def _target_from_schema(schema: ExternalDataSchema) -> RepartitionTarget:
)
-def _needs_pre_extraction_detection(schema: ExternalDataSchema, enabled: bool) -> bool:
- """Whether to read the live on-disk partition sizes to decide if a repartition is needed.
-
- We deliberately do NOT gate on the recorded `max_partition_bytes`. That value is only refreshed by
- post-load detection, so for a table whose merge OOMs before post-load it goes stale and can sit far
- below the true partition size — precisely the tables this path exists to rescue (e.g. a partition
- that has since grown to many GB while the recorded value still reads a few hundred MB). Instead,
- whenever the rollout flag is on (a targeted set of schemas) and the table isn't CDC-excluded, we
- read the live partition sizes from the Delta log each run and let `maybe_flag_for_repartition` judge
- against the real, current size. The cost is one metadata-only Delta-log read per sync, bounded to
- flagged schemas; a disabled flag still short-circuits to a zero-I/O no-op.
-
- A table nominated for coarsening is measured whether or not the rollout flag covers it, since the
- nomination is the operator asking for exactly this measurement. CDC stays excluded either way.
- """
- if schema.sync_type == ExternalDataSchema.SyncType.CDC:
- return False
- if schema.coarsen_requested is not None:
- return True
- return enabled
-
-
def _maybe_flag_pre_extraction(
schema: ExternalDataSchema,
job: ExternalDataJob,
@@ -372,7 +351,7 @@ def _maybe_repartition_table(inputs: RepartitionActivityInputs, logger: Filterin
# Fast no-op path: nothing queued and the gate says no on-disk measurement is needed (flag off, or
# CDC). Return here — before fetching the job and reading the delta log — so the common healthy
# invocation avoids all on-disk I/O. Flagged tables fall through and measure the live size below.
- if pending is None and swap is None and not _needs_pre_extraction_detection(schema, enabled):
+ if pending is None and swap is None and not needs_pre_extraction_detection(schema, enabled):
logger.info("repartition: nothing queued and no detection needed, nothing to do")
return
diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_compute_table_statistics.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_compute_table_statistics.py
index 0bebcaff657f..7ca38a92a641 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_compute_table_statistics.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_compute_table_statistics.py
@@ -12,6 +12,7 @@ from django.test.utils import CaptureQueriesContext
from django.utils import timezone
import pyarrow as pa
+from parameterized import parameterized
from temporalio.testing import ActivityEnvironment
from posthog.models import Organization, Team
@@ -145,7 +146,7 @@ class TestComputeTableStatisticsSync:
team=team,
credential=credential,
url_pattern="https://bucket.s3/data/*",
- columns=columns or {"amount": {"clickhouse": "Nullable(Int64)"}},
+ columns=columns if columns is not None else {"amount": {"clickhouse": "Nullable(Int64)"}},
)
source = ExternalDataSource.objects.create(
source_id="src", connection_id="conn", team=team, source_type="Stripe"
@@ -307,6 +308,194 @@ class TestComputeTableStatisticsSync:
assert row.row_count == 99
assert row.computed_for_delta_version == 5
+ @parameterized.expand(
+ [
+ ("same_version_within_max_age_skips", dt.timedelta(days=2), 7, "skipped"),
+ ("same_version_past_max_age_recomputes", dt.timedelta(days=8), 7, "done"),
+ ("new_version_recomputes", dt.timedelta(days=2), 8, "done"),
+ # A full refresh/reset restarts the Delta version at 0, so a stored version ahead of the
+ # table's current one means the table was recreated since the last computation — the stored
+ # version must not be trusted as a match even though it hasn't changed monotonically.
+ ("version_behind_stored_from_reset_recomputes", dt.timedelta(days=2), 1, "done"),
+ ]
+ )
+ def test_version_gate(self, _name: str, age: dt.timedelta, table_version: int, expected_status: str) -> None:
+ # The Add-action scan is the expensive step. Stats at an unchanged Delta version are already
+ # exact, so re-reading them once a day per table was pure cost; the age cap keeps a changed
+ # column registry or derivation from waiting forever behind a table that never moves.
+ team = self._team()
+ schema, table, _ = self._schema_table_job(team)
+ WarehouseColumnStatistics.objects.for_team(team.id).create(
+ team=team,
+ table=table,
+ column_name="amount",
+ row_count=1,
+ computed_at=timezone.now() - age,
+ computed_for_delta_version=7,
+ )
+ add_actions = pa.table({"num_records": [99], "null_count.amount": [0], "min.amount": [1], "max.amount": [1]})
+ helper = self._mock_delta(add_actions, version=table_version)
+ with (
+ patch.object(comp, "statistics_enabled", return_value=True),
+ patch(DELTA_HELPER_PATH, return_value=helper),
+ ):
+ result = compute_table_statistics_sync(team.id, schema.id)
+
+ row = WarehouseColumnStatistics.objects.for_team(team.id).get(table_id=table.id, column_name="amount")
+ assert result["status"] == expected_status
+ if expected_status == "skipped":
+ assert result["reason"] == "version_unchanged"
+ helper.get_delta_table.return_value.get_add_actions.assert_not_called()
+ assert row.row_count == 1
+ else:
+ assert row.row_count == 99
+ assert row.computed_for_delta_version == table_version
+
+ def test_recomputes_when_one_column_still_carries_an_earlier_version(self) -> None:
+ # `_upsert_statistics` writes one column at a time and only retries the whole batch on a
+ # transient DB error; any other failure partway through a recompute can leave one column
+ # stamped with the new version while another is still on the old one. The gate must not read
+ # that mixed state as "version unchanged" just because the column it did reach agrees.
+ team = self._team()
+ schema, table, _ = self._schema_table_job(
+ team,
+ columns={
+ "amount": {"clickhouse": "Nullable(Int64)"},
+ "currency": {"clickhouse": "Nullable(String)"},
+ },
+ )
+ computed_at = timezone.now() - dt.timedelta(days=2)
+ WarehouseColumnStatistics.objects.for_team(team.id).create(
+ team=team,
+ table=table,
+ column_name="amount",
+ row_count=1,
+ computed_at=computed_at,
+ computed_for_delta_version=7,
+ )
+ WarehouseColumnStatistics.objects.for_team(team.id).create(
+ team=team,
+ table=table,
+ column_name="currency",
+ row_count=1,
+ computed_at=computed_at,
+ computed_for_delta_version=6,
+ )
+ add_actions = pa.table(
+ {
+ "num_records": [99],
+ "null_count.amount": [0],
+ "min.amount": [1],
+ "max.amount": [1],
+ "null_count.currency": [0],
+ "min.currency": ["usd"],
+ "max.currency": ["usd"],
+ }
+ )
+ helper = self._mock_delta(add_actions, version=7)
+ with (
+ patch.object(comp, "statistics_enabled", return_value=True),
+ patch(DELTA_HELPER_PATH, return_value=helper),
+ ):
+ result = compute_table_statistics_sync(team.id, schema.id)
+
+ assert result["status"] == "done"
+ rows = {r.column_name: r for r in WarehouseColumnStatistics.objects.for_team(team.id).filter(table_id=table.id)}
+ assert rows["amount"].computed_for_delta_version == 7
+ assert rows["currency"].computed_for_delta_version == 7
+
+ def test_a_dropped_columns_stale_row_does_not_block_the_gate_forever(self) -> None:
+ # A column removed from the table keeps its old stats row (`existing` still holds it, since
+ # nothing deletes it). The gate must not let that permanently-stale row hold the version/time
+ # minimum open forever — it has to be excluded, not just outvoted.
+ team = self._team()
+ schema, table, _ = self._schema_table_job(team, columns={"amount": {"clickhouse": "Nullable(Int64)"}})
+ computed_at = timezone.now() - dt.timedelta(days=2)
+ WarehouseColumnStatistics.objects.for_team(team.id).create(
+ team=team,
+ table=table,
+ column_name="amount",
+ row_count=1,
+ computed_at=computed_at,
+ computed_for_delta_version=7,
+ )
+ WarehouseColumnStatistics.objects.for_team(team.id).create(
+ team=team,
+ table=table,
+ column_name="legacy_col",
+ row_count=1,
+ computed_at=computed_at - dt.timedelta(days=100),
+ computed_for_delta_version=1,
+ )
+ add_actions = pa.table({"num_records": [99], "null_count.amount": [0], "min.amount": [1], "max.amount": [1]})
+ helper = self._mock_delta(add_actions, version=7)
+ with (
+ patch.object(comp, "statistics_enabled", return_value=True),
+ patch(DELTA_HELPER_PATH, return_value=helper),
+ ):
+ result = compute_table_statistics_sync(team.id, schema.id)
+
+ assert result["status"] == "skipped"
+ assert result["reason"] == "version_unchanged"
+
+ def test_recomputes_when_a_registered_column_has_no_stats_row_at_all(self) -> None:
+ # Distinct from the two tests above: those cover a column whose row exists but carries a
+ # stale timestamp/version. Here "currency" has no row at all — its very first computation
+ # never landed. The min-based gates only compare columns present in `existing`, so without an
+ # explicit completeness check a table like this would read as fully fresh off "amount" alone.
+ team = self._team()
+ schema, table, _ = self._schema_table_job(
+ team,
+ columns={
+ "amount": {"clickhouse": "Nullable(Int64)"},
+ "currency": {"clickhouse": "Nullable(String)"},
+ },
+ )
+ WarehouseColumnStatistics.objects.for_team(team.id).create(
+ team=team,
+ table=table,
+ column_name="amount",
+ row_count=1,
+ computed_at=timezone.now(),
+ computed_for_delta_version=7,
+ )
+ add_actions = pa.table(
+ {
+ "num_records": [99],
+ "null_count.amount": [0],
+ "min.amount": [1],
+ "max.amount": [1],
+ "null_count.currency": [0],
+ "min.currency": ["usd"],
+ "max.currency": ["usd"],
+ }
+ )
+ helper = self._mock_delta(add_actions, version=7)
+ with (
+ patch.object(comp, "statistics_enabled", return_value=True),
+ patch(DELTA_HELPER_PATH, return_value=helper),
+ ):
+ result = compute_table_statistics_sync(team.id, schema.id)
+
+ assert result["status"] == "done"
+ rows = {r.column_name: r for r in WarehouseColumnStatistics.objects.for_team(team.id).filter(table_id=table.id)}
+ assert rows["currency"].computed_for_delta_version == 7
+
+ def test_skipped_when_no_columns_without_reading_add_actions(self) -> None:
+ # Nothing is written for a table with no registered columns, so the recency gate never
+ # engages for it; the only thing keeping the scan off every sync is checking columns first.
+ team = self._team()
+ schema, _, _ = self._schema_table_job(team, columns={})
+ helper = self._mock_delta(pa.table({"num_records": [1]}))
+ with (
+ patch.object(comp, "statistics_enabled", return_value=True),
+ patch(DELTA_HELPER_PATH, return_value=helper),
+ ):
+ result = compute_table_statistics_sync(team.id, schema.id)
+
+ assert result == {"status": "skipped", "reason": "no_columns"}
+ helper.get_delta_table.return_value.get_add_actions.assert_not_called()
+
def test_skipped_when_computed_recently(self) -> None:
team = self._team()
schema, table, _ = self._schema_table_job(team)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_repartition_table.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_repartition_table.py
index 630d4fca4ffe..6bc4bbe1309b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_repartition_table.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_repartition_table.py
@@ -1,6 +1,7 @@
import uuid
import datetime as dt
import contextvars
+from typing import Any
import pytest
from unittest.mock import AsyncMock, MagicMock, patch
@@ -23,6 +24,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.rep
)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.repartition_controller import (
MAX_REPARTITION_ATTEMPTS,
+ repartition_activity_has_work,
)
from products.warehouse_sources.backend.temporal.data_imports.workflow_activities.repartition_table import (
RepartitionActivityInputs,
@@ -32,6 +34,7 @@ from products.warehouse_sources.backend.temporal.data_imports.workflow_activitie
)
MODULE = "products.warehouse_sources.backend.temporal.data_imports.workflow_activities.repartition_table"
+CONTROLLER_MODULE = "products.warehouse_sources.backend.temporal.data_imports.pipelines.core.repartition_controller"
TEAM_ID = 1
SCHEMA_ID = str(uuid.uuid4())
@@ -1063,6 +1066,63 @@ class TestFeatureFlagGate:
assert mock_repartition.await_count == (1 if expect_rewrite else 0)
+class TestRepartitionActivityHasWork:
+ @parameterized.expand(
+ [
+ (
+ "revive_pending_stands_down",
+ {"delta_revive_required": {"at": "x"}},
+ PENDING_TARGET,
+ None,
+ None,
+ True,
+ False,
+ ),
+ ("queued_rewrite_flag_on", {}, PENDING_TARGET, None, None, True, True),
+ # The activity's own fast path treats a queued rewrite as a no-op once the flag that
+ # staged it is disabled (the flag is the only lever support has to release such a table) —
+ # this must agree, or the schema keeps paying a full activity round trip forever.
+ ("queued_rewrite_released_by_disabled_flag", {}, PENDING_TARGET, None, None, False, False),
+ (
+ "queued_rewrite_admin_reason_fails_open",
+ {},
+ {**PENDING_TARGET, "trigger_reason": "admin"},
+ None,
+ None,
+ False,
+ True,
+ ),
+ ("staged_swap", {}, None, {"state": "ready"}, None, False, True),
+ ("flag_on_measures_the_table", {}, None, None, None, True, True),
+ ("flag_off_nothing_queued", {}, None, None, None, False, False),
+ ("coarsen_nomination_without_flag", {}, None, None, {"requested_by": "op"}, False, True),
+ ("cdc_never_measures", {"sync_type": ExternalDataSchema.SyncType.CDC}, None, None, None, True, False),
+ ]
+ )
+ @patch(f"{CONTROLLER_MODULE}.is_auto_repartition_enabled")
+ def test_matches_the_activitys_own_fast_path(
+ self,
+ _name: str,
+ overrides: dict[str, Any],
+ pending: dict[str, Any] | None,
+ swap: dict[str, Any] | None,
+ coarsen_requested: dict[str, Any] | None,
+ enabled: bool,
+ expected: bool,
+ mock_enabled: MagicMock,
+ ) -> None:
+ # The workflow skips scheduling the activity on this answer, so a False here for a table the
+ # activity would have rewritten or measured silently stops that table repartitioning.
+ mock_enabled.return_value = enabled
+ schema = _schema(name="public.usages", s3_folder_name="usages", pending=pending, swap=swap)
+ schema.sync_type = ExternalDataSchema.SyncType.INCREMENTAL
+ schema.coarsen_requested = coarsen_requested
+ for attribute, value in overrides.items():
+ setattr(schema, attribute, value)
+
+ assert repartition_activity_has_work(schema) is expected
+
+
class TestMaybeFlagPreExtraction:
@parameterized.expand(
[
diff --git a/products/warehouse_sources/backend/tests/api/test_external_data_source_end_to_end.py b/products/warehouse_sources/backend/tests/api/test_external_data_source_end_to_end.py
index fd7f42e5726d..3de6e10e1c56 100644
--- a/products/warehouse_sources/backend/tests/api/test_external_data_source_end_to_end.py
+++ b/products/warehouse_sources/backend/tests/api/test_external_data_source_end_to_end.py
@@ -92,7 +92,7 @@ def run_data_import_workflow(mock_stripe_client):
)
with (
- mock.patch.object(DeltaMaintenance, "compact_table"),
+ mock.patch.object(DeltaMaintenance, "run_scheduled"),
mock.patch(
"products.warehouse_sources.backend.temporal.data_imports.external_data_job.get_data_import_finished_metric"
),