Skip to content

: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.

fix(data-warehouse): stop charging a forced repartition restart a failed attempt (#104289)

Tom Owers1ddc1365b12c
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.py
index 869b40a65535..268cdaa053dc 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
@@ -155,10 +155,12 @@ class RepartitionBudgetExceededError(Exception):
run writes hundreds of millions of rows each time and still ends where it began.
`resumed_from == 0` alone can't tell a genuine first attempt from a treadmill restart, though — both
- inherit nothing. `had_prior_checkpoint` splits them: True means a checkpoint existed at the start of
- this attempt (so re-covering ground from row 0 is a restart, not progress), False means there was
- none to inherit. `checkpoint_saved` records whether this attempt persisted a checkpoint the next run
- can resume from. A fresh first attempt that saved one is forward progress; the caller sets both.
+ inherit nothing. `had_prior_checkpoint` splits them: True means this attempt found a checkpoint it
+ could build on (so re-covering ground from row 0 is a restart, not progress), False means there was
+ none to inherit or the resume path rejected the one there was, because nobody has spent a budget
+ on the rows a restart past a rejected checkpoint covers. `checkpoint_saved` records whether this attempt
+ persisted a checkpoint the next run can resume from. A fresh first attempt that saved one is forward
+ progress; the caller sets both.
"""
def __init__(
@@ -1439,10 +1441,12 @@ async def repartition_table_in_place(
skip_rows=skip_rows,
)
except RepartitionBudgetExceededError as e:
- # A checkpoint present at the start of this attempt means a resumed_from==0 restart
- # re-covered ground rather than progressing; its absence means this is a genuine first
- # attempt. The classifier needs the distinction (see `_handle_budget_exceeded`).
- e.had_prior_checkpoint = rewrite_checkpoint is not None
+ # Only a checkpoint this attempt could build on marks a restart. One the resume path
+ # rejected was left by an attempt killed at an arbitrary point, so the ground re-covered
+ # past it measures nothing. A checkpoint a full budget did produce never reaches the
+ # rewrite, because `_restart_would_run_out_of_budget` gives up terminally ahead of it.
+ # The classifier needs the distinction (see `_handle_budget_exceeded`).
+ e.had_prior_checkpoint = resuming_rewrite
# Checkpoint the half-built temp so the next attempt resumes instead of re-streaming from
# row 0. Fenced on the claim inside the row lock, like the progress checkpoint above: a
# superseded zombie writing here would restore its own claim along with the whole config.
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.py
index 01448fbe8489..fd9c8f18f887 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
@@ -2006,6 +2006,60 @@ class TestRewriteCheckpointResume:
assert rewrite.await_args_list[0].kwargs["temp_uri"].endswith("__repartitioned_tok")
assert rewrite.await_args_list[0].kwargs["skip_rows"] == 0
+ @pytest.mark.parametrize(
+ "version_offset,expected_restart",
+ [
+ pytest.param(0, True, id="resumed_checkpoint_is_a_restart"),
+ pytest.param(999, False, id="rejected_checkpoint_is_not_a_restart"),
+ ],
+ )
+ def test_only_a_usable_checkpoint_makes_an_over_budget_attempt_a_restart(
+ self, version_offset, expected_restart, tmp_path
+ ):
+ # `had_prior_checkpoint` decides whether the activity charges this attempt against the cap.
+ # A checkpoint the resume path rejected was left by an attempt killed at an arbitrary point
+ # (a transient S3 error minutes in), so the budget spent past it is the first anybody spent
+ # on those rows, not a re-run of ground already covered. Charging it abandons a converging
+ # table after three such runs and throws away the checkpoint this attempt just saved.
+ 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() + version_offset,
+ },
+ )
+
+ 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, "save_repartition_checkpoint_if_claimed", return_value=True),
+ patch.object(
+ repartition_module,
+ "_rewrite_into_temp",
+ new=AsyncMock(side_effect=RepartitionBudgetExceededError("out of budget", rows_written=1)),
+ ),
+ ):
+ with pytest.raises(RepartitionBudgetExceededError) as raised:
+ asyncio.run(
+ repartition_table_in_place(
+ table_ref=table_ref, schema=schema, target=target, logger=logger, claim_token="tok"
+ )
+ )
+
+ assert raised.value.had_prior_checkpoint is expected_restart
+ assert raised.value.checkpoint_saved is True
+
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
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.py
index 0ca47bc81825..ca8994c05945 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
@@ -735,11 +735,13 @@ def _handle_budget_exceeded(
run and finishing nothing, because the cap could never count to three.
Two shapes count as progress. A resumed attempt that appended rows extended what it inherited. And
- a genuine first attempt — one with no prior checkpoint to inherit — that persisted a checkpoint the
+ a genuine first attempt — one with no checkpoint it could build on — that persisted a checkpoint the
next run resumes from broke new ground, even though `resumed_from` is 0. `had_prior_checkpoint`
- keeps that first attempt apart from a restart that inherited nothing because it discarded an
- existing checkpoint: the restart re-covered ground the last attempt already covered, however much it
- wrote, so only it (and an attempt that saved no checkpoint at all) falls through to `_handle_failure`.
+ keeps that first attempt apart from a restart that inherited nothing because it discarded a
+ checkpoint it could have resumed: the restart re-covered ground the last attempt already covered,
+ however much it wrote, so only it (and an attempt that saved no checkpoint at all) falls through to
+ `_handle_failure`. A checkpoint the resume path rejected does not make an attempt a restart, because
+ it was left by an attempt killed at an arbitrary point and the rows it covered measure nothing.
Returns the metric outcome: "superseded" when a newer attempt owns the claim, "progressing" when
the rewrite broke new ground, otherwise whatever `_handle_failure` returns.