Skip to content

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

fix(data-warehouse): make the repartition swap resumable, bounded and visible (#114631)

Tom Owers8297d2a27986
diff --git a/products/warehouse_sources/backend/models/external_data_schema.py b/products/warehouse_sources/backend/models/external_data_schema.py
index 406edb0e5ad5..bbe675d8e3e5 100644
--- a/products/warehouse_sources/backend/models/external_data_schema.py
+++ b/products/warehouse_sources/backend/models/external_data_schema.py
@@ -1842,6 +1842,31 @@ def save_repartition_checkpoint_if_claimed(
return claimed
+def save_repartition_swap_phase_if_claimed(
+ schema: ExternalDataSchema, *, claim_token: str, temp_uri: str, phase: str
+) -> bool:
+ """Record how far a staged swap is, only while `claim_token` still owns the schema.
+
+ Row-locked for the same reason as `save_repartition_checkpoint_if_claimed`. The phase goes on
+ the marker for `temp_uri` only, so it never lands on a swap that a newer attempt staged.
+ """
+ saved = False
+
+ def _write(config: dict[str, Any]) -> None:
+ nonlocal saved
+ claim = config.get("repartition_claim")
+ if not (claim and claim.get("token") == claim_token):
+ return
+ swap = config.get("repartition_swap")
+ if not isinstance(swap, dict) or swap.get("temp_uri") != temp_uri:
+ return
+ swap["phase"] = phase
+ saved = True
+
+ schema.sync_type_config = update_sync_type_config_keys(schema_id=schema.id, team_id=schema.team_id, mutate=_write)
+ return saved
+
+
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`).
diff --git a/products/warehouse_sources/backend/temporal/data_imports/README.md b/products/warehouse_sources/backend/temporal/data_imports/README.md
index e2c02ad1aa94..2c168d2668df 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/README.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/README.md
@@ -46,12 +46,13 @@ How it works:
Week into month is the one transition that cannot be computed exactly, because ISO weeks straddle month boundaries and the key does not say how a week's bytes divide between two months. It is sized by upper bound instead, charging each straddling week's full size to both months, so a layout that fits under the bound fits in reality. The transition is worth supporting rather than skipping: the finer path's first step is month into week, so without it a table this controller wrongly split could never be merged back. Note the bound also makes it the narrowest transition on offer, since a month holds only about 4.3 weeks against a 4x minimum reduction, so in practice it needs roughly a year of weekly partitions to qualify.
-- **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.
+- **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 (see **Swap** below). 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.
+- **Swap.** `_swap_temp_into_live` puts temp in place of live in four steps, and each step can run again after a worker death. (1) It copies temp's data files into the live folder, beside the old data files. The old log does not name them, so live stays readable on the old layout during the long step. The copy runs with a bound (`SWAP_COPY_CONCURRENCY`), one CopyObject per file with the size from the listing, in groups of `SWAP_GROUP_FILES`. A file that is already in place with the same size is not copied again, so a later attempt continues where the earlier one stopped. (2) It records `phase: switch_log` on the `repartition_swap` marker, deletes live's `_delta_log` and copies temp's. Live has no complete log only during this step, which is a few hundred small objects. (3) It verifies live: the row count, and that every data file the new log names is in the folder. (4) It records `phase: cleanup`, deletes the objects in the live folder that the new log does not name, then deletes temp. A resume reads the phase to select the copy to trust: temp until `cleanup`, live from `cleanup` on, because a part of a log reads as a valid table with fewer rows. Between groups the copy logs `repartition: swap progress` (files and bytes done and total, rate, ETA) at most once per `SWAP_PROGRESS_INTERVAL_SECONDS`, re-checks the claim, and stops when the worker shuts down or Temporal cancels the attempt. Each phase boundary logs one line, and `warehouse_load_delta_repartition_swap_files_total` and `..._swap_bytes_total` count the work. Queries read the published query folder, which the swap does not touch, and the import stays held while the marker is set.
+- **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 it touches 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.
+- **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. It stops the swap's copy after the current group of files. 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.
Tuning and gating:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/repartition.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/repartition.py
index a6fd1e2eca3c..4bfac7ecfa5c 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
@@ -38,6 +38,7 @@ from products.warehouse_sources.backend.models.external_data_schema import (
ExternalDataSchema,
finalize_repartition_scheme,
save_repartition_checkpoint_if_claimed,
+ save_repartition_swap_phase_if_claimed,
stage_partition_scheme_for_full_refresh,
)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrow_utils import (
@@ -65,11 +66,21 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.rep
resume_blocker,
storage_filesystem,
)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.repartition_swap import (
+ DELTA_LOG_PREFIX,
+ SWAP_PHASE_CLEANUP,
+ SWAP_PHASE_SWITCH_LOG,
+ SWAP_PROGRESS_INTERVAL_SECONDS,
+ SwapProgress,
+ copy_files,
+ delete_files,
+ list_table_files,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import (
PartitionFormat,
PartitionMode,
)
-from products.warehouse_sources.backend.temporal.data_imports.workload_report import report_buffer_bytes
+from products.warehouse_sources.backend.temporal.data_imports.workload_report import report_buffer_bytes, report_phase
from products.warehouse_sources.backend.types import IncrementalFieldType
if TYPE_CHECKING:
@@ -1396,11 +1407,13 @@ async def repartition_table_in_place(
`deadline` (a `time.monotonic()` value) bounds the rewrite phase only. The swap that follows
needs no bound of its own: it records `repartition_swap` before touching live, so a swap cut
- short by the activity timeout resumes from the intact temp table on a later run.
+ short by the activity timeout resumes on a later run and copies only the files that are not in
+ place yet.
- `should_stop` also applies to the rewrite phase only. When it returns True the rewrite stops after
- its next commit and raises `RepartitionStoppedError`, with the temp table and its checkpoint kept
- for the next attempt (see `_rewrite_into_temp`).
+ `should_stop` applies to the rewrite and to the swap's copy of the data files. When it returns
+ True the rewrite stops after its next commit and the swap stops after its current group of files.
+ Both raise `RepartitionStoppedError` and keep what the next attempt needs to resume (see
+ `_rewrite_into_temp` and `_swap_temp_into_live`).
"""
live_uri = await table_ref.get_table_uri()
storage_options = table_ref.get_storage_options()
@@ -1438,6 +1451,32 @@ async def repartition_table_in_place(
await ensure_claim()
+ async def set_swap_phase(phase: str) -> None:
+ await asyncio.to_thread(_save_swap_phase, schema, claim_token, temp_uri, phase)
+
+ async def resume_swap_without_live(phase: str | None) -> dict[str, Any]:
+ return await _resume_swap_with_missing_live(
+ table_ref=table_ref,
+ schema=schema,
+ target=target,
+ temp_uri=temp_uri,
+ live_uri=live_uri,
+ storage_options=storage_options,
+ logger=logger,
+ ensure_claim=ensure_claim,
+ claim_token=claim_token,
+ should_stop=should_stop,
+ phase=phase,
+ )
+
+ # A swap that already started to replace live's log cannot be judged by live's row count: a
+ # part of the new log reads as a valid, smaller table. The marker's phase names the copy to trust.
+ swap_phase = (swap or {}).get("phase") if resuming else None
+ if swap_phase in (SWAP_PHASE_SWITCH_LOG, SWAP_PHASE_CLEANUP):
+ trusted_uri = live_uri if swap_phase == SWAP_PHASE_CLEANUP else temp_uri
+ if await _valid_delta_row_count(trusted_uri, storage_options) is not None:
+ return await resume_swap_without_live(swap_phase)
+
try:
old_delta = await table_ref.get_delta_table()
except (deltalake.exceptions.DeltaError, FileNotFoundError) as e:
@@ -1459,17 +1498,7 @@ async def repartition_table_in_place(
# rather than skipping — a plain skip would strand the markers forever (every later run hits
# this same early return) and let the next sync bootstrap an empty table over the lost data.
if resuming:
- return await _resume_swap_with_missing_live(
- table_ref=table_ref,
- schema=schema,
- target=target,
- temp_uri=temp_uri,
- live_uri=live_uri,
- storage_options=storage_options,
- logger=logger,
- ensure_claim=ensure_claim,
- claim_token=claim_token,
- )
+ return await resume_swap_without_live(None)
await logger.ainfo(f"repartition: no delta table, skipping schema_id={schema.id}", schema_id=str(schema.id))
return {"outcome": "skipped", "reason": "no_delta_table"}
@@ -1494,6 +1523,16 @@ async def repartition_table_in_place(
resolved = target
rows_written = old_row_count
await logger.ainfo(f"repartition: resuming from valid temp schema_id={schema.id}", schema_id=str(schema.id))
+ elif (
+ temp_rows is not None
+ and temp_rows > old_row_count
+ and staged_target is not None
+ and await _live_matches_scheme(live_uri, storage_options, staged_target, logger)
+ ):
+ # Live is on the new layout with fewer rows than a readable temp: a swap without a phase
+ # on its marker died while it copied the log, and a part of a log is a valid table. A
+ # finished swap never leaves temp with more rows than live, so temp is the full table.
+ return await resume_swap_without_live(None)
elif staged_target is not None and await _live_matches_scheme(live_uri, storage_options, staged_target, logger):
# temp is gone because the swap finished and deleted it — only the settings write was
# lost. Live already carries the marker's keys, so there is nothing to rewrite: finish the
@@ -1731,14 +1770,17 @@ async def repartition_table_in_place(
# temp is complete now, so the rewrite checkpoint is obsolete — the swap marker supersedes it.
await asyncio.to_thread(schema.clear_repartition_rewrite)
- # Swap (idempotent): replace live with a server-side copy of temp, verify, then drop temp. temp
- # holds the full re-bucketed dataset, so deleting live is safe — temp is the new source of truth.
+ # Swap (idempotent): copy temp's data files beside live's, replace live's log, verify, then drop
+ # the old files and temp. temp holds the full re-bucketed dataset and stays until live is verified.
await _swap_temp_into_live(
temp_uri=temp_uri,
live_uri=live_uri,
storage_options=storage_options,
expected_rows=old_row_count,
+ logger=logger,
ensure_claim=ensure_claim,
+ should_stop=should_stop,
+ set_phase=set_swap_phase,
)
# The data in S3 is on the new scheme from here, so the settings, the markers and the cooldown go
@@ -1778,6 +1820,17 @@ async def repartition_table_in_place(
}
+def _save_swap_phase(schema: ExternalDataSchema, claim_token: str | None, temp_uri: str, phase: str) -> None:
+ if claim_token is None:
+ # No claim means no fencing (tests, ad-hoc use), so there is no newer writer to protect.
+ schema.set_repartition_swap({**(schema.repartition_swap or {}), "phase": phase})
+ return
+ if not save_repartition_swap_phase_if_claimed(schema, claim_token=claim_token, temp_uri=temp_uri, phase=phase):
+ raise RepartitionSupersededError(
+ f"repartition claim lost before swap phase {phase} (ours={claim_token[:8]}) schema_id={schema.id}"
+ )
+
+
async def _resume_swap_with_missing_live(
*,
table_ref: DeltaTableRef,
@@ -1789,16 +1842,24 @@ async def _resume_swap_with_missing_live(
logger: FilteringBoundLogger,
ensure_claim: Callable[[], Awaitable[None]] | None = None,
claim_token: str | None = None,
+ should_stop: Callable[[], bool] | None = None,
+ phase: str | None = None,
) -> dict[str, Any]:
- """Finish a swap whose live table was already deleted by an interrupted prior run.
-
- Entered only when the swap marker is set but live is gone — i.e. a previous run crashed inside
- `_swap_temp_into_live` after deleting live and before the copy completed. temp is the durable
- source of truth, so its own row count is the swap's expectation. If temp is *also* gone there is
- nothing left to recover (both folders lost): clear the markers and skip so the next sync rebuilds.
+ """Finish a swap that an interrupted run left without a live table to compare against.
+
+ Entered when the swap marker is set and live cannot say how many rows the table has: its log is
+ gone or incomplete (an older swap deleted live first, and the current one replaces the log in
+ its `switch_log` phase), or the marker's `phase` says the swap got that far. temp is the durable
+ source of truth, so its own row count is the swap's expectation. In the `cleanup` phase live is
+ already verified and temp can be partly deleted, so live's own row count is the expectation. If
+ temp is *also* gone there is nothing left to recover (both folders lost): clear the markers and
+ skip so the next sync rebuilds.
"""
- expected_rows = await _valid_delta_row_count(temp_uri, storage_options)
+ source_of_truth = live_uri if phase == SWAP_PHASE_CLEANUP else temp_uri
+ expected_rows = await _valid_delta_row_count(source_of_truth, storage_options)
if expected_rows is None:
+ if phase == SWAP_PHASE_CLEANUP:
+ raise ValueError(f"repartition swap: live is unreadable in the cleanup phase (schema_id={schema.id})")
# Both live and a usable temp are gone (temp missing or its `_delta_log` is corrupt) — nothing
# left to recover. Clear the markers and skip so the next sync rebuilds the table from source.
await asyncio.to_thread(schema.clear_repartition_swap)
@@ -1809,16 +1870,28 @@ async def _resume_swap_with_missing_live(
)
return {"outcome": "skipped", "reason": "no_delta_table"}
- await logger.ainfo(
- f"repartition: live missing mid-swap, resuming from temp schema_id={schema.id}", schema_id=str(schema.id)
- )
+ if phase is None:
+ await logger.ainfo(
+ f"repartition: live missing mid-swap, resuming from temp schema_id={schema.id}", schema_id=str(schema.id)
+ )
+ else:
+ await logger.ainfo(
+ f"repartition: resuming swap phase={phase} schema_id={schema.id}", schema_id=str(schema.id), phase=phase
+ )
+
+ async def set_phase(new_phase: str) -> None:
+ await asyncio.to_thread(_save_swap_phase, schema, claim_token, temp_uri, new_phase)
await _swap_temp_into_live(
temp_uri=temp_uri,
live_uri=live_uri,
storage_options=storage_options,
expected_rows=expected_rows,
+ logger=logger,
ensure_claim=ensure_claim,
+ should_stop=should_stop,
+ phase=phase,
+ set_phase=set_phase,
)
await _persist_resolved_scheme(schema, target, claim_token, logger)
@@ -1838,53 +1911,170 @@ async def _swap_temp_into_live(
live_uri: str,
storage_options: dict[str, str],
expected_rows: int,
+ logger: FilteringBoundLogger,
ensure_claim: Callable[[], Awaitable[None]] | None = None,
+ should_stop: Callable[[], bool] | None = None,
+ phase: str | None = None,
+ set_phase: Callable[[str], Awaitable[None]] | None = None,
+ progress_interval_seconds: float = SWAP_PROGRESS_INTERVAL_SECONDS,
+ claim_recheck_interval_seconds: float = CLAIM_RECHECK_INTERVAL_SECONDS,
) -> None:
- """Atomically-enough replace `live_uri` with the contents of `temp_uri`.
+ """Put the contents of `temp_uri` in place of the table at `live_uri`.
+
+ The steps, each safe to run again after a death at any point:
+
+ 1. Copy temp's data files into the live folder, beside the old data files. The old log does not
+ name them, so live stays readable on the old layout. A file that is already in place with
+ the same size is not copied again, which is how a later attempt resumes. This is the long
+ step, and the only one that stops for `should_stop`.
+ 2. Record phase `switch_log`, delete live's log and copy temp's log. Live has no complete log
+ only during this step. temp is the source of truth for it.
+ 3. Verify live: the row count, and that every data file the new log names is in the folder.
+ 4. Record phase `cleanup`, delete the objects in the live folder that the new log does not
+ name (the old data files), then delete temp.
+
+ Delta stores relative paths in `_delta_log`, so a copied folder is a valid table. Data file
+ names carry a random id, so a new file never replaces an old one.
+
+ `phase` is the marker's phase from an earlier attempt. `set_phase` records a new one, fenced
+ on the claim. The claim is also re-checked before each destructive step, and at most once per
+ `claim_recheck_interval_seconds` during the copy.
+ """
+ if not is_temp_uri_of(live_uri, temp_uri):
+ raise ValueError("repartition swap: refusing to swap, the temp path is not a temp table of the live table")
- Crash-safe ordering: delete live → server-side copy temp → live → verify → delete temp. Until
- temp is deleted it remains the durable source of truth, so any retry simply re-runs this whole
- function (Delta uses relative paths in `_delta_log`, so a copied folder is a valid table).
+ last_claim_check = time.monotonic()
+ last_progress_log = time.monotonic()
- Files are copied one at a time preserving their path relative to temp — a single recursive
- `copy(prefix, prefix)` trips over directory-marker objects on S3-compatible stores.
- """
- # Never destroy live for an incomplete temp: confirm temp is a readable Delta table holding every
- # expected row before deleting live. A partial/corrupt temp (from an interrupted rewrite or swap)
- # would otherwise be copied over live and leave both broken. Raising is safe — the caller
- # re-validates temp on the next run and rebuilds fresh from the still-intact live.
- temp_rows = await _valid_delta_row_count(temp_uri, storage_options)
- if temp_rows != expected_rows:
- raise ValueError(
- f"repartition swap: refusing to swap, temp is incomplete "
- f"(rows={temp_rows} expected={expected_rows} temp_uri={temp_uri})"
- )
+ async def claim() -> None:
+ nonlocal last_claim_check
+ if ensure_claim is not None:
+ await ensure_claim()
+ last_claim_check = time.monotonic()
- # Deleting live is the point of no return — a superseded attempt must never reach it.
- if ensure_claim is not None:
- await ensure_claim()
+ async def log(message: str, **fields: Any) -> None:
+ await logger.ainfo(f"repartition: swap {message} {_format_fields(fields)}", **fields)
- temp_prefix = temp_uri.replace("s3://", "").rstrip("/")
+ report_phase("repartition_swap")
async with aget_s3_client(fresh_instance=True) as s3:
- if await s3._exists(temp_uri):
- # Fully clear live before the copy. A leftover file from an incomplete recursive delete
- # merges into the copied `_delta_log` and inflates the row count past `expected_rows`,
- # tripping the verification below and looping the repartition forever.
- await _purge_s3_prefix(s3, live_uri)
- files = await s3._find(temp_uri)
- # Data files first, `_delta_log` last: a death mid-copy then leaves live without a
- # readable log — a state the corrupted-log revive detects and heals — instead of a
- # valid log referencing data files that never arrived.
- files = sorted(files, key=lambda f: "/_delta_log/" in f)
- for f in files:
- rel = f[len(temp_prefix) :]
- await s3._copy(f"s3://{f.lstrip('/')}", f"{live_uri}{rel}")
-
- # Verify the live copy is a valid Delta table with the expected row count before dropping temp.
- live_delta = await asyncio.to_thread(deltalake.DeltaTable, table_uri=live_uri, storage_options=storage_options)
- live_rows = await asyncio.to_thread(_table_row_count, live_delta)
- if live_rows != expected_rows:
- raise ValueError(f"repartition swap verification failed: live={live_rows} expected={expected_rows}")
+ s3.invalidate_cache()
+ if phase != SWAP_PHASE_CLEANUP:
+ # Never touch live for an incomplete temp: confirm temp is a readable Delta table holding
+ # every expected row first. A partial/corrupt temp (from an interrupted rewrite or swap)
+ # would otherwise replace live and leave both broken. Raising is safe — the caller
+ # re-validates temp on the next run and rebuilds fresh from the still-intact live.
+ temp_rows = await _valid_delta_row_count(temp_uri, storage_options)
+ if temp_rows != expected_rows:
+ raise ValueError(
+ f"repartition swap: refusing to swap, temp is incomplete "
+ f"(rows={temp_rows} expected={expected_rows} temp_uri={temp_uri})"
+ )
+ await claim()
+
+ temp_files = await list_table_files(s3, temp_uri)
+ live_files = await list_table_files(s3, live_uri)
+ data_files = {path: size for path, size in temp_files.items() if not path.startswith(DELTA_LOG_PREFIX)}
+ log_files = {path: size for path, size in temp_files.items() if path.startswith(DELTA_LOG_PREFIX)}
+ if not log_files:
+ raise ValueError(f"repartition swap: refusing to swap, temp has no log (temp_uri={temp_uri})")
+ to_copy = {path: size for path, size in data_files.items() if live_files.get(path) != size}
+ in_place = len(data_files) - len(to_copy)
+ progress = SwapProgress(
+ step="copy_data",
+ files_total=len(data_files),
+ bytes_total=sum(data_files.values()),
+ files_done=in_place,
+ bytes_done=sum(data_files.values()) - sum(to_copy.values()),
+ files_already_in_place=in_place,
+ )
+ await log(
+ "starting",
+ phase=phase or "copy_data",
+ files_total=progress.files_total,
+ bytes_total=progress.bytes_total,
+ files_already_in_place=in_place,
+ files_to_copy=len(to_copy),
+ log_files=len(log_files),
+ live_objects=len(live_files),
+ )
+
+ async def stop_if_requested() -> None:
+ if should_stop is not None and should_stop() and progress.files_done < progress.files_total:
+ await log("stopped early", **progress.fields())
+ raise RepartitionStoppedError(
+ f"swap stopped early with {progress.files_done} of {progress.files_total} data files "
+ f"in place for {temp_uri}"
+ )
+
+ async def between_groups() -> None:
+ nonlocal last_progress_log
+ now = time.monotonic()
+ if now - last_claim_check >= claim_recheck_interval_seconds:
+ await claim()
+ if now - last_progress_log >= progress_interval_seconds:
+ last_progress_log = now
+ await log("progress", **progress.fields())
+ await stop_if_requested()
+
+ if to_copy:
+ await stop_if_requested()
+ await copy_files(
+ s3,
+ source_uri=temp_uri,
+ destination_uri=live_uri,
+ files=to_copy,
+ progress=progress,
+ between_groups=between_groups,
+ )
+ await log("data files in place", **progress.fields())
+
+ # The point of no return for live's old log — a superseded attempt must never reach it.
+ await claim()
+ if set_phase is not None:
+ await set_phase(SWAP_PHASE_SWITCH_LOG)
+ switch_started = time.monotonic()
+ await _purge_s3_prefix(s3, f"{live_uri.rstrip('/')}/{DELTA_LOG_PREFIX.rstrip('/')}")
+ await copy_files(
+ s3,
+ source_uri=temp_uri,
+ destination_uri=live_uri,
+ files=log_files,
+ progress=SwapProgress(
+ step="switch_log", files_total=len(log_files), bytes_total=sum(log_files.values())
+ ),
+ )
+ await log(
+ "log switched",
+ log_files=len(log_files),
+ live_without_log_seconds=round(time.monotonic() - switch_started, 1),
+ )
+
+ # Verify live before anything is deleted: the row count, and that every file the log names
+ # is there. A log that names a file which never arrived reads as a valid table by row count.
+ live_delta = await asyncio.to_thread(deltalake.DeltaTable, table_uri=live_uri, storage_options=storage_options)
+ live_rows = await asyncio.to_thread(_table_row_count, live_delta)
+ if live_rows != expected_rows:
+ raise ValueError(f"repartition swap verification failed: live={live_rows} expected={expected_rows}")
+ named = {source.path for source in await asyncio.to_thread(plan_source_files, live_delta)}
+ live_files = await list_table_files(s3, live_uri)
+ missing = named - live_files.keys()
+ if missing:
+ raise ValueError(
+ f"repartition swap verification failed: {len(missing)} of {len(named)} data files that the "
+ f"live log names are not in place"
+ )
+
+ await claim()
+ if phase != SWAP_PHASE_CLEANUP and set_phase is not None:
+ await set_phase(SWAP_PHASE_CLEANUP)
+
+ # Everything else in the folder is the old table. Delete by name from the listing of the live
+ # folder itself, so the delete cannot reach a sibling folder or a file the new log names.
+ old_files = sorted(path for path in live_files if path not in named and not path.startswith(DELTA_LOG_PREFIX))
+ cleanup = SwapProgress(step="delete_old_files", files_total=len(old_files), bytes_total=0)
+ if old_files:
+ await delete_files(s3, live_uri, old_files, cleanup)
+ await log("old files deleted", files_deleted=len(old_files))
- async with aget_s3_client(fresh_instance=True) as s3:
await _purge_s3_prefix(s3, temp_uri)
+ await log("complete", rows=expected_rows, data_files=len(named))
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/repartition_swap.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/repartition_swap.py
new file mode 100644
index 000000000000..e4fb22c5d90b
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/repartition_swap.py
@@ -0,0 +1,176 @@
+"""Object-store work of the repartition swap: list a table folder, copy files with a bound, report progress.
+
+The swap in `repartition.py` owns the order of the steps and the recovery rules. This module holds
+the steps that touch many objects, so each of them can stop between groups of files and can say how
+far it is.
+"""
+
+from __future__ import annotations
+
+import time
+import asyncio
+import dataclasses
+from collections.abc import Awaitable, Callable, Mapping, Sequence
+from typing import Any
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.errors import (
+ is_transient_object_store_error,
+)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.load.metrics import (
+ DELTA_REPARTITION_SWAP_BYTES_TOTAL,
+ DELTA_REPARTITION_SWAP_FILES_TOTAL,
+)
+from products.warehouse_sources.backend.temporal.data_imports.util import _is_s3_throttling_error, copy_s3_file
+
+DELTA_LOG_PREFIX = "_delta_log/"
+
+# The marker's `phase` once the swap has started to replace the live log. From here live can be
+# without a complete log, so a resume takes its row count from temp and never from live.
+SWAP_PHASE_SWITCH_LOG = "switch_log"
+# The marker's `phase` once live is verified on the new layout. Only deletes are left, and temp can
+# already be partly gone, so a resume must not read temp.
+SWAP_PHASE_CLEANUP = "cleanup"
+
+# Copies in flight at one time. A copy is one server-side request with no payload, so the bound
+# protects the destination prefix from a rate limit and costs no memory.
+SWAP_COPY_CONCURRENCY = 32
+# Files between two stop checks. A worker shutdown waits for at most one group.
+SWAP_GROUP_FILES = 256
+SWAP_PROGRESS_INTERVAL_SECONDS = 30.0
+# One group is retried as a whole. 5 attempts give 30 seconds of backoff (2+4+8+16).
+SWAP_COPY_MAX_ATTEMPTS = 5
+# The object store accepts at most this many keys in one delete request.
+SWAP_DELETE_BATCH = 1000
+
+
[email protected](frozen=False)
+class SwapProgress:
+ """Counts for one step of the swap. `files_done` includes files that were already in place."""
+
+ step: str
+ files_total: int
+ bytes_total: int
+ files_done: int = 0
+ bytes_done: int = 0
+ files_already_in_place: int = 0
+ started_at: float = dataclasses.field(default_factory=time.monotonic)
+
+ def fields(self) -> dict[str, Any]:
+ elapsed = max(time.monotonic() - self.started_at, 1e-6)
+ moved = self.files_done - self.files_already_in_place
+ rate = moved / elapsed
+ left = max(self.files_total - self.files_done, 0)
+ return {
+ "step": self.step,
+ "files_done": self.files_done,
+ "files_total": self.files_total,
+ "bytes_done": self.bytes_done,
+ "bytes_total": self.bytes_total,
+ "files_already_in_place": self.files_already_in_place,
+ "percent_complete": round(100 * self.files_done / self.files_total, 1) if self.files_total else 100.0,
+ "elapsed_seconds": round(elapsed),
+ "files_per_second": round(rate, 1),
+ # No rate to project from until this attempt has moved a file.
+ "eta_seconds": round(left / rate) if rate else None,
+ }
+
+
+def object_path(uri: str) -> str:
+ """The `bucket/key` form that the object-store client returns for `uri`."""
+ return uri.split("://", 1)[-1].rstrip("/")
+
+
+async def list_table_files(s3: Any, table_uri: str) -> dict[str, int]:
+ """Map each object under `table_uri` from its path inside the table folder to its size.
+
+ One flat listing, 1000 keys per request. The trailing slash on the key prefix keeps sibling
+ folders that share the table's name as a prefix (temp tables, query folders) out of the result.
+ """
+ parent_uri, _, folder_name = table_uri.rstrip("/").rpartition("/")
+ try:
+ found = await s3._find(parent_uri, prefix=f"{folder_name}/", detail=True)
+ except FileNotFoundError:
+ return {}
+ entries = found.values() if isinstance(found, dict) else found
+ prefix = object_path(table_uri) + "/"
+ files: dict[str, int] = {}
+ for entry in entries:
+ if entry.get("type") == "directory":
+ continue
+ key = object_path(str(entry.get("Key") or entry["name"]))
+ if key.startswith(prefix) and len(key) > len(prefix):
+ files[key[len(prefix) :]] = int(entry.get("size") or 0)
+ return files
+
+
+async def copy_files(
+ s3: Any,
+ *,
+ source_uri: str,
+ destination_uri: str,
+ files: Mapping[str, int],
+ progress: SwapProgress,
+ between_groups: Callable[[], Awaitable[None]] | None = None,
+ concurrency: int | None = None,
+ group_files: int | None = None,
+) -> None:
+ """Copy `files` (path inside the table folder -> size) from one table folder to another.
+
+ At most `concurrency` copies run at one time. `between_groups` runs after each group of
+ `group_files` files: it is where the caller checks for a stop, checks its claim and logs. A file
+ that has arrived is never copied again by a later call, because the caller passes only the files
+ the destination lacks.
+ """
+ semaphore = asyncio.Semaphore(concurrency or SWAP_COPY_CONCURRENCY)
+ group_files = group_files or SWAP_GROUP_FILES
+ source_uri = source_uri.rstrip("/")
+ destination_uri = destination_uri.rstrip("/")
+
+ async def copy_one(relative: str, size: int) -> None:
+ async with semaphore:
+ await copy_s3_file(s3, f"{source_uri}/{relative}", f"{destination_uri}/{relative}", size)
+
+ pending = list(files.items())
+ for start in range(0, len(pending), group_files):
+ group = pending[start : start + group_files]
+ attempt = 0
+ while True:
+ attempt += 1
+ results = await asyncio.gather(
+ *(copy_one(relative, size) for relative, size in group), return_exceptions=True
+ )
+ failed: list[tuple[str, int]] = []
+ error: BaseException | None = None
+ for (relative, size), result in zip(group, results):
+ if isinstance(result, BaseException):
+ failed.append((relative, size))
+ error = error or result
+ else:
+ progress.files_done += 1
+ progress.bytes_done += size
+ DELTA_REPARTITION_SWAP_BYTES_TOTAL.inc(size)
+ DELTA_REPARTITION_SWAP_FILES_TOTAL.labels(action="copied").inc(len(group) - len(failed))
+ if error is None:
+ break
+ retryable = isinstance(error, OSError) and not isinstance(error, FileNotFoundError)
+ retryable = retryable and (
+ is_transient_object_store_error(error)
+ or _is_s3_throttling_error(error)
+ or isinstance(error, PermissionError)
+ )
+ if not retryable or attempt >= SWAP_COPY_MAX_ATTEMPTS:
+ raise error
+ group = failed
+ await asyncio.sleep(2**attempt)
+ if between_groups is not None:
+ await between_groups()
+
+
+async def delete_files(s3: Any, table_uri: str, relative_paths: Sequence[str], progress: SwapProgress) -> None:
+ """Delete the named objects under `table_uri`, one bulk request per `SWAP_DELETE_BATCH` keys."""
+ table_uri = table_uri.rstrip("/")
+ for start in range(0, len(relative_paths), SWAP_DELETE_BATCH):
+ batch = relative_paths[start : start + SWAP_DELETE_BATCH]
+ await s3._rm([f"{table_uri}/{relative}" for relative in batch])
+ progress.files_done += len(batch)
+ DELTA_REPARTITION_SWAP_FILES_TOTAL.labels(action="deleted").inc(len(batch))
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test_repartition.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test_repartition.py
index d5513ef1cf50..85ff8b25207d 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
@@ -7,9 +7,11 @@ import asyncio
import decimal
import datetime
import itertools
+import collections
+from collections.abc import Callable
from pathlib import Path
from types import SimpleNamespace
-from typing import TYPE_CHECKING, cast
+from typing import TYPE_CHECKING, Any, NamedTuple, cast
import pytest
from unittest.mock import AsyncMock, Mock, patch
@@ -24,7 +26,10 @@ import pyarrow.parquet as pq
from deltalake.transaction import AddAction
from parameterized import parameterized
-from products.warehouse_sources.backend.temporal.data_imports.pipelines.core import repartition as repartition_module
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core import (
+ repartition as repartition_module,
+ repartition_swap as swap_module,
+)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.consts import PARTITION_KEY
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.table import (
_PURGE_S3_PREFIX_MAX_ATTEMPTS,
@@ -54,6 +59,10 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.rep
TempTableCommitter,
copied_source_files,
)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.repartition_swap import (
+ SWAP_PHASE_CLEANUP,
+ SWAP_PHASE_SWITCH_LOG,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import PartitionFormat
from products.warehouse_sources.backend.temporal.data_imports.workload_report import (
_redis_client,
@@ -2002,32 +2011,65 @@ class TestPurgeStaleTempTables:
class _LocalS3:
- """The object-store calls the purge uses, served from a local directory that stands in for all buckets."""
+ """The object-store calls the purge and the swap use, served from local files.
- def __init__(self, root: Path) -> None:
+ With a `root`, that directory stands in for all buckets. Without one, a URI is a local path.
+ """
+
+ def __init__(self, root: Path | None = None) -> None:
self._root = root
+ self.copies: list[str] = []
+ self.max_copies_in_flight = 0
+ self.before_copy: Callable[[str], None] | None = None
+ self.before_rm: Callable[[list[str]], None] | None = None
+ self._copies_in_flight = 0
def _local(self, uri: str) -> Path:
+ if self._root is None:
+ return Path(uri)
return self._root / uri.split("://", 1)[-1].strip("/")
+ def _key(self, file: Path) -> str:
+ return str(file) if self._root is None else str(file.relative_to(self._root))
+
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]:
+ async def _find(self, uri: str, prefix: str = "", detail: bool = False) -> Any:
base = self._local(uri)
- return sorted(str(f.relative_to(self._root)) for f in base.rglob("*") if f.is_file())
+ files = sorted(f for f in base.rglob("*") if f.is_file() and str(f.relative_to(base)).startswith(prefix))
+ if not detail:
+ return [self._key(f) for f in files]
+ return {self._key(f): {"Key": self._key(f), "size": f.stat().st_size, "type": "file"} for f in files}
async def _rm(self, target: str | list[str], recursive: bool = False) -> None:
- for uri in [target] if isinstance(target, str) else target:
+ targets = [target] if isinstance(target, str) else target
+ if self.before_rm is not None:
+ self.before_rm(targets)
+ for uri in targets:
local = self._local(uri)
if local.is_dir():
shutil.rmtree(local)
elif local.exists():
local.unlink()
+ async def _copy_basic(self, source: str, destination: str) -> None:
+ self._copies_in_flight += 1
+ self.max_copies_in_flight = max(self.max_copies_in_flight, self._copies_in_flight)
+ try:
+ await asyncio.sleep(0)
+ if self.before_copy is not None:
+ self.before_copy(destination)
+ target = self._local(destination)
+ target.parent.mkdir(parents=True, exist_ok=True)
+ shutil.copyfile(self._local(source), target)
+ self.copies.append(destination)
+ finally:
+ self._copies_in_flight -= 1
+
LIVE_URI = "s3://bucket/team/source/contacts"
OWN_TEMP_URI = f"{LIVE_URI}__repartitioned_1a2b3c4d"
@@ -2132,25 +2174,35 @@ class TestPurgeAbandonedRewriteTemp:
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 the
- # destructive delete-of-live. The guard raises before any S3 op, so live stays intact and the
- # caller rebuilds fresh on the next run instead of copying a broken table over live.
- s3 = _fake_s3()
+ @pytest.mark.parametrize(
+ "temp_uri, match",
+ [
+ # A temp that does not hold every expected row must never replace live.
+ pytest.param("s3://b/live__repartitioned", "temp is incomplete", id="incomplete_temp"),
+ # The swap deletes temp at the end, so a marker that names any other path is refused.
+ pytest.param("s3://b/live", "not a temp table", id="temp_is_live"),
+ pytest.param("s3://b/other__repartitioned", "not a temp table", id="temp_of_another_table"),
+ pytest.param("s3://b/live__repartitioned/_delta_log", "not a temp table", id="path_inside_temp"),
+ ],
+ )
+ def test_refuses_before_any_object_store_write(self, temp_uri, match):
+ s3 = _fake_s3(_copy_basic=AsyncMock())
with (
patch.object(repartition_module, "_valid_delta_row_count", new=AsyncMock(return_value=5)),
patch.object(repartition_module, "aget_s3_client", return_value=_FakeS3CM(s3)),
):
- with pytest.raises(ValueError, match="temp is incomplete"):
+ with pytest.raises(ValueError, match=match):
asyncio.run(
repartition_module._swap_temp_into_live(
- temp_uri="s3://b/live__repartitioned",
+ temp_uri=temp_uri,
live_uri="s3://b/live",
storage_options={},
expected_rows=10,
+ logger=logger,
)
)
s3._rm.assert_not_called()
+ s3._copy_basic.assert_not_called()
class TestMissingLiveObjectPath:
@@ -2321,43 +2373,6 @@ class TestReviveScheduling:
self._run(tmp_path, verified_uri=None)
-class TestSwapCopyOrder:
- def test_delta_log_copied_after_every_data_file(self):
- # Crash-safety ordering: a death mid-copy must leave live without a readable log (the
- # corrupted-log revive heals that) — never a valid log referencing data files that never
- # arrived, which is stable, undetectable corruption.
- copied: list[str] = []
- s3 = _fake_s3(
- _find=AsyncMock(
- return_value=[
- "bucket/live__repartitioned/_delta_log/00000000000000000000.json",
- "bucket/live__repartitioned/_ph_partition_key=a/part-1.parquet",
- "bucket/live__repartitioned/_delta_log/00000000000000000001.json",
- "bucket/live__repartitioned/_ph_partition_key=b/part-2.parquet",
- ]
- ),
- _copy=AsyncMock(side_effect=lambda src, dst: copied.append(dst)),
- )
- with (
- patch.object(repartition_module, "aget_s3_client", return_value=_FakeS3CM(s3)),
- patch.object(repartition_module, "_valid_delta_row_count", new=AsyncMock(return_value=4)),
- patch.object(repartition_module.deltalake, "DeltaTable", return_value=Mock()),
- patch.object(repartition_module, "_table_row_count", return_value=4),
- ):
- asyncio.run(
- repartition_module._swap_temp_into_live(
- temp_uri="s3://bucket/live__repartitioned",
- live_uri="s3://bucket/live",
- storage_options={},
- expected_rows=4,
- )
- )
- log_positions = [i for i, dst in enumerate(copied) if "/_delta_log/" in dst]
- data_positions = [i for i, dst in enumerate(copied) if "/_delta_log/" not in dst]
- assert log_positions and data_positions
- assert min(log_positions) > max(data_positions)
-
-
class TestResumeWithInvalidTemp:
def test_discards_invalid_temp_and_rebuilds_fresh(self, tmp_path):
# A "ready" swap marker pointing at an incomplete/corrupt temp must NOT be trusted — resuming
@@ -3289,6 +3304,299 @@ class TestDeferToFullRefresh:
assert result["outcome"] == "deferred"
+SWAP_ROWS = [(i, datetime.datetime(2024, 1 + i % 3, 1 + i % 5)) for i in range(30)]
+SWAP_TARGET = RepartitionTarget(
+ partition_keys=["created_at"], trigger_reason="t", partition_mode="datetime", partition_format="day"
+)
+SWAP_DATA_FILES = 15
+
+
+class _StagedSwap(NamedTuple):
+ live_uri: str
+ temp_uri: str
+
+
+def _stage_swap(folder: Path) -> _StagedSwap:
+ live_uri = str(folder / "live")
+ temp_uri = f"{live_uri}__repartitioned_1a2b3c4d"
+ live = _write_month_partitioned(live_uri, SWAP_ROWS)
+ asyncio.run(
+ _rewrite_into_temp(
+ old_delta=live, temp_uri=temp_uri, storage_options={}, target=SWAP_TARGET, budget=_budget(), logger=logger
+ )
+ )
+ return _StagedSwap(live_uri, temp_uri)
+
+
+def _swap_schema(live_uri: str, temp_uri: str) -> SimpleNamespace:
+ schema = _schema(
+ id="s1",
+ repartition_swap={
+ "state": "ready",
+ "temp_uri": temp_uri,
+ "live_uri": live_uri,
+ "target": SWAP_TARGET.to_dict(),
+ },
+ clear_repartition_swap=Mock(),
+ clear_repartition_pending=Mock(),
+ )
+ schema.set_repartition_swap = lambda marker: setattr(schema, "repartition_swap", marker)
+ return schema
+
+
+def _run_staged_swap(
+ live_uri: str, schema: SimpleNamespace, s3: "_LocalS3", should_stop: Callable[[], bool] | None = None
+) -> dict:
+ async def get_delta_table() -> deltalake.DeltaTable | None:
+ if not deltalake.DeltaTable.is_deltatable(live_uri):
+ return None
+ return deltalake.DeltaTable(live_uri)
+
+ table_ref = _make_table_ref(get_table_uri=AsyncMock(return_value=live_uri), get_delta_table=get_delta_table)
+ with patch.object(repartition_module, "aget_s3_client", return_value=_FakeS3CM(s3)), _patch_finalize():
+ return asyncio.run(
+ repartition_table_in_place(
+ table_ref=cast("DeltaTableRef", table_ref),
+ schema=cast("repartition_module.ExternalDataSchema", schema),
+ target=SWAP_TARGET,
+ logger=logger,
+ should_stop=should_stop,
+ )
+ )
+
+
+def _table_state(live_uri: str) -> dict:
+ table = deltalake.DeltaTable(live_uri).to_pyarrow_table().sort_by("id")
+ return {
+ "ids": table.column("id").to_pylist(),
+ "schema": table.schema,
+ "partitions": sorted(set(table.column(PARTITION_KEY).to_pylist())),
+ "files": sorted(str(f.relative_to(live_uri)) for f in Path(live_uri).rglob("*") if f.is_file()),
+ }
+
+
+def _data_copies(s3: "_LocalS3") -> list[str]:
+ return [destination for destination in s3.copies if "/_delta_log/" not in destination]
+
+
+def _stop_after_first_copy(s3: "_LocalS3", live_uri: str) -> Callable[[], bool]:
+ return lambda: len(s3.copies) >= 1
+
+
+def _die_during_data_copy(s3: "_LocalS3", live_uri: str) -> None:
+ def before_copy(destination: str) -> None:
+ if len(s3.copies) >= 5:
+ raise RuntimeError("worker died")
+
+ s3.before_copy = before_copy
+
+
+def _die_during_log_switch(s3: "_LocalS3", live_uri: str) -> None:
+ def before_copy(destination: str) -> None:
+ if "/_delta_log/" in destination and any("/_delta_log/" in copied for copied in s3.copies):
+ raise RuntimeError("worker died")
+
+ s3.before_copy = before_copy
+
+
+def _die_during_cleanup(s3: "_LocalS3", live_uri: str) -> None:
+ def before_rm(targets: list[str]) -> None:
+ if any(target.startswith(f"{live_uri}/") and target.endswith(".parquet") for target in targets):
+ raise RuntimeError("worker died")
+
+ s3.before_rm = before_rm
+
+
+class TestSwapTempIntoLive:
+ @pytest.fixture(autouse=True)
+ def small_groups(self):
+ with patch.object(swap_module, "SWAP_GROUP_FILES", 2):
+ yield
+
+ @pytest.mark.parametrize(
+ "interrupt, error, phase_after, live_readable_after",
+ [
+ pytest.param(_stop_after_first_copy, RepartitionStoppedError, None, True, id="worker_shutdown"),
+ pytest.param(_die_during_data_copy, RuntimeError, None, True, id="death_during_data_copy"),
+ pytest.param(
+ _die_during_log_switch, RuntimeError, SWAP_PHASE_SWITCH_LOG, False, id="death_during_log_switch"
+ ),
+ pytest.param(_die_during_cleanup, RuntimeError, SWAP_PHASE_CLEANUP, True, id="death_during_cleanup"),
+ ],
+ )
+ def test_an_interrupted_swap_resumes_to_the_same_table_without_copying_a_data_file_twice(
+ self, interrupt, error, phase_after, live_readable_after, tmp_path
+ ):
+ _stage_swap(tmp_path / "base")
+ shutil.copytree(tmp_path / "base", tmp_path / "whole")
+ shutil.copytree(tmp_path / "base", tmp_path / "cut")
+ whole_live, whole_temp = (
+ str(tmp_path / "whole" / "live"),
+ f"{tmp_path / 'whole' / 'live'}__repartitioned_1a2b3c4d",
+ )
+ live_uri, temp_uri = str(tmp_path / "cut" / "live"), f"{tmp_path / 'cut' / 'live'}__repartitioned_1a2b3c4d"
+ before = _table_state(live_uri)
+ _run_staged_swap(whole_live, _swap_schema(whole_live, whole_temp), _LocalS3())
+
+ s3 = _LocalS3()
+ schema = _swap_schema(live_uri, temp_uri)
+ should_stop = interrupt(s3, live_uri)
+ with pytest.raises(error):
+ _run_staged_swap(live_uri, schema, s3, should_stop)
+
+ assert schema.repartition_swap.get("phase") == phase_after
+ assert Path(temp_uri).exists()
+ if phase_after is None:
+ # The old table stays in place and readable while the data files arrive beside it.
+ assert {key: before[key] for key in ("ids", "partitions")} == {
+ key: _table_state(live_uri)[key] for key in ("ids", "partitions")
+ }
+ assert deltalake.DeltaTable.is_deltatable(live_uri) or not live_readable_after
+
+ s3.before_copy = s3.before_rm = None
+ result = _run_staged_swap(live_uri, schema, s3)
+
+ assert result["outcome"] == "completed"
+ assert _table_state(live_uri) == _table_state(whole_live)
+ assert _table_state(live_uri)["ids"] == before["ids"]
+ assert collections.Counter(_data_copies(s3)) == collections.Counter(
+ f"{live_uri}/{path}" for path in _table_state(live_uri)["files"] if not path.startswith("_delta_log/")
+ )
+ assert not Path(temp_uri).exists()
+
+ def test_a_worker_shutdown_stops_the_copy_within_one_group(self, tmp_path):
+ live_uri, temp_uri = _stage_swap(tmp_path)
+ s3 = _LocalS3()
+
+ with pytest.raises(RepartitionStoppedError, match=f"2 of {SWAP_DATA_FILES} data files"):
+ _run_staged_swap(live_uri, _swap_schema(live_uri, temp_uri), s3, _stop_after_first_copy(s3, live_uri))
+
+ assert len(s3.copies) == 2
+
+ def test_a_swap_whose_older_version_deleted_live_resumes_from_temp(self, tmp_path):
+ # The swap used to delete live before it copied. A worker that died there left no live log
+ # and a part of temp's data files, and the marker carries no phase.
+ live_uri, temp_uri = _stage_swap(tmp_path)
+ expected_ids = _table_state(live_uri)["ids"]
+ shutil.rmtree(live_uri)
+ already_copied = sorted(f for f in Path(temp_uri).rglob("*.parquet") if "_delta_log" not in f.parts)[:4]
+ for file in already_copied:
+ target = Path(live_uri) / file.relative_to(temp_uri)
+ target.parent.mkdir(parents=True)
+ shutil.copyfile(file, target)
+ s3 = _LocalS3()
+
+ with structlog.testing.capture_logs() as logs:
+ result = _run_staged_swap(live_uri, _swap_schema(live_uri, temp_uri), s3)
+
+ assert result == {"outcome": "completed", "row_count": len(SWAP_ROWS), "recovered": True}
+ assert any("live missing mid-swap, resuming from temp" in entry["event"] for entry in logs)
+ assert _table_state(live_uri)["ids"] == expected_ids
+ assert len(_data_copies(s3)) == SWAP_DATA_FILES - len(already_copied)
+ assert not Path(temp_uri).exists()
+
+ def test_reports_progress_and_each_phase_boundary(self, tmp_path):
+ live_uri, temp_uri = _stage_swap(tmp_path)
+ copied_before = swap_module.DELTA_REPARTITION_SWAP_FILES_TOTAL.labels(action="copied")._value.get()
+
+ with (
+ patch.object(repartition_module, "aget_s3_client", return_value=_FakeS3CM(_LocalS3())),
+ structlog.testing.capture_logs() as logs,
+ ):
+ asyncio.run(
+ repartition_module._swap_temp_into_live(
+ temp_uri=temp_uri,
+ live_uri=live_uri,
+ storage_options={},
+ expected_rows=len(SWAP_ROWS),
+ logger=logger,
+ progress_interval_seconds=0,
+ )
+ )
+
+ events = [entry["event"] for entry in logs if entry["event"].startswith("repartition: swap ")]
+ boundaries = [event for event in events if not event.startswith("repartition: swap progress")]
+ expected = ["starting", "data files in place", "log switched", "old files deleted", "complete"]
+ assert len(boundaries) == len(expected)
+ assert all(event.startswith(f"repartition: swap {name} ") for event, name in zip(boundaries, expected))
+ progress = [entry for entry in logs if entry["event"].startswith("repartition: swap progress")]
+ # One line per group of two files, the last group included.
+ assert [entry["files_done"] for entry in progress] == [2, 4, 6, 8, 10, 12, 14, 15]
+ assert {entry["files_total"] for entry in progress} == {SWAP_DATA_FILES}
+ assert progress[-1]["bytes_done"] == progress[-1]["bytes_total"] > 0
+ assert all(entry["eta_seconds"] is not None and entry["files_per_second"] > 0 for entry in progress)
+ copied = swap_module.DELTA_REPARTITION_SWAP_FILES_TOTAL.labels(action="copied")._value.get() - copied_before
+ assert copied >= SWAP_DATA_FILES
+
+ @pytest.mark.parametrize("concurrency", [1, 3])
+ def test_copies_run_with_the_bound(self, concurrency, tmp_path):
+ live_uri, temp_uri = _stage_swap(tmp_path)
+ s3 = _LocalS3()
+
+ with (
+ patch.object(swap_module, "SWAP_COPY_CONCURRENCY", concurrency),
+ patch.object(swap_module, "SWAP_GROUP_FILES", 100),
+ ):
+ _run_staged_swap(live_uri, _swap_schema(live_uri, temp_uri), s3)
+
+ assert s3.max_copies_in_flight == concurrency
+
+ def test_a_data_file_that_did_not_arrive_fails_the_swap_before_any_delete(self, tmp_path):
+ live_uri, temp_uri = _stage_swap(tmp_path)
+ old_files = _table_state(live_uri)["files"]
+
+ class _LosesOneFile(_LocalS3):
+ async def _copy_basic(self, source: str, destination: str) -> None:
+ if "/_delta_log/" in destination or self.copies:
+ await super()._copy_basic(source, destination)
+ else:
+ self.copies.append(destination)
+
+ schema = _swap_schema(live_uri, temp_uri)
+ with pytest.raises(ValueError, match="1 of 15 data files that the live log names are not in place"):
+ _run_staged_swap(live_uri, schema, _LosesOneFile())
+
+ assert schema.repartition_swap["phase"] == SWAP_PHASE_SWITCH_LOG
+ assert deltalake.DeltaTable(temp_uri).to_pyarrow_table().num_rows == len(SWAP_ROWS)
+ assert all((Path(live_uri) / path).exists() for path in old_files if not path.startswith("_delta_log/"))
+
+ assert _run_staged_swap(live_uri, schema, _LocalS3())["outcome"] == "completed"
+ assert _table_state(live_uri)["ids"] == [row[0] for row in SWAP_ROWS]
+
+ def test_a_part_of_the_new_log_on_live_is_not_taken_for_a_finished_swap(self, tmp_path):
+ # A swap with no phase on its marker died while it copied the log. A part of a log is a valid
+ # table with fewer rows, on the new layout, so only the row counts tell it from a finished swap.
+ live = _write_datetime_partitioned(
+ str(tmp_path / "live"), [(1, datetime.datetime(2024, 1, 5)), (2, datetime.datetime(2024, 2, 2))], "day"
+ )
+ live_uri = str(tmp_path / "live")
+ table_ref = _make_table_ref(
+ get_table_uri=AsyncMock(return_value=live_uri), get_delta_table=AsyncMock(return_value=live)
+ )
+ schema = _swap_schema(live_uri, f"{live_uri}__repartitioned_1a2b3c4d")
+ resumed = {"outcome": "completed", "row_count": 5, "recovered": True}
+
+ with (
+ patch.object(repartition_module, "_valid_delta_row_count", new=AsyncMock(return_value=5)),
+ patch.object(
+ repartition_module, "_resume_swap_with_missing_live", new=AsyncMock(return_value=resumed)
+ ) as resume,
+ _patch_finalize() as finalize,
+ ):
+ result = asyncio.run(
+ repartition_table_in_place(
+ table_ref=table_ref,
+ schema=cast("repartition_module.ExternalDataSchema", schema),
+ target=SWAP_TARGET,
+ logger=logger,
+ )
+ )
+
+ assert result == resumed
+ resume.assert_awaited_once()
+ finalize.assert_not_called()
+
+
@pytest.mark.parametrize(
"data",
[
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.py
index 2e7506491537..5a9bc109949d 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
@@ -26,6 +26,7 @@ from products.warehouse_sources.backend.models.external_data_job import External
from products.warehouse_sources.backend.models.external_data_schema import (
ExternalDataSchema,
save_repartition_checkpoint_if_claimed,
+ save_repartition_swap_phase_if_claimed,
)
from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
from products.warehouse_sources.backend.models.oom_event import ExternalDataSchemaOOMEvent
@@ -1017,6 +1018,30 @@ class TestRepartitionActivity:
rewrite = schema.repartition_rewrite
assert rewrite is not None and rewrite["rows_written"] == 5
+ @pytest.mark.parametrize(
+ "claim_token, temp_uri, saved",
+ [
+ pytest.param("live-claim", "s3://b/t__repartitioned_aa", True, id="own_claim_own_temp"),
+ # A stale worker that saved here would let its resume trust the wrong copy of the table.
+ pytest.param("stale-claim", "s3://b/t__repartitioned_aa", False, id="superseded_claim"),
+ pytest.param("live-claim", "s3://b/t__repartitioned_bb", False, id="swap_of_another_attempt"),
+ ],
+ )
+ def test_a_swap_phase_is_recorded_only_by_the_claimant_on_its_own_swap(self, team, claim_token, temp_uri, saved):
+ marker = {"state": "ready", "temp_uri": "s3://b/t__repartitioned_aa", "live_uri": "s3://b/t"}
+ schema = _make_schema(team, {"repartition_swap": dict(marker)})
+ schema.set_repartition_claim({"token": "live-claim", "job_id": "j1", "claimed_at": _days_ago_iso(0)})
+
+ wrote = save_repartition_swap_phase_if_claimed(
+ schema, claim_token=claim_token, temp_uri=temp_uri, phase="switch_log"
+ )
+
+ schema.refresh_from_db()
+ assert wrote is saved
+ assert schema.repartition_swap == ({**marker, "phase": "switch_log"} if saved else marker)
+ claim = schema.repartition_claim
+ assert claim is not None and claim["token"] == "live-claim"
+
def test_the_checkpoint_claim_check_runs_inside_the_row_lock(self, team):
# The predicate tests below pass against a plain refresh-then-write, which is the bug: the
# check and the write have to share one locked critical section or a superseding claimant can
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/metrics.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/metrics.py
index 724706025293..794cc326c014 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/metrics.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/metrics.py
@@ -50,6 +50,19 @@ DELTA_REPARTITION_TOTAL = Counter(
labelnames=["outcome"],
)
+# Unlabelled by table. A rate above zero says a swap is moving files, and the rate is its speed. The
+# per-table counts, the total and the ETA are in the `repartition: swap progress` log line.
+DELTA_REPARTITION_SWAP_FILES_TOTAL = Counter(
+ "warehouse_load_delta_repartition_swap_files_total",
+ "Files the repartition swap handled, by action",
+ labelnames=["action"],
+)
+
+DELTA_REPARTITION_SWAP_BYTES_TOTAL = Counter(
+ "warehouse_load_delta_repartition_swap_bytes_total",
+ "Bytes of the files the repartition swap copied into the live table folder",
+)
+
DELTA_REPARTITION_SKIP_TOTAL = Counter(
"warehouse_load_delta_repartition_skip_total",
"Tables over the partition-size budget that the controller skipped, by reason",
diff --git a/products/warehouse_sources/backend/temporal/data_imports/util.py b/products/warehouse_sources/backend/temporal/data_imports/util.py
index fbd054f5a745..9deca6059a54 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/util.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/util.py
@@ -322,6 +322,29 @@ def _timestamped_folder_scan_due(
)
+async def copy_s3_file(s3: "S3FileSystem", source: str, destination: str, size: Optional[int]) -> None:
+ """Copy one object to a known destination key, with one CopyObject when the size allows it.
+
+ `_cp_file` reads the size of the source with a HEAD to select between a single CopyObject and
+ the multipart copy. A caller that has the size from the Delta log or from a listing passes it,
+ and a file at or below the s3fs managed-copy threshold then costs one request. CopyObject copies
+ the full object, so a wrong size cannot change the bytes that arrive.
+ """
+ if size is not None and size <= MANAGED_COPY_THRESHOLD:
+ try:
+ await s3._copy_basic(source, destination)
+ return
+ except FileNotFoundError:
+ raise
+ except OSError as e:
+ if _is_s3_throttling_error(e):
+ raise
+ # Object stores do not agree on the error for a source that is gone: S3 answers
+ # NoSuchKey, others answer with an invalid-argument error. The copy below reads the
+ # source first, so it raises the error the caller's retry loop expects.
+ await s3._cp_file(source, destination)
+
+
async def _list_query_folder_files(s3: "S3FileSystem", folder_uri: str) -> dict[str, str]:
"""Map each file under `folder_uri` from its folder-relative path to its full `s3://` URI.
@@ -602,24 +625,8 @@ async def prepare_s3_files_for_querying(
# files copied concurrently, that multiplies into enough LIST traffic to trigger
# S3's SlowDown rate limiting on the destination prefix.
relative = relative_path(file)
- destination = f"{s3_path_for_querying}/{relative}"
size = file_sizes.get(relative) if file_sizes is not None else None
- if size is not None and size <= MANAGED_COPY_THRESHOLD:
- # `_cp_file` reads the size of the source with a HEAD to select between this copy
- # and the multipart copy. The Delta log already has the size. CopyObject copies
- # the full object, so a wrong size cannot change the bytes that arrive.
- try:
- await s3._copy_basic(file, destination)
- return
- except FileNotFoundError:
- raise
- except OSError as e:
- if _is_s3_throttling_error(e):
- raise
- # Object stores do not agree on the error for a source that is gone: S3
- # answers NoSuchKey, others answer with an invalid-argument error. The copy
- # below reads the source first, so it raises the error the retry loop expects.
- await s3._cp_file(file, destination)
+ await copy_s3_file(s3, file, f"{s3_path_for_querying}/{relative}", size)
import deltalake.exceptions # noqa: PLC0415 — keeps the heavy deltalake dep off this module's top-level import path
diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/repartition_table.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/repartition_table.py
index 45203e93e863..b761d671c2b2 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
@@ -100,6 +100,18 @@ def _is_cancellation(error: BaseException) -> bool:
return isinstance(error, asyncio.CancelledError) or type(error).__name__ == "CancelledError"
+def _activity_cancelled() -> bool:
+ """Whether Temporal cancelled this activity, which includes an attempt that ran past its timeout.
+
+ A sync activity keeps its thread after a timeout, and learns of it only from the next heartbeat.
+ False outside an activity context (direct calls from tests).
+ """
+ try:
+ return activity.is_cancelled()
+ except RuntimeError:
+ return False
+
+
def _is_native_panic(error: BaseException) -> bool:
"""Whether `error` is a panic that escaped the native Delta/Arrow stack.
@@ -516,8 +528,9 @@ def _maybe_repartition_table(inputs: RepartitionActivityInputs, logger: Filterin
try:
# HeartbeaterSync heartbeats on a background thread while the (possibly long) rewrite streams,
# so Temporal does not time the activity out. The shutdown monitor lets the rewrite stop at
- # its next commit when the worker shuts down, so a rewrite does not hold a draining worker
- # for hours.
+ # its next commit, and the swap after its current group of files, when the worker shuts
+ # down, so neither holds a draining worker for hours. A cancelled attempt stops the same
+ # way, so an attempt that Temporal already timed out does not keep working beside its retry.
# The workload reporter makes the rewrite visible to pod co-tenant accounting (see
# `workload_report.py`): without it a rewrite-heavy pod looks idle to the OOM classifier's
# culprit rule. The run_id is prefixed because the sync's import activity reports under the
@@ -542,14 +555,18 @@ def _maybe_repartition_table(inputs: RepartitionActivityInputs, logger: Filterin
logger=logger,
claim_token=claim_token,
deadline=_rewrite_deadline(activity_started),
- should_stop=shutdown_monitor.is_worker_shutdown,
+ should_stop=lambda: shutdown_monitor.is_worker_shutdown() or _activity_cancelled(),
)
except RepartitionStoppedError as e:
- # The worker is shutting down and the rewrite stopped at a commit. Temp and its checkpoint
- # stay, so the retry that Temporal starts on another worker copies only the source files that
- # are left. This is not a failed attempt, so it must not count toward the give-up cap.
+ # The rewrite stopped at a commit, or the swap between two groups of files. Temp and its
+ # checkpoint or swap marker stay, so the next attempt copies only what is left. This is not
+ # a failed attempt, so it must not count toward the give-up cap.
+ if _activity_cancelled() and not shutdown_monitor.is_worker_shutdown():
+ logger.info(f"repartition: stopped for activity cancellation: {e}")
+ _refund_attempt(schema, charged_attempts, logger)
+ raise asyncio.CancelledError() from e
logger.info(
- f"repartition: stopped at a commit for worker shutdown, handing off rows_written={e.rows_written}",
+ f"repartition: stopped at a commit for worker shutdown, handing off rows_written={e.rows_written}: {e}",
rows_written=e.rows_written,
)
DELTA_REPARTITION_TOTAL.labels(outcome="handed_off").inc()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_repartition_table.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_repartition_table.py
index 2ad8a2f30d06..b8c10b6960d0 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
@@ -345,7 +345,13 @@ class TestBudgetExhaustion:
assert "warehouse_repartition_failed" not in emitted
assert "warehouse_repartition_skipped" in emitted
- @parameterized.expand([("first_attempt", 0), ("last_attempt_before_give_up", 2)])
+ @parameterized.expand(
+ [
+ ("first_attempt", 0, False, WorkerShuttingDownError),
+ ("last_attempt_before_give_up", 2, False, WorkerShuttingDownError),
+ ("attempt_that_temporal_cancelled", 1, True, asyncio.CancelledError),
+ ]
+ )
@patch(f"{MODULE}.capture_exception")
@patch(f"{MODULE}.capture_repartition_event")
@patch(f"{MODULE}.HeartbeaterSync")
@@ -353,10 +359,12 @@ class TestBudgetExhaustion:
@patch(f"{MODULE}.DeltaTableRef")
@patch(f"{MODULE}.ExternalDataJob")
@patch(f"{MODULE}.ExternalDataSchema")
- def test_a_worker_shutdown_hands_the_rewrite_off_without_burning_an_attempt(
+ def test_a_stop_request_hands_the_repartition_off_without_burning_an_attempt(
self,
_name: str,
prior_attempts: int,
+ cancelled: bool,
+ expected_error: type[BaseException],
mock_schema_model: MagicMock,
_mock_job_model: MagicMock,
_mock_helper_cls: MagicMock,
@@ -381,9 +389,12 @@ class TestBudgetExhaustion:
mock_repartition.side_effect = rewrite_until_asked_to_stop
environment = ActivityEnvironment()
- environment.worker_shutdown()
+ if cancelled:
+ environment.cancel()
+ else:
+ environment.worker_shutdown()
- with pytest.raises(WorkerShuttingDownError):
+ with pytest.raises(expected_error):
environment.run(
_maybe_repartition_table,
RepartitionActivityInputs(team_id=TEAM_ID, schema_id=SCHEMA_ID, job_id=JOB_ID, source_id=SOURCE_ID),