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-imports): let a stuck repartition give up and be released (#77769)

Daniel RCba6595c1c9a8
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 08d1996fad40..64a1f96cae34 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
@@ -86,6 +86,18 @@ class RepartitionUnpartitionableError(Exception):
"""The table has no column suitable for partitioning — repartition is skipped, not retried."""
+class RepartitionBudgetExceededError(Exception):
+ """The rewrite ran out of activity budget before it finished streaming the table.
+
+ Raised by the rewrite loop on reaching the deadline derived from the activity's
+ `start_to_close_timeout`. It exists so the activity observes its own budget exhaustion instead of
+ being killed by Temporal, which records nothing: the killed attempt keeps running as a zombie
+ until a claim check makes it stand down, standing down burns no attempt, so
+ `MAX_REPARTITION_ATTEMPTS` is never reached and the table re-enters the rewrite ahead of every
+ later sync forever. A table whose rewrite cannot fit in one activity needs to be told so.
+ """
+
+
class RepartitionSupersededError(Exception):
"""A newer repartition attempt has claimed this schema — this stale attempt must stop.
@@ -402,6 +414,7 @@ async def _rewrite_into_temp(
logger: FilteringBoundLogger,
ensure_claim: Callable[[], Awaitable[None]] | None = None,
claim_recheck_interval_seconds: float = CLAIM_RECHECK_INTERVAL_SECONDS,
+ deadline: float | None = None,
) -> tuple[int, RepartitionTarget]:
"""Stream the live table into a fresh temp table under the new partition scheme.
@@ -410,6 +423,9 @@ async def _rewrite_into_temp(
`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`).
+
+ `deadline` is a `time.monotonic()` value past which the rewrite gives up with
+ `RepartitionBudgetExceededError` rather than run until Temporal kills it. None runs unbounded.
"""
dataset = await asyncio.to_thread(old_delta.to_pyarrow_dataset)
reader = await asyncio.to_thread(lambda: dataset.scanner(batch_size=batch_size).to_reader())
@@ -454,6 +470,15 @@ async def _rewrite_into_temp(
batch = await asyncio.to_thread(_read_next_batch, reader)
if batch is None:
break
+ # Deliberately after the read, so exhausting the reader always beats the deadline. Checking
+ # first would let a rewrite that has already copied every row be discarded and charged an
+ # attempt because it happened to cross the deadline on the iteration that would have hit
+ # EOF, which is likeliest for a table whose rewrite lands near the budget: exactly the ones
+ # this deadline exists to rescue.
+ if deadline is not None and time.monotonic() >= deadline:
+ raise RepartitionBudgetExceededError(
+ f"rewrite exceeded its activity budget after {rows_written} rows written to {temp_uri}"
+ )
table = pa.Table.from_batches([batch])
if table.num_rows == 0:
@@ -527,6 +552,7 @@ async def repartition_table_in_place(
*,
batch_size: int = DEFAULT_REPARTITION_BATCH_SIZE,
claim_token: str | None = None,
+ deadline: float | None = None,
) -> dict[str, Any]:
"""Rewrite the schema's Delta table under `target`'s finer partition scheme, in place, from S3.
@@ -539,6 +565,10 @@ async def repartition_table_in_place(
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).
+
+ `deadline` (a `time.monotonic()` value) bounds the rewrite phase only. The swap that follows
+ needs no bound of its own: it records `repartition_swap` before touching live, so a swap cut
+ short by the activity timeout resumes from the intact temp table on a later run.
"""
live_uri = await table_ref.get_table_uri()
storage_options = table_ref.get_storage_options()
@@ -636,8 +666,9 @@ async def repartition_table_in_place(
batch_size=batch_size,
logger=logger,
ensure_claim=ensure_claim,
+ deadline=deadline,
)
- except (RepartitionSupersededError, RepartitionUnpartitionableError):
+ except (RepartitionSupersededError, RepartitionUnpartitionableError, RepartitionBudgetExceededError):
raise
except Exception as e:
missing_path = _missing_live_object_path(e, live_uri)
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 74e17d48cd4f..d87b735b12d1 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
@@ -22,6 +22,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.par
append_partition_key_to_table,
)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.repartition import (
+ RepartitionBudgetExceededError,
RepartitionSupersededError,
RepartitionTarget,
_rewrite_into_temp,
@@ -319,6 +320,78 @@ class TestRewriteIntoTemp:
for key in new_sizes:
assert key is not None and len(key) == len("2024-01-05")
+ def test_stops_mid_stream_once_the_deadline_passes(self, tmp_path):
+ rows = [
+ (1, datetime.datetime(2024, 1, 5)),
+ (2, datetime.datetime(2024, 1, 20)),
+ (3, datetime.datetime(2024, 1, 25)),
+ (4, datetime.datetime(2024, 2, 2)),
+ ]
+ old_delta = _write_month_partitioned(str(tmp_path / "src"), rows)
+ temp_uri = str(tmp_path / "tmp")
+
+ # One reading per batch read. Batches coalesce into a commit rather than writing one each,
+ # so the deadline has to fall after the buffer has flushed at least once for any row to be
+ # observable in temp at all.
+ clock = Mock(side_effect=[0.0, 0.0, 100.0])
+
+ with patch.object(repartition_module, "time", Mock(monotonic=clock)):
+ with pytest.raises(RepartitionBudgetExceededError):
+ asyncio.run(
+ _rewrite_into_temp(
+ old_delta=old_delta,
+ temp_uri=temp_uri,
+ storage_options={},
+ target=RepartitionTarget(
+ partition_keys=["created_at"],
+ trigger_reason="test",
+ partition_mode="datetime",
+ partition_format="day",
+ ),
+ batch_size=2,
+ logger=logger,
+ deadline=50.0,
+ )
+ )
+
+ # Some rows landed but not all: the deadline is checked per batch inside the streaming loop,
+ # so the rewrite gives up partway instead of either draining the reader (no bound at all) or
+ # bailing before it starts. The exact count is not asserted because the reader yields at
+ # least one batch per source file, so batch boundaries follow the source layout.
+ written = deltalake.DeltaTable(temp_uri).to_pyarrow_table().num_rows
+ assert 0 < written < len(rows)
+
+ def test_a_finished_rewrite_beats_the_deadline(self, tmp_path):
+ # One source file, one batch, so the reader is exhausted on the second loop iteration. The
+ # clock is over the deadline by then: a rewrite that has already copied every row must still
+ # reach the swap rather than be thrown away and charged a failed attempt.
+ rows = [(1, datetime.datetime(2024, 1, 5)), (2, datetime.datetime(2024, 1, 20))]
+ old_delta = _write_month_partitioned(str(tmp_path / "src"), rows)
+ temp_uri = str(tmp_path / "tmp")
+
+ clock = Mock(side_effect=[0.0, 100.0])
+
+ with patch.object(repartition_module, "time", Mock(monotonic=clock)):
+ rows_written, _ = asyncio.run(
+ _rewrite_into_temp(
+ old_delta=old_delta,
+ temp_uri=temp_uri,
+ storage_options={},
+ target=RepartitionTarget(
+ partition_keys=["created_at"],
+ trigger_reason="test",
+ partition_mode="datetime",
+ partition_format="day",
+ ),
+ batch_size=2,
+ logger=logger,
+ deadline=50.0,
+ )
+ )
+
+ assert rows_written == len(rows)
+ assert deltalake.DeltaTable(temp_uri).to_pyarrow_table().num_rows == len(rows)
+
def test_resolved_mode_is_fixed_by_first_batch(self, tmp_path):
# Auto-detect (mode=None) must resolve once and apply to every batch, not re-detect per batch.
rows = [(i, datetime.datetime(2024, 1, (i % 27) + 1)) for i in range(10)]
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 3bcea90ae434..07af609cc828 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
@@ -363,11 +363,15 @@ class TestRepartitionActivity:
def _run(self, inputs: RepartitionActivityInputs, repartition_mock: AsyncMock):
# Mock HeartbeaterSync (no real heartbeat thread / activity context needed) and the primitive,
- # so these exercise the activity's decision + bookkeeping, not the rewrite itself.
+ # so these exercise the activity's decision + bookkeeping, not the rewrite itself. The rollout
+ # flag is forced on because it now gates the queued rewrite as well as detection, so every
+ # caller of this helper (all of which stage a pending target and expect it to be acted on)
+ # would otherwise be released by the gate before reaching the bookkeeping under test.
with (
patch.object(repartition_table, "HeartbeaterSync"),
patch.object(repartition_table, "repartition_table_in_place", new=repartition_mock),
patch.object(repartition_table, "capture_repartition_event") as capture,
+ patch.object(repartition_table, "is_auto_repartition_enabled", return_value=True),
):
# ActivityEnvironment.run is synchronous for a sync activity — call it directly.
ActivityEnvironment().run(maybe_repartition_table_activity, inputs)
@@ -543,6 +547,7 @@ class TestRepartitionActivity:
patch.object(repartition_table, "HeartbeaterSync"),
patch.object(repartition_table, "repartition_table_in_place", new=mocked),
patch.object(repartition_table, "capture_repartition_event") as capture,
+ patch.object(repartition_table, "is_auto_repartition_enabled", return_value=True),
):
with pytest.raises((asyncio.CancelledError, CancelledError)):
ActivityEnvironment().run(maybe_repartition_table_activity, self._inputs(team, schema))
@@ -651,6 +656,7 @@ class TestRepartitionActivity:
patch.object(repartition_table, "repartition_table_in_place", new=mocked),
patch.object(repartition_table, "capture_repartition_event") as capture,
patch.object(repartition_table, "_still_claimant", return_value=still_claimant),
+ patch.object(repartition_table, "is_auto_repartition_enabled", return_value=True),
):
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]
@@ -728,6 +734,7 @@ class TestRepartitionActivity:
patch.object(repartition_table, "HeartbeaterSync"),
patch.object(repartition_table, "repartition_table_in_place", new=mocked),
patch.object(repartition_table, "capture_repartition_event"),
+ patch.object(repartition_table, "is_auto_repartition_enabled", return_value=True),
):
ActivityEnvironment().run(
maybe_repartition_table_activity,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_end_to_end.py b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_end_to_end.py
index e9aab31a4331..b4866f3c589b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_end_to_end.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_end_to_end.py
@@ -2192,7 +2192,14 @@ async def test_in_place_repartition_to_finer_datetime_format(team, postgres_conf
)
await postgres_connection.commit()
- await _execute_run(str(uuid.uuid4()), inputs, [])
+ # The rollout flag gates the queued rewrite, not just detection, so a table whose repartition is
+ # already pending is still released when the flag is off. Force it on for the run under test.
+ with mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.workflow_activities."
+ "repartition_table.is_auto_repartition_enabled",
+ return_value=True,
+ ):
+ await _execute_run(str(uuid.uuid4()), inputs, [])
await _replay_v3_consumer(team_id=team.pk, schema_id=inputs.external_data_schema_id)
schema = await ExternalDataSchema.objects.aget(id=inputs.external_data_schema_id)
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 145f5fbaf68c..215c166680ac 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
@@ -12,6 +12,7 @@ policy re-runs it in this run (the workflow swallows the failure if retries exha
import time
import uuid
import asyncio
+import datetime as dt
import dataclasses
from typing import Any
@@ -36,6 +37,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.del
is_transient_object_store_error,
)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.repartition import (
+ RepartitionBudgetExceededError,
RepartitionSupersededError,
RepartitionTarget,
RepartitionUnpartitionableError,
@@ -84,6 +86,32 @@ _TRANSIENT_ERROR_SNIPPETS = (
)
+# How much of the activity's budget to leave unused when the rewrite gives up, so the failed attempt
+# can still be recorded before Temporal kills the activity. Only the bookkeeping needs covering: a
+# couple of writes to the schema row and one event.
+REWRITE_DEADLINE_MARGIN = dt.timedelta(minutes=5)
+
+
+def _rewrite_deadline() -> float | None:
+ """Monotonic time by which the rewrite must stop to leave room to record its own failure.
+
+ None when there is no budget to derive one from: outside an activity context (direct calls from
+ tests), when the activity declares no `start_to_close_timeout`, or when that timeout is shorter
+ than the margin. In each case the rewrite runs unbounded, which is the behavior that predates
+ this deadline rather than an instant give-up.
+ """
+ try:
+ info = activity.info()
+ except RuntimeError:
+ return None
+ if info.start_to_close_timeout is None:
+ return None
+ budget = (info.start_to_close_timeout - REWRITE_DEADLINE_MARGIN).total_seconds()
+ if budget <= 0:
+ return None
+ return time.monotonic() + budget
+
+
def _is_transient_infra_error(error: Exception) -> bool:
if isinstance(error, OperationalError | InterfaceError):
return True
@@ -240,6 +268,20 @@ def _maybe_repartition_table(inputs: RepartitionActivityInputs, logger: Filterin
pending = schema.repartition_pending
swap = schema.repartition_swap
+ # The flag has to stop a queued rewrite too, not only detection. Once a table is flagged, the
+ # rewrite runs ahead of extraction on every sync, so a rewrite that can't finish delays the sync
+ # by the full activity budget indefinitely; the flag is the only lever support has to release
+ # such a table, and it does nothing here if it only gates detection. Two exclusions: a staged
+ # swap must always be driven to completion because temp is the source of truth in that window
+ # and live may already be deleted, and an operator-staged rewrite ignores the rollout flag
+ # because they staged it knowing that syncing on the old layout is the worse option.
+ if not enabled and pending is not None and swap is None and pending.get("trigger_reason") != "admin":
+ logger.info(
+ f"repartition: queued rewrite skipped, controller disabled by feature flag schema_id={schema.id}",
+ schema_id=str(schema.id),
+ )
+ return
+
# Fast no-op path: nothing queued and the gate says no on-disk measurement is needed (flag off, or
# CDC). Return here — before fetching the job and reading the delta log — so the common healthy
# invocation avoids all on-disk I/O. Flagged tables fall through and measure the live size below.
@@ -300,7 +342,18 @@ def _maybe_repartition_table(inputs: RepartitionActivityInputs, logger: Filterin
target=target,
logger=logger,
claim_token=claim_token,
+ deadline=_rewrite_deadline(),
)
+ except RepartitionBudgetExceededError as e:
+ # The table is telling us its rewrite doesn't fit in one activity. Record it as a real failed
+ # attempt so `MAX_REPARTITION_ATTEMPTS` is reachable and the table eventually gives up,
+ # instead of restarting the same doomed rewrite in front of every sync forever.
+ logger.warning(f"repartition: {e}")
+ DELTA_REPARTITION_TOTAL.labels(
+ team_id=str(inputs.team_id),
+ outcome=_handle_failure(inputs, schema, pending, trigger_reason, e, claim_token, logger),
+ ).inc()
+ return
except RepartitionSupersededError:
# 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),
@@ -459,6 +512,11 @@ def _handle_failure(
props["final"] = True
schema.clear_repartition_pending()
schema.clear_repartition_swap()
+ # Engage the cooldown as well, or the give-up never takes effect: the trigger that queued
+ # this rewrite (the largest partition is over budget) is just as true on the next sync and
+ # the layout is unchanged, so detection re-flags the table immediately with `attempts` back
+ # at 0 and the three attempts start over. The cooldown re-evaluates at most daily instead.
+ schema.stamp_last_repartition_at()
else:
updated = {**pending, "attempts": attempts}
schema.set_repartition_pending(updated)
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 e8e7d6191e43..1b4ed5f2b547 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
@@ -1,4 +1,5 @@
import uuid
+import datetime as dt
import pytest
from unittest.mock import AsyncMock, MagicMock, patch
@@ -8,10 +9,14 @@ from parameterized import parameterized
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.errors import (
TransientObjectStoreError,
)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.repartition import (
+ RepartitionBudgetExceededError,
+)
from products.warehouse_sources.backend.temporal.data_imports.workflow_activities.repartition_table import (
RepartitionActivityInputs,
_maybe_flag_pre_extraction,
_maybe_repartition_table,
+ _rewrite_deadline,
)
MODULE = "products.warehouse_sources.backend.temporal.data_imports.workflow_activities.repartition_table"
@@ -32,7 +37,13 @@ PENDING_TARGET = {
}
-def _schema(*, name: str, s3_folder_name: str | None) -> MagicMock:
+def _schema(
+ *,
+ name: str,
+ s3_folder_name: str | None,
+ pending: dict | None = PENDING_TARGET,
+ swap: dict | None = None,
+) -> MagicMock:
schema = MagicMock()
schema.id = SCHEMA_ID
schema.name = name
@@ -40,8 +51,11 @@ def _schema(*, name: str, s3_folder_name: str | None) -> MagicMock:
schema.resolved_s3_folder_name = s3_folder_name
schema.team_id = TEAM_ID
schema.delta_revive_required = None
- schema.repartition_swap = None
- schema.repartition_pending = PENDING_TARGET
+ schema.repartition_swap = swap
+ schema.repartition_pending = pending
+ # The failure bookkeeping re-reads the claim to check it still owns the schema, so the mock has
+ # to actually remember the token the activity just staked.
+ schema.set_repartition_claim.side_effect = lambda claim: setattr(schema, "repartition_claim", claim)
return schema
@@ -91,6 +105,132 @@ class TestRepartitionActivityDeltaFolder:
assert mock_job_model.objects.get.call_args.kwargs == {"id": JOB_ID}
+NO_ACTIVITY_CONTEXT = object()
+
+
+class TestRewriteDeadline:
+ @parameterized.expand(
+ [
+ ("outside_an_activity", NO_ACTIVITY_CONTEXT, None),
+ ("no_declared_timeout", None, None),
+ ("timeout_shorter_than_the_margin", dt.timedelta(minutes=1), None),
+ ("timeout_leaves_a_budget", dt.timedelta(hours=6), 22300.0),
+ ]
+ )
+ def test_deadline_is_set_only_when_there_is_budget_to_derive(
+ self, _name: str, timeout: object, expected: float | None
+ ) -> None:
+ info = MagicMock()
+ info.start_to_close_timeout = timeout
+ info_fn = (
+ MagicMock(side_effect=RuntimeError("not in an activity context"))
+ if timeout is NO_ACTIVITY_CONTEXT
+ else MagicMock(return_value=info)
+ )
+
+ with (
+ patch(f"{MODULE}.activity.info", info_fn),
+ patch(f"{MODULE}.time", MagicMock(monotonic=MagicMock(return_value=1000.0))),
+ ):
+ assert _rewrite_deadline() == expected
+
+
+class TestBudgetExhaustion:
+ @parameterized.expand([("below_max", 0, False), ("reaching_max", 2, True)])
+ @patch(f"{MODULE}.capture_exception")
+ @patch(f"{MODULE}.capture_repartition_event")
+ @patch(f"{MODULE}.HeartbeaterSync")
+ @patch(f"{MODULE}.repartition_table_in_place", new_callable=AsyncMock)
+ @patch(f"{MODULE}.DeltaTableRef")
+ @patch(f"{MODULE}.is_auto_repartition_enabled", return_value=True)
+ @patch(f"{MODULE}.ExternalDataJob")
+ @patch(f"{MODULE}.ExternalDataSchema")
+ def test_budget_exhaustion_burns_an_attempt_and_gives_up_with_a_cooldown(
+ self,
+ _name: str,
+ prior_attempts: int,
+ expect_give_up: bool,
+ mock_schema_model: MagicMock,
+ _mock_job_model: MagicMock,
+ _mock_enabled: MagicMock,
+ _mock_helper_cls: MagicMock,
+ mock_repartition: AsyncMock,
+ _mock_heartbeater: MagicMock,
+ _mock_capture_event: MagicMock,
+ _mock_capture_exception: MagicMock,
+ ) -> None:
+ schema = _schema(
+ name="public.usages",
+ s3_folder_name="usages",
+ pending={**PENDING_TARGET, "attempts": prior_attempts},
+ )
+ mock_schema_model.objects.select_related.return_value.get.return_value = schema
+ mock_repartition.side_effect = RepartitionBudgetExceededError("out of budget after 12 rows")
+
+ _maybe_repartition_table(
+ RepartitionActivityInputs(team_id=TEAM_ID, schema_id=SCHEMA_ID, job_id=JOB_ID, source_id=SOURCE_ID),
+ MagicMock(),
+ )
+
+ if expect_give_up:
+ schema.clear_repartition_pending.assert_called_once()
+ schema.stamp_last_repartition_at.assert_called_once()
+ schema.set_repartition_pending.assert_not_called()
+ else:
+ assert schema.set_repartition_pending.call_args.args[0]["attempts"] == prior_attempts + 1
+ schema.clear_repartition_pending.assert_not_called()
+ schema.stamp_last_repartition_at.assert_not_called()
+
+
+class TestFeatureFlagGate:
+ @parameterized.expand(
+ [
+ ("flag_off_releases_a_queued_rewrite", False, None, "proactive_threshold", False),
+ ("flag_off_still_finishes_a_staged_swap", False, {"state": "ready"}, "proactive_threshold", True),
+ ("flag_off_does_not_block_an_operator", False, None, "admin", True),
+ ("flag_on_rewrites_as_usual", True, None, "proactive_threshold", True),
+ ]
+ )
+ @patch(f"{MODULE}.capture_repartition_event")
+ @patch(f"{MODULE}.HeartbeaterSync")
+ @patch(f"{MODULE}.repartition_table_in_place", new_callable=AsyncMock)
+ @patch(f"{MODULE}.DeltaTableRef")
+ @patch(f"{MODULE}.is_auto_repartition_enabled")
+ @patch(f"{MODULE}.ExternalDataJob")
+ @patch(f"{MODULE}.ExternalDataSchema")
+ def test_flag_gates_the_queued_rewrite(
+ self,
+ _name: str,
+ enabled: bool,
+ swap: dict | None,
+ trigger_reason: str,
+ expect_rewrite: bool,
+ mock_schema_model: MagicMock,
+ _mock_job_model: MagicMock,
+ mock_enabled: MagicMock,
+ _mock_helper_cls: MagicMock,
+ mock_repartition: AsyncMock,
+ _mock_heartbeater: MagicMock,
+ _mock_capture_event: MagicMock,
+ ) -> None:
+ mock_enabled.return_value = enabled
+ schema = _schema(
+ name="public.usages",
+ s3_folder_name="usages",
+ pending={**PENDING_TARGET, "trigger_reason": trigger_reason},
+ swap=swap,
+ )
+ mock_schema_model.objects.select_related.return_value.get.return_value = schema
+ mock_repartition.return_value = {"outcome": "completed"}
+
+ _maybe_repartition_table(
+ RepartitionActivityInputs(team_id=TEAM_ID, schema_id=SCHEMA_ID, job_id=JOB_ID, source_id=SOURCE_ID),
+ MagicMock(),
+ )
+
+ assert mock_repartition.await_count == (1 if expect_rewrite else 0)
+
+
class TestMaybeFlagPreExtraction:
@parameterized.expand(
[