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): count repartition retries per sync run, not per attempt (#95014)

Tom Owers5811d4ef6df9
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 adb247f674b8..f82bfd0b4ecc 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
@@ -205,10 +205,10 @@ class RepartitionAttemptsExhausted(Exception):
"""Every one of `MAX_REPARTITION_ATTEMPTS` rewrites was charged but none survived to record an
outcome, so the controller gives up and backs the table off to the daily cooldown.
- Each attempt is charged before the rewrite runs and refunded on a clean stand-down (supersession,
- cancellation, transient infra), so reaching the cap this way means every attempt was hard-killed
- mid-run — worker OOM, activity timeout, or an eviction that didn't surface as a cancellation —
- before it could fail cleanly or checkpoint progress. Terminal, and unlike a caught failure it
+ One attempt is charged per sync run before the rewrite runs, and refunded on a clean stand-down
+ (supersession, cancellation, transient infra), so reaching the cap this way means the rewrite was
+ hard-killed in every one of those runs — worker OOM, activity timeout, or an eviction that didn't
+ surface as a cancellation — before it could fail cleanly or checkpoint progress. Terminal, and unlike a caught failure it
carries no underlying exception, so the give-up path constructs and captures this to keep the most
severe repartition outcome visible in error tracking rather than silently abandoned.
"""
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/repartition_controller.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/repartition_controller.py
index 48b06535a83f..ae84a9b4ba4c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/repartition_controller.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/repartition_controller.py
@@ -68,8 +68,8 @@ COARSEN_OOM_FREE_DAYS = 14
# trips repeatedly should converge over a few daily cycles, not thrash every sync.
REPARTITION_COOLDOWN_SECONDS = 24 * 60 * 60
-# Give up (and alert) after this many consecutive failed attempts so a permanently-failing table
-# doesn't re-attempt the rewrite on every sync forever.
+# Give up (and alert) after this many consecutive failed attempts, at most one per sync run, so a
+# permanently-failing table doesn't re-attempt the rewrite on every sync forever.
MAX_REPARTITION_ATTEMPTS = 3
diff --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.py
index ebf28c81f41b..2159e326743e 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
@@ -803,6 +803,33 @@ class TestRepartitionActivity:
assert schema.repartition_pending is None
+ def test_retries_inside_one_sync_run_burn_a_single_attempt(self, team):
+ # Temporal retries this activity up to MAX_REPARTITION_ATTEMPTS times inside one sync run. A
+ # hard-killed attempt records no outcome, so charging every retry let a single bad run spend
+ # the whole cap: the next run gave up and abandoned a table no later sync ever retried.
+ schema = _make_schema(team, {})
+ schema.set_repartition_pending(
+ {
+ "partition_mode": "md5",
+ "partition_count": 4,
+ "partition_keys": ["id"],
+ "trigger_reason": "t",
+ "attempts": 0,
+ }
+ )
+ inputs = self._inputs(team, schema)
+
+ def killed_mid_rewrite(**kwargs):
+ raise KeyboardInterrupt("worker killed")
+
+ for _ in range(MAX_REPARTITION_ATTEMPTS):
+ with contextlib.suppress(BaseException):
+ self._run(inputs, AsyncMock(side_effect=killed_mid_rewrite))
+ schema.refresh_from_db()
+
+ pending = schema.repartition_pending
+ assert pending is not None and pending["attempts"] == 1
+
def test_an_overlapping_attempt_charge_survives_another_attempts_refund(self, team):
# Overlapping attempts must not erase each other's charge, or the cap never counts up and the
# retry loop this change exists to stop comes back.
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 c940f8f4d8b6..6de632430ed5 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
@@ -426,7 +426,7 @@ def _maybe_repartition_table(inputs: RepartitionActivityInputs, logger: Filterin
# instead bounds nothing: a worker killed mid-rewrite records no outcome, so the cap never moves.
# A staged swap runs no rewrite (temp is already complete), so its recovery is not a rewrite
# attempt and is not charged, the same reason the give-up above exempts it.
- charged_attempts = None if swap is not None else _charge_attempt(schema, pending, logger)
+ charged_attempts = None if swap is not None else _charge_attempt(schema, pending, inputs.job_id, logger)
start = time.monotonic()
try:
@@ -755,18 +755,27 @@ def _give_up(
def _charge_attempt(
- schema: ExternalDataSchema, pending: dict[str, Any] | None, logger: FilteringBoundLogger
+ schema: ExternalDataSchema, pending: dict[str, Any] | None, job_id: str, logger: FilteringBoundLogger
) -> int | None:
- """Record this attempt against the retry cap before the rewrite runs; return the prior count.
+ """Record this sync run against the retry cap before the rewrite runs; return the prior count.
- `_refund_attempt` restores that count. None means nothing was charged (no pending marker, or a DB
- failure) — bookkeeping must never block the rewrite.
+ Charged at most once per run, keyed on `job_id`. Temporal retries this activity up to three times
+ inside a single sync, and an attempt that is hard-killed records no outcome, so charging each
+ retry lets one bad sync spend the whole cap: the table is then abandoned by the give-up on the
+ next run, before any later sync ever retries the rewrite. The cap counts syncs that failed, not
+ the retries within one.
+
+ `_refund_attempt` restores the prior count and releases the run's charge. None means nothing was
+ charged (no pending marker, or a DB failure) — bookkeeping must never block the rewrite.
"""
if pending is None:
return None
prior = int(pending.get("attempts", 0))
+ if pending.get("charged_job_id") == job_id:
+ # A retry of a run that already paid: the persisted count already includes its charge.
+ return max(prior - 1, 0)
try:
- schema.set_repartition_pending({**pending, "attempts": prior + 1})
+ schema.set_repartition_pending({**pending, "attempts": prior + 1, "charged_job_id": job_id})
except Exception:
logger.warning("repartition: could not charge attempt, proceeding uncharged", exc_info=True)
return None
@@ -779,7 +788,8 @@ def _refund_attempt(schema: ExternalDataSchema, prior: int | None, logger: Filte
Supersession, transient infra and a checkpoint that advanced are noise or progress, not evidence
the rewrite is doomed. Refunds only when the persisted count is still the one this attempt wrote:
overlapping attempts otherwise let each refund erase the other's charge, and a cap that never
- counts up is the loop this whole change exists to stop.
+ counts up is the loop this whole change exists to stop. Releases the run's charge marker too, so
+ a later retry within the same run charges again rather than riding a refunded charge.
"""
if prior is None:
return
@@ -787,7 +797,7 @@ def _refund_attempt(schema: ExternalDataSchema, prior: int | None, logger: Filte
schema.refresh_from_db(fields=["sync_type_config"])
pending = schema.repartition_pending
if pending is not None and int(pending.get("attempts", 0)) == prior + 1:
- schema.set_repartition_pending({**pending, "attempts": prior})
+ schema.set_repartition_pending({**pending, "attempts": prior, "charged_job_id": None})
except Exception:
logger.warning("repartition: could not refund attempt", exc_info=True)