:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(data-warehouse): skip the repartition rewrite before a table reset (#113783)
Tom Owers3f2d5f9dd691
diff --git a/products/warehouse_sources/backend/models/external_data_schema.py b/products/warehouse_sources/backend/models/external_data_schema.pyindex ba31e0de9647..406edb0e5ad5 100644--- a/products/warehouse_sources/backend/models/external_data_schema.py+++ b/products/warehouse_sources/backend/models/external_data_schema.py@@ -895,6 +895,10 @@ class ExternalDataSchema( # nosemgrep: semgrep.rules.security.prefer-uuid7-djanreturn pendingreturn None+ @property+ def pending_scheme_for_table_replacement(self) -> dict[str, Any] | None:+ return pending_scheme_for_table_replacement(self.sync_type_config or {})+@propertydef repartition_swap(self) -> dict[str, Any] | None:if self.sync_type_config:@@ -1285,7 +1289,15 @@ class ExternalDataSchema( # nosemgrep: semgrep.rules.security.prefer-uuid7-djanslack = min(slack, self.sync_frequency_interval / 2)return (now or timezone.now()) >= self.next_full_refresh_at - slack- def update_sync_type_config_for_reset_pipeline(self, *, clear_initial_sync_complete: bool = True) -> None:+ def update_sync_type_config_for_reset_pipeline(+ self, *, clear_initial_sync_complete: bool = True, promote_pending_repartition: bool = False+ ) -> None:+ """Clear the settings that describe the table a reset deleted.++ `promote_pending_repartition` is for a caller that loads the table again in the same run. A+ queued repartition target then becomes the scheme of the new table (see+ `promote_pending_repartition_for_replaced_table`), so no rewrite of the new table is necessary.+ """removes = ["reset_pipeline",# Any reset resolves a pending safe-widening marker; the re-created table adopts the new@@ -1331,6 +1343,7 @@ class ExternalDataSchema( # nosemgrep: semgrep.rules.security.prefer-uuid7-djanself.id,self.team_id,removes=removes,+ mutate=promote_pending_repartition_for_replaced_table if promote_pending_repartition else None,extra_model_fields=extra_model_fields,restart_full_refresh_clock=True,)@@ -1829,6 +1842,44 @@ def save_repartition_checkpoint_if_claimed(return claimed+def release_repartition_hold_if_claimed(schema: ExternalDataSchema, *, claim_token: str) -> None:+ """Stop an abandoned rewrite checkpoint from holding the import (see `repartition_holds_import`).++ The checkpoint stays as the record of the temp table that still must be deleted.+ """++ def _write(config: dict[str, Any]) -> None:+ claim = config.get("repartition_claim")+ checkpoint = config.get("repartition_rewrite")+ if claim and claim.get("token") == claim_token and isinstance(checkpoint, dict):+ checkpoint.pop("held_at", None)++ schema.sync_type_config = update_sync_type_config_keys(schema_id=schema.id, team_id=schema.team_id, mutate=_write)+++def clear_repartition_checkpoint_if_claimed(schema: ExternalDataSchema, *, claim_token: str, temp_uri: str) -> bool:+ """Remove the rewrite checkpoint for `temp_uri` while `claim_token` still owns the schema.++ Row-locked for the same reason as `save_repartition_checkpoint_if_claimed`. A checkpoint that a+ newer attempt wrote names a different temp table and stays.+ """+ cleared = False++ def _write(config: dict[str, Any]) -> None:+ nonlocal cleared+ claim = config.get("repartition_claim")+ if not (claim and claim.get("token") == claim_token):+ return+ checkpoint = config.get("repartition_rewrite")+ if not isinstance(checkpoint, dict) or checkpoint.get("temp_uri") != temp_uri:+ return+ config.pop("repartition_rewrite", None)+ cleared = True++ schema.sync_type_config = update_sync_type_config_keys(schema_id=schema.id, team_id=schema.team_id, mutate=_write)+ return cleared++def finalize_repartition_scheme(schema: ExternalDataSchema,*,@@ -1888,6 +1939,43 @@ def finalize_repartition_scheme(return wrote+PARTITION_SCHEME_OVERRIDE_KEYS = (+ "partitioning_keys_override",+ "partition_count_override",+ "partition_size_override",+ "partition_mode_override",+)+++def _stage_partition_scheme(+ config: dict[str, Any],+ *,+ partitioning_keys: list[str] | None,+ partition_count: int | None,+ partition_size: int | None,+ partition_mode: PartitionMode | None,+ partition_format: PartitionFormat | None,+) -> None:+ """Pin a scheme in `config` for the load that writes the table again, and retire the repartition markers."""+ overrides: dict[str, Any] = {+ "partitioning_keys_override": partitioning_keys or None,+ "partition_count_override": partition_count,+ "partition_size_override": partition_size,+ "partition_mode_override": partition_mode,+ }+ for key, value in overrides.items():+ if value is None:+ config.pop(key, None)+ else:+ config[key] = value+ if partition_format is not None:+ config["partition_format"] = partition_format+ # The cooldown stops detection from flagging the old layout again before the sync rewrites it.+ config["last_repartition_at"] = timezone.now().isoformat()+ for key in ("repartition_swap", "repartition_pending", "repartition_rewrite"):+ config.pop(key, None)++def stage_partition_scheme_for_full_refresh(schema: ExternalDataSchema,*,@@ -1906,13 +1994,6 @@ def stage_partition_scheme_for_full_refresh(sync to consume (see `update_sync_type_config_for_reset_pipeline` and `set_partitioning_enabled`).`partition_format` survives the reset on its own."""- overrides: dict[str, Any] = {- "partitioning_keys_override": partitioning_keys or None,- "partition_count_override": partition_count,- "partition_size_override": partition_size,- "partition_mode_override": partition_mode,- }-wrote = Falsedef _write(config: dict[str, Any]) -> None:@@ -1923,23 +2004,65 @@ def stage_partition_scheme_for_full_refresh(returnif config.get("repartition_swap") is not None:return- for key, value in overrides.items():- if value is None:- config.pop(key, None)- else:- config[key] = value- if partition_format is not None:- config["partition_format"] = partition_format- # The cooldown stops detection from flagging the old layout again before the sync rewrites it.- config["last_repartition_at"] = timezone.now().isoformat()- for key in ("repartition_swap", "repartition_pending", "repartition_rewrite"):- config.pop(key, None)+ _stage_partition_scheme(+ config,+ partitioning_keys=partitioning_keys,+ partition_count=partition_count,+ partition_size=partition_size,+ partition_mode=partition_mode,+ partition_format=partition_format,+ )wrote = Trueschema.sync_type_config = update_sync_type_config_keys(schema_id=schema.id, team_id=schema.team_id, mutate=_write)return wrote+def pending_scheme_for_table_replacement(config: dict[str, Any]) -> dict[str, Any] | None:+ """The queued repartition target that a load which replaces the table must write, or None.++ None while a swap is staged, because the temp table can then be the only intact copy and the+ swap recovery owns the scheme. None when an operator pinned a scheme, because that pin is the+ newer decision. A marker with no keys holds bookkeeping only and describes no scheme.+ """+ pending = config.get("repartition_pending")+ if not isinstance(pending, dict) or not pending.get("partition_keys"):+ return None+ if config.get("repartition_swap") is not None:+ return None+ if any(config.get(key) is not None for key in PARTITION_SCHEME_OVERRIDE_KEYS):+ return None+ return pending+++def promote_pending_repartition_for_replaced_table(config: dict[str, Any]) -> None:+ """Make a queued repartition target the scheme of the table that a reset is about to load again.++ The load writes every row again, so it can write the target layout directly. A rewrite of the+ old table before the reset is work that the reset deletes. The target is staged the same way as+ for a full-refresh table (see `stage_partition_scheme_for_full_refresh`).++ A target that cannot be promoted is removed with its checkpoint: it describes a table that no+ longer exists, and post-load detection measures the new table. A staged swap stays, because its+ recovery owns those markers.+ """+ if config.get("repartition_swap") is not None:+ return+ pending = pending_scheme_for_table_replacement(config)+ if pending is None:+ for key in ("repartition_pending", "repartition_rewrite"):+ config.pop(key, None)+ return+ _stage_partition_scheme(+ config,+ partitioning_keys=pending.get("partition_keys"),+ partition_count=pending.get("partition_count"),+ partition_size=pending.get("partition_size"),+ partition_mode=pending.get("partition_mode"),+ partition_format=pending.get("partition_format"),+ )++def mark_schema_running_unless_halted(schema: ExternalDataSchema) -> bool:"""Paint a schema Running at the start of a run, unless a CDC halt marker holds.diff --git a/products/warehouse_sources/backend/temporal/data_imports/README.md b/products/warehouse_sources/backend/temporal/data_imports/README.mdindex 83c3e1047566..e2c02ad1aa94 100644--- a/products/warehouse_sources/backend/temporal/data_imports/README.md+++ b/products/warehouse_sources/backend/temporal/data_imports/README.md@@ -49,6 +49,7 @@ Week into month is the one transition that cannot be computed exactly, because I- **Rewrite.** On the next run, a pre-extraction activity copies the live Delta table into a sibling temp table under the new scheme, recomputing `_ph_partition_key` for every row. It then does a crash-safe swap: delete live → server-side copy temp → verify row count → delete temp. The copy (`pipelines/core/repartition_stream.py`) never opens a dataset over the whole table, because a dataset keeps the parquet footer of every file it has scanned and its memory grows with each file. It plans from the add actions of the loaded version and reads one source file at a time: small files whole, a few ahead on worker threads, large files by row group. It writes through a capped set of open parquet files, one per target partition, and commits them as add actions with stats. One memory-governor slot sizes every buffer, so memory depends on that budget, not on the table's size, its file count or the rows already written. Commits land on source-file boundaries, at least once per checkpoint interval, and each records the source files it completes.- **Resume.** A rewrite cut short (deadline, OOM, worker restart) resumes from the source files its temp commits record, not from a row count. Delta data files never change, so the resume stays valid after the sync commits to live, as long as every copied file is still live, live has no new column, and temp's row count matches the copied files (`resume_blocker`). Files the sync appended are copied with the rest. Otherwise the checkpoint is discarded and the rewrite starts again. A temp written before source files were recorded is rebuilt the same way.- **Full-refresh tables are not rewritten.** Their next sync deletes the table and writes it again, so a rewrite would only copy rows that sync throws away. The activity stages the target as the `*_override` partition keys, which survive that sync's reset, plus `partition_format`, and the sync writes the new layout (`stage_partition_scheme_for_full_refresh`). It also rotates the claim, so a rewrite still running as a zombie cannot swap its copy back over live. It leaves claim-scoped temp tables alone because a wildcard S3 sweep cannot stay fenced against a newer recovery attempt while awaiting storage. The event is `warehouse_repartition_skipped` with `outcome=deferred`. A staged swap still completes first. Temp stays the source of truth until the swap is verified, so a worker death at any point loses wasted compute, never data. An interruption (OOM, worker restart) can leave the `__repartitioned` temp partial, so every step that could destroy live re-validates temp first: the swap opens temp and checks it holds the full row count before deleting live, and a resume re-validates the temp the `ready` marker points at — discarding it and rebuilding fresh from the intact live rather than copying a broken temp over live. A live table whose own log is unreadable is skipped (the import activity's revival handles it), not counted as a repartition failure.+- **A table with a pending reset is not rewritten.** When the import that follows will delete the table and load it again (`reset_pipeline` in `sync_type_config` or in the workflow input), a rewrite only copies rows that the import deletes. The activity and the import read the same decision (`import_replaces_table` and `reset_pipeline_requested` in `pipelines/common/extract.py`). The activity leaves `repartition_pending` in place and deletes the temp table of an earlier rewrite by its exact prefix (`purge_abandoned_rewrite_temp`). The import then writes the queued target directly: the batches of the attempt that deletes the table carry it, and the reset stages it as the `*_override` keys for later attempts (`promote_pending_repartition_for_replaced_table`). The queued target wins over the partition settings that the source computes, and an operator pin wins over the queued target. If the reset does not happen, `repartition_pending` is unchanged and a later run does the rewrite. A webhook schema can keep its table on a reset, so it still gets the rewrite.- **Keeping the data and the settings in step.** The swap re-buckets the data in S3, but the scheme it was re-bucketed under lives in the schema row, and the merge computes each incoming row's `_ph_partition_key` from that row. Between the two the table would be describing a layout it no longer has, and a merge there scopes its predicate to a partition the table cannot contain, matches nothing, and inserts every fetched row instead of upserting it — the whole incremental lookback window duplicated, with the job still reporting Completed. Three things keep that window shut. The `repartition_swap` marker records the resolved scheme before the swap starts, so the scheme survives a worker death. The settings, the markers and the cooldown are saved together in one row-locked write (`finalize_repartition_scheme`), so there is no half-applied state to observe. And while the marker is set the table's layout is mid-change by definition, so the import activity holds this schema's syncs — unconditionally, not behind the hold rollout flag, because the alternative is corruption rather than staleness. A run that finds the marker set and temp already gone recomputes a sample of live's keys under the marker's scheme (`_live_matches_scheme`): matching means the swap finished and only its scheme write was lost, so the run saves the scheme and stops instead of rewriting the table for a layout it already has. A swap whose scheme cannot be saved raises `RepartitionSchemePersistError`, which is never classified as transient noise however transient the database error under it was, and the attempt cap never clears an unresolved swap marker.- **Safety.** Concurrent _syncs_ are excluded (the schedule's `OnlyOne` overlap policy plus the v3 pipeline lock), but concurrent _repartition attempts_ are not: an attempt Temporal heartbeat-times-out keeps running as a zombie (heartbeat failures are swallowed) while its retry starts, and S3 has no locking. The schema row's `repartition_claim` is the fence — each attempt mints a claim token, temp tables are scoped to it (`__repartitioned_<token>`), and the claim is re-checked before every batch write and every destructive step (temp sweep, swap marker, live delete). A superseded attempt raises `RepartitionSupersededError` and stands down silently; orphaned temp variants from superseded or crashed attempts are swept by name prefix before each fresh rebuild. A repartition failure never fails the sync — it's swallowed, retried on a later run, and capped at `MAX_REPARTITION_ATTEMPTS` (3) consecutive failures before it gives up and alerts. Cancellations, superseded attempts, transient infra errors (DB pooler drops, S3 rate limits), and budget-exceeded attempts that advanced the rewrite checkpoint don't count against that cap — a table too large to rewrite in one activity budget converges across runs via the checkpoint, and only an attempt that made no forward progress is charged. A worker that shuts down stops the rewrite at its next commit, which is at most one source file later, or `STOP_GRACE_SECONDS` later when one large source file is still open. The activity saves the checkpoint, refunds the attempt and raises `WorkerShuttingDownError`, so Temporal retries on another worker and the retry copies only the source files that are left (`reason=worker_shutdown`). The activity gets `MAX_REPARTITION_ACTIVITY_ATTEMPTS` Temporal attempts for that reason: each stop uses one, and a sync that runs out of them merges on the old layout, which can invalidate the checkpoint. A panic from the native delta stack (pyo3 raises those as `BaseException`, so they do not stop at an `except Exception`) is recorded as a failure too, rather than being left to fail the activity and spend the remaining retries re-reading a log that panics in the same place. An attempt killed outright (a SIGKILLed worker runs no `except` and no `finally`) records nothing at all, so the activity's own retries judge it on the checkpoint instead: a retry re-runs the rewrite only while the attempt it retries left the checkpoint further along than it found it, because repeating a rewrite that died in place holds the sync for another activity budget and the next sync resumes from the same checkpoint anyway. The stand-down reports `reason=attempt_killed_without_progress`. The cap applies that same test across syncs, since a killed attempt is the one shape it cannot read an outcome for: a spent count is reset when the last attempt still moved the checkpoint on, so a table converging one worker death per sync keeps its progress, and the give-up fires only once the checkpoint stops moving. The terminal give-up carries how far the rewrite got.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.pyindex 124eead0663c..ee5d900cdbfa 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@@ -1106,6 +1106,7 @@ class ExternalDataJobWorkflow(PostHogWorkflow):schema_id=str(inputs.external_data_schema_id),job_id=str(job_id),source_id=str(inputs.external_data_source_id),+ reset_pipeline=inputs.reset_pipeline,),start_to_close_timeout=dt.timedelta(hours=6),heartbeat_timeout=dt.timedelta(minutes=5),diff --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 27e97d30404e..66053c11de9a 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,53 @@ async def setup_row_tracking_with_billing_check()+def reset_pipeline_requested(+ schema: "ExternalDataSchema",+ *,+ workflow_reset_pipeline: bool | None,+ scheduled_full_refresh: bool,+ job_created_at: datetime,+) -> bool:+ """Whether this run was asked to load the table again from the start.++ The import and the pre-extraction repartition both read this answer. One function keeps them+ from a disagreement, in which the repartition rewrites a table that the import then deletes.+ """+ if workflow_reset_pipeline is not None:+ return workflow_reset_pipeline+ if schema.sync_type_config.get("reset_pipeline", False) is True:+ return True+ # Each attempt loads the schema again. Checked at the job's creation, it stays due until the wipe moves the due+ # time past that point, so a retry after the wipe carries on instead of wiping again. The current time is not+ # safe: with a 1-day interval and a set time, a wipe more than an hour early leaves that day's slot due.+ return scheduled_full_refresh and schema.scheduled_full_refresh_due(now=job_created_at)+++def import_replaces_table(+ schema: "ExternalDataSchema", *, workflow_reset_pipeline: bool | None, job_created_at: datetime+) -> bool:+ """Whether the import that follows the repartition step deletes the table and loads it again.++ Answers before the source is built, so it cannot see three things that the import sees later: a+ resumed run, a webhook-only resource, and a reset that the source asks for. A resumed run is the+ second attempt or later, and the repartition step runs before the first. A webhook schema counts+ as webhook-only here, so the answer for it is always False. In each unseen case the answer is+ False and the repartition step does what it did before.++ A scheduled full refresh is not an input, because the workflow does not run the repartition step+ for it.+ """+ reset_pipeline = reset_pipeline_requested(+ schema,+ workflow_reset_pipeline=workflow_reset_pipeline,+ scheduled_full_refresh=False,+ job_created_at=job_created_at,+ )+ return resets_table_before_extraction(+ reset_pipeline, should_resume=False, schema=schema, webhook_only=schema.is_webhook+ )++def resets_table_before_extraction(reset_pipeline: bool, should_resume: bool, schema: "ExternalDataSchema", webhook_only: bool = False) -> bool:@@ -534,7 +581,9 @@ async def handle_reset_or_full_refresh(elif reset_pipeline and not should_resume:await logger.adebug("Deleting existing table due to reset_pipeline being set")await delta_table_ref.reset_table()- await database_sync_to_async_pool(schema.update_sync_type_config_for_reset_pipeline)()+ await database_sync_to_async_pool(schema.update_sync_type_config_for_reset_pipeline)(+ promote_pending_repartition=True+ )elif schema.sync_type == ExternalDataSchema.SyncType.FULL_REFRESH and not should_resume:# Avoid schema mismatches from existing data about to be overwrittenawait logger.adebug("Deleting existing table due to sync being full refresh")@@ -542,7 +591,7 @@ async def handle_reset_or_full_refresh(# Keep the initial_sync_complete latch: this branch runs on every scheduled full-refresh# sync, and a run that extracts zero rows never reaches post-load to re-set it.await database_sync_to_async_pool(schema.update_sync_type_config_for_reset_pipeline)(- clear_initial_sync_complete=False+ clear_initial_sync_complete=False, promote_pending_repartition=True)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.pyindex 02ad3864c78f..a6fd1e2eca3c 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@@ -442,6 +442,64 @@ async def _purge_stale_temp_tables(s3: Any, live_uri: str) -> None:await s3._rm([f"s3://{f.lstrip('/')}" for f in files])+# A temp table sits beside its live table: the live URI, the suffix, then at most the 8 characters of+# a claim token (see `_temp_uri_for`). No path separator can follow, so a match is never the live+# table, a path inside it, or a path above it.+_TEMP_URI_CLAIM_PART = re.compile(r"(_[0-9a-f]{1,8})?")+++def is_temp_uri_of(live_uri: str, temp_uri: str) -> bool:+ """Whether `temp_uri` is a repartition temp table of the table at `live_uri`, and nothing else."""+ live = live_uri.rstrip("/")+ prefix = f"{live}{TEMP_URI_SUFFIX}"+ # The live URI must name a table directory below a bucket, not a bucket or an empty path.+ if "/" not in live.rpartition("://")[2].strip("/"):+ return False+ if not temp_uri.startswith(prefix):+ return False+ return _TEMP_URI_CLAIM_PART.fullmatch(temp_uri[len(prefix) :]) is not None+++async def purge_abandoned_rewrite_temp(+ table_ref: DeltaTableRef,+ schema: ExternalDataSchema,+ temp_uri: str | None,+ logger: FilteringBoundLogger,+ *,+ claim_token: str | None,+) -> bool:+ """Delete the temp table of a rewrite that will not continue. Returns whether it deleted.++ Deletes one exact prefix, not every temp variant of the table. A wildcard sweep can remove the+ temp table of a newer attempt, and the database claim cannot fence a delete that is in progress.+ A newer attempt builds under its own claim token, so it never writes to this prefix again.++ The caller clears the checkpoint that names `temp_uri` after this returns, not before. If the+ delete fails, the checkpoint still records the temp table, and a later run deletes it.+ """+ if not temp_uri:+ return False+ live_uri = await table_ref.get_table_uri()+ if not is_temp_uri_of(live_uri, temp_uri):+ await logger.awarning(+ f"repartition: refusing to delete a path that is not a temp table of this table schema_id={schema.id}",+ schema_id=str(schema.id),+ )+ return False+ await _ensure_claim(schema, claim_token)+ swap = schema.repartition_swap+ if swap is not None and swap.get("temp_uri") == temp_uri:+ # A staged swap makes temp the only intact copy.+ return False+ async with aget_s3_client(fresh_instance=True) as s3:+ await _purge_s3_prefix(s3, temp_uri)+ await logger.ainfo(+ f"repartition: deleted the temp table of an abandoned rewrite schema_id={schema.id}",+ schema_id=str(schema.id),+ )+ return True++def _temp_uri_for(live_uri: str, claim_token: str | None) -> str:suffix = f"{TEMP_URI_SUFFIX}_{claim_token[:8]}" if claim_token else TEMP_URI_SUFFIXreturn f"{live_uri}{suffix}"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.pyindex c838b9353e54..d5513ef1cf50 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@@ -2,12 +2,14 @@ import osimport globimport jsonimport math+import shutilimport asyncioimport decimalimport datetimeimport itertools+from pathlib import Pathfrom types import SimpleNamespace-from typing import cast+from typing import TYPE_CHECKING, castimport pytestfrom unittest.mock import AsyncMock, Mock, patch@@ -37,7 +39,9 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.repRepartitionTarget,RepartitionTooLargeForBudgetError,_rewrite_into_temp,+ is_temp_uri_of,measure_partition_bytes,+ purge_abandoned_rewrite_temp,repartition_table_in_place,select_coarsen_target,select_repartition_target,@@ -57,6 +61,9 @@ from products.warehouse_sources.backend.temporal.data_imports.workload_report imworkload_reporting,)+if TYPE_CHECKING:+ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.table import DeltaTableRef+logger = structlog.get_logger(__name__)@@ -1994,6 +2001,136 @@ class TestPurgeStaleTempTables:)+class _LocalS3:+ """The object-store calls the purge uses, served from a local directory that stands in for all buckets."""++ def __init__(self, root: Path) -> None:+ self._root = root++ def _local(self, uri: str) -> Path:+ return self._root / uri.split("://", 1)[-1].strip("/")++ def invalidate_cache(self) -> None:+ pass++ async def _exists(self, uri: str) -> bool:+ return self._local(uri).exists()++ async def _find(self, uri: str) -> list[str]:+ base = self._local(uri)+ return sorted(str(f.relative_to(self._root)) for f in base.rglob("*") if f.is_file())++ async def _rm(self, target: str | list[str], recursive: bool = False) -> None:+ for uri in [target] if isinstance(target, str) else target:+ local = self._local(uri)+ if local.is_dir():+ shutil.rmtree(local)+ elif local.exists():+ local.unlink()+++LIVE_URI = "s3://bucket/team/source/contacts"+OWN_TEMP_URI = f"{LIVE_URI}__repartitioned_1a2b3c4d"+++class TestPurgeAbandonedRewriteTemp:+ @pytest.mark.parametrize(+ "temp_uri, expected",+ [+ (OWN_TEMP_URI, True),+ (f"{LIVE_URI}__repartitioned", True),+ (LIVE_URI, False),+ (f"{LIVE_URI}/", False),+ (f"{LIVE_URI}/_delta_log", False),+ (f"{LIVE_URI}__repartitioned_1a2b3c4d/../contacts", False),+ (f"{LIVE_URI}__repartitioned_1a2b3c4d/part-0.parquet", False),+ (f"{LIVE_URI}__repartitioned_1a2b3c4d5", False),+ (f"{LIVE_URI}__repartitioned_other", False),+ (f"{LIVE_URI}_v2__repartitioned_1a2b3c4d", False),+ ("s3://bucket/team/source/accounts__repartitioned_1a2b3c4d", False),+ ("s3://bucket/team/source", False),+ ("s3://bucket/team", False),+ ("s3://other/team/source/contacts__repartitioned_1a2b3c4d", False),+ ("", False),+ ],+ )+ def test_only_a_temp_table_of_the_same_table_qualifies(self, temp_uri: str, expected: bool) -> None:+ assert is_temp_uri_of(LIVE_URI, temp_uri) is expected++ @pytest.mark.parametrize("live_uri", ["s3://bucket", "s3://bucket/", "s3://", ""])+ def test_a_live_uri_that_is_not_a_table_directory_has_no_temp_tables(self, live_uri: str) -> None:+ assert is_temp_uri_of(live_uri, f"{live_uri}__repartitioned_1a2b3c4d") is False++ def _write_tree(self, root: Path) -> dict[str, Path]:+ files = {+ "live": root / "bucket/team/source/contacts/part-0.parquet",+ "live_log": root / "bucket/team/source/contacts/_delta_log/0.json",+ "own_temp": root / "bucket/team/source/contacts__repartitioned_1a2b3c4d/k=1/part-0.parquet",+ "own_temp_log": root / "bucket/team/source/contacts__repartitioned_1a2b3c4d/_delta_log/0.json",+ "newer_temp": root / "bucket/team/source/contacts__repartitioned_5e6f7a8b/part-0.parquet",+ "sibling_table": root / "bucket/team/source/contacts_v2/part-0.parquet",+ "sibling_temp": root / "bucket/team/source/accounts__repartitioned_1a2b3c4d/part-0.parquet",+ }+ for path in files.values():+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_bytes(b"x")+ return files++ def _purge(self, root: Path, temp_uri: str, *, swap: dict | None = None) -> bool:+ table_ref = _make_table_ref(get_table_uri=AsyncMock(return_value=LIVE_URI))+ schema = _schema(id="schema-1", repartition_swap=swap)+ with patch.object(repartition_module, "aget_s3_client", return_value=_FakeS3CM(_LocalS3(root))):+ return asyncio.run(+ purge_abandoned_rewrite_temp(+ cast("DeltaTableRef", table_ref), schema, temp_uri, logger, claim_token=None+ )+ )++ def test_deletes_the_named_temp_table_and_nothing_else(self, tmp_path: Path) -> None:+ files = self._write_tree(tmp_path)++ assert self._purge(tmp_path, OWN_TEMP_URI) is True++ remaining = {name for name, path in files.items() if path.exists()}+ assert remaining == {"live", "live_log", "newer_temp", "sibling_table", "sibling_temp"}++ @pytest.mark.parametrize(+ "temp_uri, swap",+ [+ (LIVE_URI, None),+ ("s3://bucket/team/source", None),+ ("s3://bucket/team/source/accounts__repartitioned_1a2b3c4d", None),+ (f"{LIVE_URI}__repartitioned_1a2b3c4d/../contacts", None),+ (OWN_TEMP_URI, {"state": "ready", "temp_uri": OWN_TEMP_URI}),+ ],+ ids=["live_table", "parent_directory", "temp_of_another_table", "path_traversal", "temp_of_a_staged_swap"],+ )+ def test_refuses_a_path_it_must_not_delete(self, tmp_path: Path, temp_uri: str, swap: dict | None) -> None:+ files = self._write_tree(tmp_path)++ assert self._purge(tmp_path, temp_uri, swap=swap) is False++ assert all(path.exists() for path in files.values())++ def test_a_lost_claim_deletes_nothing(self, tmp_path: Path) -> None:+ files = self._write_tree(tmp_path)+ table_ref = _make_table_ref(get_table_uri=AsyncMock(return_value=LIVE_URI))+ schema = _schema(id="schema-1", repartition_swap=None)++ with (+ patch.object(repartition_module, "aget_s3_client", return_value=_FakeS3CM(_LocalS3(tmp_path))),+ patch.object(repartition_module, "_current_claim_token", return_value="newer-token"),+ pytest.raises(RepartitionSupersededError),+ ):+ asyncio.run(+ purge_abandoned_rewrite_temp(+ cast("DeltaTableRef", table_ref), schema, OWN_TEMP_URI, logger, claim_token="older-token"+ )+ )++ assert all(path.exists() for path in files.values())++class TestSwapTempIntoLiveGuard:def test_refuses_incomplete_temp_without_deleting_live(self):# The core safety invariant: a temp that doesn't hold every expected row must never trigger thediff --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 864ed3b4b095..29d98aab9059 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@@ -124,6 +124,10 @@ def should_coalesce_tables(*, resume_manager: ResumableSourceManager[Any] | Nonereturn resume_manager is None and not is_webhook+class StagedSchemeWithoutResetError(Exception):+ """The attempt took the partition scheme of a new table, and then did not delete the old table."""++class PipelineV3(Generic[ResumableData]):_resource: SourceResponse_resource_name: str@@ -157,6 +161,7 @@ class PipelineV3(Generic[ResumableData]):_continues_incremental_handoff: bool = False_resumed_incremental_run_uuid: str | None = None_sent_resumed_run_finalization: bool = False+ _writes_staged_repartition_scheme: bool = Falsedef __init__(self,@@ -217,26 +222,6 @@ class PipelineV3(Generic[ResumableData]):elif self._schema.is_append:sync_type = "append"- # Operator-pinned overrides (admin repartition action) win over the auto-detected- # persisted value and the source-computed value. See setup_partitioning in the v2- # pipeline for the same precedence and rationale.- partition_count = (- self._schema.partition_count_override or self._schema.partition_count or self._resource.partition_count- )- partition_size = (- self._schema.partition_size_override or self._schema.partition_size or self._resource.partition_size- )- partition_keys = (- self._schema.partitioning_keys_override- or self._schema.partitioning_keys- or self._resource.partition_keys- or self._resource.primary_keys- )- partition_format = self._schema.partition_format or self._resource.partition_format- partition_mode = (- self._schema.partition_mode_override or self._schema.partition_mode or self._resource.partition_mode- )-# Determine if this is the first-ever sync (no DWH table exists yet)is_first_ever_sync = self._schema.table is None@@ -260,6 +245,47 @@ class PipelineV3(Generic[ResumableData]):self._handoff_checkpoint = IncrementalHandoffCheckpoint(resumed_incremental_value)self._batch_range_reader = IncrementalBatchRangeReader(self._schema)+ # A queued repartition target is the scheme of the table when this attempt deletes the table+ # and loads it again. The reset then stages that target (see `handle_reset_or_full_refresh`),+ # so no rewrite of the old table is necessary.+ staged_scheme = (+ self._schema.pending_scheme_for_table_replacement+ if attempt <= 1+ and resets_table_before_extraction(reset_pipeline, is_resume, self._schema, self._resource.webhook_only)+ else None+ )+ self._writes_staged_repartition_scheme = staged_scheme is not None+ if staged_scheme is not None:+ partition_count = staged_scheme.get("partition_count") or self._resource.partition_count+ partition_size = staged_scheme.get("partition_size") or self._resource.partition_size+ partition_keys = staged_scheme["partition_keys"]+ partition_format = (+ staged_scheme.get("partition_format")+ or self._schema.partition_format+ or self._resource.partition_format+ )+ partition_mode = staged_scheme.get("partition_mode") or self._resource.partition_mode+ else:+ # Operator-pinned overrides (admin repartition action) win over the auto-detected+ # persisted value and the source-computed value. See setup_partitioning in the v2+ # pipeline for the same precedence and rationale.+ partition_count = (+ self._schema.partition_count_override or self._schema.partition_count or self._resource.partition_count+ )+ partition_size = (+ self._schema.partition_size_override or self._schema.partition_size or self._resource.partition_size+ )+ partition_keys = (+ self._schema.partitioning_keys_override+ or self._schema.partitioning_keys+ or self._resource.partition_keys+ or self._resource.primary_keys+ )+ partition_format = self._schema.partition_format or self._resource.partition_format+ partition_mode = (+ self._schema.partition_mode_override or self._schema.partition_mode or self._resource.partition_mode+ )+# Resolved in `_get_models`, not here: the pipeline is built inside an async activity,# so the query that tells the warehouse from an external destination cannot run here.self._external_destination_ids: list[str] = list(models.external_destination_ids)@@ -566,6 +592,16 @@ class PipelineV3(Generic[ResumableData]):# On retry (attempt > 1) skip reset_table() - the consumer-side batch-0# overwrite handles it. Wiping the delta table mid-retry while the consumer# is loading the previous attempt's batches causes data loss.+ table_will_be_reset = self._attempt <= 1 and resets_table_before_extraction(+ self._reset_pipeline, should_resume, self._schema, self._resource.webhook_only+ )+ if self._writes_staged_repartition_scheme and not table_will_be_reset:+ # The batches of this attempt carry a scheme that is only correct for a new table.+ # The next attempt reads the scheme of the table that stays.+ raise StagedSchemeWithoutResetError(+ "The run was built to replace the table, but the table stays. Retrying."+ )+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).@@ -574,9 +610,7 @@ class PipelineV3(Generic[ResumableData]):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- ),+ table_will_be_reset=table_will_be_reset,)await handle_reset_or_full_refresh(diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/test_pipeline.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/test_pipeline.pyindex e3466b057431..514d50243d3e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/test_pipeline.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/test_pipeline.py@@ -9,11 +9,21 @@ import pytestfrom unittest.mock import AsyncMock, MagicMock, patchimport pyarrow as pa+import deltalakefrom asgiref.sync import async_to_syncfrom posthog.temporal.common.shutdown import WorkerShuttingDownError+from products.warehouse_sources.backend.models import external_data_schema as schema_models+from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema+from products.warehouse_sources.backend.temporal.data_imports.pipelines.common.extract import (+ handle_reset_or_full_refresh,+)from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.batcher import Batcher+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.consts import PARTITION_KEY+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.partitioning import (+ append_partition_key_to_table,+)from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.handoff_checkpoint import (IncrementalBatchRangeReader,IncrementalHandoffCheckpoint,@@ -24,6 +34,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline)from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.pipeline import (PipelineV3,+ StagedSchemeWithoutResetError,should_coalesce_tables,)from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.producer import (@@ -315,6 +326,255 @@ class TestCDCSourceWiring:assert mock_producer_cls.call_args.kwargs["cdc_write_mode"] is None+_PENDING_SCHEME = {+ "partition_keys": ["id"],+ "partition_mode": "md5",+ "partition_count": 7,+ "partition_size": None,+ "partition_format": None,+ "trigger_reason": "proactive_threshold",+ "attempts": 1,+}+# What the table has on disk before the reset, and what the source proposes for a new table.+_OLD_COUNT = 3+_SOURCE_COUNT = 5+++def _in_memory_config_update(schema: ExternalDataSchema):+ def _update(schema_id, team_id, *, updates=None, removes=None, mutate=None, **_kwargs):+ config = dict(schema.sync_type_config)+ config.update(updates or {})+ for key in removes or []:+ config.pop(key, None)+ if mutate is not None:+ mutate(config)+ return config++ return _update+++class TestResetLoadWritesTheQueuedScheme:+ def _schema(self, sync_type: str = "incremental", **config: Any) -> ExternalDataSchema:+ return ExternalDataSchema(+ name="users",+ team_id=1,+ sync_type=sync_type,+ sync_type_config={+ "partitioning_enabled": True,+ "partition_mode": "md5",+ "partition_count": _OLD_COUNT,+ "partitioning_keys": ["id"],+ **config,+ },+ )++ def _producer_kwargs(+ self,+ schema: ExternalDataSchema,+ *,+ reset_pipeline: bool,+ attempt: int = 1,+ can_resume: bool = False,+ webhook_only: bool = False,+ ) -> dict[str, Any]:+ resource = MagicMock(+ name="users",+ primary_keys=["id"],+ partition_count=_SOURCE_COUNT,+ partition_size=None,+ partition_keys=["id"],+ partition_format=None,+ partition_mode="md5",+ cdc_write_mode=None,+ lanes=None,+ webhook_only=webhook_only,+ )+ manager = MagicMock(can_resume=MagicMock(return_value=True)) if can_resume else None+ with (+ patch(f"{_PIPELINE}.current_import_attempt", return_value=attempt),+ patch(f"{_PIPELINE}.current_workflow_id", return_value="wf-1"),+ patch(f"{_PIPELINE}.current_workflow_run_id", return_value="wfrun-abc"),+ patch(f"{_PIPELINE}.S3BatchWriter"),+ patch(f"{_PIPELINE}.PostgresProducer") as mock_producer_cls,+ patch(f"{_PIPELINE}.DeltaTableRef"),+ patch(f"{_PIPELINE}.resolve_resume_manager", return_value=manager),+ ):+ PipelineV3(+ source_response=resource,+ logger=_make_logger(),+ job_id="job-1",+ reset_pipeline=reset_pipeline,+ shutdown_monitor=MagicMock(),+ resumable_source_manager=manager,+ models=ImportJobModels(+ job=MagicMock(team_id=1, workflow_run_id="wfrun-abc", billable=False, id="job-1"),+ schema=schema,+ source=MagicMock(source_type="Postgres"),+ table=None,+ ),+ )+ return dict(mock_producer_cls.call_args.kwargs)++ @pytest.mark.parametrize(+ "sync_type, config, run, expected_count",+ [+ ("incremental", {"repartition_pending": _PENDING_SCHEME}, {"reset_pipeline": True}, 7),+ ("full_refresh", {"repartition_pending": _PENDING_SCHEME}, {"reset_pipeline": False}, 7),+ ("incremental", {"repartition_pending": _PENDING_SCHEME}, {"reset_pipeline": False}, _OLD_COUNT),+ (+ "incremental",+ {"repartition_pending": _PENDING_SCHEME},+ {"reset_pipeline": True, "attempt": 2},+ _OLD_COUNT,+ ),+ (+ "incremental",+ {"repartition_pending": _PENDING_SCHEME},+ {"reset_pipeline": True, "can_resume": True},+ _OLD_COUNT,+ ),+ (+ "incremental",+ {"repartition_pending": _PENDING_SCHEME},+ {"reset_pipeline": True, "webhook_only": True},+ _OLD_COUNT,+ ),+ (+ "incremental",+ {"repartition_pending": _PENDING_SCHEME, "repartition_swap": {"state": "ready"}},+ {"reset_pipeline": True},+ _OLD_COUNT,+ ),+ (+ "incremental",+ {"repartition_pending": _PENDING_SCHEME, "partition_count_override": 11},+ {"reset_pipeline": True},+ 11,+ ),+ ("incremental", {"repartition_pending": {"attempts": 2}}, {"reset_pipeline": True}, _OLD_COUNT),+ ],+ ids=[+ "reset_takes_the_queued_scheme",+ "full_refresh_takes_the_queued_scheme",+ "no_reset_keeps_the_scheme_on_disk",+ "retry_does_not_reset_so_keeps_the_scheme_on_disk",+ "resumed_run_keeps_the_scheme_on_disk",+ "webhook_only_reset_keeps_the_scheme_on_disk",+ "staged_swap_owns_the_scheme",+ "operator_pin_wins",+ "bookkeeping_only_marker_has_no_scheme",+ ],+ )+ def test_batches_carry_the_queued_scheme_only_when_the_table_is_replaced(+ self, sync_type: str, config: dict[str, Any], run: dict[str, Any], expected_count: int+ ) -> None:+ kwargs = self._producer_kwargs(self._schema(sync_type, **config), **run)++ assert kwargs["partition_count"] == expected_count+ assert kwargs["partition_mode"] == "md5"+ assert kwargs["partition_keys"] == ["id"]++ @pytest.mark.asyncio+ async def test_the_reset_load_writes_the_queued_scheme_and_later_attempts_agree(self, tmp_path) -> None:+ schema = self._schema(reset_pipeline=True, repartition_pending=_PENDING_SCHEME, repartition_rewrite={"a": 1})+ first_attempt = self._producer_kwargs(schema, reset_pipeline=True)++ with (+ patch.object(schema_models, "update_sync_type_config_keys", _in_memory_config_update(schema)),+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.common.extract.database_sync_to_async_pool",+ _passthrough_pool,+ ),+ ):+ await handle_reset_or_full_refresh(True, False, schema, MagicMock(reset_table=AsyncMock()), _make_logger())++ # The reset consumed the request and the queued target, so no rewrite of the new table follows.+ assert "reset_pipeline" not in schema.sync_type_config+ assert schema.repartition_pending is None+ assert schema.repartition_rewrite is None+ assert schema.last_repartition_at is not None++ # An attempt after the reset does not delete the table again. It must use the same scheme.+ later_attempt = self._producer_kwargs(schema, reset_pipeline=False, attempt=2)+ for key in ("partition_count", "partition_mode", "partition_keys", "partition_format", "partition_size"):+ assert later_attempt[key] == first_attempt[key], key++ rows = pa.table({"id": pa.array(range(500), type=pa.int64())})+ partitioned = append_partition_key_to_table(+ table=rows,+ partition_count=first_attempt["partition_count"],+ partition_size=first_attempt["partition_size"],+ partition_keys=first_attempt["partition_keys"],+ partition_mode=first_attempt["partition_mode"],+ partition_format=first_attempt["partition_format"],+ logger=_make_logger(),+ )+ assert partitioned is not None+ deltalake.write_deltalake(str(tmp_path / "users"), partitioned.table, partition_by=PARTITION_KEY)++ written = deltalake.DeltaTable(str(tmp_path / "users")).to_pyarrow_table()+ assert set(written.column(PARTITION_KEY).to_pylist()) == {str(bucket) for bucket in range(7)}++ @pytest.mark.parametrize(+ "config, expected",+ [+ (+ {"repartition_pending": _PENDING_SCHEME, "repartition_rewrite": {"temp_uri": "x"}},+ {"partition_count_override": 7, "partition_mode_override": "md5", "partitioning_keys_override": ["id"]},+ ),+ (+ {"repartition_pending": _PENDING_SCHEME, "partition_count_override": 11},+ {"partition_count_override": 11},+ ),+ ({"repartition_pending": {"attempts": 2}, "repartition_rewrite": {"temp_uri": "x"}}, {}),+ ({}, {}),+ ],+ ids=[+ "queued_target_becomes_the_scheme",+ "operator_pin_stays",+ "bookkeeping_only_marker_goes",+ "nothing_queued",+ ],+ )+ def test_a_reset_retires_the_queued_target(self, config: dict[str, Any], expected: dict[str, Any]) -> None:+ schema_models.promote_pending_repartition_for_replaced_table(config)++ overrides = {key: config[key] for key in schema_models.PARTITION_SCHEME_OVERRIDE_KEYS if key in config}+ assert overrides == expected+ assert "repartition_pending" not in config+ assert "repartition_rewrite" not in config++ def test_a_reset_leaves_a_staged_swap_and_its_markers(self) -> None:+ config = {"repartition_pending": _PENDING_SCHEME, "repartition_swap": {"state": "ready", "temp_uri": "x"}}+ before = json.loads(json.dumps(config))++ schema_models.promote_pending_repartition_for_replaced_table(config)++ assert config == before++ @pytest.mark.asyncio+ async def test_an_attempt_built_for_a_new_table_stops_when_the_table_stays(self) -> None:+ pipeline = _make_pipeline()+ pipeline._writes_staged_repartition_scheme = True+ pipeline._reset_pipeline = False+ pipeline._schema.sync_type = "incremental"+ pipeline._resource.webhook_only = False++ with (+ patch(f"{_PIPELINE}.reset_rows_synced_if_needed", new_callable=AsyncMock),+ patch(f"{_PIPELINE}.validate_incremental_sync"),+ patch(f"{_PIPELINE}.persist_primary_keys", new_callable=AsyncMock),+ patch(f"{_PIPELINE}.setup_row_tracking_with_billing_check", new_callable=AsyncMock),+ patch(f"{_PIPELINE}.handle_reset_or_full_refresh", new_callable=AsyncMock) as mock_reset,+ patch(f"{_PIPELINE}.activity") as mock_activity,+ ):+ mock_activity.in_activity.return_value = False+ with pytest.raises(StagedSchemeWithoutResetError):+ await pipeline.run()++ mock_reset.assert_not_called()++class TestCDCSeqProvenanceSurvivesStaging:def test_the_stamp_survives_every_extract_side_hop(self) -> None:# The loader gates all position resolution on the provenance stamp. If any hop between thediff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/import_data_sync.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/import_data_sync.pyindex aaaa15e2a807..2f3ab5bfbfea 100644--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/import_data_sync.py+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/import_data_sync.py@@ -58,6 +58,7 @@ from products.warehouse_sources.backend.temporal.data_imports.metrics import (from products.warehouse_sources.backend.temporal.data_imports.pipelines.common.extract import (handle_non_retryable_error,report_heartbeat_timeout,+ reset_pipeline_requested,trim_source_job_inputs,)from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrow_utils import (@@ -160,14 +161,12 @@ class ImportDataActivityInputs:def _resolve_reset_pipeline(inputs: ImportDataActivityInputs, schema: ExternalDataSchema, *, job_created_at: dt.datetime) -> bool:- if inputs.reset_pipeline is not None:- return inputs.reset_pipeline- if schema.sync_type_config.get("reset_pipeline", False) is True:- return True- # Each attempt loads the schema again. Checked at the job's creation, it stays due until the wipe moves the due- # time past that point, so a retry after the wipe carries on instead of wiping again. The current time is not- # safe: with a 1-day interval and a set time, a wipe more than an hour early leaves that day's slot due.- return inputs.scheduled_full_refresh and schema.scheduled_full_refresh_due(now=job_created_at)+ return reset_pipeline_requested(+ schema,+ workflow_reset_pipeline=inputs.reset_pipeline,+ scheduled_full_refresh=inputs.scheduled_full_refresh,+ job_created_at=job_created_at,+ )@database_sync_to_async_pooldiff --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 da597ec2db1d..45203e93e863 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@@ -37,7 +37,12 @@ from posthog.temporal.common.shutdown import ShutdownMonitor, WorkerShuttingDownfrom posthog.temporal.common.utils import retry_on_db_connection_dropfrom products.warehouse_sources.backend.models.external_data_job import ExternalDataJob-from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema+from products.warehouse_sources.backend.models.external_data_schema import (+ ExternalDataSchema,+ clear_repartition_checkpoint_if_claimed,+ release_repartition_hold_if_claimed,+)+from products.warehouse_sources.backend.temporal.data_imports.pipelines.common.extract import import_replaces_tablefrom products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.errors import (is_transient_maintenance_error,is_transient_object_store_error,@@ -53,6 +58,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.repRepartitionTooLargeForBudgetError,RepartitionUnpartitionableError,defer_repartition_to_full_refresh,+ purge_abandoned_rewrite_temp,repartition_table_in_place,)from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.repartition_controller import (@@ -80,6 +86,9 @@ class RepartitionActivityInputs:schema_id: strjob_id: strsource_id: str+ # The reset that the workflow input asks for. It never reaches `sync_type_config`, and the import+ # reads it too. Defaults None so the payload of a workflow that predates the field still loads.+ reset_pipeline: bool | None = Nonedef _is_cancellation(error: BaseException) -> bool:@@ -378,7 +387,14 @@ def _maybe_repartition_table(inputs: RepartitionActivityInputs, logger: Filterinresource_name=resource_name, job=job, logger=logger, expect_missing=schema.table_id is None)+ replaces_table = swap is None and _import_replaces_table(schema, job, inputs, logger)+if pending is None and swap is None:+ if replaces_table and not schema.initial_sync_complete:+ # A reset that an earlier run started left a part of the table on disk. A target sized+ # from that part is too small for the full table, and the import deletes the part.+ logger.info("repartition: the import replaces a table that is not fully loaded, not measuring it")+ return# Nothing was queued by a prior run's post-load detection. Measure now and self-flag if it's# over budget — the only path that can rescue a table which OOMs its merge every run (and so# never reaches post-load detection).@@ -387,13 +403,15 @@ def _maybe_repartition_table(inputs: RepartitionActivityInputs, logger: Filterinlogger.debug("repartition: pre-extraction measurement found no repartition needed")return- if swap is None and schema.sync_type == ExternalDataSchema.SyncType.FULL_REFRESH:+ if replaces_table:# The marker snapshot predates the job fetch and Delta-log work above. A heartbeat-timed-out# predecessor can stage a swap in that window, making temp the only intact copy; deferring# from the stale snapshot would purge that temp and erase its recovery marker.schema.refresh_from_db(fields=["sync_type_config"])swap = schema.repartition_swappending = schema.repartition_pending or pending+ # The reset can be cleared in the same window, and the table then needs its rewrite.+ replaces_table = swap is None and _import_replaces_table(schema, job, inputs, logger)# A pending marker carrying only bookkeeping (an attempt count written when nothing was queued)# has no keys to rebuild a target from, and `from_dict` would raise before the rewrite even@@ -407,8 +425,11 @@ def _maybe_repartition_table(inputs: RepartitionActivityInputs, logger: Filterintrigger_reason = (pending or {}).get("trigger_reason", "resume")# Never while a swap is staged: live may already be deleted, and temp is then the only intact copy.- if swap is None and schema.sync_type == ExternalDataSchema.SyncType.FULL_REFRESH:- _defer_to_full_refresh(inputs, schema, table_ref, target, trigger_reason, logger)+ if replaces_table:+ if schema.sync_type == ExternalDataSchema.SyncType.FULL_REFRESH:+ _defer_to_full_refresh(inputs, schema, table_ref, target, trigger_reason, logger)+ else:+ _defer_to_reset(inputs, schema, table_ref, trigger_reason, logger)return# `_handle_failure` also gives up at the cap, but only for an attempt that survives to run it.@@ -444,7 +465,7 @@ def _maybe_repartition_table(inputs: RepartitionActivityInputs, logger: Filterin)pending = _clear_attempts_after_progress(schema, pending, logger)else:- _give_up(inputs, schema, pending, trigger_reason, logger)+ _give_up(inputs, schema, table_ref, pending, trigger_reason, logger)return# Never while a swap is staged: that recovery runs no rewrite, so the checkpoint says nothing@@ -567,7 +588,9 @@ def _maybe_repartition_table(inputs: RepartitionActivityInputs, logger: Filterin# schema's imports until then (see `_import_held_for_repartition`).logger.error("repartition: the swap landed but its scheme could not be saved; imports stay held", exc_info=True)DELTA_REPARTITION_TOTAL.labels(- outcome=_handle_failure(inputs, schema, pending, trigger_reason, e, claim_token, logger, charged_attempts),+ outcome=_handle_failure(+ inputs, schema, pending, trigger_reason, e, claim_token, logger, charged_attempts, table_ref+ ),).inc()returnexcept (RepartitionUnpartitionableError, RepartitionTooLargeForBudgetError) as e:@@ -578,6 +601,7 @@ def _maybe_repartition_table(inputs: RepartitionActivityInputs, logger: Filterin# table churns flag → start → skip every 5 minutes forever. The cooldown re-evaluates at most# daily instead.schema.refresh_from_db(fields=["sync_type_config"])+ _purge_abandoned_temp(schema, table_ref, claim_token, logger)schema.clear_repartition_pending()schema.clear_repartition_rewrite()schema.stamp_last_repartition_at()@@ -641,7 +665,7 @@ def _maybe_repartition_table(inputs: RepartitionActivityInputs, logger: Filterin_capture_stood_down(schema, inputs, trigger_reason, "transient_infra_error", logger)returnfailure_outcome = _handle_failure(- inputs, schema, pending, trigger_reason, e, claim_token, logger, charged_attempts+ inputs, schema, pending, trigger_reason, e, claim_token, logger, charged_attempts, table_ref)DELTA_REPARTITION_TOTAL.labels(outcome=failure_outcome).inc()return@@ -655,7 +679,9 @@ def _maybe_repartition_table(inputs: RepartitionActivityInputs, logger: Filterin# the remaining retries on it and holds the sync behind a rewrite that cannot finish.logger.error("repartition: the rewrite panicked inside the native delta stack", exc_info=True)DELTA_REPARTITION_TOTAL.labels(- outcome=_handle_failure(inputs, schema, pending, trigger_reason, e, claim_token, logger, charged_attempts),+ outcome=_handle_failure(+ inputs, schema, pending, trigger_reason, e, claim_token, logger, charged_attempts, table_ref+ ),).inc()return@@ -733,6 +759,91 @@ def _defer_to_full_refresh(capture_repartition_event("warehouse_repartition_skipped", props)+def _import_replaces_table(+ schema: ExternalDataSchema, job: ExternalDataJob, inputs: RepartitionActivityInputs, logger: FilteringBoundLogger+) -> bool:+ """Whether the import that runs next deletes the table and loads it again. Never raises.++ Any doubt gives False, and the activity then does what it does for a table that stays.+ """+ try:+ return import_replaces_table(+ schema, workflow_reset_pipeline=inputs.reset_pipeline, job_created_at=job.created_at+ )+ except Exception:+ logger.warning("repartition: could not tell if the import replaces the table", exc_info=True)+ return False+++def _defer_to_reset(+ inputs: RepartitionActivityInputs,+ schema: ExternalDataSchema,+ table_ref: DeltaTableRef,+ trigger_reason: str,+ logger: FilteringBoundLogger,+) -> None:+ """Leave the queued scheme for the reset that runs next, instead of rewriting the table.++ The import deletes the table and loads every row again, so a rewrite only copies data that the+ import deletes. `repartition_pending` stays as it is. The reset turns it into the scheme of the new+ table (see `promote_pending_repartition_for_replaced_table`). A reset that does not happen leaves+ the marker in place, and a later run does the rewrite.++ The fresh claim fences out a rewrite attempt that may still run as a zombie. The checkpoint of+ an earlier rewrite describes a table that the import deletes, so its temp table goes now.+ """+ claim_token = str(uuid.uuid4())+ if not schema.set_repartition_claim(+ {"token": claim_token, "job_id": inputs.job_id, "claimed_at": timezone.now().isoformat()}+ ):+ logger.info("repartition: reset deferral superseded before it claimed the schema")+ return+ if schema.repartition_rewrite is not None:+ # First, so that a failed delete cannot hold the import that does the reset.+ release_repartition_hold_if_claimed(schema, claim_token=claim_token)+ _purge_abandoned_temp(schema, table_ref, claim_token, logger, clear_checkpoint=True)+ logger.info(+ f"repartition: the import replaces the table, left the queued scheme for it to write schema_id={schema.id}",+ schema_id=str(schema.id),+ )+ DELTA_REPARTITION_TOTAL.labels(outcome="deferred").inc()+ _capture_stood_down(schema, inputs, trigger_reason, "reset_replaces_the_table", logger)+++def _purge_abandoned_temp(+ schema: ExternalDataSchema,+ table_ref: DeltaTableRef,+ claim_token: str,+ logger: FilteringBoundLogger,+ *,+ clear_checkpoint: bool = False,+) -> None:+ """Delete the temp table that the rewrite checkpoint names. Best effort.++ A failure leaves the checkpoint in place when this function owns its removal, so the next run+ tries the delete again. It must not block the sync.+ """+ temp_uri = _rewrite_checkpoint_id(schema)+ if not temp_uri:+ return+ try:+ # A large temp table takes longer to delete than the heartbeat timeout.+ with HeartbeaterSync(logger=logger):+ purged = async_to_sync(purge_abandoned_rewrite_temp)(+ table_ref, schema, temp_uri, logger, claim_token=claim_token+ )+ if purged and clear_checkpoint:+ clear_repartition_checkpoint_if_claimed(schema, claim_token=claim_token, temp_uri=temp_uri)+ except RepartitionSupersededError:+ logger.info("repartition: temp cleanup superseded by a newer claim")+ except Exception as e:+ if _is_cancellation(e):+ raise+ if not _is_transient_infra_error(e):+ capture_exception(e)+ logger.warning("repartition: could not delete the temp table of an abandoned rewrite", exc_info=True)++def _capture_stood_down(schema: ExternalDataSchema,inputs: RepartitionActivityInputs,@@ -963,6 +1074,7 @@ def _retrying_a_killed_attempt(schema: ExternalDataSchema, pending: dict[str, Andef _give_up(inputs: RepartitionActivityInputs,schema: ExternalDataSchema,+ table_ref: DeltaTableRef,pending: dict[str, Any] | None,trigger_reason: str,logger: FilteringBoundLogger,@@ -988,7 +1100,12 @@ def _give_up(claim_token = str(uuid.uuid4())if not schema.set_repartition_claim({"token": claim_token, "job_id": inputs.job_id, "claimed_at": timezone.now().isoformat()}- ) or not schema.abandon_repartition_if_claimed(claim_token):+ ):+ logger.info("repartition: give-up superseded by a newer claim")+ return+ # Before the checkpoint goes, because it is the only record of where the temp table is.+ _purge_abandoned_temp(schema, table_ref, claim_token, logger)+ if not schema.abandon_repartition_if_claimed(claim_token):logger.info("repartition: give-up superseded by a newer claim")returnerror = RepartitionAttemptsExhausted(@@ -1089,6 +1206,7 @@ def _handle_failure(claim_token: str,logger: FilteringBoundLogger,charged_attempts: int | None = None,+ table_ref: DeltaTableRef | None = None,) -> str:"""Record a failed attempt; give up (and clear the flag) after MAX_REPARTITION_ATTEMPTS.@@ -1138,6 +1256,8 @@ def _handle_failure()# Drop any partial-rewrite checkpoint too: leaving it set would make the next flag cycle# resume the same doomed temp instead of giving up, so the give-up would never take effect.+ if table_ref is not None:+ _purge_abandoned_temp(schema, table_ref, claim_token, logger)schema.clear_repartition_rewrite()# Engage the cooldown as well, or the give-up never takes effect: the trigger that queued# this rewrite (the largest partition is over budget) is just as true on the next sync anddiff --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 f4c39676bd98..2ad8a2f30d06 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@@ -25,6 +25,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.repRepartitionBudgetExceededError,RepartitionSchemePersistError,RepartitionStoppedError,+ RepartitionTooLargeForBudgetError,)from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.repartition_controller import (MAX_REPARTITION_ATTEMPTS,@@ -34,6 +35,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.repfrom products.warehouse_sources.backend.temporal.data_imports.workflow_activities.repartition_table import (RepartitionActivityInputs,_defer_to_full_refresh,+ _defer_to_reset,_maybe_flag_pre_extraction,_maybe_repartition_table,_rewrite_deadline,@@ -47,6 +49,7 @@ JOB_ID = str(uuid.uuid4())SOURCE_ID = str(uuid.uuid4())TEMP_URI = "s3://bucket/folder/table__repartition_tmp_1a2b3c4d"OTHER_TEMP_URI = "s3://bucket/folder/table__repartition_tmp_5e6f7a8b"+CHECKPOINT = {"temp_uri": TEMP_URI, "rows_written": 10, "held_at": "2026-01-01T00:00:00+00:00"}PENDING_TARGET = {"partition_mode": "datetime",@@ -1452,3 +1455,258 @@ class TestFullRefreshDeferral:# A fresh claim fences out a rewrite attempt that may still be running as a zombie.schema.set_repartition_claim.assert_called_once()assert mock_capture.call_args.args[0] == "warehouse_repartition_skipped"+++def _reset_schema(+ *,+ sync_type: str = "incremental",+ config_reset: bool = False,+ pending: dict | None = PENDING_TARGET,+ swap: dict | None = None,+ rewrite: dict | None = None,+ initial_sync_complete: bool = True,+) -> MagicMock:+ schema = _schema(name="contacts", s3_folder_name="contacts", pending=pending, swap=swap, rewrite=rewrite)+ schema.sync_type = sync_type+ schema.is_webhook = sync_type == "webhook"+ schema.sync_type_config = {"reset_pipeline": True} if config_reset else {}+ schema.initial_sync_complete = initial_sync_complete+ return schema+++class TestResetDeferral:+ @pytest.mark.parametrize(+ "sync_type, config_reset, workflow_reset, swap, expect_rewrite",+ [+ ("incremental", True, None, None, False),+ ("append", True, None, None, False),+ ("incremental", False, True, None, False),+ ("incremental", False, None, None, True),+ ("incremental", True, False, None, True),+ ("webhook", True, None, None, True),+ ("incremental", True, None, {"state": "ready", "temp_uri": TEMP_URI}, True),+ ],+ ids=[+ "reset_in_schema_config_defers",+ "reset_of_an_append_table_defers",+ "reset_in_workflow_input_defers",+ "no_reset_rewrites",+ "workflow_input_overrules_the_schema_config",+ "webhook_reset_keeps_the_table_so_rewrites",+ "staged_swap_still_completes",+ ],+ )+ @patch(f"{MODULE}.clear_repartition_checkpoint_if_claimed")+ @patch(f"{MODULE}.release_repartition_hold_if_claimed")+ @patch(f"{MODULE}.purge_abandoned_rewrite_temp", new_callable=AsyncMock)+ @patch(f"{MODULE}.capture_repartition_event")+ @patch(f"{MODULE}.HeartbeaterSync")+ @patch(f"{MODULE}.defer_repartition_to_full_refresh", new_callable=AsyncMock)+ @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_table_that_the_import_replaces_is_not_rewritten(+ self,+ mock_schema_model: MagicMock,+ _mock_job_model: MagicMock,+ _mock_helper_cls: MagicMock,+ mock_repartition: AsyncMock,+ mock_defer_full_refresh: AsyncMock,+ _mock_heartbeater: MagicMock,+ mock_capture: MagicMock,+ mock_purge: AsyncMock,+ _mock_release: MagicMock,+ mock_clear_checkpoint: MagicMock,+ sync_type: str,+ config_reset: bool,+ workflow_reset: bool | None,+ swap: dict | None,+ expect_rewrite: bool,+ ) -> None:+ mock_schema_model.SyncType.FULL_REFRESH = "full_refresh"+ schema = _reset_schema(sync_type=sync_type, config_reset=config_reset, swap=swap, rewrite=dict(CHECKPOINT))+ mock_schema_model.objects.select_related.return_value.get.return_value = schema+ mock_repartition.return_value = {"outcome": "completed"}+ mock_purge.return_value = True++ _maybe_repartition_table(+ RepartitionActivityInputs(+ team_id=TEAM_ID, schema_id=SCHEMA_ID, job_id=JOB_ID, source_id=SOURCE_ID, reset_pipeline=workflow_reset+ ),+ MagicMock(),+ )++ assert mock_repartition.await_count == (1 if expect_rewrite else 0)+ mock_defer_full_refresh.assert_not_awaited()+ if expect_rewrite:+ mock_purge.assert_not_awaited()+ return+ # The queued target stays for the reset to write, and for a later rewrite if no reset happens.+ assert schema.repartition_pending == PENDING_TARGET+ schema.set_repartition_pending.assert_not_called()+ schema.clear_repartition_pending.assert_not_called()+ schema.stamp_last_repartition_at.assert_not_called()+ schema.set_repartition_claim.assert_called_once()+ assert mock_purge.await_args is not None+ assert mock_purge.await_args.args[2] == TEMP_URI+ assert mock_clear_checkpoint.call_args.kwargs["temp_uri"] == TEMP_URI+ assert mock_capture.call_args.args[0] == "warehouse_repartition_skipped"+ assert mock_capture.call_args.args[1]["reason"] == "reset_replaces_the_table"++ @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_cleared_reset_rewrites_on_the_next_run(+ self,+ mock_schema_model: MagicMock,+ _mock_job_model: MagicMock,+ _mock_helper_cls: MagicMock,+ mock_repartition: AsyncMock,+ _mock_heartbeater: MagicMock,+ _mock_capture: MagicMock,+ ) -> None:+ mock_schema_model.SyncType.FULL_REFRESH = "full_refresh"+ schema = _reset_schema(config_reset=True)+ mock_schema_model.objects.select_related.return_value.get.return_value = schema+ mock_repartition.return_value = {"outcome": "completed"}+ inputs = RepartitionActivityInputs(team_id=TEAM_ID, schema_id=SCHEMA_ID, job_id=JOB_ID, source_id=SOURCE_ID)++ _maybe_repartition_table(inputs, MagicMock())+ mock_repartition.assert_not_awaited()++ schema.sync_type_config = {}+ _maybe_repartition_table(inputs, MagicMock())++ mock_repartition.assert_awaited_once()+ assert mock_repartition.await_args is not None+ assert mock_repartition.await_args.kwargs["target"].partition_format == PENDING_TARGET["partition_format"]++ @pytest.mark.parametrize(+ "initial_sync_complete, expect_measured",+ [(True, True), (False, False)],+ ids=["complete_table_is_measured", "partly_loaded_table_is_not_measured"],+ )+ @patch(f"{MODULE}._maybe_flag_pre_extraction")+ @patch(f"{MODULE}.needs_pre_extraction_detection", return_value=True)+ @patch(f"{MODULE}.pre_extraction_measurement_is_redundant", return_value=False)+ @patch(f"{MODULE}.capture_repartition_event")+ @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_pending_reset_only_takes_a_target_from_a_complete_table(+ self,+ mock_schema_model: MagicMock,+ _mock_job_model: MagicMock,+ _mock_helper_cls: MagicMock,+ mock_repartition: AsyncMock,+ _mock_capture: MagicMock,+ _mock_redundant: MagicMock,+ _mock_needs_detection: MagicMock,+ mock_flag: MagicMock,+ initial_sync_complete: bool,+ expect_measured: bool,+ ) -> None:+ mock_schema_model.SyncType.FULL_REFRESH = "full_refresh"+ schema = _reset_schema(config_reset=True, pending=None, initial_sync_complete=initial_sync_complete)+ mock_schema_model.objects.select_related.return_value.get.return_value = schema+ mock_flag.return_value = PENDING_TARGET++ _maybe_repartition_table(+ RepartitionActivityInputs(team_id=TEAM_ID, schema_id=SCHEMA_ID, job_id=JOB_ID, source_id=SOURCE_ID),+ MagicMock(),+ )++ assert mock_flag.call_count == (1 if expect_measured else 0)+ mock_repartition.assert_not_awaited()++ @pytest.mark.parametrize(+ "purge_result, expect_checkpoint_cleared",+ [(True, True), (False, False), (OSError("delete failed"), False)],+ ids=["deleted", "refused", "failed"],+ )+ @patch(f"{MODULE}.capture_exception")+ @patch(f"{MODULE}.capture_repartition_event")+ @patch(f"{MODULE}.HeartbeaterSync")+ @patch(f"{MODULE}.clear_repartition_checkpoint_if_claimed")+ @patch(f"{MODULE}.release_repartition_hold_if_claimed")+ @patch(f"{MODULE}.purge_abandoned_rewrite_temp", new_callable=AsyncMock)+ def test_the_checkpoint_stays_until_its_temp_table_is_deleted(+ self,+ mock_purge: AsyncMock,+ mock_release: MagicMock,+ mock_clear_checkpoint: MagicMock,+ _mock_heartbeater: MagicMock,+ _mock_capture: MagicMock,+ _mock_capture_exception: MagicMock,+ purge_result: bool | Exception,+ expect_checkpoint_cleared: bool,+ ) -> None:+ schema = _reset_schema(config_reset=True, rewrite=dict(CHECKPOINT))+ if isinstance(purge_result, Exception):+ mock_purge.side_effect = purge_result+ else:+ mock_purge.return_value = purge_result++ _defer_to_reset(+ RepartitionActivityInputs(team_id=TEAM_ID, schema_id=SCHEMA_ID, job_id=JOB_ID, source_id=SOURCE_ID),+ schema,+ MagicMock(),+ "proactive_threshold",+ MagicMock(),+ )++ # A checkpoint that stays must not hold the import that does the reset.+ mock_release.assert_called_once()+ assert mock_clear_checkpoint.call_count == (1 if expect_checkpoint_cleared else 0)+++class TestAbandonedTempCleanup:+ @pytest.mark.parametrize(+ "attempts, rewrite_error",+ [+ (0, RepartitionTooLargeForBudgetError("one budget cannot cover the table")),+ (MAX_REPARTITION_ATTEMPTS - 1, ValueError("rewrite failed")),+ (MAX_REPARTITION_ATTEMPTS, None),+ ],+ ids=["too_large_for_budget", "failed_on_the_last_attempt", "attempts_spent_before_the_rewrite"],+ )+ @patch(f"{MODULE}.capture_exception")+ @patch(f"{MODULE}.purge_abandoned_rewrite_temp", new_callable=AsyncMock)+ @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_rewrite_that_is_given_up_deletes_its_temp_table(+ self,+ mock_schema_model: MagicMock,+ _mock_job_model: MagicMock,+ _mock_helper_cls: MagicMock,+ mock_repartition: AsyncMock,+ _mock_heartbeater: MagicMock,+ _mock_capture: MagicMock,+ mock_purge: AsyncMock,+ _mock_capture_exception: MagicMock,+ attempts: int,+ rewrite_error: Exception | None,+ ) -> None:+ mock_schema_model.SyncType.FULL_REFRESH = "full_refresh"+ schema = _reset_schema(pending={**PENDING_TARGET, "attempts": attempts}, rewrite=dict(CHECKPOINT))+ mock_schema_model.objects.select_related.return_value.get.return_value = schema+ mock_repartition.side_effect = rewrite_error+ mock_purge.return_value = True++ _maybe_repartition_table(+ RepartitionActivityInputs(team_id=TEAM_ID, schema_id=SCHEMA_ID, job_id=JOB_ID, source_id=SOURCE_ID),+ MagicMock(),+ )++ mock_purge.assert_awaited_once()+ assert mock_purge.await_args is not None+ assert mock_purge.await_args.args[2] == TEMP_URI