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): run long repartition rewrites one sync interval at a time (#117906)

Daniel RC1519ec459f82
diff --git a/products/warehouse_sources/backend/models/external_data_schema.py b/products/warehouse_sources/backend/models/external_data_schema.py
index 581c8d5cd8d9..6ac7a269ef3f 100644
--- a/products/warehouse_sources/backend/models/external_data_schema.py
+++ b/products/warehouse_sources/backend/models/external_data_schema.py
@@ -920,7 +920,7 @@ class ExternalDataSchema( # nosemgrep: semgrep.rules.security.prefer-uuid7-djan
in one activity converges across attempts rather than giving up terminally. Cleared once temp
is fully built (a swap is staged) or when the controller gives up. Shape:
{"temp_uri": str, "rows_written": int, "target": dict, "live_version": int, "held_at": str,
- "budget_exhausted": bool}.
+ "budget_exhausted": bool, "sliced": bool}.
"""
if self.sync_type_config:
marker = self.sync_type_config.get("repartition_rewrite", None)
@@ -1058,6 +1058,14 @@ class ExternalDataSchema( # nosemgrep: semgrep.rules.security.prefer-uuid7-djan
)
)
+ def disable_repartition_slicing(self) -> None:
+ def _write(config: dict[str, Any]) -> None:
+ pending = config.get("repartition_pending")
+ if isinstance(pending, dict):
+ pending["slice_disabled"] = True
+
+ self.sync_type_config = update_sync_type_config_keys(schema_id=self.id, team_id=self.team_id, mutate=_write)
+
def clear_repartition_swap(self) -> None:
self.sync_type_config.pop("repartition_swap", None)
self._save_sync_type_config()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/README.md b/products/warehouse_sources/backend/temporal/data_imports/README.md
index 2c168d2668df..cef517f09b2b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/README.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/README.md
@@ -57,6 +57,7 @@ Week into month is the one transition that cannot be computed exactly, because I
Tuning and gating:
- Gated by a 24h per-table cooldown. Neither direction is behind a feature flag.
+- A rewrite streams for about one sync interval per sync (`MIN_REWRITE_SLICE` at least), then pauses at the end of its open source file and lets the import run (`reason=sync_slice_ended`). The next sync resumes from the checkpoint, so a long rewrite no longer keeps the table stale for a whole activity budget on every sync. The slice never stops a swap. An operator target (`trigger_reason=admin`), a schema that holds its imports for the rewrite, and a slice longer than the activity budget run unsliced. When an import between two slices invalidates the checkpoint, the target turns slicing off (`slice_disabled`) and runs unsliced from then on, because a sliced rewrite of that table would restart after every slice.
- **Repairing the existing backlog.** The automatic coarsening path will not reach a table that keeps recording OOM occurrences, and the tables most in need of coarsening are exactly the ones the unreliable OOM signal keeps firing on. `./manage.py stage_warehouse_coarsening` is the way in: it nominates tables by setting a `coarsen_requested` marker, and the next sync evaluates them. A nomination skips the policy gates (OOM history, layout age, minimum partition count) because an operator has made that call, but never the safety check: the controller still measures the live layout and refuses any target that would not fit the budget, so a nomination can only ever be a no-op. Nominated rewrites report `trigger_reason=coarsening_requested`. Dry run by default, `--limit` defaults low, and it is worth keeping low: a rewrite blocks that table's sync for as long as it runs, which is seconds for small tables and hours for the largest.
- **Putting back a table that was split too fine.** A table split from just over the budget cannot pass the coarsening safety check, because its coarser partitions are larger than half the budget. `./manage.py stage_warehouse_repartition --schema-id <id> --format <tier>` covers that case for datetime tables. The operator names the coarser tier, and the command measures the live table and refuses a target whose largest partition would be over the full budget. It then stages the same `repartition_pending` target as the admin page (`trigger_reason=admin`), and the next scheduled sync runs the rewrite. A scheduled full refresh skips the repartition step, so the target then waits for the sync after it. `--schema-id` repeats, and it is a dry run by default.
- The budget is tunable via the `DATA_WAREHOUSE_TARGET_PARTITION_BYTES` setting (default ~0.5 GB at-rest → ~10 GB worst-case merge). Worker pods are multi-tenant, so the budget leaves headroom for concurrent merges under the 29 GB pod limit rather than sizing to a single merge.
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 4bfac7ecfa5c..5f45859e1a60 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
@@ -204,6 +204,10 @@ class RepartitionStoppedError(Exception):
self.rows_written = rows_written
+class RepartitionSliceEndedError(RepartitionStoppedError):
+ """The rewrite paused at a source file boundary because the slice its sync gives it ended."""
+
+
class RepartitionSchemePersistError(Exception):
"""The swap re-bucketed the table in S3 but the new scheme could not be saved to the schema row.
@@ -1008,6 +1012,7 @@ async def _rewrite_into_temp(
copied_files: frozenset[str] = frozenset(),
should_stop: Callable[[], bool] | None = None,
stop_grace_seconds: float = STOP_GRACE_SECONDS,
+ pause_at_file_end: Callable[[], bool] | None = None,
) -> tuple[int, RepartitionTarget]:
"""Stream the live table into a temp table under the new partition scheme.
@@ -1225,7 +1230,7 @@ async def _rewrite_into_temp(
stop_requested_at = time.monotonic()
return True
- async def stop() -> NoReturn:
+ async def stop(*, paused: bool = False) -> NoReturn:
# The throttled checkpoint can be older than the last commit. The next attempt resumes only
# from a checkpoint, so save one now. Without a commit from this attempt there is nothing new
# to record, and temp may not exist yet.
@@ -1233,9 +1238,8 @@ async def _rewrite_into_temp(
await maybe_checkpoint(force=True)
fields = progress()
await logger.ainfo(f"repartition: rewrite stopped early {_format_fields(fields)}", **fields)
- raise RepartitionStoppedError(
- f"rewrite stopped early after {rows_written} rows written to {temp_uri}", rows_written=rows_written
- )
+ error = RepartitionSliceEndedError if paused else RepartitionStoppedError
+ raise error(f"rewrite stopped early after {rows_written} rows written to {temp_uri}", rows_written=rows_written)
last_claim_check: float | None = None
files_left = len(plan)
@@ -1281,7 +1285,11 @@ async def _rewrite_into_temp(
files_left -= 1
# After the last file only the final commit is left, so finishing costs less than a stop
# and a new attempt.
- stopping = files_left > 0 and stop_requested()
+ # A pause never abandons an open file, unlike a stop, so a file longer than the grace
+ # still ends in a commit and the next attempt does not read it again.
+ stop_now = stop_requested()
+ pause_now = not stop_now and pause_at_file_end is not None and pause_at_file_end()
+ stopping = files_left > 0 and (stop_now or pause_now)
if (
(writer is not None and writer.bytes_since_commit >= budget.commit_bytes)
or len(completed_sources) >= budget.max_source_files_per_commit
@@ -1290,7 +1298,7 @@ async def _rewrite_into_temp(
):
await commit()
if stopping:
- await stop()
+ await stop(paused=pause_now)
await commit()
except BaseException:
if writer is not None:
@@ -1388,6 +1396,7 @@ async def repartition_table_in_place(
claim_token: str | None = None,
deadline: float | None = None,
should_stop: Callable[[], bool] | None = None,
+ rewrite_slice_seconds: float | None = None,
) -> dict[str, Any]:
"""Rewrite the schema's Delta table under `target`'s finer partition scheme, in place, from S3.
@@ -1414,6 +1423,10 @@ async def repartition_table_in_place(
True the rewrite stops after its next commit and the swap stops after its current group of files.
Both raise `RepartitionStoppedError` and keep what the next attempt needs to resume (see
`_rewrite_into_temp` and `_swap_temp_into_live`).
+
+ `rewrite_slice_seconds` pauses the rewrite that long after it starts streaming, at the end of its
+ open source file, so the sync can import between two parts of a long rewrite. It never stops the
+ swap, because a staged swap holds the import until it lands.
"""
live_uri = await table_ref.get_table_uri()
storage_options = table_ref.get_storage_options()
@@ -1616,6 +1629,11 @@ async def repartition_table_in_place(
schema_id=str(schema.id),
reason=blocker,
)
+ if (rewrite_checkpoint or {}).get("sliced"):
+ # The import between two slices changed a file the rewrite had copied, so a
+ # sliced rewrite of this table restarts after every slice and never finishes.
+ await asyncio.to_thread(retry_on_db_connection_drop, schema.disable_repartition_slicing)
+ rewrite_slice_seconds = None
await asyncio.to_thread(schema.clear_repartition_rewrite)
resuming_rewrite = False
temp_uri = _temp_uri_for(live_uri, claim_token)
@@ -1664,9 +1682,12 @@ async def repartition_table_in_place(
"target": resolved_target.to_dict(),
"live_version": checkpoint_version,
"held_at": datetime.now(UTC).isoformat(),
+ # A resume that discards a sliced checkpoint turns slicing off for this target.
+ "sliced": rewrite_slice_seconds is not None,
},
)
+ slice_ends_at = None if rewrite_slice_seconds is None else time.monotonic() + rewrite_slice_seconds
try:
rows_written, resolved = await _rewrite_into_temp(
old_delta=old_delta,
@@ -1681,6 +1702,7 @@ async def repartition_table_in_place(
total_rows=old_row_count,
copied_files=copied,
should_stop=should_stop,
+ pause_at_file_end=lambda: slice_ends_at is not None and time.monotonic() >= slice_ends_at,
)
except RepartitionBudgetExceededError as e:
# Only a checkpoint this attempt could build on marks a restart. One the resume path
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 85ff8b25207d..9e86d63b971d 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
@@ -39,6 +39,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.par
)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.repartition import (
RepartitionBudgetExceededError,
+ RepartitionSliceEndedError,
RepartitionStoppedError,
RepartitionSupersededError,
RepartitionTarget,
@@ -1034,6 +1035,34 @@ class TestRewriteIntoTemp:
final = deltalake.DeltaTable(temp_uri).to_pyarrow_table()
assert sorted(cast(list[int], final.column("id").to_pylist())) == [row[0] for row in rows]
+ def test_a_slice_pause_finishes_the_open_source_file_however_long_it_takes(self, tmp_path):
+ rows = [(i, datetime.datetime(2024, 1, 1 + i)) for i in range(3)] + [(3, datetime.datetime(2024, 2, 1))]
+ live = _write_month_partitioned(str(tmp_path / "live"), rows)
+ save_checkpoint = AsyncMock()
+
+ with pytest.raises(RepartitionSliceEndedError) as stopped:
+ asyncio.run(
+ _rewrite_into_temp(
+ old_delta=live,
+ temp_uri=str(tmp_path / "tmp"),
+ storage_options={},
+ target=RepartitionTarget(
+ partition_keys=["created_at"],
+ trigger_reason="t",
+ partition_mode="datetime",
+ partition_format="day",
+ ),
+ budget=_budget(),
+ logger=logger,
+ save_checkpoint=save_checkpoint,
+ pause_at_file_end=lambda: True,
+ stop_grace_seconds=0.0,
+ )
+ )
+
+ assert stopped.value.rows_written == 3
+ save_checkpoint.assert_awaited()
+
def test_a_stop_request_on_the_last_source_file_lets_the_rewrite_finish(self, tmp_path):
rows = [(1, datetime.datetime(2024, 1, 5)), (2, datetime.datetime(2024, 1, 20))]
live = _write_month_partitioned(str(tmp_path / "live"), rows)
@@ -2740,7 +2769,8 @@ class TestRewriteCheckpointResume:
assert saved.call_args.kwargs["checkpoint"]["rows_written"] == 3
- def test_discards_the_checkpoint_when_a_copied_file_is_no_longer_live(self, tmp_path):
+ @pytest.mark.parametrize("sliced", [False, True])
+ def test_discards_the_checkpoint_when_a_copied_file_is_no_longer_live(self, sliced, tmp_path):
# A merge between attempts rewrote a file temp already copied, so temp holds stale rows. The
# checkpoint must be discarded and a fresh rebuild started into our own claim-scoped temp,
# never resumed — resuming would swap stale data over live.
@@ -2757,7 +2787,9 @@ class TestRewriteCheckpointResume:
"rows_written": 1,
"target": target.to_dict(),
"live_version": live.version() + 999,
+ "sliced": sliced,
},
+ disable_repartition_slicing=Mock(),
)
with (
@@ -2773,7 +2805,12 @@ class TestRewriteCheckpointResume:
):
asyncio.run(
repartition_table_in_place(
- table_ref=table_ref, schema=schema, target=target, logger=logger, claim_token="tok"
+ table_ref=table_ref,
+ schema=schema,
+ target=target,
+ logger=logger,
+ claim_token="tok",
+ rewrite_slice_seconds=0.0,
)
)
@@ -2781,6 +2818,47 @@ class TestRewriteCheckpointResume:
purge.assert_awaited_once() # fresh rebuild sweeps orphans
assert rewrite.await_args_list[0].kwargs["temp_uri"].endswith("__repartitioned_tok")
assert rewrite.await_args_list[0].kwargs["copied_files"] == frozenset()
+ assert schema.disable_repartition_slicing.call_count == (1 if sliced else 0)
+ assert rewrite.await_args_list[0].kwargs["pause_at_file_end"]() is (not sliced)
+
+ def test_a_sync_slice_stops_the_rewrite_but_never_the_swap(self, tmp_path):
+ 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()
+
+ 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=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,
+ ):
+ asyncio.run(
+ repartition_table_in_place(
+ table_ref=table_ref,
+ schema=schema,
+ target=target,
+ logger=logger,
+ claim_token="tok",
+ should_stop=lambda: False,
+ rewrite_slice_seconds=0.0,
+ )
+ )
+
+ assert rewrite.await_args is not None and swap.await_args is not None
+ assert rewrite.await_args.kwargs["pause_at_file_end"]() is True
+ assert rewrite.await_args.kwargs["should_stop"]() is False
+ assert swap.await_args.kwargs["should_stop"]() is False
+ with patch.object(repartition_module, "save_repartition_checkpoint_if_claimed", return_value=True) as saved:
+ asyncio.run(rewrite.await_args.kwargs["save_checkpoint"](1, target))
+ assert saved.call_args.kwargs["checkpoint"]["sliced"] is True
@pytest.mark.parametrize(
"version_offset,blocker,expected_restart",
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 b761d671c2b2..1b33f177363c 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
@@ -52,6 +52,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.rep
RepartitionAttemptsExhausted,
RepartitionBudgetExceededError,
RepartitionSchemePersistError,
+ RepartitionSliceEndedError,
RepartitionStoppedError,
RepartitionSupersededError,
RepartitionTarget,
@@ -65,6 +66,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.rep
MAX_REPARTITION_ATTEMPTS,
base_event_props,
capture_repartition_event,
+ is_repartition_hold_enabled,
maybe_flag_for_repartition,
needs_pre_extraction_detection,
pre_extraction_measurement_is_redundant,
@@ -171,6 +173,40 @@ def _rewrite_deadline(activity_started: float) -> float | None:
return activity_started + budget
+# Each slice pays for a resume, which lists the live table and the temp table again.
+MIN_REWRITE_SLICE = dt.timedelta(minutes=30)
+
+
+def _rewrite_slice_seconds(
+ schema: ExternalDataSchema,
+ pending: dict[str, Any] | None,
+ trigger_reason: str,
+ *,
+ activity_started: float,
+ deadline: float | None,
+ logger: FilteringBoundLogger,
+) -> float | None:
+ """How long the rewrite streams before it pauses so that this sync can import, or None for no slice.
+
+ No slice for an operator target, because the operator wants that rewrite done first. No slice
+ when the schema holds its imports for the rewrite, because the import would not run anyway.
+ """
+ if trigger_reason == "admin" or (pending or {}).get("slice_disabled"):
+ return None
+ interval = schema.sync_frequency_interval
+ if interval is None:
+ return None
+ slice_seconds = max(interval, MIN_REWRITE_SLICE).total_seconds()
+ if deadline is not None and activity_started + slice_seconds >= deadline:
+ return None
+ try:
+ if is_repartition_hold_enabled(schema):
+ return None
+ except Exception:
+ logger.warning("repartition: could not evaluate the repartition hold flag; slicing", exc_info=True)
+ return slice_seconds
+
+
def _is_transient_infra_error(error: Exception) -> bool:
if isinstance(error, OperationalError | InterfaceError):
return True
@@ -524,6 +560,15 @@ def _maybe_repartition_table(inputs: RepartitionActivityInputs, logger: Filterin
# 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, inputs.job_id, logger)
+ deadline = _rewrite_deadline(activity_started)
+ rewrite_slice_seconds = (
+ None
+ if swap is not None
+ else _rewrite_slice_seconds(
+ schema, pending, trigger_reason, activity_started=activity_started, deadline=deadline, logger=logger
+ )
+ )
+
start = time.monotonic()
try:
# HeartbeaterSync heartbeats on a background thread while the (possibly long) rewrite streams,
@@ -554,9 +599,19 @@ def _maybe_repartition_table(inputs: RepartitionActivityInputs, logger: Filterin
target=target,
logger=logger,
claim_token=claim_token,
- deadline=_rewrite_deadline(activity_started),
+ deadline=deadline,
should_stop=lambda: shutdown_monitor.is_worker_shutdown() or _activity_cancelled(),
+ rewrite_slice_seconds=rewrite_slice_seconds,
)
+ except RepartitionSliceEndedError as e:
+ logger.info(
+ f"repartition: rewrite slice ended, resuming on the next sync rows_written={e.rows_written}",
+ rows_written=e.rows_written,
+ )
+ DELTA_REPARTITION_TOTAL.labels(outcome="sliced").inc()
+ _refund_attempt(schema, charged_attempts, logger)
+ _capture_stood_down(schema, inputs, trigger_reason, "sync_slice_ended", logger)
+ return
except RepartitionStoppedError as e:
# The rewrite stopped at a commit, or the swap between two groups of files. Temp and its
# checkpoint or swap marker stay, so the next attempt copies only what is left. This is not
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 b8c10b6960d0..9a457cfc4da0 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
@@ -24,6 +24,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.del
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.repartition import (
RepartitionBudgetExceededError,
RepartitionSchemePersistError,
+ RepartitionSliceEndedError,
RepartitionStoppedError,
RepartitionTooLargeForBudgetError,
)
@@ -39,6 +40,7 @@ from products.warehouse_sources.backend.temporal.data_imports.workflow_activitie
_maybe_flag_pre_extraction,
_maybe_repartition_table,
_rewrite_deadline,
+ _rewrite_slice_seconds,
)
MODULE = "products.warehouse_sources.backend.temporal.data_imports.workflow_activities.repartition_table"
@@ -91,6 +93,7 @@ def _schema(
schema.resolved_s3_folder_name = s3_folder_name
schema.team_id = TEAM_ID
schema.delta_revive_required = None
+ schema.sync_frequency_interval = None
schema.repartition_swap = swap
schema.repartition_pending = pending
schema.repartition_rewrite = rewrite
@@ -243,6 +246,78 @@ class TestRewriteDeadline:
assert _rewrite_deadline(1000.0) == 22300.0
+class TestRewriteSlice:
+ @parameterized.expand(
+ [
+ ("one_sync_interval", dt.timedelta(hours=1), "proactive_threshold", {}, False, 3600.0),
+ ("floor_for_frequent_syncs", dt.timedelta(minutes=5), "proactive_threshold", {}, False, 1800.0),
+ ("no_schedule", None, "proactive_threshold", {}, False, None),
+ ("slice_past_the_activity_budget", dt.timedelta(hours=24), "coarsening", {}, False, None),
+ ("operator_target", dt.timedelta(hours=1), "admin", {}, False, None),
+ ("slicing_disabled", dt.timedelta(hours=1), "proactive_threshold", {"slice_disabled": True}, False, None),
+ ("imports_held_for_the_rewrite", dt.timedelta(hours=1), "proactive_threshold", {}, True, None),
+ ]
+ )
+ def test_a_rewrite_runs_for_one_sync_interval_at_a_time(
+ self,
+ _name: str,
+ interval: dt.timedelta | None,
+ trigger_reason: str,
+ pending_extra: dict,
+ hold_enabled: bool,
+ expected: float | None,
+ ) -> None:
+ schema = _schema(name="contacts", s3_folder_name="contacts")
+ schema.sync_frequency_interval = interval
+ with patch(f"{MODULE}.is_repartition_hold_enabled", return_value=hold_enabled):
+ slice_seconds = _rewrite_slice_seconds(
+ schema,
+ {**PENDING_TARGET, **pending_extra},
+ trigger_reason,
+ activity_started=1000.0,
+ deadline=22300.0,
+ logger=MagicMock(),
+ )
+ assert slice_seconds == expected
+
+ @patch(f"{MODULE}.is_repartition_hold_enabled", return_value=False)
+ @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}.ExternalDataJob")
+ @patch(f"{MODULE}.ExternalDataSchema")
+ def test_a_rewrite_stopped_at_the_end_of_its_slice_lets_the_import_run(
+ self,
+ mock_schema_model: MagicMock,
+ _mock_job_model: MagicMock,
+ _mock_helper_cls: MagicMock,
+ mock_repartition: AsyncMock,
+ _mock_heartbeater: MagicMock,
+ mock_capture_event: MagicMock,
+ _mock_hold: MagicMock,
+ ) -> None:
+ schema = _schema(
+ name="public.usages",
+ s3_folder_name="usages",
+ pending={**PENDING_TARGET, "attempts": 1},
+ rewrite={"rows_written": 50_000, "temp_uri": TEMP_URI},
+ )
+ schema.sync_frequency_interval = dt.timedelta(hours=1)
+ mock_schema_model.objects.select_related.return_value.get.return_value = schema
+ mock_repartition.side_effect = RepartitionSliceEndedError("paused", rows_written=180_000)
+
+ ActivityEnvironment().run(
+ _maybe_repartition_table,
+ RepartitionActivityInputs(team_id=TEAM_ID, schema_id=SCHEMA_ID, job_id=JOB_ID, source_id=SOURCE_ID),
+ MagicMock(),
+ )
+
+ assert schema.repartition_pending["attempts"] == 1
+ skipped = [c.args[1] for c in mock_capture_event.call_args_list if c.args[0] == "warehouse_repartition_skipped"]
+ assert [props["reason"] for props in skipped] == ["sync_slice_ended"]
+
+
class TestBudgetExhaustion:
@parameterized.expand([("below_max", 0, False), ("reaching_max", 2, True)])
@patch(f"{MODULE}.capture_exception")