:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(warehouse-sources): stop rewrites that OOM-kill their worker looping forever (#86717)
Daniel RC1ea44f50c571
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/repartition.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/repartition.pyindex af4c5ca2f649..bae21a5c3740 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@@ -60,8 +60,13 @@ if TYPE_CHECKING:# Coarse → fine. A datetime table that's OOMing steps one tier finer each repartition cycle.DATETIME_FORMAT_TIERS: list[PartitionFormat] = ["month", "week", "day", "hour"]-# Rows per streamed record-batch. Bounds the repartition's peak memory independent of partition size.-DEFAULT_REPARTITION_BATCH_SIZE = 50_000+# Rows per scanned record-batch. A row count cannot bound memory on its own — the same count is a few+# MB of a narrow table and gigabytes of nested records — so this is deliberately low rather than+# tuned, the way `MAX_FETCH_PAGE_ROWS` is in `sources/common/sql/batching.py`. It bounds the window+# that is still unmeasured when the scan hands a batch over; `REWRITE_BUFFER_MAX_BYTES` bounds what+# is materialised, from real measurements. Low is cheap here: the parquet row group is read either+# way, and the coalescing buffer merges small batches back before any commit.+DEFAULT_REPARTITION_BATCH_SIZE = 1_000# Minimum gap between claim re-reads during the rewrite loop. The loop yields at least one batch per# source *file*, so an over-fragmented table (the exact kind being repartitioned) produces one batch@@ -81,6 +86,11 @@ CLAIM_RECHECK_INTERVAL_SECONDS = 10.0# that matters — the win comes from merging thousands of KB-sized batches, not from filling the cap.REWRITE_BUFFER_MAX_BYTES = DEFAULT_MAX_TABLE_BYTES // 2+# Arrow's default 16-batch readahead keeps memory in flight that never reaches the coalescing buffer,+# so no buffer budget bounds it. Fragment readahead is left at its default: serialising file reads+# would cost the most on the many-small-files tables this module rewrites.+REWRITE_BATCH_READAHEAD = 1+TEMP_URI_SUFFIX = "__repartitioned"@@ -721,7 +731,12 @@ async def _rewrite_into_temp()dataset = await asyncio.to_thread(old_delta.to_pyarrow_dataset)- reader = await asyncio.to_thread(lambda: dataset.scanner(batch_size=batch_size).to_reader())+ reader = await asyncio.to_thread(+ lambda: dataset.scanner(+ batch_size=batch_size,+ batch_readahead=REWRITE_BATCH_READAHEAD,+ ).to_reader()+ )live_schema = await asyncio.to_thread(old_delta.schema)resolved: RepartitionTarget | None = Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test_repartition.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test_repartition.pyindex 1f6eb5a3e6b8..2c8f2c4ec566 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@@ -24,6 +24,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.parappend_partition_key_to_table,)from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.repartition import (+ REWRITE_BATCH_READAHEAD,RepartitionBudgetExceededError,RepartitionSupersededError,RepartitionTarget,@@ -559,6 +560,38 @@ class TestRewriteIntoTemp:sample = json.loads(redis.get(run_key("repartition:rw-test")))assert sample["peak_buffer_bytes"] > 0+ def test_scanner_bounds_readahead_so_the_scan_cannot_outrun_the_buffer(self, tmp_path):+ # The default 16-batch prefetch is invisible to the coalescing buffer.+ rows = [(i, datetime.datetime(2024, 1, 1 + (i % 28))) for i in range(40)]+ old_delta = _write_month_partitioned(str(tmp_path / "src"), rows)+ captured: dict = {}+ real_scanner = old_delta.to_pyarrow_dataset().scanner++ def spy(**kwargs):+ captured.update(kwargs)+ return real_scanner(**kwargs)++ with patch.object(deltalake.DeltaTable, "to_pyarrow_dataset") as dataset:+ dataset.return_value = SimpleNamespace(scanner=spy)+ asyncio.run(+ _rewrite_into_temp(+ old_delta=old_delta,+ temp_uri=str(tmp_path / "tmp"),+ storage_options={},+ target=RepartitionTarget(+ partition_keys=["created_at"],+ trigger_reason="test",+ partition_mode="datetime",+ partition_format="day",+ ),+ batch_size=10,+ logger=logger,+ )+ )++ assert captured["batch_readahead"] == REWRITE_BATCH_READAHEAD+ assert "fragment_readahead" not in captured+def test_stops_mid_stream_once_the_deadline_passes(self, tmp_path):rows = [(1, datetime.datetime(2024, 1, 5)),@@ -830,7 +863,7 @@ class TestRewriteIntoTemp:old_delta = SimpleNamespace(to_pyarrow_dataset=lambda: SimpleNamespace(- scanner=lambda batch_size: SimpleNamespace(to_reader=lambda: _FakeReader(batch_table))+ scanner=lambda **kwargs: SimpleNamespace(to_reader=lambda: _FakeReader(batch_table))),schema=lambda: deltalake.Schema.from_arrow(live_pa_schema),)diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test_repartition_controller.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test_repartition_controller.pyindex ac548485cee3..6e3db6a91f42 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@@ -3,6 +3,7 @@ import uuidimport asyncioimport datetimeimport tempfile+import contextlibimport pytestfrom unittest.mock import AsyncMock, MagicMock, patch@@ -31,6 +32,9 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.repRepartitionSupersededError,RepartitionUnpartitionableError,)+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.repartition_controller import (+ MAX_REPARTITION_ATTEMPTS,+)from products.warehouse_sources.backend.temporal.data_imports.workflow_activities import repartition_tablefrom products.warehouse_sources.backend.temporal.data_imports.workflow_activities.repartition_table import (RepartitionActivityInputs,@@ -768,6 +772,92 @@ class TestRepartitionActivity:assert samples and samples[0]["phase"] == "repartition"assert samples[0]["schema_id"] == str(schema.id)+ def test_a_rewrite_whose_worker_dies_still_burns_an_attempt(self, team):+ # A worker OOM-killed mid-rewrite records nothing, so the cap never moved and these retried+ # forever.+ schema = _make_schema(team, {})+ schema.set_repartition_pending(+ {+ "partition_mode": "md5",+ "partition_count": 4,+ "partition_keys": ["id"],+ "trigger_reason": "t",+ "attempts": 0,+ }+ )++ def killed_mid_rewrite(**kwargs):+ raise KeyboardInterrupt("worker killed")++ # Three attempts run and die; the next evaluation finds the cap spent and gives up.+ for _ in range(MAX_REPARTITION_ATTEMPTS + 1):+ with contextlib.suppress(BaseException):+ self._run(self._inputs(team, schema), AsyncMock(side_effect=killed_mid_rewrite))+ schema.refresh_from_db()++ assert schema.repartition_pending is None++ def test_an_overlapping_attempt_charge_survives_another_attempts_refund(self, team):+ # Overlapping attempts must not erase each other's charge, or the cap never counts up and the+ # retry loop this change exists to stop comes back.+ schema = _make_schema(team, {})+ schema.set_repartition_pending(+ {+ "partition_mode": "md5",+ "partition_count": 4,+ "partition_keys": ["id"],+ "trigger_reason": "t",+ "attempts": 2,+ }+ )+ # This attempt charged 0 -> 1; a concurrent one then charged 1 -> 2. Refunding to 0 here would+ # erase that second charge.+ repartition_table._refund_attempt(schema, 0, logger)++ schema.refresh_from_db()+ pending = schema.repartition_pending+ assert pending is not None and pending["attempts"] == 2++ def test_a_staged_swap_is_never_abandoned_by_the_attempt_cap(self, team):+ # An interrupted swap may already have deleted live, leaving temp the only intact copy. Giving+ # up clears the marker that points at it, so the next sync would bootstrap an empty table.+ schema = _make_schema(team, {})+ schema.set_repartition_pending(+ {+ "partition_mode": "md5",+ "partition_count": 4,+ "partition_keys": ["id"],+ "trigger_reason": "t",+ "attempts": MAX_REPARTITION_ATTEMPTS,+ }+ )+ schema.set_repartition_swap({"state": "ready", "temp_uri": "s3://t/__repartitioned", "live_uri": "s3://t"})++ mocked = AsyncMock(return_value={"outcome": "completed"})+ self._run(self._inputs(team, schema), mocked)++ # The rewrite runs and resumes the swap, rather than the cap short-circuiting it.+ mocked.assert_awaited_once()++ def test_a_superseded_attempt_costs_no_attempt(self, team):+ # A zombie displaced by a newer claim is not evidence the rewrite is doomed.+ schema = _make_schema(team, {})+ schema.set_repartition_pending(+ {+ "partition_mode": "md5",+ "partition_count": 4,+ "partition_keys": ["id"],+ "trigger_reason": "t",+ "attempts": 0,+ }+ )++ self._run(self._inputs(team, schema), AsyncMock(side_effect=RepartitionSupersededError("newer claim")))++ schema.refresh_from_db()+ assert schema.repartition_pending is not None+ assert schema.repartition_pending["attempts"] == 0+def test_unpartitionable_clears_pending(self, team):schema = _make_schema(team, {})schema.set_repartition_pending(diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/repartition_table.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/repartition_table.pyindex a8b3d6cdd831..95c81bc0465d 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@@ -356,6 +356,15 @@ def _maybe_repartition_table(inputs: RepartitionActivityInputs, logger: Filterintarget = RepartitionTarget.from_dict(pending) if pending is not None else _target_from_schema(schema)trigger_reason = (pending or {}).get("trigger_reason", "resume")+ # `_handle_failure` also gives up at the cap, but only for an attempt that survives to run it.+ # A rewrite whose worker is OOM-killed never reaches it, so the count has to be read here too.+ # Never while a swap is staged: an interrupted swap may already have deleted live, leaving temp+ # the only intact copy, and `_give_up` clears the marker that points at it. A ready swap has to be+ # completed however many attempts it took to get here.+ if swap is None and _exhausted_attempts(pending):+ _give_up(inputs, schema, pending, trigger_reason, logger)+ return+started_props = base_event_props(schema, schema.source, inputs.job_id)started_props["trigger_reason"] = trigger_reasoncapture_repartition_event("warehouse_repartition_started", started_props)@@ -370,6 +379,12 @@ def _maybe_repartition_table(inputs: RepartitionActivityInputs, logger: Filterin{"token": claim_token, "job_id": inputs.job_id, "claimed_at": timezone.now().isoformat()})+ # Charged before the rewrite and refunded on the stand-down paths below. Charging on failure+ # instead bounds nothing: a worker killed mid-rewrite records no outcome, so the cap never moves.+ # A staged swap runs no rewrite (temp is already complete), so its recovery is not a rewrite+ # attempt and is not charged, the same reason the give-up above exempts it.+ charged_attempts = None if swap is not None else _charge_attempt(schema, pending, logger)+start = time.monotonic()try:# HeartbeaterSync heartbeats on a background thread while the (possibly long) rewrite streams,@@ -406,7 +421,9 @@ def _maybe_repartition_table(inputs: RepartitionActivityInputs, logger: Filterinlogger.warning(f"repartition: {e}")DELTA_REPARTITION_TOTAL.labels(team_id=str(inputs.team_id),- outcome=_handle_budget_exceeded(inputs, schema, pending, trigger_reason, e, claim_token, logger),+ outcome=_handle_budget_exceeded(+ inputs, schema, pending, trigger_reason, e, claim_token, logger, charged_attempts+ ),).inc()returnexcept RepartitionSupersededError:@@ -416,6 +433,7 @@ def _maybe_repartition_table(inputs: RepartitionActivityInputs, logger: Filterin# set and no way to tell a stood-down attempt from one that vanished.logger.info("repartition: superseded by a newer attempt, standing down")DELTA_REPARTITION_TOTAL.labels(team_id=str(inputs.team_id), outcome="superseded").inc()+ _refund_attempt(schema, charged_attempts, logger)_capture_stood_down(schema, inputs, trigger_reason, "superseded", logger)returnexcept RepartitionUnpartitionableError as e:@@ -439,6 +457,7 @@ def _maybe_repartition_table(inputs: RepartitionActivityInputs, logger: Filterin# Temporal reschedules the activity — so propagate rather than record it, else every deploy fills# error tracking with `warehouse_repartition_failed` noise and burns a repartition attempt.logger.info("repartition: cancelled mid-run, will be retried")+ _refund_attempt(schema, charged_attempts, logger)raiseexcept Exception as e:# Do NOT re-raise: a repartition failure must not block the sync — the table is retried on a@@ -447,6 +466,7 @@ def _maybe_repartition_table(inputs: RepartitionActivityInputs, logger: Filterin# Some cancellations surface through async_to_sync as an Exception-derived CancelledError.# Treat identically to the branch above: propagate, never record it as a failure.logger.info("repartition: cancelled mid-run, will be retried")+ _refund_attempt(schema, charged_attempts, logger)raiseif not _still_claimant(schema, claim_token):# The error is almost certainly collateral from the newer claimant clobbering our S3 state@@ -454,6 +474,7 @@ def _maybe_repartition_table(inputs: RepartitionActivityInputs, logger: Filterin# failure would burn an attempt and pollute error tracking with self-inflicted noise.logger.info("repartition: failed after being superseded, standing down", exc_info=True)DELTA_REPARTITION_TOTAL.labels(team_id=str(inputs.team_id), outcome="superseded").inc()+ _refund_attempt(schema, charged_attempts, logger)_capture_stood_down(schema, inputs, trigger_reason, "superseded_after_error", logger)returnif _is_transient_infra_error(e):@@ -475,14 +496,18 @@ def _maybe_repartition_table(inputs: RepartitionActivityInputs, logger: Filterin# and error-tracking events here would spam (and can trigger automated remediation);# the log line and the transient metric carry the visibility.logger.warning("repartition: transient infra error, re-raising for activity retry", exc_info=True)+ _refund_attempt(schema, charged_attempts, logger)raise ApplicationError(f"Transient infra error during admin-staged repartition: {e}",type="TransientRepartitionError",) from elogger.warning("repartition: transient infra error, will retry on next sync", exc_info=True)+ _refund_attempt(schema, charged_attempts, logger)_capture_stood_down(schema, inputs, trigger_reason, "transient_infra_error", logger)return- failure_outcome = _handle_failure(inputs, schema, pending, trigger_reason, e, claim_token, logger)+ failure_outcome = _handle_failure(+ inputs, schema, pending, trigger_reason, e, claim_token, logger, charged_attempts+ )DELTA_REPARTITION_TOTAL.labels(team_id=str(inputs.team_id), outcome=failure_outcome).inc()return@@ -490,6 +515,15 @@ def _maybe_repartition_table(inputs: RepartitionActivityInputs, logger: FilterinDELTA_REPARTITION_DURATION_SECONDS.labels(team_id=str(inputs.team_id), schema_id=inputs.schema_id).observe(duration)DELTA_REPARTITION_TOTAL.labels(team_id=str(inputs.team_id), outcome=result.get("outcome", "completed")).inc()+ if result.get("outcome") != "completed":+ # A non-completed result is a skip that ran no rewrite (live unreadable or no delta table on+ # disk), and those paths leave `repartition_pending` set so a later run retries once the table+ # is revived. The attempt was charged up front, so without this refund three such skips would+ # spend the whole cap without a rewrite ever running, and the next run would `_give_up`,+ # discarding the queued rewrite and stamping the cooldown that blocks re-detection. A skip is+ # not a failed attempt, so it must not count. (A completed rewrite clears the marker itself.)+ _refund_attempt(schema, charged_attempts, logger)+props = base_event_props(schema, schema.source, inputs.job_id)props["trigger_reason"] = trigger_reasonprops["duration_seconds"] = duration@@ -539,6 +573,7 @@ def _handle_budget_exceeded(error: RepartitionBudgetExceededError,claim_token: str,logger: FilteringBoundLogger,+ charged_attempts: int | None = None,) -> str:"""Record a rewrite that ran out of one activity's budget, distinguishing progress from a stall.@@ -572,6 +607,7 @@ def _handle_budget_exceeded(claim = schema.repartition_claimif not (claim and claim.get("token") == claim_token):logger.info("repartition: superseded (claim changed under us), standing down without recording failure")+ _refund_attempt(schema, charged_attempts, logger)return "superseded"pending = schema.repartition_pending or pending or {}@@ -603,7 +639,90 @@ def _handle_budget_exceeded(rows_written=error.rows_written,resumed_from=error.resumed_from,)- return _handle_failure(inputs, schema, pending, trigger_reason, error, claim_token, logger)+ return _handle_failure(inputs, schema, pending, trigger_reason, error, claim_token, logger, charged_attempts)+++def _exhausted_attempts(pending: dict[str, Any] | None) -> bool:+ return pending is not None and int(pending.get("attempts", 0)) >= MAX_REPARTITION_ATTEMPTS+++def _give_up(+ inputs: RepartitionActivityInputs,+ schema: ExternalDataSchema,+ pending: dict[str, Any] | None,+ trigger_reason: str,+ logger: FilteringBoundLogger,+) -> None:+ """Abandon a rewrite whose attempts are spent, clearing the markers that would re-arm it.++ Stamps the cooldown as well, or detection re-flags the table on the next sync and the attempts+ start over — same reason `_handle_failure` does.+ """+ logger.warning(+ f"repartition: giving up after {MAX_REPARTITION_ATTEMPTS} attempts that did not survive to "+ f"record an outcome schema_id={inputs.schema_id}",+ schema_id=inputs.schema_id,+ )+ # Stake a fresh claim before clearing anything. This runs before the activity mints its own, so a+ # timed-out predecessor may still be running and still hold the old token; leaving it valid would+ # let it pass `ensure_claim` and go on mutating live after we declared the rewrite abandoned.+ schema.set_repartition_claim(+ {"token": str(uuid.uuid4()), "job_id": inputs.job_id, "claimed_at": timezone.now().isoformat()}+ )+ schema.clear_repartition_pending()+ schema.clear_repartition_swap()+ 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,+ "attempts": int((pending or {}).get("attempts", 0)),+ "final": True,+ "error_type": "RepartitionAttemptsExhausted",+ "error_message": "attempts exhausted without any surviving to record an outcome",+ }+ )+ capture_repartition_event("warehouse_repartition_failed", props)+ DELTA_REPARTITION_TOTAL.labels(team_id=str(inputs.team_id), outcome="failed").inc()+++def _charge_attempt(+ schema: ExternalDataSchema, pending: dict[str, Any] | None, logger: FilteringBoundLogger+) -> int | None:+ """Record this attempt against the retry cap before the rewrite runs; return the prior count.++ `_refund_attempt` restores that count. None means nothing was charged (no pending marker, or a DB+ failure) — bookkeeping must never block the rewrite.+ """+ if pending is None:+ return None+ prior = int(pending.get("attempts", 0))+ try:+ schema.set_repartition_pending({**pending, "attempts": prior + 1})+ except Exception:+ logger.warning("repartition: could not charge attempt, proceeding uncharged", exc_info=True)+ return None+ return prior+++def _refund_attempt(schema: ExternalDataSchema, prior: int | None, logger: FilteringBoundLogger) -> None:+ """Undo `_charge_attempt` for a stand-down that must not count against the retry cap.++ Supersession, transient infra and a checkpoint that advanced are noise or progress, not evidence+ the rewrite is doomed. Refunds only when the persisted count is still the one this attempt wrote:+ overlapping attempts otherwise let each refund erase the other's charge, and a cap that never+ counts up is the loop this whole change exists to stop.+ """+ if prior is None:+ return+ try:+ schema.refresh_from_db(fields=["sync_type_config"])+ pending = schema.repartition_pending+ if pending is not None and int(pending.get("attempts", 0)) == prior + 1:+ schema.set_repartition_pending({**pending, "attempts": prior})+ except Exception:+ logger.warning("repartition: could not refund attempt", exc_info=True)def _handle_failure(@@ -614,6 +733,7 @@ def _handle_failure(error: Exception,claim_token: str,logger: FilteringBoundLogger,+ charged_attempts: int | None = None,) -> str:"""Record a failed attempt; give up (and clear the flag) after MAX_REPARTITION_ATTEMPTS.@@ -627,9 +747,13 @@ def _handle_failure(claim = schema.repartition_claimif not (claim and claim.get("token") == claim_token):logger.info("repartition: superseded (claim changed under us), standing down without recording failure")+ _refund_attempt(schema, charged_attempts, logger)return "superseded"pending = schema.repartition_pending or pending or {}- attempts = int(pending.get("attempts", 0)) + 1+ # Use the charge this attempt made rather than re-reading it: the persisted value is only visible+ # after a round trip, and the count must not depend on that landing. Falls back to incrementing+ # what was read when nothing was charged.+ attempts = (charged_attempts + 1) if charged_attempts is not None else int(pending.get("attempts", 0)) + 1props = base_event_props(schema, schema.source, inputs.job_id)props.update(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.pyindex 578b6502abfb..8d5be47ca48a 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@@ -17,6 +17,9 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.core.repartition import (RepartitionBudgetExceededError,)+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.repartition_controller import (+ MAX_REPARTITION_ATTEMPTS,+)from products.warehouse_sources.backend.temporal.data_imports.workflow_activities.repartition_table import (RepartitionActivityInputs,_maybe_flag_pre_extraction,@@ -63,6 +66,9 @@ def _schema(# The failure bookkeeping re-reads the claim to check it still owns the schema, so the mock has# to actually remember the token the activity just staked.schema.set_repartition_claim.side_effect = lambda claim: setattr(schema, "repartition_claim", claim)+ # Same for the pending marker: the attempt is charged before the rewrite and refunded after, and+ # the refund only fires when it reads back the count it wrote.+ schema.set_repartition_pending.side_effect = lambda p: setattr(schema, "repartition_pending", p)return schema@@ -236,12 +242,13 @@ class TestBudgetExhaustion:if expect_give_up:schema.clear_repartition_pending.assert_called_once()schema.stamp_last_repartition_at.assert_called_once()- schema.set_repartition_pending.assert_not_called()+ # Charged once, then the marker is cleared rather than re-armed at a higher count.+ assert schema.set_repartition_pending.call_count == 1# 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+ assert schema.repartition_pending["attempts"] == prior_attempts + 1schema.clear_repartition_pending.assert_not_called()schema.stamp_last_repartition_at.assert_not_called()schema.clear_repartition_rewrite.assert_not_called()@@ -389,6 +396,94 @@ class TestBudgetExhaustion:else:assert schema.set_repartition_pending.call_args.args[0]["attempts"] == prior_attempts + 1+ @patch(f"{MODULE}.capture_exception")+ @patch(f"{MODULE}.capture_repartition_event")+ @patch(f"{MODULE}.HeartbeaterSync")+ @patch(f"{MODULE}.repartition_table_in_place", new_callable=AsyncMock)+ @patch(f"{MODULE}.DeltaTableRef")+ @patch(f"{MODULE}.is_auto_repartition_enabled", return_value=True)+ @patch(f"{MODULE}.ExternalDataJob")+ @patch(f"{MODULE}.ExternalDataSchema")+ def test_a_staged_swap_is_resumed_even_after_attempts_are_spent(+ self,+ mock_schema_model: MagicMock,+ _mock_job_model: MagicMock,+ _mock_enabled: MagicMock,+ _mock_helper_cls: MagicMock,+ mock_repartition: AsyncMock,+ _mock_heartbeater: MagicMock,+ mock_capture_event: MagicMock,+ _mock_capture_exception: MagicMock,+ ) -> None:+ # A worker can die inside the swap after recording the ready marker, leaving temp the source of+ # truth and live possibly already deleted, with the pending marker still carrying the spent+ # count. The attempt cap must not abandon that swap: giving up clears the marker and disarms the+ # missing-live recovery, so the swap is driven to completion (resumed) instead. The rewrite+ # already ran, so this recovery must also not be charged against the cap.+ schema = _schema(+ name="public.usages",+ s3_folder_name="usages",+ pending={**PENDING_TARGET, "attempts": MAX_REPARTITION_ATTEMPTS},+ swap={"state": "ready"},+ )+ mock_schema_model.objects.select_related.return_value.get.return_value = schema+ mock_repartition.return_value = {"outcome": "completed"}++ _maybe_repartition_table(+ RepartitionActivityInputs(team_id=TEAM_ID, schema_id=SCHEMA_ID, job_id=JOB_ID, source_id=SOURCE_ID),+ MagicMock(),+ )++ assert mock_repartition.await_count == 1+ schema.clear_repartition_swap.assert_not_called()+ schema.set_repartition_pending.assert_not_called()+ emitted = [c.args[0] for c in mock_capture_event.call_args_list]+ assert "warehouse_repartition_failed" not in emitted++ @parameterized.expand([("live_unreadable",), ("no_delta_table",)])+ @patch(f"{MODULE}.capture_exception")+ @patch(f"{MODULE}.capture_repartition_event")+ @patch(f"{MODULE}.HeartbeaterSync")+ @patch(f"{MODULE}.repartition_table_in_place", new_callable=AsyncMock)+ @patch(f"{MODULE}.DeltaTableRef")+ @patch(f"{MODULE}.is_auto_repartition_enabled", return_value=True)+ @patch(f"{MODULE}.ExternalDataJob")+ @patch(f"{MODULE}.ExternalDataSchema")+ def test_a_skipped_rewrite_does_not_consume_an_attempt(+ self,+ reason: str,+ mock_schema_model: MagicMock,+ _mock_job_model: MagicMock,+ _mock_enabled: MagicMock,+ _mock_helper_cls: MagicMock,+ mock_repartition: AsyncMock,+ _mock_heartbeater: MagicMock,+ _mock_capture_event: MagicMock,+ _mock_capture_exception: MagicMock,+ ) -> None:+ # A rewrite queued on a table whose delta log is unreadable (an OOM-crashed merge) returns a+ # skip every run until the import activity's revive heals it, and the skip leaves the pending+ # marker set for a later run. The attempt is charged up front, so a skip must refund it: three+ # banked skips would otherwise spend the whole cap without a rewrite ever running, and the next+ # run would give up and discard the queued rewrite.+ schema = _schema(+ name="public.usages",+ s3_folder_name="usages",+ pending={**PENDING_TARGET, "attempts": 0},+ )+ # Let charge/refund round-trip through the marker so the net attempt count is observable.+ schema.set_repartition_pending.side_effect = lambda p: setattr(schema, "repartition_pending", p)+ mock_schema_model.objects.select_related.return_value.get.return_value = schema+ mock_repartition.return_value = {"outcome": "skipped", "reason": reason}++ _maybe_repartition_table(+ RepartitionActivityInputs(team_id=TEAM_ID, schema_id=SCHEMA_ID, job_id=JOB_ID, source_id=SOURCE_ID),+ MagicMock(),+ )++ assert schema.repartition_pending["attempts"] == 0+ schema.clear_repartition_pending.assert_not_called()+class TestTransientObjectStoreFailure:@patch(f"{MODULE}.capture_exception")@@ -424,7 +519,8 @@ class TestTransientObjectStoreFailure:emitted = [c.args[0] for c in mock_capture_event.call_args_list]assert "warehouse_repartition_failed" not in emitted- schema.set_repartition_pending.assert_not_called()+ # Charged before the rewrite and refunded here, so the net cost is zero.+ assert schema.repartition_pending["attempts"] == 0schema.clear_repartition_pending.assert_not_called()@parameterized.expand(