: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 restarting a rewrite one budget cannot cover (#95584)
Tom Owersca1ac8b20d08
diff --git a/products/warehouse_sources/backend/models/external_data_schema.py b/products/warehouse_sources/backend/models/external_data_schema.pyindex e7d08f04eabb..4fa2aa71544f 100644--- a/products/warehouse_sources/backend/models/external_data_schema.py+++ b/products/warehouse_sources/backend/models/external_data_schema.py@@ -645,7 +645,8 @@ class ExternalDataSchema(ModelActivityMixin, CreatedMetaFields, UpdatedMetaFieldappending from that offset instead of re-streaming from row 0, so a table too large to rewritein one activity converges across attempts rather than giving up terminally. Cleared once tempis fully built (a swap is staged) or when the controller gives up. Shape:- {"temp_uri": str, "rows_written": int, "target": dict, "live_version": int, "held_at": str}.+ {"temp_uri": str, "rows_written": int, "target": dict, "live_version": int, "held_at": str,+ "budget_exhausted": bool}."""if self.sync_type_config:marker = self.sync_type_config.get("repartition_rewrite", None)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 19efdceeaa95..adb247f674b8 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@@ -117,6 +117,20 @@ class RepartitionUnpartitionableError(Exception):"""The table has no column suitable for partitioning — repartition is skipped, not retried."""+class RepartitionTooLargeForBudgetError(Exception):+ """One activity budget already failed to cover this table, and its checkpoint cannot be resumed.++ A rewrite that runs out of budget resumes only while live stays at the Delta version its+ checkpoint was built against, and the schema's own merge moves that version between runs. The+ restart that follows re-streams from row 0, with the same budget, over a table that has only+ grown, so it runs out in the same place and is discarded again on the next run. Three of those+ spend the attempt cap and the controller abandons the rewrite terminally, having spent a full+ budget per run to learn nothing. Raised instead of starting that restart, and terminal like+ `RepartitionUnpartitionableError`: the flag is cleared and the cooldown engaged, so the table is+ measured again on a later cycle rather than re-streamed on every sync.+ """++class RepartitionBudgetExceededError(Exception):"""The rewrite ran out of activity budget before it finished streaming the table.@@ -1094,6 +1108,20 @@ async def _rewrite_into_temp(return rows_written, resolved+def _restart_would_run_out_of_budget(checkpoint: dict[str, Any], live_rows: int) -> bool:+ """Whether re-streaming this table from row 0 would run out of budget the way the last attempt did.++ Only a checkpoint left behind by budget exhaustion says anything about the budget. One written by+ the periodic saves belongs to an attempt killed at an arbitrary point — a worker OOM ten minutes+ in — and the rows it covered measure nothing. `rows_written` from a budget-exhausted attempt is+ that measure, so a live table holding more rows than it cannot be rewritten in one budget either.+ """+ if not checkpoint.get("budget_exhausted"):+ return False+ covered = int(checkpoint.get("rows_written") or 0)+ return 0 < covered < live_rows++async def repartition_table_in_place(table_ref: DeltaTableRef,schema: ExternalDataSchema,@@ -1110,9 +1138,10 @@ async def repartition_table_in_place(`repartition_swap` marker (resume re-drives the swap from the intact temp table). On success,persists the new partition settings and clears the controller markers in one row-locked write.Returns a stats dict for observability. Raises `RepartitionUnpartitionableError` (terminal) if no- partition mode applies, and `RepartitionSchemePersistError` if the swap lands but its scheme- cannot be saved — the one failure the caller must not shrug off, since the table's data and its- settings disagree until a later run finishes that write.+ partition mode applies, `RepartitionTooLargeForBudgetError` (terminal) if the table needs more+ than one activity budget and its checkpoint cannot be resumed, and `RepartitionSchemePersistError`+ if the swap lands but its scheme cannot be saved — the one failure the caller must not shrug off,+ since the table's data and its settings disagree until a later run finishes that write.`claim_token` fences out zombie attempts: the temp table is scoped to the token so concurrentwriters can never share one, and the claim is re-checked before every destructive step — and,@@ -1255,6 +1284,12 @@ async def repartition_table_in_place(checkpoint_version = (rewrite_checkpoint or {}).get("live_version")temp_rows = await _valid_delta_row_count(temp_uri, storage_options)if temp_rows is None or temp_rows > old_row_count or checkpoint_version != live_version:+ if _restart_would_run_out_of_budget(rewrite_checkpoint or {}, old_row_count):+ raise RepartitionTooLargeForBudgetError(+ f"a full activity budget covered {(rewrite_checkpoint or {}).get('rows_written')} of "+ f"{old_row_count} rows and the checkpoint cannot be resumed, so re-streaming from row 0 "+ f"cannot finish either (schema_id={schema.id})"+ )await logger.awarning(f"repartition: rewrite checkpoint is unusable (temp_rows={temp_rows} live={old_row_count} "f"checkpoint_version={checkpoint_version} live_version={live_version}), discarding and "@@ -1343,6 +1378,10 @@ async def repartition_table_in_place(# Fences the resume: only valid while live stays at this version (see the# resume path). A merge that commits between attempts bumps it and invalidates."live_version": live_version,+ # Set only here, so the rows above measure what one whole budget covers — the+ # periodic saves record an arbitrary point instead (see+ # `_restart_would_run_out_of_budget`).+ "budget_exhausted": True,# Stamped on every checkpoint write, so it moves forward only while the rewrite# keeps advancing. The import gate reads it to decide whether this rewrite is# still live enough to be worth pausing ingestion for.diff --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 369f78c2c962..87a4462696ae 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@@ -28,6 +28,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.repRepartitionBudgetExceededError,RepartitionSupersededError,RepartitionTarget,+ RepartitionTooLargeForBudgetError,_rewrite_into_temp,measure_partition_bytes,repartition_table_in_place,@@ -1737,6 +1738,8 @@ class TestRewriteCheckpointResume:checkpoint = saved.call_args.kwargs["checkpoint"]assert checkpoint["rows_written"] == 1assert checkpoint["live_version"] == live.version()+ # Marks the rows above as what one whole budget covered, which is what says a restart is futile.+ assert checkpoint["budget_exhausted"] is Trueassert checkpoint["target"]["partition_format"] == "day"assert checkpoint["temp_uri"].endswith("__repartitioned_tok")@@ -1825,6 +1828,45 @@ class TestRewriteCheckpointResume:assert rewrite.await_args_list[0].kwargs["temp_uri"].endswith("__repartitioned_tok")assert rewrite.await_args_list[0].kwargs["skip_rows"] == 0+ def test_refuses_to_restart_a_table_one_budget_already_failed_to_cover(self, tmp_path):+ # The discarded checkpoint above is only harmless while a restart can finish. Once a full+ # budget has been spent covering fewer rows than live holds, re-streaming from row 0 runs out+ # in the same place, so every sync spends a budget to learn nothing and the attempt cap+ # abandons the table. Stop before the rewrite instead, terminally.+ live = _write_month_partitioned(+ str(tmp_path / "live"), [(1, datetime.datetime(2024, 1, 5)), (2, datetime.datetime(2024, 2, 2))]+ )+ table_ref = _make_table_ref(get_delta_table=AsyncMock(return_value=live))+ target = RepartitionTarget(+ partition_keys=["created_at"], trigger_reason="t", partition_mode="datetime", partition_format="day"+ )+ schema = self._base_schema(+ repartition_rewrite={+ "temp_uri": "s3://bucket/live__repartitioned_old",+ "rows_written": 1,+ "target": target.to_dict(),+ "live_version": live.version() + 999,+ "budget_exhausted": True,+ },+ )++ with (+ patch.object(repartition_module, "aget_s3_client", return_value=_FakeS3CM(_fake_s3())),+ patch.object(repartition_module, "_purge_stale_temp_tables", new=AsyncMock()),+ patch.object(repartition_module, "_current_claim_token", return_value="tok"),+ _patch_finalize(),+ patch.object(repartition_module, "_valid_delta_row_count", new=AsyncMock(return_value=1)),+ patch.object(repartition_module, "_rewrite_into_temp", new=AsyncMock()) as rewrite,+ ):+ with pytest.raises(RepartitionTooLargeForBudgetError):+ asyncio.run(+ repartition_table_in_place(+ table_ref=table_ref, schema=schema, target=target, logger=logger, claim_token="tok"+ )+ )++ rewrite.assert_not_awaited()+class TestClaimFencing:"""A heartbeat-timed-out attempt keeps running as a zombie while its Temporal retry starts; bothdiff --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 e289d9318f88..ebf28c81f41b 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@@ -35,6 +35,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.confrom products.warehouse_sources.backend.temporal.data_imports.pipelines.core.repartition import (RepartitionAttemptsExhausted,RepartitionSupersededError,+ RepartitionTooLargeForBudgetError,RepartitionUnpartitionableError,)from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.repartition_controller import (@@ -962,16 +963,27 @@ class TestRepartitionActivity:assert schema.repartition_pending is not Noneassert schema.repartition_pending["attempts"] == 0- def test_unpartitionable_clears_pending(self, team):+ @pytest.mark.parametrize(+ "error",+ [+ RepartitionUnpartitionableError("no keys"),+ RepartitionTooLargeForBudgetError("one budget cannot cover the table"),+ ],+ )+ def test_a_terminal_rewrite_error_clears_pending(self, team, error):schema = _make_schema(team, {})schema.set_repartition_pending({"partition_mode": None, "partition_keys": [], "trigger_reason": "test", "attempts": 0})- mocked = AsyncMock(side_effect=RepartitionUnpartitionableError("no keys"))+ schema.set_repartition_rewrite({"temp_uri": "s3://bucket/t", "rows_written": 10, "budget_exhausted": True})+ mocked = AsyncMock(side_effect=error)capture = self._run(self._inputs(team, schema), mocked)schema.refresh_from_db()assert schema.repartition_pending is None+ # A checkpoint left behind would resume the rewrite the give-up just abandoned.+ assert schema.repartition_rewrite is Noneassert "warehouse_repartition_skipped" in [c.args[0] for c in capture.call_args_list]+ assert "warehouse_repartition_failed" not in [c.args[0] for c in capture.call_args_list]# Clearing pending alone re-arms the loop — detection re-flags the unchanged table next sync.# The cooldown stamp is what actually stops the flag → start → skip churn every 5 minutes.assert schema.last_repartition_at is not Nonediff --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 48a1093e9297..c940f8f4d8b6 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@@ -47,6 +47,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.repRepartitionSchemePersistError,RepartitionSupersededError,RepartitionTarget,+ RepartitionTooLargeForBudgetError,RepartitionUnpartitionableError,repartition_table_in_place,)@@ -492,8 +493,9 @@ def _maybe_repartition_table(inputs: RepartitionActivityInputs, logger: Filterinoutcome=_handle_failure(inputs, schema, pending, trigger_reason, e, claim_token, logger, charged_attempts),).inc()return- except RepartitionUnpartitionableError as e:- # Terminal: the table can't be partitioned on its keys. Clear the flag AND engage the cooldown —+ except (RepartitionUnpartitionableError, RepartitionTooLargeForBudgetError) as e:+ # Terminal: the table can't be partitioned on its keys, or one activity budget can't cover it+ # and its checkpoint can't be resumed. Clear the flag AND engage the cooldown —# clearing `repartition_pending` alone re-arms the loop, because detection re-flags on the very# next sync (the OOM/size trigger is still true and the table's scheme is unchanged), so the# table churns flag → start → skip every 5 minutes forever. The cooldown re-evaluates at most