: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): let large repartitions converge across attempts (#81085)
Tom Owers6872dee477c4
diff --git a/products/warehouse_sources/backend/temporal/data_imports/README.md b/products/warehouse_sources/backend/temporal/data_imports/README.mdindex 17d846f634ae..a4c8181f0dd9 100644--- a/products/warehouse_sources/backend/temporal/data_imports/README.md+++ b/products/warehouse_sources/backend/temporal/data_imports/README.md@@ -47,7 +47,7 @@ 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 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.-- **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, and transient infra errors (DB pooler drops, S3 rate limits) don't count against that cap.+- **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.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 09f80c4a76fa..0bedcd37cd5b 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@@ -376,13 +376,14 @@ def _maybe_repartition_table(inputs: RepartitionActivityInputs, logger: Filterindeadline=_rewrite_deadline(),)except RepartitionBudgetExceededError as e:- # The table is telling us its rewrite doesn't fit in one activity. Record it as a real failed- # attempt so `MAX_REPARTITION_ATTEMPTS` is reachable and the table eventually gives up,- # instead of restarting the same doomed rewrite in front of every sync forever.+ # The rewrite didn't fit in one activity's budget. Checkpoint/resume lets a large table+ # converge across runs, so an attempt that advanced the checkpoint is progress, not a failure,+ # and must not burn an attempt (see `_handle_budget_exceeded`); only a stuck one that made no+ # progress counts toward `MAX_REPARTITION_ATTEMPTS` so a doomed rewrite still gives up.logger.warning(f"repartition: {e}")DELTA_REPARTITION_TOTAL.labels(team_id=str(inputs.team_id),- outcome=_handle_failure(inputs, schema, pending, trigger_reason, e, claim_token, logger),+ outcome=_handle_budget_exceeded(inputs, schema, pending, trigger_reason, e, claim_token, logger),).inc()returnexcept RepartitionSupersededError:@@ -505,6 +506,53 @@ def _capture_stood_down(logger.warning("repartition: failed to capture stand-down event", exc_info=True)+def _handle_budget_exceeded(+ inputs: RepartitionActivityInputs,+ schema: ExternalDataSchema,+ pending: dict[str, Any] | None,+ trigger_reason: str,+ error: RepartitionBudgetExceededError,+ claim_token: str,+ logger: FilteringBoundLogger,+) -> str:+ """Record a rewrite that ran out of one activity's budget, distinguishing progress from a stall.++ Checkpoint/resume lets a table too large to rewrite in one activity converge across runs (see+ `RepartitionBudgetExceededError`), so an attempt that advanced the checkpoint is forward progress,+ not a failure: counting it against the finite `MAX_REPARTITION_ATTEMPTS` would abandon a table that+ simply needs more than three budgets mid-convergence and leave it un-repartitioned. Only an attempt+ that wrote no new rows since the last checkpoint is stuck; that one falls through to+ `_handle_failure` so a rewrite which genuinely can't advance in one budget still gives up.++ Returns the metric outcome: "superseded" when a newer attempt owns the claim, "progressing" when+ the rewrite advanced, otherwise whatever `_handle_failure` returns.+ """+ schema.refresh_from_db(fields=["sync_type_config"])+ claim = schema.repartition_claim+ if not (claim and claim.get("token") == claim_token):+ logger.info("repartition: superseded (claim changed under us), standing down without recording failure")+ return "superseded"++ pending = schema.repartition_pending or pending or {}+ rows_written = int((schema.repartition_rewrite or {}).get("rows_written", 0))+ high_water = int(pending.get("rewrite_high_water", 0))+ if rows_written > high_water:+ # Forward progress this attempt: keep the checkpoint, record the new high-water mark, and reset+ # the failure counter — a rewrite still advancing is not the doomed one the cap exists to stop.+ # The next run resumes from the checkpoint rather than re-streaming from row 0.+ schema.set_repartition_pending({**pending, "attempts": 0, "rewrite_high_water": rows_written})+ logger.info(+ f"repartition: over budget but rewrite advanced to {rows_written} rows, resuming next run",+ rows_written=rows_written,+ )+ _capture_stood_down(schema, inputs, trigger_reason, "rewrite_progressing", logger)+ return "progressing"++ # No new rows since the last checkpoint: the rewrite can't make headway inside one budget, so count+ # it as a real failed attempt and let `MAX_REPARTITION_ATTEMPTS` eventually give up on it.+ return _handle_failure(inputs, schema, pending, trigger_reason, error, claim_token, logger)++def _handle_failure(inputs: RepartitionActivityInputs,schema: ExternalDataSchema,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 3af52b01e49e..b64e026cf044 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@@ -48,6 +48,7 @@ def _schema(s3_folder_name: str | None,pending: dict | None = PENDING_TARGET,swap: dict | None = None,+ rewrite: dict | None = None,) -> MagicMock:schema = MagicMock()schema.id = SCHEMA_ID@@ -58,6 +59,7 @@ def _schema(schema.delta_revive_required = Noneschema.repartition_swap = swapschema.repartition_pending = pending+ schema.repartition_rewrite = rewrite# 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)@@ -201,7 +203,7 @@ class TestBudgetExhaustion:@patch(f"{MODULE}.is_auto_repartition_enabled", return_value=True)@patch(f"{MODULE}.ExternalDataJob")@patch(f"{MODULE}.ExternalDataSchema")- def test_budget_exhaustion_burns_an_attempt_and_gives_up_with_a_cooldown(+ def test_stalled_rewrite_burns_an_attempt_and_gives_up_with_a_cooldown(self,_name: str,prior_attempts: int,@@ -215,13 +217,16 @@ class TestBudgetExhaustion:_mock_capture_event: MagicMock,_mock_capture_exception: MagicMock,) -> None:+ # A rewrite that wrote no new rows since the last checkpoint (rows_written == high_water) is+ # stuck, so budget exhaustion counts as a real failed attempt.schema = _schema(name="public.usages",s3_folder_name="usages",- pending={**PENDING_TARGET, "attempts": prior_attempts},+ pending={**PENDING_TARGET, "attempts": prior_attempts, "rewrite_high_water": 12},+ rewrite={"rows_written": 12},)mock_schema_model.objects.select_related.return_value.get.return_value = schema- mock_repartition.side_effect = RepartitionBudgetExceededError("out of budget after 12 rows")+ mock_repartition.side_effect = RepartitionBudgetExceededError("out of budget")_maybe_repartition_table(RepartitionActivityInputs(team_id=TEAM_ID, schema_id=SCHEMA_ID, job_id=JOB_ID, source_id=SOURCE_ID),@@ -241,6 +246,57 @@ class TestBudgetExhaustion:schema.stamp_last_repartition_at.assert_not_called()schema.clear_repartition_rewrite.assert_not_called()+ @parameterized.expand([("first_attempt", 0, 0), ("last_attempt_before_give_up", 2, 100)])+ @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_progressing_rewrite_resumes_without_burning_an_attempt(+ self,+ _name: str,+ prior_attempts: int,+ prior_high_water: int,+ 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:+ # The checkpoint advanced (rows_written > high_water), so a table too large for one budget is+ # converging across runs. It must never give up — even sitting at the last attempt before the+ # cap — and must reset the failure counter and record the new high-water mark so the next run+ # resumes rather than re-streaming from row 0.+ schema = _schema(+ name="public.usages",+ s3_folder_name="usages",+ pending={**PENDING_TARGET, "attempts": prior_attempts, "rewrite_high_water": prior_high_water},+ rewrite={"rows_written": prior_high_water + 500},+ )+ mock_schema_model.objects.select_related.return_value.get.return_value = schema+ mock_repartition.side_effect = RepartitionBudgetExceededError("out of budget")++ _maybe_repartition_table(+ RepartitionActivityInputs(team_id=TEAM_ID, schema_id=SCHEMA_ID, job_id=JOB_ID, source_id=SOURCE_ID),+ MagicMock(),+ )++ schema.clear_repartition_pending.assert_not_called()+ schema.clear_repartition_rewrite.assert_not_called()+ schema.stamp_last_repartition_at.assert_not_called()+ updated = schema.set_repartition_pending.call_args.args[0]+ assert updated["attempts"] == 0+ assert updated["rewrite_high_water"] == prior_high_water + 500+ emitted = [c.args[0] for c in mock_capture_event.call_args_list]+ assert "warehouse_repartition_failed" not in emitted+ assert "warehouse_repartition_skipped" in emitted+class TestFeatureFlagGate:@parameterized.expand(