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): keep a repartition that restarts from row 0 (#109013)

Tom Owerse76fd0c2c0a2
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 71e3924c56cb..b1cc03228d0a 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
@@ -798,6 +798,43 @@ def _rewrite_rows_written(schema: ExternalDataSchema) -> int:
return int((schema.repartition_rewrite or {}).get("rows_written") or 0)
+def _rewrite_checkpoint_id(schema: ExternalDataSchema) -> str | None:
+ """Which rewrite the current checkpoint belongs to, or None when there is no checkpoint.
+
+ The temp table is claim-scoped, so a rewrite that discards its checkpoint and restarts from row 0
+ builds a different one while a resume keeps the URI it inherited — which makes the URI the
+ identity of a rewrite across runs. Compared only, never reported: it carries the team's bucket and
+ table names.
+ """
+ return (schema.repartition_rewrite or {}).get("temp_uri")
+
+
+def _rewrite_advanced_past(
+ schema: ExternalDataSchema, pending: dict[str, Any], rows_key: str, rewrite_key: str
+) -> bool:
+ """Whether the checkpoint now stands further on than the stamp under `rows_key`/`rewrite_key`.
+
+ A cumulative row count alone cannot answer this, because it is not monotonic across runs. A
+ checkpoint is only resumable while live is byte-identical to when it was written, and the sync's
+ own merge commits to live after every swallowed repartition failure, so a later run routinely
+ discards it and rebuilds from row 0. The fresh checkpoint then reads *below* the stamp, and an
+ attempt that streamed hundreds of thousands of rows records as a stall — the same
+ non-monotonicity `_handle_budget_exceeded` weighs `had_prior_checkpoint` against. So a checkpoint
+ belonging to a different rewrite than the stamp's is ground this attempt broke, and only one on
+ the same rewrite is judged by its row count.
+
+ A stamp written before the rewrite id existed carries nothing to compare, so it keeps the
+ row-count reading it was written for.
+ """
+ rows_stamp = pending.get(rows_key)
+ if rows_stamp is None:
+ return False
+ current = _rewrite_checkpoint_id(schema)
+ if rewrite_key in pending and current is not None and current != pending[rewrite_key]:
+ return _rewrite_rows_written(schema) > 0
+ return _rewrite_rows_written(schema) > int(rows_stamp)
+
+
def _last_run_advanced_rewrite(schema: ExternalDataSchema, pending: dict[str, Any] | None) -> bool:
"""Whether the last sync run left the rewrite checkpoint further along than it found it.
@@ -815,10 +852,9 @@ def _last_run_advanced_rewrite(schema: ExternalDataSchema, pending: dict[str, An
"""
if pending is None:
return False
- started_from = pending.get("run_rows")
- if started_from is None:
- started_from = pending.get("attempt_rows")
- return started_from is not None and _rewrite_rows_written(schema) > int(started_from)
+ if pending.get("run_rows") is not None:
+ return _rewrite_advanced_past(schema, pending, "run_rows", "run_rewrite_id")
+ return _rewrite_advanced_past(schema, pending, "attempt_rows", "attempt_rewrite_id")
def _clear_attempts_after_progress(
@@ -858,8 +894,9 @@ def _retrying_a_killed_attempt(schema: ExternalDataSchema, pending: dict[str, An
return False
if pending.get("charged_job_id") != job_id:
return False
- started_from = pending.get("attempt_rows")
- return started_from is not None and _rewrite_rows_written(schema) <= int(started_from)
+ if pending.get("attempt_rows") is None:
+ return False
+ return not _rewrite_advanced_past(schema, pending, "attempt_rows", "attempt_rewrite_id")
def _give_up(
@@ -936,16 +973,24 @@ def _charge_attempt(
or not: an attempt killed outright records nothing itself, so that stamp is the only thing a
retry can judge the attempt it retries against (see `_retrying_a_killed_attempt`). `run_rows` is
the same reading kept once per charged run, so the give-up check weighs the run the cap actually
- counted rather than whichever retry happened to end it (see `_last_run_advanced_rewrite`).
+ counted rather than whichever retry happened to end it (see `_last_run_advanced_rewrite`). Each
+ stamp records which rewrite that reading came from too, because the reading alone is not
+ comparable across a restart (see `_rewrite_advanced_past`).
"""
if pending is None:
return None
prior = int(pending.get("attempts", 0))
already_charged = pending.get("charged_job_id") == job_id
rows_at_start = _rewrite_rows_written(schema)
- marker = {**pending, "attempt_rows": rows_at_start}
+ rewrite_at_start = _rewrite_checkpoint_id(schema)
+ marker = {**pending, "attempt_rows": rows_at_start, "attempt_rewrite_id": rewrite_at_start}
if not already_charged:
- marker |= {"attempts": prior + 1, "charged_job_id": job_id, "run_rows": rows_at_start}
+ marker |= {
+ "attempts": prior + 1,
+ "charged_job_id": job_id,
+ "run_rows": rows_at_start,
+ "run_rewrite_id": rewrite_at_start,
+ }
try:
schema.set_repartition_pending(marker)
except Exception:
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.py
index 7efef2b53396..5fd1700d63b0 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
@@ -40,6 +40,8 @@ TEAM_ID = 1
SCHEMA_ID = str(uuid.uuid4())
JOB_ID = str(uuid.uuid4())
SOURCE_ID = str(uuid.uuid4())
+TEMP_URI = "s3://bucket/folder/table__repartition_tmp_1a2b3c4d"
+OTHER_TEMP_URI = "s3://bucket/folder/table__repartition_tmp_5e6f7a8b"
PENDING_TARGET = {
"partition_mode": "datetime",
@@ -521,8 +523,10 @@ class TestBudgetExhaustion:
class TestKilledAttemptRetry:
@parameterized.expand(
[
- ("checkpoint_stood_still", 39097, 39097, False),
- ("checkpoint_advanced", 39097, 12, True),
+ ("checkpoint_stood_still", 39097, TEMP_URI, 39097, TEMP_URI, False),
+ ("checkpoint_advanced", 39097, TEMP_URI, 12, TEMP_URI, True),
+ ("rewrite_restarted_and_wrote_rows", 12, OTHER_TEMP_URI, 39097, TEMP_URI, True),
+ ("rewrite_restarted_and_wrote_nothing", 0, None, 39097, TEMP_URI, False),
]
)
@patch(f"{MODULE}.current_activity_attempt", return_value=2)
@@ -537,7 +541,9 @@ class TestKilledAttemptRetry:
self,
_name: str,
checkpoint_rows: int,
+ checkpoint_temp_uri: str | None,
started_from: int,
+ started_temp_uri: str,
expect_rewrite: bool,
mock_schema_model: MagicMock,
_mock_job_model: MagicMock,
@@ -551,12 +557,20 @@ class TestKilledAttemptRetry:
# Temporal retries the activity only for an attempt that recorded no outcome, and a charge
# still outstanding means it was killed outright rather than re-raised deliberately. Running
# the same rewrite again holds the sync for another activity budget and dies in the same
- # place, so it is worth doing only while the checkpoint keeps moving.
+ # place, so it is worth doing only while the checkpoint keeps moving. A restart is the case
+ # the row count alone gets wrong: the dead attempt rebuilt from row 0, so its checkpoint
+ # reads below the stamp however many rows it committed.
schema = _schema(
name="public.usages",
s3_folder_name="usages",
- pending={**PENDING_TARGET, "attempts": 1, "charged_job_id": JOB_ID, "attempt_rows": started_from},
- rewrite={"rows_written": checkpoint_rows},
+ pending={
+ **PENDING_TARGET,
+ "attempts": 1,
+ "charged_job_id": JOB_ID,
+ "attempt_rows": started_from,
+ "attempt_rewrite_id": started_temp_uri,
+ },
+ rewrite={"rows_written": checkpoint_rows, "temp_uri": checkpoint_temp_uri},
)
mock_schema_model.objects.select_related.return_value.get.return_value = schema
mock_repartition.return_value = {"outcome": "completed", "row_count": 101633}
@@ -590,10 +604,12 @@ class TestKilledAttemptRetry:
@parameterized.expand(
[
- ("checkpoint_advanced", 488925, 301744, None, True),
- ("checkpoint_stood_still", 488925, 488925, None, False),
- ("no_recorded_start", 488925, None, None, False),
- ("run_advanced_though_its_last_retry_did_not", 488925, 488925, 301744, True),
+ ("checkpoint_advanced", 488925, TEMP_URI, 301744, None, True),
+ ("checkpoint_stood_still", 488925, TEMP_URI, 488925, None, False),
+ ("no_recorded_start", 488925, TEMP_URI, None, None, False),
+ ("run_advanced_though_its_last_retry_did_not", 488925, TEMP_URI, 488925, 301744, True),
+ ("run_restarted_the_rewrite_and_wrote_rows", 301744, OTHER_TEMP_URI, 488925, 488925, True),
+ ("run_restarted_the_rewrite_and_wrote_nothing", 0, None, 488925, 488925, False),
]
)
@patch(f"{MODULE}.capture_exception")
@@ -609,6 +625,7 @@ class TestKilledAttemptRetry:
self,
_name: str,
checkpoint_rows: int,
+ checkpoint_temp_uri: str | None,
started_from: int | None,
run_started_from: int | None,
expect_resume: bool,
@@ -624,21 +641,25 @@ class TestKilledAttemptRetry:
) -> None:
# A hard-killed attempt records no outcome; only its checkpoint can prove progress. The cap
# counts sync runs, so a run that advanced the rewrite and then spent its last retry dying
- # on arrival still converged and must keep the table.
+ # on arrival still converged and must keep the table. The sync's own merge invalidates the
+ # checkpoint often enough that a run routinely rebuilds from row 0, and the rebuilt
+ # checkpoint reads below the stamp even when the run committed a large prefix.
pending = {
**PENDING_TARGET,
"trigger_reason": "coarsening",
"attempts": MAX_REPARTITION_ATTEMPTS,
"charged_job_id": str(uuid.uuid4()),
"attempt_rows": started_from,
+ "attempt_rewrite_id": TEMP_URI,
}
if run_started_from is not None:
pending["run_rows"] = run_started_from
+ pending["run_rewrite_id"] = TEMP_URI
schema = _schema(
name="public.deals",
s3_folder_name="deals",
pending=pending,
- rewrite={"rows_written": checkpoint_rows},
+ rewrite={"rows_written": checkpoint_rows, "temp_uri": checkpoint_temp_uri},
)
mock_schema_model.objects.select_related.return_value.get.return_value = schema
mock_repartition.return_value = {"outcome": "completed"}