:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
perf(data-warehouse): open the delta table once per extract job (#113093)
Tom Owerscc34e7a27396
diff --git a/products/warehouse_sources/backend/models/external_data_schema.py b/products/warehouse_sources/backend/models/external_data_schema.pyindex 2b3d18d2a350..938aa6eaf347 100644--- a/products/warehouse_sources/backend/models/external_data_schema.py+++ b/products/warehouse_sources/backend/models/external_data_schema.py@@ -277,7 +277,7 @@ class ExternalDataSchema( # nosemgrep: semgrep.rules.security.prefer-uuid7-djan# See `sources/common/history_window.py`. A column rather than a `sync_type_config` key# because it has to outlive a reset, and clearing that blob is what a reset is for.history_start = models.DateTimeField(null=True, blank=True)- # { "incremental_field": string, "incremental_field_type": string, "incremental_field_last_value": any, "incremental_field_earliest_value": any, "incremental_field_lookback_seconds": int | None, "reset_pipeline": bool, "partitioning_enabled": bool, "partition_count": int, "partition_size": int, "partition_mode": str, "partitioning_keys": list[str], "chunk_size_override": int | None, "primary_key_columns": list[str] | None, "verified_primary_keys": list[str] | None, "source_cursor": { "kind": str, "data": dict }, "max_partition_bytes": int, "last_repartition_at": iso8601 str, "repartition_pending": { "partition_mode": str, "partition_format": str | None, "partition_count": int | None, "partition_size": int | None, "partition_keys": list[str], "trigger_reason": str }, "repartition_swap": { "state": "ready", "temp_uri": str, "live_uri": str }, "repartition_rewrite": { "temp_uri": str, "rows_written": int, "target": dict }, "query_folder_state": { "<table>__query": { "active": str, "active_since": iso8601 str, "active_job_id": str, "history_since": iso8601 str, "inactive_since": { str: iso8601 str } } }, "registered_schema_fingerprint": str }+ # { "incremental_field": string, "incremental_field_type": string, "incremental_field_last_value": any, "incremental_field_earliest_value": any, "incremental_field_lookback_seconds": int | None, "reset_pipeline": bool, "partitioning_enabled": bool, "partition_count": int, "partition_size": int, "partition_mode": str, "partitioning_keys": list[str], "chunk_size_override": int | None, "primary_key_columns": list[str] | None, "verified_primary_keys": list[str] | None, "source_cursor": { "kind": str, "data": dict }, "max_partition_bytes": int, "partition_measurement": { "job_id": str, "phase": "pre_extraction" | "post_load", "budget": int, "healthy": bool }, "last_repartition_at": iso8601 str, "repartition_pending": { "partition_mode": str, "partition_format": str | None, "partition_count": int | None, "partition_size": int | None, "partition_keys": list[str], "trigger_reason": str }, "repartition_swap": { "state": "ready", "temp_uri": str, "live_uri": str }, "repartition_rewrite": { "temp_uri": str, "rows_written": int, "target": dict }, "query_folder_state": { "<table>__query": { "active": str, "active_since": iso8601 str, "active_job_id": str, "history_since": iso8601 str, "inactive_since": { str: iso8601 str } } }, "registered_schema_fingerprint": str }sync_type_config = models.JSONField(default=dict,blank=True,@@ -784,6 +784,14 @@ class ExternalDataSchema( # nosemgrep: semgrep.rules.security.prefer-uuid7-djanreturn self.sync_type_config.get("max_partition_bytes", None)return None+ @property+ def partition_measurement(self) -> dict[str, Any] | None:+ if self.sync_type_config:+ measurement = self.sync_type_config.get("partition_measurement", None)+ if isinstance(measurement, dict):+ return measurement+ return None+@propertydef last_repartition_at(self) -> str | None:if self.sync_type_config:@@ -883,16 +891,15 @@ class ExternalDataSchema( # nosemgrep: semgrep.rules.security.prefer-uuid7-djanlambda: self.save(update_fields=["sync_type_config", "updated_at"], skip_activity_log=True))- def record_partition_measurement(self, max_partition_bytes: int) -> None:+ def record_partition_measurement(self, max_partition_bytes: int, measurement: dict[str, Any] | None = None) -> None:# Deferred: this module loads during django.setup() and the util pulls in temporalio.from posthog.temporal.common.utils import retry_on_db_connection_drop # noqa: PLC0415+ updates: dict[str, Any] = {"max_partition_bytes": max_partition_bytes}+ if measurement is not None:+ updates["partition_measurement"] = measurementself.sync_type_config = retry_on_db_connection_drop(- lambda: update_sync_type_config_keys(- self.id,- self.team_id,- updates={"max_partition_bytes": max_partition_bytes},- )+ lambda: update_sync_type_config_keys(self.id, self.team_id, updates=updates))def set_repartition_pending(self, target: dict[str, Any]) -> None:@@ -1206,6 +1213,7 @@ class ExternalDataSchema( # nosemgrep: semgrep.rules.security.prefer-uuid7-djan"partitioning_keys","partition_mode","backfilled_partition_format",+ "partition_measurement",SOURCE_CURSOR_KEY,# Cursor keys from before `source_cursor`. A source still reads them when it has no# `source_cursor`, so a reset has to drop them too.@@ -1777,6 +1785,7 @@ def finalize_repartition_scheme("repartition_swap","repartition_pending","repartition_rewrite",+ "partition_measurement",):config.pop(key, None)wrote = Truediff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/extract.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/extract.pyindex fee94fc0ba35..27e97d30404e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/extract.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/extract.py@@ -484,6 +484,21 @@ async def setup_row_tracking_with_billing_check()+def resets_table_before_extraction(+ reset_pipeline: bool, should_resume: bool, schema: "ExternalDataSchema", webhook_only: bool = False+) -> bool:+ """Whether `handle_reset_or_full_refresh` deletes the table for these inputs."""+ from products.warehouse_sources.backend.models.external_data_schema import ( # noqa: PLC0415 — Django model import kept off this activity module's load path+ ExternalDataSchema,+ )++ if should_resume:+ return False+ if reset_pipeline:+ return not webhook_only+ return schema.sync_type == ExternalDataSchema.SyncType.FULL_REFRESH++async def handle_reset_or_full_refresh(reset_pipeline: bool,should_resume: bool,@@ -559,6 +574,8 @@ async def handle_corrupted_delta_log(job: "ExternalDataJob",delta_table_ref: DeltaTableRef,logger: FilteringBoundLogger,+ *,+ table_will_be_reset: bool = False,) -> bool:"""Detect and revive a corrupt Delta table before extraction.@@ -579,10 +596,17 @@ async def handle_corrupted_delta_log(- Otherwise the table is reset so this run rebuilds it from source, and the job is markednon-billable — the corruption is our fault, not the customer's.+ `table_will_be_reset` says that this run deletes the table before extraction in any case (a+ scheduled full refresh or a requested reset). The delete does not read the log, so an unreadable+ log needs no detection there, and the open is skipped. A revive marker and a staged swap are+ still handled, because they need more than the delete.+Returns True if a revive happened. Best-effort: any failure here must not block the sync."""revive_marker = schema.delta_revive_requiredif revive_marker is None:+ if table_will_be_reset and schema.repartition_swap is None:+ return Falsetry:if not await delta_table_ref.is_table_corrupted():return Falsediff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/load.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/load.pyindex 751dfd3c80c5..3cdba7aafdd4 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@@ -621,7 +621,7 @@ async def _maybe_flag_repartition_step(delta_table = await delta_table_ref.get_delta_table()if delta_table is not None:- await maybe_flag_for_repartition(schema, source, job, delta_table, logger)+ await maybe_flag_for_repartition(schema, source, job, delta_table, logger, phase="post_load")# Product-facing side effects outside the core publish/register flow. Entries share the PostLoadStepdiff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/test/test_extract.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/test/test_extract.pyindex 76fa08df75c4..bb9a2026010d 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/test/test_extract.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/test/test_extract.py@@ -27,6 +27,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.common.epersist_primary_keys,report_heartbeat_timeout,reset_rows_synced_if_needed,+ resets_table_before_extraction,resolve_primary_keys,should_check_shutdown,trim_source_job_inputs,@@ -715,6 +716,69 @@ class TestHandleResetOrFullRefresh:assert "incremental_field_last_value" not in schema.sync_type_config+def _reset_inputs() -> list[tuple[str, bool, bool, str, bool]]:+ return [+ (+ f"reset_{reset}_resume_{resume}_{sync_type}_webhook_only_{webhook_only}",+ reset,+ resume,+ sync_type,+ webhook_only,+ )+ for reset in (False, True)+ for resume in (False, True)+ for sync_type in (ExternalDataSchema.SyncType.FULL_REFRESH, ExternalDataSchema.SyncType.INCREMENTAL)+ for webhook_only in (False, True)+ ]+++class TestCorruptionCheckBeforeAReset:+ def _schema(self, sync_type: str, swap: dict | None = None) -> MagicMock:+ schema = MagicMock(sync_type=sync_type, sync_type_config={}, delta_revive_required=None)+ schema.repartition_swap = swap+ return schema++ def _logger(self) -> MagicMock:+ return MagicMock(awarning=AsyncMock(), ainfo=AsyncMock(), aexception=AsyncMock(), adebug=AsyncMock())++ @parameterized.expand(_reset_inputs())+ def test_prediction_matches_what_the_reset_step_does(+ self, _name: str, reset_pipeline: bool, should_resume: bool, sync_type: str, webhook_only: bool+ ) -> None:+ schema = self._schema(sync_type)+ table_ref = MagicMock(reset_table=AsyncMock())++ with patch("products.warehouse_sources.backend.models.external_data_schema.update_sync_type_config_keys"):+ async_to_sync(handle_reset_or_full_refresh)(+ reset_pipeline, should_resume, schema, table_ref, self._logger(), webhook_only=webhook_only+ )++ predicted = resets_table_before_extraction(reset_pipeline, should_resume, schema, webhook_only)+ assert predicted is (table_ref.reset_table.await_count == 1)++ @parameterized.expand(+ [+ # (name, table_will_be_reset, staged swap, the table is opened for the check)+ ("incremental_run_checks", False, None, True),+ ("run_that_resets_the_table_skips_the_open", True, None, False),+ ("staged_swap_is_still_checked_before_a_reset", True, {"state": "ready"}, True),+ ]+ )+ def test_open_for_the_corruption_check(+ self, _name: str, table_will_be_reset: bool, swap: dict | None, expect_open: bool+ ) -> None:+ schema = self._schema(ExternalDataSchema.SyncType.FULL_REFRESH, swap)+ table_ref = MagicMock(is_table_corrupted=AsyncMock(return_value=False), reset_table=AsyncMock())++ revived = async_to_sync(handle_corrupted_delta_log)(+ schema, MagicMock(), table_ref, self._logger(), table_will_be_reset=table_will_be_reset+ )++ assert revived is False+ assert table_ref.is_table_corrupted.await_count == int(expect_open)+ table_ref.reset_table.assert_not_awaited()++class TestValidateIncrementalSync:@parameterized.expand([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.pyindex 26f201d2ba8b..dbc83b131ca9 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@@ -485,16 +485,27 @@ class DeltaTableRef:The signature of a `_delta_log` left inconsistent by an interrupted repartition swap or anOOM-crashed merge — after which every sync fails to open the table and loops. Non-destructive:- only attempts an open (bypassing the get_delta_table cache). A table that simply doesn't exist is+ only attempts an open. A table that simply doesn't exist isnot corrupt; an unknown open error is not classified as corrupt, so a transient failure nevertriggers a destructive revive. A recognized transient blip (see is_transient_object_store_error,is_transient_delta_maintenance_error) is excluded the same way — otherwise a concurrent purgeracing this open would misread as corruption and trigger a needless destructive revive.++ A table that opens stays on this ref as the cached handle, so the next `get_delta_table`+ call in the same run does not read the log again. A handle that this ref already holds is+ proof that the table opened, so it answers the question with no request."""+ if self._cached_table is not None:+ return False+delta_uri = await self._get_delta_table_uri()storage_options = self._get_credentials()- if await self._open_directly(delta_uri, storage_options) is not None:+ table = await self._open_directly(delta_uri, storage_options)+ if table is not None:+ self._cached_table = table+ self._cached_table_stale = False+ self._known_missing = Falsereturn Falseis_delta = await asyncio.to_thread(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.pyindex b7ef308d8fe6..502bda9d0b7f 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@@ -312,6 +312,71 @@ class TestOpenWithoutExistenceCheck:mock_delta_table.is_deltatable.assert_called_once()+class TestCorruptionCheckSharesItsOpen:+ @parameterized.expand(+ [+ # (name, step between the check and the read, opens made by the read)+ ("read_reuses_the_handle", "nothing", 0),+ ("reset_drops_the_handle", "reset", 1),+ ("invalidate_drops_the_handle", "invalidate", 1),+ ]+ )+ @pytest.mark.asyncio+ async def test_read_after_the_corruption_check(self, _name: str, step: str, later_opens: int) -> None:+ with tempfile.TemporaryDirectory() as tmp:+ uri = str(Path(tmp) / "table")+ deltalake.write_deltalake(uri, pa.table({"id": [1]}))+ ref = make_local_table_ref(uri)+ module = "products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.table"+ s3_cm = MagicMock(__aenter__=AsyncMock(return_value=MagicMock()), __aexit__=AsyncMock(return_value=False))++ with (+ patch.object(ref, "_open_delta_table", AsyncMock(side_effect=ref._open_delta_table)) as later_open,+ patch(f"{module}.aget_s3_client", MagicMock(return_value=s3_cm)),+ patch(f"{module}._purge_s3_prefix", AsyncMock()),+ ):+ assert await ref.is_table_corrupted() is False+ if step == "reset":+ await ref.reset_table()+ elif step == "invalidate":+ ref.invalidate_cached_table()++ table = await ref.get_delta_table()++ assert table is not None+ assert later_open.await_count == later_opens++ @pytest.mark.asyncio+ async def test_a_commit_through_the_shared_handle_is_visible_to_the_next_reader(self) -> None:+ with tempfile.TemporaryDirectory() as tmp:+ uri = str(Path(tmp) / "table")+ deltalake.write_deltalake(uri, pa.table({"id": [1]}))+ ref = make_local_table_ref(uri)++ assert await ref.is_table_corrupted() is False+ maintenance_handle = await ref.get_delta_table()+ assert maintenance_handle is not None+ deltalake.write_deltalake(maintenance_handle, pa.table({"id": [2]}), mode="append")+ deltalite.DeltaLiteTable.open(uri).upsert(pa.table({"id": [3]}), primary_keys=["id"])+ ref.note_deltalite_commit(None)++ reader = await ref.get_delta_table()++ assert reader is not None+ assert reader.version() == deltalake.DeltaTable(uri).version() == 2+ assert set(reader.to_pyarrow_table().column("id").to_pylist()) == {1, 2, 3}++ @pytest.mark.asyncio+ async def test_a_corrupt_table_leaves_no_handle_behind(self) -> None:+ with tempfile.TemporaryDirectory() as tmp:+ path = Path(tmp) / "table"+ _commit_without_metadata(path)+ ref = make_local_table_ref(str(path))++ assert await ref.is_table_corrupted() is True+ assert ref.pop_cached_table() is None++class TestKnownMissingTable:@parameterized.expand([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.pyindex e9e5f92f2b9c..1c8be4b29b3b 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 `repartfrom __future__ import annotationsimport asyncio+from collections.abc import Sequencefrom typing import TYPE_CHECKING, Any, Literalfrom django.conf import settings@@ -122,6 +123,73 @@ def needs_pre_extraction_detection(schema: ExternalDataSchema) -> bool:return schema.sync_type != ExternalDataSchema.SyncType.CDC+MeasurementPhase = Literal["pre_extraction", "post_load"]++# How many earlier jobs the gate below reads to connect a run to the measurement it relies on. A+# longer run of jobs with no rows costs one measurement and then starts a new chain.+MEASUREMENT_CHAIN_LIMIT = 20+++def partition_measurement_holds(+ measurement: dict[str, Any] | None, earlier_jobs: Sequence[tuple[str, str, int | None]]+) -> bool:+ """Whether the recorded measurement still describes the table that is on disk now.++ `earlier_jobs` are the schema's jobs before the current one, newest first, as (id, status, rows+ synced). The measurement holds when the job that took it completed, every job after it completed+ with no rows, and the job itself wrote nothing after the measurement: a post-load measurement is+ after its job's last write, and a pre-extraction one needs that job to have synced no rows.++ Only a healthy measurement counts: one where detection had nothing to act on and nothing that+ time alone can change (see `maybe_flag_for_repartition`). A failed or running job anywhere in the+ chain breaks it. That keeps the on-disk read for a table whose merge runs out of memory, because+ such a job never completes.+ """+ if not measurement or measurement.get("healthy") is not True:+ return False+ measured_job_id = measurement.get("job_id")+ for job_id, status, rows_synced in earlier_jobs:+ if status != ExternalDataJob.Status.COMPLETED:+ return False+ if job_id == measured_job_id:+ return measurement.get("phase") == "post_load" or rows_synced == 0+ if rows_synced != 0:+ return False+ return False+++def pre_extraction_measurement_is_redundant(schema: ExternalDataSchema, job: ExternalDataJob) -> bool:+ """Whether the pre-extraction activity can skip its read of the Delta log for this run.++ True only when a new read would give the verdict that the last one gave, which was to do+ nothing. No data reached the table since that measurement (see `partition_measurement_holds`),+ so the partition sizes are the same. The inputs that can change with no write are checked here:+ the budget, an operator nomination, and the count of recent OOM kills. The measurement itself is+ healthy only for a table that the coarsening path cannot pick up as time passes.+ """+ if schema.coarsen_requested is not None:+ return False+ measurement = schema.partition_measurement+ if not measurement or measurement.get("healthy") is not True:+ return False+ if measurement.get("budget") != target_partition_bytes():+ return False+ if (+ ExternalDataSchemaOOMEvent.recent_count(schema, days=repartition_oom_window_days())+ >= repartition_oom_threshold()+ ):+ return False+ earlier_jobs = [+ (str(job_id), status, rows_synced)+ for job_id, status, rows_synced in ExternalDataJob.objects.filter(+ pipeline_id=schema.source_id, schema_id=schema.id, created_at__lt=job.created_at+ )+ .order_by("-created_at")+ .values_list("id", "status", "rows_synced")[:MEASUREMENT_CHAIN_LIMIT]+ ]+ return partition_measurement_holds(measurement, earlier_jobs)++def repartition_activity_has_work(schema: ExternalDataSchema) -> bool:"""Whether the pre-extraction repartition activity would do more than log and return.@@ -361,11 +429,16 @@ async def maybe_flag_for_repartition(job: ExternalDataJob,delta_table: deltalake.DeltaTable,logger: FilteringBoundLogger,+ *,+ phase: MeasurementPhase = "pre_extraction",) -> None:"""Measure partition sizes and, if over budget, record a `repartition_pending` target.Always records `max_partition_bytes` for observability (even when the table is in cooldown). Therewrite itself happens on the next run. Never raises — detection must not break post-load.++ The measurement is recorded with the job, the `phase` and the verdict, so the next run can tell+ whether it still describes the table (see `partition_measurement_holds`)."""try:# A table pending a corruption revive must heal before it's rewritten — flagging it here would@@ -387,7 +460,6 @@ async def maybe_flag_for_repartition(returnmax_bytes = max(partition_bytes.values())- await asyncio.to_thread(schema.record_partition_measurement, max_bytes)budget = target_partition_bytes()over_budget = max_bytes > budget@@ -407,6 +479,23 @@ async def maybe_flag_for_repartition()oom_triggered = oom_count >= repartition_oom_threshold()+ # A table with this shape is one that the coarsening path evaluates on each run, and its+ # gates open with time (layout age, days without an OOM). Such a table is never healthy, so+ # the next run measures it again.+ coarsen_candidate = (+ len(partition_bytes) >= COARSEN_MIN_PARTITIONS and max_bytes * COARSEN_TRIGGER_DIVISOR <= budget+ )+ await asyncio.to_thread(+ schema.record_partition_measurement,+ max_bytes,+ {+ "job_id": str(job.id),+ "phase": phase,+ "budget": budget,+ "healthy": not over_budget and not oom_triggered and not coarsen_candidate,+ },+ )+if not over_budget and not oom_triggered:await logger.adebug(f"repartition: not needed, within budget and no repeated OOMs schema_id={schema.id} "diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test_repartition_controller.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test_repartition_controller.pyindex a3b85cfb1bf1..2e7506491537 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test_repartition_controller.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test_repartition_controller.py@@ -283,6 +283,123 @@ class TestRepartitionDetection:assert schema.repartition_pending["partition_keys"] == ["id"]+class TestPartitionMeasurementRecord:+ @pytest.mark.parametrize(+ "budget, phase, healthy",+ [(10**12, "post_load", True), (10**12, "pre_extraction", True), (1, "post_load", False)],+ ids=["within_budget_after_load", "within_budget_before_extraction", "over_budget"],+ )+ def test_detection_records_who_measured_and_the_verdict(+ self, team, budget: int, phase: ctrl.MeasurementPhase, healthy: bool+ ):+ schema = _make_schema(+ team,+ {"partitioning_enabled": True, "partition_mode": "md5", "partition_count": 2, "partitioning_keys": ["id"]},+ )+ job = _make_job(team, schema)+ with tempfile.TemporaryDirectory() as d:+ delta = _write_partitioned_delta(f"{d}/t", ["0", "0", "1", "1"])+ with (+ patch.object(ctrl, "target_partition_bytes", return_value=budget),+ patch.object(ctrl, "capture_repartition_event"),+ ):+ async_to_sync(ctrl.maybe_flag_for_repartition)(schema, schema.source, job, delta, logger, phase=phase)++ schema.refresh_from_db()+ assert schema.partition_measurement == {+ "job_id": str(job.id),+ "phase": phase,+ "budget": budget,+ "healthy": healthy,+ }++ def test_reset_invalidates_the_measurement(self, team):+ schema = _make_schema(+ team,+ {+ "partition_measurement": {+ "job_id": "previous-job",+ "phase": "post_load",+ "budget": 500,+ "healthy": True,+ }+ },+ )++ schema.update_sync_type_config_for_reset_pipeline()++ assert schema.partition_measurement is None++ def test_a_table_that_coarsening_can_pick_up_is_measured_on_each_run(self, team):+ schema = _make_schema(+ team,+ {"partitioning_enabled": True, "partition_mode": "md5", "partition_count": 32, "partitioning_keys": ["id"]},+ )+ job = _make_job(team, schema)+ with tempfile.TemporaryDirectory() as d:+ delta = _write_partitioned_delta(f"{d}/t", [str(bucket) for bucket in range(ctrl.COARSEN_MIN_PARTITIONS)])+ with patch.object(ctrl, "capture_repartition_event"):+ async_to_sync(ctrl.maybe_flag_for_repartition)(+ schema, schema.source, job, delta, logger, phase="post_load"+ )++ schema.refresh_from_db()+ measurement = schema.partition_measurement+ assert measurement is not None and measurement["healthy"] is False++ @pytest.mark.parametrize(+ "previous_status, nominated, measured_budget, recent_ooms, redundant",+ [+ (ExternalDataJob.Status.COMPLETED, False, 500, 0, True),+ (ExternalDataJob.Status.FAILED, False, 500, 0, False),+ (ExternalDataJob.Status.COMPLETED, True, 500, 0, False),+ (ExternalDataJob.Status.COMPLETED, False, 400, 0, False),+ (ExternalDataJob.Status.COMPLETED, False, 500, 3, False),+ ],+ ids=[+ "previous_run_completed",+ "previous_run_failed",+ "operator_nomination_waits",+ "budget_changed_since_the_measurement",+ "repeated_oom_kills_since_the_measurement",+ ],+ )+ def test_gate_reads_what_can_change_without_a_write(+ self, team, previous_status: str, nominated: bool, measured_budget: int, recent_ooms: int, redundant: bool+ ):+ schema = _make_schema(team, {})+ other_schema = ExternalDataSchema.objects.create(+ name="other", team=team, source=schema.source, sync_type_config={}+ )+ now = datetime.datetime.now(datetime.UTC)+ previous = _make_job(team, schema)+ ExternalDataJob.objects.filter(id=previous.id).update(+ status=previous_status, rows_synced=10, created_at=now - datetime.timedelta(minutes=10)+ )+ # A failed job of another schema of the same source must not break this schema's chain.+ ExternalDataJob.objects.filter(id=_make_job(team, other_schema).id).update(+ status=ExternalDataJob.Status.FAILED, created_at=now - datetime.timedelta(minutes=5)+ )+ current = _make_job(team, schema)+ ExternalDataJob.objects.filter(id=current.id).update(created_at=now)+ current.refresh_from_db()+ schema.sync_type_config = {+ "partition_measurement": {+ "job_id": str(previous.id),+ "phase": "post_load",+ "budget": measured_budget,+ "healthy": True,+ },+ **({"coarsen_requested": _NOMINATION} if nominated else {}),+ }++ with (+ patch.object(ctrl, "target_partition_bytes", return_value=500),+ patch.object(ctrl.ExternalDataSchemaOOMEvent, "recent_count", return_value=recent_ooms),+ ):+ assert ctrl.pre_extraction_measurement_is_redundant(schema, current) is redundant++class TestIsRepartitionHoldEnabled:def test_retries_once_on_transient_db_connection_drop(self, team):# The Team lookup runs on a long-lived Temporal worker thread; a pooler-dropped connection@@ -921,7 +1038,20 @@ class TestRepartitionActivity:# all-or-nothing. Landing the settings but keeping the swap marker holds the schema's imports# forever; clearing the markers without the cooldown re-flags the table on the very next sync;# keeping the operator pin re-applies it on a later reset.- schema = _make_schema(team, {"partition_mode": "md5", "partition_count": 4, "partition_count_override": 4})+ schema = _make_schema(+ team,+ {+ "partition_mode": "md5",+ "partition_count": 4,+ "partition_count_override": 4,+ "partition_measurement": {+ "job_id": "previous-job",+ "phase": "post_load",+ "budget": 500,+ "healthy": True,+ },+ },+ )schema.set_repartition_claim({"token": "live-claim", "job_id": "j1", "claimed_at": _days_ago_iso(0)})schema.set_repartition_pending({"partition_mode": "md5", "partition_count": 8, "partition_keys": ["id"], "trigger_reason": "t"}@@ -947,6 +1077,7 @@ class TestRepartitionActivity:assert schema.repartition_swap is Noneassert schema.repartition_pending is Noneassert schema.repartition_rewrite is None+ assert schema.partition_measurement is Noneassert schema.last_repartition_at is not None@pytest.mark.parametrize(diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/pipeline.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/pipeline.pyindex ebc5f3e5f71c..de2207f1a692 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/pipeline.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/pipeline.py@@ -36,6 +36,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.common.ehandle_reset_or_full_refresh,persist_primary_keys,reset_rows_synced_if_needed,+ resets_table_before_extraction,resolve_primary_keys,setup_row_tracking_with_billing_check,should_check_shutdown,@@ -559,7 +560,15 @@ class PipelineV3(Generic[ResumableData]):if self._attempt <= 1:# Revive a corrupt-`_delta_log` table before extraction so it self-heals in this run# instead of looping forever (an interrupted repartition swap or OOM-crashed merge).- await handle_corrupted_delta_log(self._schema, self._job, self._delta_table_ref, self._logger)+ await handle_corrupted_delta_log(+ self._schema,+ self._job,+ self._delta_table_ref,+ self._logger,+ table_will_be_reset=resets_table_before_extraction(+ self._reset_pipeline, should_resume, self._schema, self._resource.webhook_only+ ),+ )await handle_reset_or_full_refresh(self._reset_pipeline,@@ -573,6 +582,9 @@ class PipelineV3(Generic[ResumableData]):is_fresh_sync = self._delta_table_ref.is_first_sync or self._schema.table is Noneif is_fresh_sync:self._mark_first_ever_sync()+ # No pre-write maintenance runs, so nothing here reads the handle that the corruption+ # check opened. Release it before extraction.+ self._delta_table_ref.pop_cached_table()# Defensive pre-write compaction so a sync that arrived at a fragmented Delta# target cleans up before adding more small files; see DeltaMaintenance.run_scheduled.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.pyindex fb5dcd043592..a33f0256ea7f 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@@ -61,6 +61,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.repcapture_repartition_event,maybe_flag_for_repartition,needs_pre_extraction_detection,+ pre_extraction_measurement_is_redundant,target_partition_bytes,)from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.load.metrics import (@@ -204,6 +205,18 @@ def _target_from_schema(schema: ExternalDataSchema) -> RepartitionTarget:)+def _measurement_is_redundant(schema: ExternalDataSchema, job: ExternalDataJob, logger: FilteringBoundLogger) -> bool:+ """Whether the last recorded measurement makes the on-disk read unnecessary. Never raises.++ Any doubt gives False, and the activity then reads the table as before.+ """+ try:+ return pre_extraction_measurement_is_redundant(schema, job)+ except Exception:+ logger.warning("repartition: could not check the last measurement, measuring on disk", exc_info=True)+ return False++def _maybe_flag_pre_extraction(schema: ExternalDataSchema,job: ExternalDataJob,@@ -356,6 +369,10 @@ def _maybe_repartition_table(inputs: RepartitionActivityInputs, logger: Filterin# renamed during the multi-schema migration keeps its folder pinned to the original path (name# `public.users`, folder `users`), and the pipeline writes there too. Deriving the folder from# `name` alone probes a path that was never written and the repartition skips as `no_delta_table`.+ if pending is None and swap is None and _measurement_is_redundant(schema, job, logger):+ logger.info("repartition: no data reached the table since the last healthy measurement, nothing to do")+ return+resource_name = schema.resolved_s3_folder_name or schema.nametable_ref = DeltaTableRef(resource_name=resource_name, job=job, logger=logger, expect_missing=schema.table_id is Nonediff --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.pyindex 19a3f96475f6..f4c39676bd98 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@@ -28,6 +28,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,+ partition_measurement_holds,repartition_activity_has_work,)from products.warehouse_sources.backend.temporal.data_imports.workflow_activities.repartition_table import (@@ -1150,6 +1151,142 @@ class TestRepartitionActivityHasWork:assert repartition_activity_has_work(schema) is expected+_COMPLETED = ExternalDataJob.Status.COMPLETED+_FAILED = ExternalDataJob.Status.FAILED+_RUNNING = ExternalDataJob.Status.RUNNING+++def _measurement(job_id: str, phase: str = "post_load", healthy: bool = True) -> dict[str, Any]:+ return {"job_id": job_id, "phase": phase, "healthy": healthy}+++class TestPartitionMeasurementHolds:+ @parameterized.expand(+ [+ # (name, measurement, earlier jobs newest first as (id, status, rows synced), holds)+ ("previous_job_measured_after_its_load", _measurement("p"), [("p", _COMPLETED, 500)], True),+ ("no_measurement_recorded", None, [("p", _COMPLETED, 500)], False),+ ("measurement_from_before_this_gate_existed", {"job_id": "p"}, [("p", _COMPLETED, 500)], False),+ ("over_budget_measurement", _measurement("p", healthy=False), [("p", _COMPLETED, 500)], False),+ ("no_earlier_job", _measurement("p"), [], False),+ # A merge that runs out of memory fails its job, and that table must be measured on disk.+ ("previous_job_failed", _measurement("p"), [("p", _FAILED, 500)], False),+ ("previous_job_still_running", _measurement("p"), [("p", _RUNNING, 500)], False),+ (+ "a_failed_job_after_the_measurement",+ _measurement("p"),+ [("n", _FAILED, 0), ("p", _COMPLETED, 500)],+ False,+ ),+ # The previous job wrote rows but recorded no measurement, so the table changed since.+ ("a_later_job_wrote_rows", _measurement("p"), [("n", _COMPLETED, 3), ("p", _COMPLETED, 500)], False),+ (+ "a_later_job_has_an_unknown_row_count",+ _measurement("p"),+ [("n", _COMPLETED, None), ("p", _COMPLETED, 5)],+ False,+ ),+ (+ "later_jobs_wrote_nothing",+ _measurement("p"),+ [("n", _COMPLETED, 0), ("m", _COMPLETED, 0), ("p", _COMPLETED, 500)],+ True,+ ),+ ("measured_before_a_run_with_no_rows", _measurement("p", "pre_extraction"), [("p", _COMPLETED, 0)], True),+ (+ "measured_before_a_run_that_wrote_rows",+ _measurement("p", "pre_extraction"),+ [("p", _COMPLETED, 500)],+ False,+ ),+ (+ "measuring_job_is_out_of_the_window",+ _measurement("p"),+ [("n", _COMPLETED, 0), ("m", _COMPLETED, 0)],+ False,+ ),+ ]+ )+ def test_holds(+ self,+ _name: str,+ measurement: dict[str, Any] | None,+ earlier_jobs: list[tuple[str, str, int | None]],+ holds: bool,+ ) -> None:+ assert partition_measurement_holds(measurement, earlier_jobs) is holds+++class TestPreExtractionMeasurementGate:+ @parameterized.expand(+ [+ # (name, gate result or the error it raises, pending target, the table is read on disk)+ ("current_measurement_skips_the_read", True, None, False),+ ("stale_measurement_reads_the_table", False, None, True),+ ("a_failed_check_reads_the_table", OperationalError("server closed the connection"), None, True),+ ]+ )+ @patch(f"{MODULE}._maybe_flag_pre_extraction", return_value=None)+ @patch(f"{MODULE}.DeltaTableRef")+ @patch(f"{MODULE}.ExternalDataJob")+ @patch(f"{MODULE}.ExternalDataSchema")+ def test_on_disk_read(+ self,+ _name: str,+ gate: bool | Exception,+ pending: dict[str, Any] | None,+ expect_read: bool,+ mock_schema_model: MagicMock,+ _mock_job_model: MagicMock,+ _mock_table_ref: MagicMock,+ mock_measure: MagicMock,+ ) -> None:+ schema = _schema(name="stripe_charge", s3_folder_name=None, pending=pending)+ schema.sync_type = ExternalDataSchema.SyncType.INCREMENTAL+ mock_schema_model.objects.select_related.return_value.get.return_value = schema+ mock_schema_model.SyncType = ExternalDataSchema.SyncType++ with patch(+ f"{MODULE}.pre_extraction_measurement_is_redundant",+ side_effect=gate if isinstance(gate, Exception) else None,+ return_value=gate,+ ):+ _maybe_repartition_table(+ RepartitionActivityInputs(team_id=TEAM_ID, schema_id=SCHEMA_ID, job_id=JOB_ID, source_id=SOURCE_ID),+ MagicMock(),+ )++ assert mock_measure.call_count == int(expect_read)++ @patch(f"{MODULE}.capture_repartition_event")+ @patch(f"{MODULE}.HeartbeaterSync")+ @patch(f"{MODULE}.repartition_table_in_place", new_callable=AsyncMock)+ @patch(f"{MODULE}.DeltaTableRef")+ @patch(f"{MODULE}.ExternalDataJob")+ @patch(f"{MODULE}.ExternalDataSchema")+ def test_a_queued_rewrite_runs_whatever_the_measurement_says(+ self,+ mock_schema_model: MagicMock,+ _mock_job_model: MagicMock,+ _mock_table_ref: MagicMock,+ mock_repartition: AsyncMock,+ _mock_heartbeater: MagicMock,+ _mock_capture: MagicMock,+ ) -> None:+ schema = _schema(name="stripe_charge", s3_folder_name=None)+ mock_schema_model.objects.select_related.return_value.get.return_value = schema+ mock_repartition.return_value = {"outcome": "completed"}++ with patch(f"{MODULE}.pre_extraction_measurement_is_redundant", return_value=True) as gate:+ _maybe_repartition_table(+ RepartitionActivityInputs(team_id=TEAM_ID, schema_id=SCHEMA_ID, job_id=JOB_ID, source_id=SOURCE_ID),+ MagicMock(),+ )++ gate.assert_not_called()+ assert mock_repartition.await_count == 1++class TestMaybeFlagPreExtraction:@parameterized.expand([