: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): give up on a repartition that restarts every attempt (#83126)
Tom Owers646acbb6ba71
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 cf9bfa3a6a1e..905035a965e9 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@@ -101,12 +101,25 @@ class RepartitionBudgetExceededError(Exception):half-built temp table: the next attempt resumes appending from that offset rather thanre-streaming from row 0, letting a table too large to rewrite in one activity converge acrossattempts instead of failing the same way every time.++ `resumed_from` is how many rows this attempt inherited: 0 when it started fresh, either because it+ is the first attempt or because the resume path rejected the prior checkpoint. The caller needs it+ to tell convergence from a treadmill. `rows_written` alone cannot: a rewrite that restarts every+ run writes hundreds of millions of rows each time and still ends where it began."""- def __init__(self, message: str, *, rows_written: int = 0, resolved: RepartitionTarget | None = None) -> None:+ def __init__(+ self,+ message: str,+ *,+ rows_written: int = 0,+ resolved: RepartitionTarget | None = None,+ resumed_from: int = 0,+ ) -> None:super().__init__(message)self.rows_written = rows_writtenself.resolved = resolved+ self.resumed_from = resumed_fromclass RepartitionSupersededError(Exception):@@ -773,6 +786,7 @@ async def _rewrite_into_temp(f"rewrite exceeded its activity budget after {rows_written} rows written to {temp_uri}",rows_written=rows_written,resolved=resolved,+ resumed_from=skip_rows,)# Resume: temp already holds the first `skip_rows` rows in scan order, so read past them anddiff --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 5ffb5517bfc7..c0f7fd1f3708 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@@ -531,14 +531,19 @@ def _handle_budget_exceeded(appended nothing this run is stuck; that one falls through to `_handle_failure` so a rewrite whichgenuinely can't advance in one budget still gives up.- Progress is judged from the rows this attempt wrote (`error.rows_written`), not the checkpoint's- cumulative temp size against a stored high-water mark: the rewrite restarts from row 0 whenever its- checkpoint is discarded (the source's Delta version moved between runs), so the cumulative size is- not monotonic across attempts, and a genuinely progressing fresh rebuild that read back below an- earlier, longer attempt's mark was charged a spurious failure.+ Progress means this attempt inherited rows and added to them. Neither count alone can say that. A+ cumulative temp size against a stored high-water mark is not monotonic, because the rewrite+ restarts from row 0 whenever its checkpoint is discarded (the source's Delta version moved between+ runs), so a fresh rebuild reading back below an earlier attempt's mark was charged a spurious+ failure. But the rows written this attempt cannot say it either: a rewrite that restarts every run+ writes hundreds of millions of rows each time, clears any `> 0` test, and ends exactly where it+ began. Three schemas sat in that loop for six weeks, each burning a full budget per run and+ finishing nothing, because the cap could never count to three. `resumed_from` separates them: an+ attempt that inherited nothing re-covered ground the last one already covered, however much it+ wrote.Returns the metric outcome: "superseded" when a newer attempt owns the claim, "progressing" when- the rewrite advanced, otherwise whatever `_handle_failure` returns.+ the rewrite extended what it inherited, otherwise whatever `_handle_failure` returns."""schema.refresh_from_db(fields=["sync_type_config"])claim = schema.repartition_claim@@ -547,20 +552,29 @@ def _handle_budget_exceeded(return "superseded"pending = schema.repartition_pending or pending or {}- if error.rows_written > 0:+ if error.resumed_from > 0 and error.rows_written > 0:# Forward progress this attempt: keep the checkpoint 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 (or rebuilds fresh if it was invalidated) rather than giving up.+ # checkpoint rather than giving up.schema.set_repartition_pending({**pending, "attempts": 0})logger.info(- f"repartition: over budget but rewrite advanced {error.rows_written} rows this attempt, resuming next run",+ f"repartition: over budget but rewrite advanced {error.rows_written} rows past the "+ f"{error.resumed_from} it inherited, resuming next run",rows_written=error.rows_written,+ resumed_from=error.resumed_from,)_capture_stood_down(schema, inputs, trigger_reason, "rewrite_progressing", logger)return "progressing"- # Nothing appended this attempt: 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.+ # Either this attempt inherited nothing (so it re-streamed ground already covered) or it inherited+ # a checkpoint and appended nothing. Both mean the rewrite can't converge on the budget it has, so+ # count a real failed attempt and let `MAX_REPARTITION_ATTEMPTS` eventually give up on it.+ logger.info(+ f"repartition: over budget without converging (resumed_from={error.resumed_from} "+ f"rows_written={error.rows_written})",+ rows_written=error.rows_written,+ resumed_from=error.resumed_from,+ )return _handle_failure(inputs, schema, pending, trigger_reason, error, claim_token, logger)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 a979f0922238..a9ce1fd86e5a 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@@ -268,12 +268,11 @@ class TestBudgetExhaustion:mock_capture_event: MagicMock,_mock_capture_exception: MagicMock,) -> None:- # This attempt appended new rows, so a table too large for one budget is converging across runs.- # It must never give up — even at the last attempt before the cap — and must reset the failure- # counter. The checkpoint's cumulative temp size (`repartition_rewrite.rows_written`) sits far- # below a longer earlier attempt's high-water mark here: the case a fresh rebuild hits after its- # checkpoint is discarded. Judging progress by that cumulative size mislabeled it a stall and- # emitted a spurious `warehouse_repartition_failed`; the rows written this run are the signal.+ # This attempt inherited a checkpoint and appended to it, so a table too large for one budget is+ # converging across runs. It must never give up — even at the last attempt before the cap — and+ # must reset the failure counter. The checkpoint's cumulative temp size sits far below an+ # earlier, longer attempt's high-water mark here, so judging progress by that cumulative size+ # would mislabel a converging rewrite as a stall.schema = _schema(name="public.usages",s3_folder_name="usages",@@ -281,7 +280,9 @@ class TestBudgetExhaustion:rewrite={"rows_written": 230_000},)mock_schema_model.objects.select_related.return_value.get.return_value = schema- mock_repartition.side_effect = RepartitionBudgetExceededError("out of budget", rows_written=230_000)+ mock_repartition.side_effect = RepartitionBudgetExceededError(+ "out of budget", rows_written=180_000, resumed_from=50_000+ )_maybe_repartition_table(RepartitionActivityInputs(team_id=TEAM_ID, schema_id=SCHEMA_ID, job_id=JOB_ID, source_id=SOURCE_ID),@@ -297,6 +298,56 @@ class TestBudgetExhaustion:assert "warehouse_repartition_failed" not in emittedassert "warehouse_repartition_skipped" in emitted+ @parameterized.expand([("below_max", 0, False), ("reaching_max", 2, True)])+ @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_restarted_rewrite_burns_an_attempt_however_many_rows_it_wrote(+ self,+ _name: str,+ prior_attempts: int,+ expect_give_up: 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_capture_exception: MagicMock,+ ) -> None:+ # This attempt inherited nothing: the resume path discarded the checkpoint, so it re-streamed+ # from row 0 and covered ground the last attempt already covered. It writes 230M rows doing it,+ # which clears any "did this attempt write anything" test and resets the failure counter. Three+ # schemas looped that way for six weeks, each burning a full budget per run and converging on+ # nothing, because the cap could never count to three.+ schema = _schema(+ name="public.usages",+ s3_folder_name="usages",+ pending={**PENDING_TARGET, "attempts": prior_attempts},+ rewrite={"rows_written": 230_000_000},+ )+ mock_schema_model.objects.select_related.return_value.get.return_value = schema+ mock_repartition.side_effect = RepartitionBudgetExceededError(+ "out of budget", rows_written=230_000_000, resumed_from=0+ )++ _maybe_repartition_table(+ RepartitionActivityInputs(team_id=TEAM_ID, schema_id=SCHEMA_ID, job_id=JOB_ID, source_id=SOURCE_ID),+ MagicMock(),+ )++ if expect_give_up:+ schema.clear_repartition_pending.assert_called_once()+ schema.clear_repartition_rewrite.assert_called_once()+ else:+ assert schema.set_repartition_pending.call_args.args[0]["attempts"] == prior_attempts + 1+class TestTransientObjectStoreFailure:@patch(f"{MODULE}.capture_exception")