: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): keep a repartition that is still advancing (#103440)
Tom Owers82812680c59c
diff --git a/products/warehouse_sources/backend/temporal/data_imports/README.md b/products/warehouse_sources/backend/temporal/data_imports/README.mdindex 5e11fed35d08..e8cf398f74d1 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. 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`, and 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 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/workflow_activities/repartition_table.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/repartition_table.pyindex c9ffb69a37ef..0ca47bc81825 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@@ -440,8 +440,23 @@ def _maybe_repartition_table(inputs: RepartitionActivityInputs, logger: Filterin# 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, inputs.job_id):- _give_up(inputs, schema, pending, trigger_reason, logger)- return+ # A killed attempt that still moved the checkpoint on is forward progress, not evidence the+ # rewrite is doomed, which is the distinction `_handle_budget_exceeded` already draws for an+ # attempt that ran out of budget. The checkpoint is the only signal available here, because a+ # killed attempt records no outcome of its own. Otherwise a large table that converges one+ # worker death per sync is abandoned at the cap, and `_give_up` discards its progress too.+ if _last_attempt_advanced_rewrite(schema, pending):+ logger.warning(+ f"repartition: attempts are spent but the rewrite advanced to "+ f"{_rewrite_rows_written(schema)} rows, resetting the count and resuming "+ f"schema_id={schema.id}",+ schema_id=str(schema.id),+ rewrite_rows=_rewrite_rows_written(schema),+ )+ pending = _clear_attempts_after_progress(schema, pending, logger)+ else:+ _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.@@ -790,6 +805,42 @@ def _rewrite_rows_written(schema: ExternalDataSchema) -> int:return int((schema.repartition_rewrite or {}).get("rows_written") or 0)+def _last_attempt_advanced_rewrite(schema: ExternalDataSchema, pending: dict[str, Any] | None) -> bool:+ """Whether the last attempt left the rewrite checkpoint further along than it found it.++ Every attempt stamps `attempt_rows` with the checkpoint it is about to run from (see+ `_charge_attempt`), so a checkpoint reading past that stamp is the only trace an attempt killed+ outright can leave of the rows it committed. Strictly past: a checkpoint standing exactly where+ the attempt began is the stalled rewrite the cap exists to stop. A marker written before that+ stamp existed carries no `attempt_rows` and claims no progress.+ """+ if pending is None:+ return False+ started_from = pending.get("attempt_rows")+ return started_from is not None and _rewrite_rows_written(schema) > int(started_from)+++def _clear_attempts_after_progress(+ schema: ExternalDataSchema, pending: dict[str, Any] | None, logger: FilteringBoundLogger+) -> dict[str, Any] | None:+ """Reset the failure count for a rewrite that is still advancing; return the marker now in force.++ Resets rather than refunds, the same way `_handle_budget_exceeded` treats an attempt that+ advanced: the count records consecutive attempts that got nowhere. A failed write leaves the+ spent count in place, so the rewrite still runs this time and the next run re-reads the cap,+ because bookkeeping must never block it.+ """+ if pending is None:+ return None+ marker = {**pending, "attempts": 0}+ try:+ schema.set_repartition_pending(marker)+ except Exception:+ logger.warning("repartition: could not reset the attempt count, proceeding on the spent one", exc_info=True)+ return pending+ return marker++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.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 80e6760bffd0..eddca14666c4 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@@ -583,6 +583,76 @@ class TestKilledAttemptRetry:# running, so standing down has to rotate the claim that fences it out of the swap.schema.set_repartition_claim.assert_called_once()+ @parameterized.expand(+ [+ ("checkpoint_advanced", 488925, 301744, True),+ ("checkpoint_stood_still", 488925, 488925, False),+ ("no_recorded_start", 488925, None, False),+ ]+ )+ @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_coarsen_enabled", return_value=True)+ @patch(f"{MODULE}.is_auto_repartition_enabled", return_value=True)+ @patch(f"{MODULE}.ExternalDataJob")+ @patch(f"{MODULE}.ExternalDataSchema")+ def test_the_cap_gives_up_only_on_a_rewrite_that_stopped_advancing(+ self,+ _name: str,+ checkpoint_rows: int,+ started_from: int | None,+ expect_resume: bool,+ mock_schema_model: MagicMock,+ _mock_job_model: MagicMock,+ _mock_enabled: MagicMock,+ _mock_coarsen_enabled: MagicMock,+ _mock_helper_cls: MagicMock,+ mock_repartition: AsyncMock,+ _mock_heartbeater: MagicMock,+ mock_capture_event: MagicMock,+ _mock_capture_exception: MagicMock,+ ) -> None:+ # A hard-killed attempt records no outcome; only its checkpoint can prove progress.+ schema = _schema(+ name="public.deals",+ s3_folder_name="deals",+ pending={+ **PENDING_TARGET,+ "trigger_reason": "coarsening",+ "attempts": MAX_REPARTITION_ATTEMPTS,+ "charged_job_id": str(uuid.uuid4()),+ "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"}++ _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_resume:+ mock_repartition.assert_awaited_once()+ assert "warehouse_repartition_failed" not in emitted+ assert schema.set_repartition_pending.call_args_list[0].args[0]["attempts"] == 0+ schema.clear_repartition_rewrite.assert_not_called()+ else:+ mock_repartition.assert_not_awaited()+ failed = [+ c.args[1] for c in mock_capture_event.call_args_list if c.args[0] == "warehouse_repartition_failed"+ ]+ assert len(failed) == 1+ assert failed[0]["final"] is True+ assert failed[0]["error_type"] == "RepartitionAttemptsExhausted"+ schema.clear_repartition_pending.assert_called_once()+ schema.stamp_last_repartition_at.assert_called_once()+class TestTransientObjectStoreFailure:@patch(f"{MODULE}.capture_exception")