:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(data-warehouse): stop repeating a repartition rewrite killed in place (#99649)
Tom Owers25bdd3c84972
diff --git a/products/warehouse_sources/backend/temporal/data_imports/README.md b/products/warehouse_sources/backend/temporal/data_imports/README.mdindex 4cfdb95683ff..631b3cd95d9a 100644--- a/products/warehouse_sources/backend/temporal/data_imports/README.md+++ b/products/warehouse_sources/backend/temporal/data_imports/README.md@@ -48,7 +48,7 @@ Week into month is the one transition that cannot be computed exactly, because I- **Rewrite.** On the next run, a pre-extraction activity streams the live Delta table one record-batch at a time, recomputes `_ph_partition_key` under the finer scheme, and writes a sibling temp table. It then does a crash-safe swap: delete live → server-side copy temp → verify row count → delete temp. Memory is bounded by batch size, independent of partition size. 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.- **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.+- **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. 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`, and the terminal give-up carries how far the rewrite got.Tuning and gating: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 efeab860e4c7..96839c96b777 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@@ -408,6 +408,25 @@ def _maybe_repartition_table(inputs: RepartitionActivityInputs, logger: Filterin_give_up(inputs, schema, pending, trigger_reason, logger)return+ # Never while a swap is staged: that recovery runs no rewrite, so the checkpoint says nothing+ # about it, and temp is the only intact copy until it completes.+ if swap is None and _retrying_a_killed_attempt(schema, pending, inputs.job_id):+ # Stake a fresh claim on the way out, the same way `_give_up` does. A retry also starts when+ # the predecessor is only heartbeat-timed-out, and that one keeps running as a zombie holding+ # the claim it minted; standing down without rotating it would leave the zombie free to swap+ # the live table while the sync this run releases merges into it.+ schema.set_repartition_claim(+ {"token": str(uuid.uuid4()), "job_id": inputs.job_id, "claimed_at": timezone.now().isoformat()}+ )+ logger.warning(+ f"repartition: the attempt this run retries wrote nothing before it stopped, standing "+ f"down until the next sync schema_id={schema.id}",+ schema_id=str(schema.id),+ )+ DELTA_REPARTITION_TOTAL.labels(team_id=str(inputs.team_id), outcome="killed").inc()+ _capture_stood_down(schema, inputs, trigger_reason, "attempt_killed_without_progress", 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)@@ -717,6 +736,31 @@ def _exhausted_attempts(pending: dict[str, Any] | None, job_id: str) -> bool:return attempts >= MAX_REPARTITION_ATTEMPTS+def _rewrite_rows_written(schema: ExternalDataSchema) -> int:+ """Rows the rewrite checkpoint says temp already holds, or 0 when there is no checkpoint."""+ return int((schema.repartition_rewrite or {}).get("rows_written") or 0)+++def _retrying_a_killed_attempt(schema: ExternalDataSchema, pending: dict[str, Any] | None, job_id: str) -> bool:+ """Whether this run retries an attempt that was killed without moving the rewrite on.++ Temporal re-runs the activity only when the previous attempt neither finished nor recorded an+ outcome, because every handled failure returns normally. A retry whose charge is still+ outstanding is therefore retrying an attempt that was killed outright — a SIGKILLed worker runs+ no `except` and no `finally` — rather than one that deliberately re-raised, since those refund+ the charge on their way out (`_refund_attempt`). Running the same rewrite again costs the sync+ another activity budget for the same death, so it is only worth doing while the dead attempt+ left the checkpoint further along than it found it; the checkpoint keeps whatever it did write+ for the next sync either way.+ """+ if current_activity_attempt() <= 1 or pending is None:+ return False+ if pending.get("charged_job_id") != job_id:+ return False+ started_from = pending.get("attempt_rows")+ return started_from is not None and _rewrite_rows_written(schema) <= int(started_from)++def _give_up(inputs: RepartitionActivityInputs,schema: ExternalDataSchema,@@ -729,10 +773,15 @@ def _give_up(Stamps the cooldown as well, or detection re-flags the table on the next sync and the attemptsstart over — same reason `_handle_failure` does."""+ # Read before the markers are cleared below. An attempt killed outright leaves the checkpoint as+ # its only trace, so this count is all the terminal record can say about how far the rewrite got.+ # The count alone: the checkpoint's temp URI carries the team's bucket and table names.+ rewrite_rows = _rewrite_rows_written(schema)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}",+ f"record an outcome, rewrite stuck at {rewrite_rows} rows schema_id={inputs.schema_id}",schema_id=inputs.schema_id,+ rewrite_rows=rewrite_rows,)# 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@@ -746,13 +795,14 @@ def _give_up(schema.stamp_last_repartition_at()error = RepartitionAttemptsExhausted(f"repartition gave up after {MAX_REPARTITION_ATTEMPTS} attempts that did not survive to record "- f"an outcome (trigger_reason={trigger_reason})"+ f"an outcome, with the rewrite stuck at {rewrite_rows} rows (trigger_reason={trigger_reason})")props = base_event_props(schema, schema.source, inputs.job_id)props.update({"trigger_reason": trigger_reason,"attempts": int((pending or {}).get("attempts", 0)),+ "rewrite_rows": rewrite_rows,"final": True,"error_type": type(error).__name__,"error_message": str(error),@@ -780,19 +830,25 @@ def _charge_attempt(`_refund_attempt` restores the prior count and releases the run's charge. None means nothing wascharged (no pending marker, or a DB failure) — bookkeeping must never block the rewrite.++ Every attempt also stamps `attempt_rows`, the rewrite checkpoint it is about to run from, charged+ or not: an attempt killed outright records nothing itself, so that stamp is the only thing a+ retry can judge the attempt it retries against (see `_retrying_a_killed_attempt`)."""if pending is None:return Noneprior = int(pending.get("attempts", 0))- if pending.get("charged_job_id") == job_id:- # A retry of a run that already paid: the persisted count already includes its charge.- return max(prior - 1, 0)+ already_charged = pending.get("charged_job_id") == job_id+ marker = {**pending, "attempt_rows": _rewrite_rows_written(schema)}+ if not already_charged:+ marker |= {"attempts": prior + 1, "charged_job_id": job_id}try:- schema.set_repartition_pending({**pending, "attempts": prior + 1, "charged_job_id": job_id})+ schema.set_repartition_pending(marker)except Exception:logger.warning("repartition: could not charge attempt, proceeding uncharged", exc_info=True)return None- return prior+ # A retry of a run that already paid: the persisted count already includes its charge.+ return max(prior - 1, 0) if already_charged else priordef _refund_attempt(schema: ExternalDataSchema, prior: int | None, logger: FilteringBoundLogger) -> None: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 2da2e98e4034..4e99a7b6979d 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@@ -507,6 +507,75 @@ class TestBudgetExhaustion:schema.clear_repartition_pending.assert_not_called()+class TestKilledAttemptRetry:+ @parameterized.expand(+ [+ ("checkpoint_stood_still", 39097, 39097, False),+ ("checkpoint_advanced", 39097, 12, True),+ ]+ )+ @patch(f"{MODULE}.current_activity_attempt", return_value=2)+ @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_retry_reruns_the_rewrite_only_when_the_dead_attempt_advanced_it(+ self,+ _name: str,+ checkpoint_rows: int,+ started_from: int,+ expect_rewrite: bool,+ 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_attempt: MagicMock,+ ) -> None:+ # Temporal retries the activity only for an attempt that recorded no outcome, and a charge+ # still outstanding means it was killed outright rather than re-raised deliberately. Running+ # the same rewrite again holds the sync for another activity budget and dies in the same+ # place, so it is worth doing only while the checkpoint keeps moving.+ schema = _schema(+ name="public.usages",+ s3_folder_name="usages",+ pending={**PENDING_TARGET, "attempts": 1, "charged_job_id": JOB_ID, "attempt_rows": started_from},+ rewrite={"rows_written": checkpoint_rows},+ )+ mock_schema_model.objects.select_related.return_value.get.return_value = schema+ mock_repartition.return_value = {"outcome": "completed", "row_count": 101633}++ _maybe_repartition_table(+ RepartitionActivityInputs(team_id=TEAM_ID, schema_id=SCHEMA_ID, job_id=JOB_ID, source_id=SOURCE_ID),+ MagicMock(),+ )++ emitted = [c.args[0] for c in mock_capture_event.call_args_list]+ if expect_rewrite:+ mock_repartition.assert_awaited_once()+ # Recorded for the next retry, which can only judge this attempt against where it began.+ assert schema.repartition_pending["attempt_rows"] == checkpoint_rows+ else:+ mock_repartition.assert_not_awaited()+ skipped = [+ c.args[1] for c in mock_capture_event.call_args_list if c.args[0] == "warehouse_repartition_skipped"+ ]+ assert len(skipped) == 1+ assert skipped[0]["reason"] == "attempt_killed_without_progress"+ assert skipped[0]["terminal"] is False+ assert "warehouse_repartition_started" not in emitted+ # The sync already paid for the attempt that died; standing down must not charge again.+ assert schema.repartition_pending["attempts"] == 1+ # A retry also starts for a predecessor that is only heartbeat-timed-out and still+ # running, so standing down has to rotate the claim that fences it out of the swap.+ schema.set_repartition_claim.assert_called_once()++class TestTransientObjectStoreFailure:@patch(f"{MODULE}.capture_exception")@patch(f"{MODULE}.capture_repartition_event")