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): resume budget-exceeded repartition instead of restarting (#80079)

Tom Owers2c0aef131c4e
diff --git a/products/warehouse_sources/backend/models/external_data_schema.py b/products/warehouse_sources/backend/models/external_data_schema.py
index eb611e12acc9..c875e507958e 100644
--- a/products/warehouse_sources/backend/models/external_data_schema.py
+++ b/products/warehouse_sources/backend/models/external_data_schema.py
@@ -77,7 +77,7 @@ class ExternalDataSchema(ModelActivityMixin, CreatedMetaFields, UpdatedMetaField
# ignored by version-migration tooling — only the user changes it. Not available for
# webhook-sync schemas (webhook payload versions are configured per source at the vendor).
api_version = models.CharField(max_length=128, null=True, blank=True)
- # { "incremental_field": string, "incremental_field_type": string, "incremental_field_last_value": any, "incremental_field_earliest_value": any, "incremental_field_lookback_seconds": int | None, "reset_pipeline": bool, "partitioning_enabled": bool, "partition_count": int, "partition_size": int, "partition_mode": str, "partitioning_keys": list[str], "chunk_size_override": int | None, "primary_key_columns": list[str] | None, "xmin_last_value": int, "xmin_ceiling": int, "xmin_num_wraparound": int, "max_partition_bytes": int, "last_repartition_at": iso8601 str, "repartition_pending": { "partition_mode": str, "partition_format": str | None, "partition_count": int | None, "partition_size": int | None, "partition_keys": list[str], "trigger_reason": str }, "repartition_swap": { "state": "ready", "temp_uri": str, "live_uri": str } }
+ # { "incremental_field": string, "incremental_field_type": string, "incremental_field_last_value": any, "incremental_field_earliest_value": any, "incremental_field_lookback_seconds": int | None, "reset_pipeline": bool, "partitioning_enabled": bool, "partition_count": int, "partition_size": int, "partition_mode": str, "partitioning_keys": list[str], "chunk_size_override": int | None, "primary_key_columns": list[str] | None, "xmin_last_value": int, "xmin_ceiling": int, "xmin_num_wraparound": int, "max_partition_bytes": int, "last_repartition_at": iso8601 str, "repartition_pending": { "partition_mode": str, "partition_format": str | None, "partition_count": int | None, "partition_size": int | None, "partition_keys": list[str], "trigger_reason": str }, "repartition_swap": { "state": "ready", "temp_uri": str, "live_uri": str }, "repartition_rewrite": { "temp_uri": str, "rows_written": int, "target": dict } }
sync_type_config = models.JSONField(
default=dict,
blank=True,
@@ -484,6 +484,22 @@ class ExternalDataSchema(ModelActivityMixin, CreatedMetaFields, UpdatedMetaField
return swap
return None
+ @property
+ def repartition_rewrite(self) -> dict[str, Any] | None:
+ """Checkpoint of a rewrite that ran out of activity budget before finishing streaming.
+
+ Its temp table holds a scan-ordered prefix of the live table's rows. The next attempt resumes
+ appending from that offset instead of re-streaming from row 0, so a table too large to rewrite
+ in one activity converges across attempts rather than giving up terminally. Cleared once temp
+ is fully built (a swap is staged) or when the controller gives up. Shape:
+ {"temp_uri": str, "rows_written": int, "target": dict}.
+ """
+ if self.sync_type_config:
+ marker = self.sync_type_config.get("repartition_rewrite", None)
+ if isinstance(marker, dict):
+ return marker
+ return None
+
@property
def repartition_claim(self) -> dict[str, Any] | None:
"""The fencing claim of the newest repartition attempt: {"token", "job_id", "claimed_at"}.
@@ -537,6 +553,14 @@ class ExternalDataSchema(ModelActivityMixin, CreatedMetaFields, UpdatedMetaField
self.sync_type_config.pop("repartition_swap", None)
self._save_sync_type_config()
+ def set_repartition_rewrite(self, checkpoint: dict[str, Any]) -> None:
+ self.sync_type_config["repartition_rewrite"] = checkpoint
+ self._save_sync_type_config()
+
+ def clear_repartition_rewrite(self) -> None:
+ self.sync_type_config.pop("repartition_rewrite", None)
+ self._save_sync_type_config()
+
@property
def delta_revive_required(self) -> dict[str, Any] | None:
"""Set when the live Delta table is readable but hollow — its log references data files that
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 913d876b0653..5f3b298720db 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
@@ -95,9 +95,19 @@ class RepartitionBudgetExceededError(Exception):
being killed by Temporal, which records nothing: the killed attempt keeps running as a zombie
until a claim check makes it stand down, standing down burns no attempt, so
`MAX_REPARTITION_ATTEMPTS` is never reached and the table re-enters the rewrite ahead of every
- later sync forever. A table whose rewrite cannot fit in one activity needs to be told so.
+ later sync forever.
+
+ Carries the partial progress (`rows_written`, `resolved`) so the caller can checkpoint the
+ half-built temp table: the next attempt resumes appending from that offset rather than
+ re-streaming from row 0, letting a table too large to rewrite in one activity converge across
+ attempts instead of failing the same way every time.
"""
+ def __init__(self, message: str, *, rows_written: int = 0, resolved: RepartitionTarget | None = None) -> None:
+ super().__init__(message)
+ self.rows_written = rows_written
+ self.resolved = resolved
+
class RepartitionSupersededError(Exception):
"""A newer repartition attempt has claimed this schema — this stale attempt must stop.
@@ -643,19 +653,26 @@ async def _rewrite_into_temp(
claim_recheck_interval_seconds: float = CLAIM_RECHECK_INTERVAL_SECONDS,
deadline: float | None = None,
total_rows: int | None = None,
+ skip_rows: int = 0,
) -> tuple[int, RepartitionTarget]:
- """Stream the live table into a fresh temp table under the new partition scheme.
+ """Stream the live table into a temp table under the new partition scheme.
- Returns (rows_written, resolved_target). The first batch resolves any auto-detected mode/format/
- keys so every subsequent batch is bucketed identically (a per-batch auto-detect could disagree).
- `ensure_claim` runs before the first batch and then at most once per
- `claim_recheck_interval_seconds`, so a superseded attempt stops within that window rather than
- paying a database round-trip per batch (see `CLAIM_RECHECK_INTERVAL_SECONDS`).
+ Returns (rows_written, resolved_target) — `rows_written` counts only the rows written by *this*
+ call. The first processed batch resolves any auto-detected mode/format/keys so every subsequent
+ batch is bucketed identically (a per-batch auto-detect could disagree). `ensure_claim` runs before
+ the first batch and then at most once per `claim_recheck_interval_seconds`, so a superseded attempt
+ stops within that window rather than paying a database round-trip per batch (see
+ `CLAIM_RECHECK_INTERVAL_SECONDS`).
`deadline` is a `time.monotonic()` value past which the rewrite gives up with
`RepartitionBudgetExceededError` rather than run until Temporal kills it. None runs unbounded.
`total_rows` is the source row count, used only to report progress as a percentage and an ETA.
+
+ `skip_rows` resumes a prior attempt that ran out of budget: temp already holds a scan-ordered
+ prefix of `skip_rows` rows, so this call reads-and-discards that many source rows (the source is
+ immutable during the rewrite, so the scan order is stable) and appends only the remainder. The
+ rewrite writes in `append` mode, so resuming builds on the existing temp rather than replacing it.
"""
await logger.ainfo(
f"repartition: rewrite starting target_scheme={_format_scheme(target)} total_rows={total_rows} "
@@ -722,6 +739,7 @@ async def _rewrite_into_temp(
await logger.ainfo(f"repartition: rewrite progress {_format_fields(fields)}", **fields)
last_claim_check: float | None = None
+ source_rows_read = 0
while True:
if ensure_claim is not None:
@@ -739,9 +757,22 @@ async def _rewrite_into_temp(
# this deadline exists to rescue.
if deadline is not None and time.monotonic() >= deadline:
raise RepartitionBudgetExceededError(
- f"rewrite exceeded its activity budget after {rows_written} rows written to {temp_uri}"
+ f"rewrite exceeded its activity budget after {rows_written} rows written to {temp_uri}",
+ rows_written=rows_written,
+ resolved=resolved,
)
+ # Resume: temp already holds the first `skip_rows` rows in scan order, so read past them and
+ # only append the remainder. The boundary batch is sliced so no row is written twice or lost.
+ if source_rows_read < skip_rows:
+ to_skip = min(batch.num_rows, skip_rows - source_rows_read)
+ source_rows_read += batch.num_rows
+ if to_skip == batch.num_rows:
+ continue
+ batch = batch.slice(to_skip)
+ else:
+ source_rows_read += batch.num_rows
+
table = pa.Table.from_batches([batch])
if table.num_rows == 0:
continue
@@ -848,8 +879,18 @@ async def repartition_table_in_place(
# marker's temp_uri is authoritative — it may be scoped to the attempt that built it.
swap = schema.repartition_swap
resuming = bool(swap and swap.get("state") == "ready")
- temp_uri = (swap or {}).get("temp_uri") if resuming else None
- if not temp_uri:
+
+ # Rewrite-resume path: a prior attempt ran out of activity budget with temp holding a prefix of
+ # the table. Continue appending to that temp instead of rebuilding from row 0. A staged swap wins
+ # (temp is already complete there), so only consider the checkpoint when not swap-resuming.
+ rewrite_checkpoint = None if resuming else schema.repartition_rewrite
+ resuming_rewrite = rewrite_checkpoint is not None
+
+ if resuming:
+ temp_uri = (swap or {}).get("temp_uri") or _temp_uri_for(live_uri, claim_token)
+ elif resuming_rewrite:
+ temp_uri = (rewrite_checkpoint or {}).get("temp_uri") or _temp_uri_for(live_uri, claim_token)
+ else:
temp_uri = _temp_uri_for(live_uri, claim_token)
await ensure_claim()
@@ -921,23 +962,83 @@ async def repartition_table_in_place(
temp_uri = _temp_uri_for(live_uri, claim_token)
if not resuming:
- # Fresh build: sweep every stale/orphaned temp variant, then stream the live table into ours.
- async with aget_s3_client(fresh_instance=True) as s3:
- await _purge_stale_temp_tables(s3, live_uri)
+ skip_rows = 0
+ rewrite_target = target
+ if resuming_rewrite:
+ # A prior attempt ran out of budget with temp holding a scan-ordered prefix of the table.
+ # Resuming skips that prefix and appends the rest, which is only correct while live is
+ # byte-identical to when the checkpoint was written: the sync's merge runs after a
+ # swallowed repartition failure, so on any run where that merge committed, live has grown
+ # and the recorded prefix no longer lines up with the current scan. The Delta version is
+ # the fence — equal means no commit has touched live since, so the prefix still holds.
+ # A checkpoint whose temp is unreadable, larger than live, or built against a different
+ # live version is unusable: discard it and rebuild fresh from the still-intact live table.
+ live_version = await asyncio.to_thread(old_delta.version)
+ checkpoint_version = (rewrite_checkpoint or {}).get("live_version")
+ temp_rows = await _valid_delta_row_count(temp_uri, storage_options)
+ if temp_rows is None or temp_rows > old_row_count or checkpoint_version != live_version:
+ await logger.awarning(
+ f"repartition: rewrite checkpoint is unusable (temp_rows={temp_rows} live={old_row_count} "
+ f"checkpoint_version={checkpoint_version} live_version={live_version}), discarding and "
+ f"rebuilding fresh schema_id={schema.id}",
+ schema_id=str(schema.id),
+ )
+ await asyncio.to_thread(schema.clear_repartition_rewrite)
+ resuming_rewrite = False
+ temp_uri = _temp_uri_for(live_uri, claim_token)
+ else:
+ skip_rows = temp_rows
+ checkpoint_target = (rewrite_checkpoint or {}).get("target")
+ if checkpoint_target:
+ # Pin the scheme the prior attempt resolved, so a resumed auto-detect can't pick a
+ # different one for the remaining rows than the ones already in temp.
+ rewrite_target = RepartitionTarget.from_dict(checkpoint_target)
+ await logger.ainfo(
+ f"repartition: resuming rewrite from {skip_rows}/{old_row_count} rows already written "
+ f"schema_id={schema.id}",
+ schema_id=str(schema.id),
+ )
+
+ if not resuming_rewrite:
+ # Fresh build: sweep every stale/orphaned temp variant, then stream the live table into ours.
+ async with aget_s3_client(fresh_instance=True) as s3:
+ await _purge_stale_temp_tables(s3, live_uri)
try:
rows_written, resolved = await _rewrite_into_temp(
old_delta=old_delta,
temp_uri=temp_uri,
storage_options=storage_options,
- target=target,
+ target=rewrite_target,
batch_size=batch_size,
logger=logger,
ensure_claim=ensure_claim,
deadline=deadline,
total_rows=old_row_count,
+ skip_rows=skip_rows,
)
- except (RepartitionSupersededError, RepartitionUnpartitionableError, RepartitionBudgetExceededError):
+ except RepartitionBudgetExceededError as e:
+ # Checkpoint the half-built temp so the next attempt resumes instead of re-streaming from
+ # row 0. Guard with a claim check first: a superseded zombie must not clobber the newer
+ # claimant's state (the check raises RepartitionSupersededError, which the caller handles
+ # by standing down without recording a failure). Only checkpoint real forward progress.
+ await ensure_claim()
+ partial_rows = await _valid_delta_row_count(temp_uri, storage_options)
+ if partial_rows:
+ live_version = await asyncio.to_thread(old_delta.version)
+ await asyncio.to_thread(
+ schema.set_repartition_rewrite,
+ {
+ "temp_uri": temp_uri,
+ "rows_written": partial_rows,
+ "target": (e.resolved or rewrite_target).to_dict(),
+ # Fences the resume: only valid while live stays at this version (see the
+ # resume path). A merge that commits between attempts bumps it and invalidates.
+ "live_version": live_version,
+ },
+ )
+ raise
+ except (RepartitionSupersededError, RepartitionUnpartitionableError):
raise
except Exception as e:
missing_path = _missing_live_object_path(e, live_uri)
@@ -960,6 +1061,7 @@ async def repartition_table_in_place(
)
await asyncio.to_thread(schema.clear_repartition_pending)
await asyncio.to_thread(schema.clear_repartition_swap)
+ await asyncio.to_thread(schema.clear_repartition_rewrite)
await logger.awarning(
f"repartition: live table references a missing data file, scheduling revive "
f"schema_id={schema.id} missing={missing_path}",
@@ -980,6 +1082,8 @@ async def repartition_table_in_place(
await asyncio.to_thread(
schema.set_repartition_swap, {"state": "ready", "temp_uri": temp_uri, "live_uri": live_uri}
)
+ # 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.
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 ff147a174524..5e40e069bfa1 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
@@ -47,6 +47,9 @@ def _schema(**kwargs):
"incremental_field": None,
"incremental_field_type": None,
"schema_metadata": None,
+ "repartition_rewrite": None,
+ "set_repartition_rewrite": Mock(),
+ "clear_repartition_rewrite": Mock(),
}
defaults.update(kwargs)
return SimpleNamespace(**defaults)
@@ -567,6 +570,54 @@ class TestRewriteIntoTemp:
written = deltalake.DeltaTable(temp_uri).to_pyarrow_table().num_rows
assert 0 < written < len(rows)
+ def test_resume_from_a_prefix_completes_the_table_exactly_once(self, tmp_path):
+ # A budget-exceeded rewrite leaves temp holding a scan-ordered prefix. Resuming with
+ # skip_rows=<prefix length> must append exactly the remaining rows: every source row present
+ # once, none duplicated, none dropped. This is the fix's core guarantee, and it also guards the
+ # assumption the skip relies on — that the scan order is stable across the two passes. A
+ # reordering would re-write rows already in temp and skip others, which this catches.
+ rows = [(i, datetime.datetime(2024, 1, 1) + datetime.timedelta(days=3 * i)) for i in range(8)]
+ live = _write_month_partitioned(str(tmp_path / "live"), rows)
+ temp_uri = str(tmp_path / "tmp")
+ target = RepartitionTarget(
+ partition_keys=["created_at"], trigger_reason="t", partition_mode="datetime", partition_format="day"
+ )
+
+ # Stop the first pass after the buffer has flushed once, so temp holds a partial prefix.
+ clock = Mock(side_effect=itertools.chain([0.0] * 4, itertools.repeat(100.0)))
+ with patch.object(repartition_module, "time", Mock(monotonic=clock)):
+ with pytest.raises(RepartitionBudgetExceededError):
+ asyncio.run(
+ _rewrite_into_temp(
+ old_delta=live,
+ temp_uri=temp_uri,
+ storage_options={},
+ target=target,
+ batch_size=2,
+ logger=logger,
+ deadline=50.0,
+ )
+ )
+ partial = deltalake.DeltaTable(temp_uri).to_pyarrow_table().num_rows
+ assert 0 < partial < len(rows)
+
+ asyncio.run(
+ _rewrite_into_temp(
+ old_delta=live,
+ temp_uri=temp_uri,
+ storage_options={},
+ target=target,
+ batch_size=2,
+ logger=logger,
+ skip_rows=partial,
+ )
+ )
+
+ final = deltalake.DeltaTable(temp_uri).to_pyarrow_table()
+ # Count plus set: every source id present exactly once (equal count rules out duplicates).
+ assert final.num_rows == len(rows)
+ assert set(final.column("id").to_pylist()) == set(range(len(rows)))
+
def test_a_finished_rewrite_beats_the_deadline(self, tmp_path):
# One source file, one batch, so the reader is exhausted on the second loop iteration. The
# clock is over the deadline by then: a rewrite that has already copied every row must still
@@ -1221,6 +1272,150 @@ class TestResumeWithInvalidTemp:
assert result["outcome"] == "completed"
+class TestRewriteCheckpointResume:
+ """A rewrite that runs out of activity budget checkpoints its half-built temp so the next attempt
+ resumes instead of re-streaming from row 0 — the loop that used to leave large tables giving up
+ terminally. The checkpoint is fenced on the live Delta version: the sync's merge runs after a
+ swallowed repartition failure, so a resume is only safe while live is unchanged."""
+
+ def _base_schema(self, **kwargs):
+ return _schema(
+ id="s1",
+ repartition_swap=None,
+ set_repartition_swap=Mock(),
+ clear_repartition_swap=Mock(),
+ clear_repartition_pending=Mock(),
+ set_repartition_rewrite=Mock(),
+ clear_repartition_rewrite=Mock(),
+ set_partitioning_enabled=Mock(),
+ stamp_last_repartition_at=Mock(),
+ **kwargs,
+ )
+
+ def test_budget_exceeded_checkpoints_the_partial_temp(self, tmp_path):
+ # On budget exhaustion the partial temp, its row count, the resolved scheme, and the live
+ # version are recorded so a later attempt can resume — and the error still propagates so the
+ # activity records the attempt.
+ live = _write_month_partitioned(
+ str(tmp_path / "live"), [(1, datetime.datetime(2024, 1, 5)), (2, datetime.datetime(2024, 2, 2))]
+ )
+ table_ref = _make_table_ref(get_delta_table=AsyncMock(return_value=live))
+ target = RepartitionTarget(
+ partition_keys=["created_at"], trigger_reason="t", partition_mode="datetime", partition_format="day"
+ )
+ schema = self._base_schema()
+
+ with (
+ patch.object(repartition_module, "aget_s3_client", return_value=_FakeS3CM(_fake_s3())),
+ patch.object(repartition_module, "_purge_stale_temp_tables", new=AsyncMock()),
+ patch.object(repartition_module, "_current_claim_token", return_value="tok"),
+ patch.object(repartition_module, "_valid_delta_row_count", new=AsyncMock(return_value=1)),
+ patch.object(
+ repartition_module,
+ "_rewrite_into_temp",
+ new=AsyncMock(
+ side_effect=RepartitionBudgetExceededError("out of budget", rows_written=1, resolved=target)
+ ),
+ ),
+ ):
+ with pytest.raises(RepartitionBudgetExceededError):
+ asyncio.run(
+ repartition_table_in_place(
+ table_ref=table_ref, schema=schema, target=target, logger=logger, claim_token="tok"
+ )
+ )
+
+ schema.set_repartition_rewrite.assert_called_once()
+ checkpoint = schema.set_repartition_rewrite.call_args.args[0]
+ assert checkpoint["rows_written"] == 1
+ assert checkpoint["live_version"] == live.version()
+ assert checkpoint["target"]["partition_format"] == "day"
+ assert checkpoint["temp_uri"].endswith("__repartitioned_tok")
+
+ def test_resumes_when_the_live_version_still_matches(self, tmp_path):
+ # Version matches → resume: append from the recorded offset into the checkpoint's own temp,
+ # without sweeping temps (a fresh rebuild would discard the prefix).
+ live = _write_month_partitioned(
+ str(tmp_path / "live"),
+ [
+ (1, datetime.datetime(2024, 1, 5)),
+ (2, datetime.datetime(2024, 2, 2)),
+ (3, datetime.datetime(2024, 3, 3)),
+ ],
+ )
+ table_ref = _make_table_ref(get_delta_table=AsyncMock(return_value=live))
+ target = RepartitionTarget(
+ partition_keys=["created_at"], trigger_reason="t", partition_mode="datetime", partition_format="day"
+ )
+ schema = self._base_schema(
+ repartition_rewrite={
+ "temp_uri": "s3://bucket/live__repartitioned_old",
+ "rows_written": 1,
+ "target": target.to_dict(),
+ "live_version": live.version(),
+ },
+ )
+
+ with (
+ patch.object(repartition_module, "_purge_stale_temp_tables", new=AsyncMock()) as purge,
+ patch.object(repartition_module, "_current_claim_token", return_value="tok"),
+ # First read validates the checkpoint temp (1 row); second validates the completed rewrite.
+ patch.object(repartition_module, "_valid_delta_row_count", new=AsyncMock(side_effect=[1, 3])),
+ patch.object(repartition_module, "_rewrite_into_temp", new=AsyncMock(return_value=(2, target))) as rewrite,
+ patch.object(repartition_module, "_swap_temp_into_live", new=AsyncMock()),
+ ):
+ result = asyncio.run(
+ repartition_table_in_place(
+ table_ref=table_ref, schema=schema, target=target, logger=logger, claim_token="tok"
+ )
+ )
+
+ purge.assert_not_awaited() # the prefix must not be swept
+ assert rewrite.await_args_list[0].kwargs["temp_uri"] == "s3://bucket/live__repartitioned_old"
+ assert rewrite.await_args_list[0].kwargs["skip_rows"] == 1
+ schema.clear_repartition_rewrite.assert_called_once() # obsolete once temp is complete
+ assert result["outcome"] == "completed"
+
+ def test_discards_the_checkpoint_when_the_live_version_moved_on(self, tmp_path):
+ # Version moved on (a merge committed between attempts) → the recorded prefix no longer lines up
+ # with the current scan. The checkpoint must be discarded and a fresh rebuild started into our
+ # own claim-scoped temp, never resumed — resuming would swap misaligned data over live.
+ live = _write_month_partitioned(
+ str(tmp_path / "live"), [(1, datetime.datetime(2024, 1, 5)), (2, datetime.datetime(2024, 2, 2))]
+ )
+ table_ref = _make_table_ref(get_delta_table=AsyncMock(return_value=live))
+ target = RepartitionTarget(
+ partition_keys=["created_at"], trigger_reason="t", partition_mode="datetime", partition_format="day"
+ )
+ schema = self._base_schema(
+ repartition_rewrite={
+ "temp_uri": "s3://bucket/live__repartitioned_old",
+ "rows_written": 1,
+ "target": target.to_dict(),
+ "live_version": live.version() + 999,
+ },
+ )
+
+ with (
+ patch.object(repartition_module, "aget_s3_client", return_value=_FakeS3CM(_fake_s3())),
+ patch.object(repartition_module, "_purge_stale_temp_tables", new=AsyncMock()) as purge,
+ patch.object(repartition_module, "_current_claim_token", return_value="tok"),
+ patch.object(repartition_module, "_valid_delta_row_count", new=AsyncMock(side_effect=[1, 2])),
+ patch.object(repartition_module, "_rewrite_into_temp", new=AsyncMock(return_value=(2, target))) as rewrite,
+ patch.object(repartition_module, "_swap_temp_into_live", new=AsyncMock()),
+ ):
+ asyncio.run(
+ repartition_table_in_place(
+ table_ref=table_ref, schema=schema, target=target, logger=logger, claim_token="tok"
+ )
+ )
+
+ schema.clear_repartition_rewrite.assert_called() # stale checkpoint dropped
+ purge.assert_awaited_once() # fresh rebuild sweeps orphans
+ assert rewrite.await_args_list[0].kwargs["temp_uri"].endswith("__repartitioned_tok")
+ assert rewrite.await_args_list[0].kwargs["skip_rows"] == 0
+
+
class TestClaimFencing:
"""A heartbeat-timed-out attempt keeps running as a zombie while its Temporal retry starts; both
used to write into the same temp table and corrupt each other (headless `_delta_log`, inflated row
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 a682e2cf5c46..09f80c4a76fa 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
@@ -402,6 +402,7 @@ def _maybe_repartition_table(inputs: RepartitionActivityInputs, logger: Filterin
# daily instead.
schema.refresh_from_db(fields=["sync_type_config"])
schema.clear_repartition_pending()
+ schema.clear_repartition_rewrite()
schema.stamp_last_repartition_at()
props = base_event_props(schema, schema.source, inputs.job_id)
props.update({"trigger_reason": trigger_reason, "reason": str(e)})
@@ -543,6 +544,9 @@ def _handle_failure(
props["final"] = True
schema.clear_repartition_pending()
schema.clear_repartition_swap()
+ # 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.
+ 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 and
# the layout is unchanged, so detection re-flags the table immediately with `attempts` back
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 22239d4f323f..3af52b01e49e 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
@@ -232,10 +232,14 @@ class TestBudgetExhaustion:
schema.clear_repartition_pending.assert_called_once()
schema.stamp_last_repartition_at.assert_called_once()
schema.set_repartition_pending.assert_not_called()
+ # The rewrite checkpoint must be dropped too, or the next flag cycle would resume the same
+ # doomed temp and the give-up would never take effect.
+ schema.clear_repartition_rewrite.assert_called_once()
else:
assert schema.set_repartition_pending.call_args.args[0]["attempts"] == prior_attempts + 1
schema.clear_repartition_pending.assert_not_called()
schema.stamp_last_repartition_at.assert_not_called()
+ schema.clear_repartition_rewrite.assert_not_called()
class TestFeatureFlagGate: