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(warehouse): scale repartition rewrite by data size not file count (#76957)

Daniel RCba10f7b7f015
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 681e0b6b77cf..08d1996fad40 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
@@ -17,6 +17,7 @@ from __future__ import annotations
import re
import math
+import time
import asyncio
import dataclasses
from collections import defaultdict
@@ -29,6 +30,8 @@ import deltalake as deltalake
import deltalake.exceptions
from structlog.types import FilteringBoundLogger
+from posthog.temporal.common.utils import retry_on_db_connection_drop
+
from products.data_warehouse.backend.facade.api import aget_s3_client
from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrow_utils import (
@@ -36,11 +39,13 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arr
normalize_column_name,
realign_decimal_buffers,
)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.batcher import DEFAULT_MAX_TABLE_BYTES
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.consts import PARTITION_KEY
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.table import _purge_s3_prefix
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.partitioning import (
append_partition_key_to_table,
)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.table_stats import table_payload_bytes
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import (
PartitionFormat,
PartitionMode,
@@ -56,6 +61,24 @@ DATETIME_FORMAT_TIERS: list[PartitionFormat] = ["month", "week", "day", "hour"]
# Rows per streamed record-batch. Bounds the repartition's peak memory independent of partition size.
DEFAULT_REPARTITION_BATCH_SIZE = 50_000
+# Minimum gap between claim re-reads during the rewrite loop. The loop yields at least one batch per
+# source *file*, so an over-fragmented table (the exact kind being repartitioned) produces one batch
+# per partition regardless of `DEFAULT_REPARTITION_BATCH_SIZE` — a few thousand rows spread over a few
+# thousand hour-partitions is a few thousand batches. Re-reading the claim on every one turns a small
+# rewrite into thousands of Postgres round-trips, and any single failure discards the whole rewrite.
+# Throttling is safe because the rewrite writes only to a temp table scoped to our own claim token
+# (`_temp_uri_for`), so a superseded writer cannot reach a newer attempt's rebuild no matter how long
+# it keeps going; the claim's real teeth are the unthrottled checks around the destructive swap steps.
+# 0 disables the throttle (check every batch).
+CLAIM_RECHECK_INTERVAL_SECONDS = 10.0
+
+# Arrow payload the rewrite may hold in its coalescing buffer. Half the package's per-table cap
+# deliberately: the batch that triggers a flush is already materialised and stays resident while the
+# buffer drains, so the true peak is buffer + one incoming batch. Budgeting half keeps that sum inside
+# one `DEFAULT_MAX_TABLE_BYTES` instead of letting it reach twice the cap. Coalescing loses nothing
+# that matters — the win comes from merging thousands of KB-sized batches, not from filling the cap.
+REWRITE_BUFFER_MAX_BYTES = DEFAULT_MAX_TABLE_BYTES // 2
+
TEMP_URI_SUFFIX = "__repartitioned"
@@ -168,7 +191,10 @@ def _temp_uri_for(live_uri: str, claim_token: str | None) -> str:
def _current_claim_token(schema: ExternalDataSchema) -> str | None:
- schema.refresh_from_db(fields=["sync_type_config"])
+ # Retry a dropped pooled connection: this read runs repeatedly across a rewrite that can span tens
+ # of minutes, and pgbouncer recycling one connection under it would otherwise discard all of that
+ # work — the read failing tells us nothing about whether we still hold the claim.
+ retry_on_db_connection_drop(lambda: schema.refresh_from_db(fields=["sync_type_config"]))
claim = schema.repartition_claim
return claim.get("token") if claim else None
@@ -375,13 +401,15 @@ async def _rewrite_into_temp(
batch_size: int,
logger: FilteringBoundLogger,
ensure_claim: Callable[[], Awaitable[None]] | None = None,
+ claim_recheck_interval_seconds: float = CLAIM_RECHECK_INTERVAL_SECONDS,
) -> tuple[int, RepartitionTarget]:
"""Stream the live table into a fresh temp table under the new partition scheme.
Returns (rows_written, resolved_target). The first batch resolves any auto-detected mode/format/
keys so every subsequent batch is bucketed identically (a per-batch auto-detect could disagree).
- `ensure_claim` runs before every batch write so a superseded attempt stops within one batch
- instead of appending into (and corrupting) the newer attempt's rebuild.
+ `ensure_claim` runs before the first batch and then at most once per
+ `claim_recheck_interval_seconds`, so a superseded attempt stops within that window rather than
+ paying a database round-trip per batch (see `CLAIM_RECHECK_INTERVAL_SECONDS`).
"""
dataset = await asyncio.to_thread(old_delta.to_pyarrow_dataset)
reader = await asyncio.to_thread(lambda: dataset.scanner(batch_size=batch_size).to_reader())
@@ -390,9 +418,39 @@ async def _rewrite_into_temp(
resolved: RepartitionTarget | None = None
rows_written = 0
+ buffered: list[pa.Table] = []
+ buffered_rows = 0
+ buffered_bytes = 0
+
+ async def flush() -> int:
+ """Write the buffered batches as one Delta commit and return the rows written."""
+ nonlocal buffered, buffered_rows, buffered_bytes
+ if not buffered:
+ return 0
+ # Every buffered table was already aligned to `live_schema`, so they concat without promotion.
+ combined = buffered[0] if len(buffered) == 1 else pa.concat_tables(buffered)
+ buffered = []
+ buffered_rows = 0
+ buffered_bytes = 0
+ await asyncio.to_thread(
+ deltalake.write_deltalake,
+ temp_uri,
+ combined,
+ partition_by=PARTITION_KEY,
+ mode="append",
+ schema_mode="merge",
+ storage_options=storage_options,
+ )
+ return combined.num_rows
+
+ last_claim_check: float | None = None
+
while True:
if ensure_claim is not None:
- await ensure_claim()
+ now = time.monotonic()
+ if last_claim_check is None or now - last_claim_check >= claim_recheck_interval_seconds:
+ await ensure_claim()
+ last_claim_check = now
batch = await asyncio.to_thread(_read_next_batch, reader)
if batch is None:
break
@@ -437,16 +495,23 @@ async def _rewrite_into_temp(
partitioned_table = evolve_pyarrow_schema(partitioned_table, live_schema)
partitioned_table = realign_decimal_buffers(partitioned_table)
- await asyncio.to_thread(
- deltalake.write_deltalake,
- temp_uri,
- partitioned_table,
- partition_by=PARTITION_KEY,
- mode="append",
- schema_mode="merge",
- storage_options=storage_options,
- )
- rows_written += partitioned_table.num_rows
+ # Coalesce before writing, so commits scale with data size rather than source file count
+ # (see `CLAIM_RECHECK_INTERVAL_SECONDS`). Bound the buffer by bytes as well as rows: a row
+ # count says nothing about width once `evolve_pyarrow_schema` has flattened struct and list
+ # columns into JSON strings. Flush *before* appending whatever would overflow, never after,
+ # or a nearly-full buffer could still take a further full-sized batch. Peak residency is this
+ # buffer plus the batch in hand, which `REWRITE_BUFFER_MAX_BYTES` budgets for.
+ table_bytes = table_payload_bytes(partitioned_table)
+ if buffered and (
+ buffered_rows + partitioned_table.num_rows > batch_size
+ or buffered_bytes + table_bytes > REWRITE_BUFFER_MAX_BYTES
+ ):
+ rows_written += await flush()
+ buffered.append(partitioned_table)
+ buffered_rows += partitioned_table.num_rows
+ buffered_bytes += table_bytes
+
+ rows_written += await flush()
if resolved is None:
# Empty source table — nothing to rewrite.
@@ -471,8 +536,9 @@ async def repartition_table_in_place(
observability. Raises `RepartitionUnpartitionableError` (terminal) if no partition mode applies.
`claim_token` fences out zombie attempts: the temp table is scoped to the token so concurrent
- writers can never share one, and the claim is re-checked before every batch write and every
- destructive step (raising `RepartitionSupersededError` when a newer attempt has taken over).
+ writers can never share one, and the claim is re-checked before every destructive step — and,
+ during the rewrite, at most once per `CLAIM_RECHECK_INTERVAL_SECONDS` (raising
+ `RepartitionSupersededError` when a newer attempt has taken over).
"""
live_uri = await table_ref.get_table_uri()
storage_options = table_ref.get_storage_options()
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 3f4194e9e7b0..74e17d48cd4f 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
@@ -6,6 +6,8 @@ from types import SimpleNamespace
import pytest
from unittest.mock import AsyncMock, Mock, patch
+import django.db
+
import pyarrow as pa
import deltalake as deltalake
import structlog
@@ -920,12 +922,19 @@ class TestResumeWithInvalidTemp:
patch.object(repartition_module, "_valid_delta_row_count", new=AsyncMock(side_effect=[99, 2])),
patch.object(repartition_module, "_rewrite_into_temp", new=AsyncMock(return_value=(2, target))) as rewrite,
patch.object(repartition_module, "_swap_temp_into_live", new=AsyncMock()) as swap,
+ patch.object(repartition_module, "_current_claim_token", return_value="tok"),
):
result = asyncio.run(
- repartition_table_in_place(table_ref=table_ref, schema=schema, target=target, logger=logger)
+ repartition_table_in_place(
+ table_ref=table_ref, schema=schema, target=target, logger=logger, claim_token="tok"
+ )
)
rewrite.assert_awaited_once() # fresh rebuild happened rather than trusting the bad temp
+ # The rebuild must target our own claim-scoped temp, not the marker's URI. Throttled claim
+ # checks mean a zombie can keep writing for a while, so sharing that URI would let it stream
+ # into a temp a newer attempt is also building.
+ assert rewrite.await_args_list[0].kwargs["temp_uri"].endswith("__repartitioned_tok")
swap.assert_awaited_once()
schema.set_repartition_swap.assert_called_once() # fresh temp validated and re-marked
assert result["outcome"] == "completed"
@@ -972,9 +981,9 @@ class TestClaimFencing:
swap.assert_not_awaited()
def test_rewrite_stops_at_batch_boundary_when_claim_lost(self, tmp_path):
- # The zombie's damage window is the rewrite loop, so the claim is re-checked before every batch
- # write — a superseded writer must stop within one batch, not stream its whole table into (and
- # corrupt) the newer attempt's rebuild.
+ # A superseded writer must stop at the next batch boundary once a check is due, rather than
+ # streaming its whole table. Interval 0 forces a check every batch, isolating the stop
+ # behaviour from the throttle covered by test_rewrite_throttles_claim_rechecks.
live = _write_month_partitioned(
str(tmp_path / "live"), [(1, datetime.datetime(2024, 1, 5)), (2, datetime.datetime(2024, 2, 2))]
)
@@ -992,10 +1001,163 @@ class TestClaimFencing:
batch_size=1,
logger=logger,
ensure_claim=ensure,
+ claim_recheck_interval_seconds=0,
)
)
assert ensure.await_count == 2
+ def test_rewrite_throttles_claim_rechecks(self, tmp_path):
+ # A per-batch claim read costs one Postgres round-trip per source file; under the throttle
+ # the whole rewrite checks once.
+ live = _write_month_partitioned(
+ str(tmp_path / "live"), [(i, datetime.datetime(2024, 1 + (i % 12), 5)) for i in range(1, 25)]
+ )
+ ensure = AsyncMock(return_value=None)
+ target = RepartitionTarget(
+ partition_keys=["created_at"], trigger_reason="t", partition_mode="datetime", partition_format="day"
+ )
+ rows_written, _ = asyncio.run(
+ _rewrite_into_temp(
+ old_delta=live,
+ temp_uri=str(tmp_path / "temp"),
+ storage_options={},
+ target=target,
+ batch_size=1,
+ logger=logger,
+ ensure_claim=ensure,
+ claim_recheck_interval_seconds=3600,
+ )
+ )
+ assert rows_written == 24
+ assert ensure.await_count == 1
+
+ def test_rewrite_coalesces_batches_into_one_commit(self, tmp_path):
+ # Commits must scale with data size, not source file count: under one batch_size worth of
+ # rows the whole rewrite lands as a single commit, losing no rows.
+ rows = [(i, datetime.datetime(2024, 1 + (i % 12), 5)) for i in range(1, 37)]
+ live = _write_month_partitioned(str(tmp_path / "live"), rows)
+ assert len(measure_partition_bytes(live)) == 12
+
+ target = RepartitionTarget(
+ partition_keys=["created_at"], trigger_reason="t", partition_mode="datetime", partition_format="day"
+ )
+ temp_uri = str(tmp_path / "temp")
+ rows_written, _ = asyncio.run(
+ _rewrite_into_temp(
+ old_delta=live,
+ temp_uri=temp_uri,
+ storage_options={},
+ target=target,
+ batch_size=50_000,
+ logger=logger,
+ )
+ )
+
+ temp = deltalake.DeltaTable(temp_uri)
+ assert rows_written == 36
+ assert temp.to_pyarrow_dataset().count_rows() == 36
+ # Version 0 is the sole commit; one-per-source-file would leave version 11.
+ assert temp.version() == 0
+
+ def test_rewrite_of_empty_source_writes_nothing(self, tmp_path):
+ # The post-loop drain always runs, so flush() has to tolerate an empty buffer — an empty
+ # source, or a loop that flushed exactly on the bound. Without the guard it indexes an empty
+ # list and raises instead of completing with nothing written.
+ live_uri = str(tmp_path / "live")
+ empty = pa.table(
+ {
+ "id": pa.array([], type=pa.int64()),
+ "created_at": pa.array([], type=pa.timestamp("us")),
+ PARTITION_KEY: pa.array([], type=pa.string()),
+ }
+ )
+ deltalake.write_deltalake(live_uri, empty, partition_by=PARTITION_KEY)
+
+ target = RepartitionTarget(
+ partition_keys=["created_at"], trigger_reason="t", partition_mode="datetime", partition_format="day"
+ )
+ rows_written, resolved = asyncio.run(
+ _rewrite_into_temp(
+ old_delta=deltalake.DeltaTable(live_uri),
+ temp_uri=str(tmp_path / "temp"),
+ storage_options={},
+ target=target,
+ batch_size=50_000,
+ logger=logger,
+ )
+ )
+ assert rows_written == 0
+ assert resolved == target
+
+ def test_rewrite_flushes_on_byte_bound_before_row_bound(self, tmp_path):
+ # A row count says nothing about width once struct/list columns are flattened into JSON
+ # strings, so a row-only bound lets wide rows buffer arbitrarily many bytes and OOM the
+ # worker — the failure this module exists to prevent. Rows stay far under batch_size here,
+ # so only the byte bound can force the extra commits.
+ rows = [(i, datetime.datetime(2024, 1 + (i % 4), 5)) for i in range(1, 25)]
+ live = _write_month_partitioned(str(tmp_path / "live"), rows)
+
+ target = RepartitionTarget(
+ partition_keys=["created_at"], trigger_reason="t", partition_mode="datetime", partition_format="day"
+ )
+ temp_uri = str(tmp_path / "temp")
+ with patch.object(repartition_module, "REWRITE_BUFFER_MAX_BYTES", 100):
+ rows_written, _ = asyncio.run(
+ _rewrite_into_temp(
+ old_delta=live,
+ temp_uri=temp_uri,
+ storage_options={},
+ target=target,
+ batch_size=50_000,
+ logger=logger,
+ )
+ )
+
+ temp = deltalake.DeltaTable(temp_uri)
+ assert rows_written == 24
+ assert temp.to_pyarrow_dataset().count_rows() == 24
+ assert temp.version() > 0
+
+ def test_rewrite_never_buffers_beyond_batch_size(self, tmp_path):
+ # Appending before the size check lets a nearly-full buffer take another full-sized batch, so
+ # peak memory reaches ~2x batch_size — a regression on the one-batch bound the rewrite held
+ # before it coalesced, in the module that exists because oversized in-memory data OOMs the
+ # worker. Four 6-row source files against batch_size=10 catch it: flushing after the append
+ # writes commits of 12 rows, flushing before it keeps every commit within the bound.
+ rows = [(i, datetime.datetime(2024, 1 + (i % 4), 5)) for i in range(1, 25)]
+ live = _write_month_partitioned(str(tmp_path / "live"), rows)
+ assert len(measure_partition_bytes(live)) == 4
+
+ target = RepartitionTarget(
+ partition_keys=["created_at"], trigger_reason="t", partition_mode="datetime", partition_format="day"
+ )
+ temp_uri = str(tmp_path / "temp")
+ rows_written, _ = asyncio.run(
+ _rewrite_into_temp(
+ old_delta=live,
+ temp_uri=temp_uri,
+ storage_options={},
+ target=target,
+ batch_size=10,
+ logger=logger,
+ )
+ )
+
+ temp = deltalake.DeltaTable(temp_uri)
+ assert rows_written == 24
+ assert temp.to_pyarrow_dataset().count_rows() == 24
+ per_commit = [e["operationMetrics"]["num_added_rows"] for e in temp.history()]
+ assert max(per_commit) <= 10
+
+ def test_claim_token_read_retries_dropped_connection(self):
+ # pgbouncer recycling a pooled connection surfaces as OperationalError on first use. Treating
+ # that as a lost claim discarded rewrites that were tens of minutes in, so the read retries.
+ schema = _schema(id="s1", repartition_claim={"token": "tok-ours"})
+ schema.refresh_from_db = Mock(side_effect=[django.db.OperationalError("query_wait_timeout"), None])
+
+ assert repartition_module._current_claim_token(schema) == "tok-ours"
+ assert schema.refresh_from_db.call_count == 2
+
def test_resume_targets_marker_temp_uri_not_claim_scoped(self, tmp_path):
# In-flight prod markers predate claim-scoped temp names; a resume must validate and swap the
# exact temp the marker records — deriving a fresh claim-scoped name instead would "lose" the
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 b366db6f7385..3bcea90ae434 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
@@ -580,6 +580,10 @@ class TestRepartitionActivity:
emitted = [c.args[0] for c in capture.call_args_list]
assert "warehouse_repartition_started" in emitted
assert "warehouse_repartition_failed" not in emitted
+ # A started event with no closing event is indistinguishable from an attempt that vanished.
+ skipped = [c.args[1] for c in capture.call_args_list if c.args[0] == "warehouse_repartition_skipped"]
+ assert [p["reason"] for p in skipped] == ["transient_infra_error"]
+ assert skipped[0]["terminal"] is False
schema.refresh_from_db()
assert schema.repartition_pending is not None
assert schema.repartition_pending["attempts"] == 0
@@ -616,17 +620,21 @@ class TestRepartitionActivity:
assert schema.repartition_pending["attempts"] == 0
@pytest.mark.parametrize(
- "error,still_claimant",
+ "error,still_claimant,expected_reason",
[
- pytest.param(RepartitionSupersededError("claim lost"), True, id="clean_abort"),
- pytest.param(ValueError("boom from clobbered temp"), False, id="collateral_failure"),
+ pytest.param(RepartitionSupersededError("claim lost"), True, "superseded", id="clean_abort"),
+ pytest.param(
+ ValueError("boom from clobbered temp"), False, "superseded_after_error", id="collateral_failure"
+ ),
],
)
- def test_superseded_attempt_is_silent_and_burns_no_attempt(self, team, error, still_claimant):
+ def test_superseded_attempt_is_silent_and_burns_no_attempt(self, team, error, still_claimant, expected_reason):
# A zombie attempt (heartbeat-timed-out but still running) that either stands down cleanly or
# crashes on state its replacement clobbered must not emit warehouse_repartition_failed or
# consume an attempt — the newer claimant owns the run and reports for it. Without this, every
# superseded zombie double-reports and can burn the whole attempt budget on one bad table.
+ # It must still emit a terminal skip: a lone started event with pending left set is
+ # indistinguishable from an attempt that vanished, which made a real incident undiagnosable.
schema = _make_schema(team, {})
schema.set_repartition_pending(
{
@@ -646,12 +654,42 @@ class TestRepartitionActivity:
):
ActivityEnvironment().run(maybe_repartition_table_activity, self._inputs(team, schema))
assert "warehouse_repartition_failed" not in [c.args[0] for c in capture.call_args_list]
+ skipped = [c for c in capture.call_args_list if c.args[0] == "warehouse_repartition_skipped"]
+ assert [c.args[1]["reason"] for c in skipped] == [expected_reason]
schema.refresh_from_db()
assert schema.repartition_pending is not None
assert schema.repartition_pending["attempts"] == 0
# The activity minted a fencing claim before starting the rewrite.
assert schema.repartition_claim is not None
+ def test_stand_down_survives_a_failing_telemetry_capture(self, team):
+ # The stand-down emitters run inside except-handlers whose contract is to swallow. A raising
+ # capture must not escape: it would fail an activity that deliberately stood down, retrying
+ # work the newer claimant already owns.
+ schema = _make_schema(team, {})
+ schema.set_repartition_pending(
+ {"partition_mode": "md5", "partition_count": 4, "partition_keys": ["id"], "trigger_reason": "t"}
+ )
+
+ def _capture(event, props):
+ if event == "warehouse_repartition_skipped":
+ raise RuntimeError("analytics unavailable")
+
+ with (
+ patch.object(repartition_table, "HeartbeaterSync"),
+ patch.object(
+ repartition_table,
+ "repartition_table_in_place",
+ new=AsyncMock(side_effect=RepartitionSupersededError("claim lost")),
+ ),
+ patch.object(repartition_table, "capture_repartition_event", side_effect=_capture),
+ patch.object(repartition_table, "_still_claimant", return_value=True),
+ ):
+ ActivityEnvironment().run(maybe_repartition_table_activity, self._inputs(team, schema))
+
+ schema.refresh_from_db()
+ assert schema.repartition_pending is not None
+
def test_schema_fetch_retries_once_on_transient_db_connection_drop(self, team):
# The schema fetch runs on a long-lived Temporal worker thread, so a pooler-dropped
# connection can raise OperationalError on first use. Unlike every DB read past this point,
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 d461fd6d377d..145f5fbaf68c 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
@@ -302,10 +302,13 @@ def _maybe_repartition_table(inputs: RepartitionActivityInputs, logger: Filterin
claim_token=claim_token,
)
except RepartitionSupersededError:
- # A newer attempt claimed the schema and owns the table now. Stop quietly: recording a failure
- # here would burn an attempt and double-report the run the newer claimant is already handling.
+ # A newer attempt claimed the schema and owns the table now. Stop without recording a *failure*
+ # (that would burn an attempt and double-report the run the newer claimant is already handling),
+ # but still emit the skip: a started event with no terminal event leaves `repartition_pending`
+ # set and no way to tell a stood-down attempt from one that vanished.
logger.info("repartition: superseded by a newer attempt, standing down")
DELTA_REPARTITION_TOTAL.labels(team_id=str(inputs.team_id), outcome="superseded").inc()
+ _capture_stood_down(schema, inputs, trigger_reason, "superseded", logger)
return
except RepartitionUnpartitionableError as e:
# Terminal: the table can't be partitioned on its keys. Clear the flag AND engage the cooldown —
@@ -342,6 +345,7 @@ def _maybe_repartition_table(inputs: RepartitionActivityInputs, logger: Filterin
# failure would burn an attempt and pollute error tracking with self-inflicted noise.
logger.info("repartition: failed after being superseded, standing down", exc_info=True)
DELTA_REPARTITION_TOTAL.labels(team_id=str(inputs.team_id), outcome="superseded").inc()
+ _capture_stood_down(schema, inputs, trigger_reason, "superseded_after_error", logger)
return
if _is_transient_infra_error(e):
# Transient infra noise mid-repartition (app-DB pooler drop, S3 rate limit, credential
@@ -365,6 +369,7 @@ def _maybe_repartition_table(inputs: RepartitionActivityInputs, logger: Filterin
) from e
logger.warning("repartition: transient infra error, will retry on next sync", exc_info=True)
capture_exception(e)
+ _capture_stood_down(schema, inputs, trigger_reason, "transient_infra_error", logger)
return
failure_outcome = _handle_failure(inputs, schema, pending, trigger_reason, e, claim_token, logger)
DELTA_REPARTITION_TOTAL.labels(team_id=str(inputs.team_id), outcome=failure_outcome).inc()
@@ -390,6 +395,31 @@ def _maybe_repartition_table(inputs: RepartitionActivityInputs, logger: Filterin
)
+def _capture_stood_down(
+ schema: ExternalDataSchema,
+ inputs: RepartitionActivityInputs,
+ trigger_reason: str,
+ reason: str,
+ logger: FilteringBoundLogger,
+) -> None:
+ """Emit the closing event for an attempt that stopped without finishing or failing.
+
+ These paths deliberately record no failure, but without a closing event a rewrite that stood down
+ is indistinguishable from one that disappeared mid-flight — both leave `repartition_pending` set
+ and a lone `warehouse_repartition_started`. Reported as skipped so failure dashboards stay clean,
+ and `terminal=False` because the pending marker survives: a later run retries the rewrite, unlike
+ the skips that clear it.
+ """
+ props = base_event_props(schema, schema.source, inputs.job_id)
+ props.update({"trigger_reason": trigger_reason, "reason": reason, "terminal": False})
+ try:
+ capture_repartition_event("warehouse_repartition_skipped", props)
+ except Exception:
+ # Every caller is an except-handler whose contract is to swallow, so a telemetry failure must
+ # not escape: it would fail an activity that deliberately stood down and trigger a retry.
+ logger.warning("repartition: failed to capture stand-down event", exc_info=True)
+
+
def _handle_failure(
inputs: RepartitionActivityInputs,
schema: ExternalDataSchema,