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-sources): make repartition swap and scheme settings atomic (#90181)

posthog[bot]687c7eee5aa4
diff --git a/products/warehouse_sources/backend/models/external_data_schema.py b/products/warehouse_sources/backend/models/external_data_schema.py
index f6d89fd20918..e1f736c07db9 100644
--- a/products/warehouse_sources/backend/models/external_data_schema.py
+++ b/products/warehouse_sources/backend/models/external_data_schema.py
@@ -1220,6 +1220,64 @@ def save_repartition_checkpoint_if_claimed(
return claimed
+def finalize_repartition_scheme(
+ schema: ExternalDataSchema,
+ *,
+ partitioning_keys: list[str],
+ partition_count: int | None,
+ partition_size: int | None,
+ partition_mode: PartitionMode | None,
+ partition_format: PartitionFormat | None,
+ claim_token: str | None = None,
+) -> bool:
+ """Adopt the scheme a completed repartition swap put on disk, and retire its markers, in one write.
+
+ The swap has already re-bucketed the data in S3, so until these settings land the schema row
+ describes a layout the table no longer has. An incremental merge in that window scopes its
+ predicate to a `_ph_partition_key` value the table cannot contain, matches nothing, and inserts
+ every fetched row instead of upserting it. `set_partitioning_enabled` plus the three marker
+ writes leave four separate chances to stop halfway; doing it under one row lock means a reader
+ sees either the whole new scheme or the untouched `repartition_swap` marker that says the swap is
+ still unresolved.
+
+ Returns whether the write happened. False means `claim_token` no longer owns the schema, so a
+ newer attempt owns this swap and will finalize it.
+ """
+ wrote = False
+
+ def _write(config: dict[str, Any]) -> None:
+ nonlocal wrote
+ if claim_token is not None:
+ claim = config.get("repartition_claim")
+ if not (claim and claim.get("token") == claim_token):
+ return
+ config["partitioning_enabled"] = True
+ config["partition_count"] = partition_count
+ config["partition_size"] = partition_size
+ config["partitioning_keys"] = partitioning_keys
+ config["partition_mode"] = partition_mode
+ config["partition_format"] = partition_format
+ # Engage the cooldown here rather than in a follow-up write, or a stop between the two
+ # re-flags the table on the next sync and repartitions it again straight away.
+ config["last_repartition_at"] = timezone.now().isoformat()
+ for key in (
+ # Operator pins are one-shot: they are baked into the settings above, so a later reset
+ # falls back to auto-detection (see `set_partitioning_enabled`).
+ "partition_count_override",
+ "partition_size_override",
+ "partition_mode_override",
+ "partitioning_keys_override",
+ "repartition_swap",
+ "repartition_pending",
+ "repartition_rewrite",
+ ):
+ config.pop(key, None)
+ wrote = True
+
+ schema.sync_type_config = update_sync_type_config_keys(schema_id=schema.id, team_id=schema.team_id, mutate=_write)
+ return wrote
+
+
def complete_schema_run(schema: ExternalDataSchema, *, last_synced_at: datetime) -> bool:
"""Mark a schema COMPLETED after a successful run, atomically with the broken-state check.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/README.md b/products/warehouse_sources/backend/temporal/data_imports/README.md
index c1a2b58fe897..4cfdb95683ff 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/README.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/README.md
@@ -47,6 +47,7 @@ How it works:
Week into month is the one transition that cannot be computed exactly, because ISO weeks straddle month boundaries and the key does not say how a week's bytes divide between two months. It is sized by upper bound instead, charging each straddling week's full size to both months, so a layout that fits under the bound fits in reality. The transition is worth supporting rather than skipping: the finer path's first step is month into week, so without it a table this controller wrongly split could never be merged back. Note the bound also makes it the narrowest transition on offer, since a month holds only about 4.3 weeks against a 4x minimum reduction, so in practice it needs roughly a year of weekly partitions to qualify.
- **Rewrite.** On the next run, a pre-extraction activity streams the live Delta table one record-batch at a time, recomputes `_ph_partition_key` under the finer scheme, and writes a sibling temp table. It then does a crash-safe swap: delete live → server-side copy temp → verify row count → delete temp. Memory is bounded by batch size, independent of partition size. Temp stays the source of truth until the swap is verified, so a worker death at any point loses wasted compute, never data. An interruption (OOM, worker restart) can leave the `__repartitioned` temp partial, so every step that could destroy live re-validates temp first: the swap opens temp and checks it holds the full row count before deleting live, and a resume re-validates the temp the `ready` marker points at — discarding it and rebuilding fresh from the intact live rather than copying a broken temp over live. A live table whose own log is unreadable is skipped (the import activity's revival handles it), not counted as a repartition failure.
+- **Keeping the data and the settings in step.** The swap re-buckets the data in S3, but the scheme it was re-bucketed under lives in the schema row, and the merge computes each incoming row's `_ph_partition_key` from that row. Between the two the table would be describing a layout it no longer has, and a merge there scopes its predicate to a partition the table cannot contain, matches nothing, and inserts every fetched row instead of upserting it — the whole incremental lookback window duplicated, with the job still reporting Completed. Three things keep that window shut. The `repartition_swap` marker records the resolved scheme before the swap starts, so the scheme survives a worker death. The settings, the markers and the cooldown are saved together in one row-locked write (`finalize_repartition_scheme`), so there is no half-applied state to observe. And while the marker is set the table's layout is mid-change by definition, so the import activity holds this schema's syncs — unconditionally, not behind the hold rollout flag, because the alternative is corruption rather than staleness. A run that finds the marker set and temp already gone recomputes a sample of live's keys under the marker's scheme (`_live_matches_scheme`): matching means the swap finished and only its scheme write was lost, so the run saves the scheme and stops instead of rewriting the table for a layout it already has. A swap whose scheme cannot be saved raises `RepartitionSchemePersistError`, which is never classified as transient noise however transient the database error under it was, and the attempt cap never clears an unresolved swap marker.
- **Safety.** Concurrent _syncs_ are excluded (the schedule's `OnlyOne` overlap policy plus the v3 pipeline lock), but concurrent _repartition attempts_ are not: an attempt Temporal heartbeat-times-out keeps running as a zombie (heartbeat failures are swallowed) while its retry starts, and S3 has no locking. The schema row's `repartition_claim` is the fence — each attempt mints a claim token, temp tables are scoped to it (`__repartitioned_<token>`), and the claim is re-checked before every batch write and every destructive step (temp sweep, swap marker, live delete). A superseded attempt raises `RepartitionSupersededError` and stands down silently; orphaned temp variants from superseded or crashed attempts are swept by name prefix before each fresh rebuild. A repartition failure never fails the sync — it's swallowed, retried on a later run, and capped at `MAX_REPARTITION_ATTEMPTS` (3) consecutive failures before it gives up and alerts. Cancellations, superseded attempts, transient infra errors (DB pooler drops, S3 rate limits), and budget-exceeded attempts that advanced the rewrite checkpoint don't count against that cap — a table too large to rewrite in one activity budget converges across runs via the checkpoint, and only an attempt that made no forward progress is charged.
Tuning and gating:
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 47227a2cc6dd..76818ffdc9f6 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
@@ -27,6 +27,7 @@ from typing import TYPE_CHECKING, Any
import pyarrow as pa
import deltalake as deltalake
+import pyarrow.compute as pc
import deltalake.exceptions
from structlog.types import FilteringBoundLogger
@@ -35,6 +36,7 @@ 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,
+ finalize_repartition_scheme,
save_repartition_checkpoint_if_claimed,
)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrow_utils import (
@@ -160,6 +162,20 @@ class RepartitionBudgetExceededError(Exception):
self.checkpoint_saved = checkpoint_saved
+class RepartitionSchemePersistError(Exception):
+ """The swap re-bucketed the table in S3 but the new scheme could not be saved to the schema row.
+
+ Never treated as transient noise, however transient the underlying database error was. The data in
+ S3 now carries `_ph_partition_key` values the schema row does not describe, and the incremental
+ merge scopes its predicate to `target._ph_partition_key = '<partition>'`: under that mismatch
+ nothing matches and every fetched row inserts instead of upserting, duplicating the whole
+ incremental lookback window with the job still reporting Completed.
+
+ The `repartition_swap` marker stays set, which holds this schema's imports until a later run
+ finishes the write — from the marker's recorded scheme, with no rebuild.
+ """
+
+
class RepartitionSupersededError(Exception):
"""A newer repartition attempt has claimed this schema — this stale attempt must stop.
@@ -255,6 +271,111 @@ async def _valid_delta_row_count(uri: str, storage_options: dict[str, str]) -> i
return None
+# Rows read from the live table to tell which partition scheme its data is bucketed under. The
+# question is answered by recomputing one sample's keys, and every row of a scan-ordered sample is an
+# equally good witness, so this only has to be large enough to survive a table whose first rows have
+# a null partition key. Small enough to stay a single parquet row-group read.
+LAYOUT_CHECK_SAMPLE_ROWS = 1_000
+
+
+async def _live_matches_scheme(
+ live_uri: str,
+ storage_options: dict[str, str],
+ target: RepartitionTarget,
+ logger: FilteringBoundLogger,
+ sample_rows: int = LAYOUT_CHECK_SAMPLE_ROWS,
+) -> bool | None:
+ """Whether the live table's stored `_ph_partition_key` values are the ones `target` produces.
+
+ The schema row is the only record of which scheme the data in S3 was bucketed under, so a lost
+ settings write leaves no way to tell the two schemes apart — except by asking the data. This reads
+ a small sample of live rows, recomputes their partition key under `target`, and compares it with
+ the value already stored on the row.
+
+ True means the data is bucketed under `target`, False means it is not, and None means the question
+ could not be answered: the table is unreadable or unpartitioned, the sample is empty, or `target`
+ leaves the mode to auto-detection (which a sample can resolve differently from the full table, so
+ a mismatch would say nothing). Callers must treat None as "unknown", never as "no".
+ """
+ if target.partition_mode is None:
+ return None
+ try:
+ live_delta = await asyncio.to_thread(deltalake.DeltaTable, table_uri=live_uri, storage_options=storage_options)
+ dataset = await asyncio.to_thread(live_delta.to_pyarrow_dataset)
+ sample = await asyncio.to_thread(dataset.head, sample_rows)
+ except Exception:
+ # Every caller has a rebuild to fall back on, so a probe that cannot read the table answers
+ # "unknown" rather than turning a recoverable state into a repartition failure.
+ await logger.awarning("repartition: could not sample the live table's partition keys", exc_info=True)
+ return None
+ if sample.num_rows == 0 or PARTITION_KEY not in sample.column_names:
+ return None
+
+ stored = sample.column(PARTITION_KEY).cast(pa.string())
+ result = append_partition_key_to_table(
+ table=sample.drop([PARTITION_KEY]),
+ partition_count=target.partition_count,
+ partition_size=target.partition_size,
+ partition_keys=target.partition_keys,
+ partition_mode=target.partition_mode,
+ partition_format=target.partition_format,
+ logger=logger,
+ )
+ if result is None:
+ return None
+ recomputed = result.table.column(PARTITION_KEY).cast(pa.string())
+ # Counted rather than reduced with `all`, which skips nulls: a null on either side is a row this
+ # cannot vouch for, and the only use of True is to skip a rebuild, so it has to mean every row.
+ matched = pc.sum(pc.equal(recomputed, stored).cast(pa.int64())).as_py()
+ return matched == sample.num_rows
+
+
+async def _persist_resolved_scheme(
+ schema: ExternalDataSchema,
+ resolved: RepartitionTarget,
+ claim_token: str | None,
+ logger: FilteringBoundLogger,
+) -> None:
+ """Save the scheme the swap just put on disk, and retire the repartition markers with it.
+
+ Raises `RepartitionSchemePersistError` if the write does not land: the table's data and its
+ settings disagree from here until it does, so this is the one failure in the whole flow that the
+ sync must not shrug off. Retried once on a dropped pooled connection — the swap is already done,
+ and losing this small write to a pgbouncer recycle is the likeliest way to reach that state.
+ """
+
+ def _write() -> bool:
+ return finalize_repartition_scheme(
+ schema,
+ partitioning_keys=resolved.partition_keys,
+ partition_count=resolved.partition_count,
+ partition_size=resolved.partition_size,
+ partition_mode=resolved.partition_mode,
+ partition_format=resolved.partition_format,
+ claim_token=claim_token,
+ )
+
+ try:
+ wrote = await asyncio.to_thread(retry_on_db_connection_drop, _write)
+ except Exception as e:
+ raise RepartitionSchemePersistError(
+ f"repartition: the swap landed but the new scheme could not be saved "
+ f"(schema_id={schema.id} scheme={_format_scheme(resolved)}): {e}"
+ ) from e
+ if not wrote:
+ # A newer attempt owns the schema now. It re-drives the swap from the marker we left set, so
+ # standing down here loses nothing — and writing settings under its claim could describe a
+ # layout it is in the middle of replacing.
+ raise RepartitionSupersededError(
+ f"repartition claim lost before the new scheme could be saved schema_id={schema.id}"
+ )
+ await logger.ainfo(
+ f"repartition: saved new scheme scheme={_format_scheme(resolved)} schema_id={schema.id}",
+ scheme=_format_scheme(resolved),
+ schema_id=str(schema.id),
+ )
+
+
async def _purge_stale_temp_tables(s3: Any, live_uri: str) -> None:
"""Delete every `{live_uri}__repartitioned*` temp variant before a fresh rebuild.
@@ -969,8 +1090,11 @@ async def repartition_table_in_place(
Memory is bounded by `batch_size`; the source is never re-read. Crash-safe via the
`repartition_swap` marker (resume re-drives the swap from the intact temp table). On success,
- persists the new partition settings and clears the controller markers. Returns a stats dict for
- observability. Raises `RepartitionUnpartitionableError` (terminal) if no partition mode applies.
+ persists the new partition settings and clears the controller markers in one row-locked write.
+ Returns a stats dict for observability. Raises `RepartitionUnpartitionableError` (terminal) if no
+ partition mode applies, and `RepartitionSchemePersistError` if the swap lands but its scheme
+ cannot be saved — the one failure the caller must not shrug off, since the table's data and its
+ settings disagree until a later run finishes that write.
`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 destructive step — and,
@@ -992,6 +1116,16 @@ async def repartition_table_in_place(
swap = schema.repartition_swap
resuming = bool(swap and swap.get("state") == "ready")
+ # The marker also records the scheme its temp table was built under, and that recording is
+ # authoritative for the whole resume. The `target` passed in is reconstructed from the schema's
+ # *current* settings whenever the pending marker is gone (see `_target_from_schema`), and those
+ # settings still describe the pre-swap layout — saving them once temp is swapped in would write
+ # the exact data/settings mismatch the marker exists to prevent.
+ staged_scheme = (swap or {}).get("target") if resuming else None
+ staged_target = RepartitionTarget.from_dict(staged_scheme) if staged_scheme else None
+ if staged_target is not None:
+ target = staged_target
+
# Rewrite-resume path: a prior attempt ran out of activity budget with temp holding a prefix of
# the table. Continue appending to that temp instead of rebuilding from row 0. A staged swap wins
# (temp is already complete there), so only consider the checkpoint when not swap-resuming.
@@ -1037,6 +1171,7 @@ async def repartition_table_in_place(
storage_options=storage_options,
logger=logger,
ensure_claim=ensure_claim,
+ claim_token=claim_token,
)
await logger.ainfo(f"repartition: no delta table, skipping schema_id={schema.id}", schema_id=str(schema.id))
return {"outcome": "skipped", "reason": "no_delta_table"}
@@ -1062,6 +1197,19 @@ async def repartition_table_in_place(
resolved = target
rows_written = old_row_count
await logger.ainfo(f"repartition: resuming from valid temp schema_id={schema.id}", schema_id=str(schema.id))
+ elif staged_target is not None and await _live_matches_scheme(live_uri, storage_options, staged_target, logger):
+ # temp is gone because the swap finished and deleted it — only the settings write was
+ # lost. Live already carries the marker's keys, so there is nothing to rewrite: finish the
+ # interrupted write instead of re-streaming the whole table for a scheme it already has.
+ await ensure_claim()
+ await _persist_resolved_scheme(schema, staged_target, claim_token, logger)
+ table_ref.get_delta_table.cache_clear()
+ await logger.ainfo(
+ f"repartition: recovered an unrecorded swap, saved scheme={_format_scheme(staged_target)} "
+ f"schema_id={schema.id}",
+ schema_id=str(schema.id),
+ )
+ return {"outcome": "completed", "row_count": old_row_count, "recovered": "scheme_only"}
else:
await logger.awarning(
f"repartition: resume marker points at an invalid temp (rows={temp_rows} "
@@ -1224,9 +1372,13 @@ async def repartition_table_in_place(
)
# Marker makes the swap idempotent: temp stays the source of truth until it's confirmed live.
+ # It carries the resolved scheme as well, because from the moment the swap starts the schema
+ # row's own settings no longer describe what is (or is about to be) on disk — the marker is
+ # then the only record of the scheme a later run has to finish writing.
await ensure_claim()
await asyncio.to_thread(
- schema.set_repartition_swap, {"state": "ready", "temp_uri": temp_uri, "live_uri": live_uri}
+ schema.set_repartition_swap,
+ {"state": "ready", "temp_uri": temp_uri, "live_uri": live_uri, "target": resolved.to_dict()},
)
# temp is complete now, so the rewrite checkpoint is obsolete — the swap marker supersedes it.
await asyncio.to_thread(schema.clear_repartition_rewrite)
@@ -1241,18 +1393,9 @@ async def repartition_table_in_place(
ensure_claim=ensure_claim,
)
- # Persist the new scheme and clear controller state. set_partitioning_enabled saves + pops overrides.
- await asyncio.to_thread(
- schema.set_partitioning_enabled,
- resolved.partition_keys,
- resolved.partition_count,
- resolved.partition_size,
- resolved.partition_mode,
- resolved.partition_format,
- )
- await asyncio.to_thread(schema.clear_repartition_swap)
- await asyncio.to_thread(schema.clear_repartition_pending)
- await asyncio.to_thread(schema.stamp_last_repartition_at)
+ # The data in S3 is on the new scheme from here, so the settings, the markers and the cooldown go
+ # in as one write — a half-applied mix is a table whose merges silently duplicate every row.
+ await _persist_resolved_scheme(schema, resolved, claim_token, logger)
# The cached delta-table object points at the pre-swap files; drop it so callers re-read live.
table_ref.get_delta_table.cache_clear()
@@ -1297,6 +1440,7 @@ async def _resume_swap_with_missing_live(
storage_options: dict[str, str],
logger: FilteringBoundLogger,
ensure_claim: Callable[[], Awaitable[None]] | None = None,
+ claim_token: str | None = None,
) -> dict[str, Any]:
"""Finish a swap whose live table was already deleted by an interrupted prior run.
@@ -1329,17 +1473,7 @@ async def _resume_swap_with_missing_live(
ensure_claim=ensure_claim,
)
- await asyncio.to_thread(
- schema.set_partitioning_enabled,
- target.partition_keys,
- target.partition_count,
- target.partition_size,
- target.partition_mode,
- target.partition_format,
- )
- await asyncio.to_thread(schema.clear_repartition_swap)
- await asyncio.to_thread(schema.clear_repartition_pending)
- await asyncio.to_thread(schema.stamp_last_repartition_at)
+ await _persist_resolved_scheme(schema, target, claim_token, logger)
table_ref.get_delta_table.cache_clear()
await logger.ainfo(
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 d2c75c4456ee..dc5af9566764 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
@@ -34,6 +34,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.rep
select_coarsen_target,
select_repartition_target,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import PartitionFormat
from products.warehouse_sources.backend.temporal.data_imports.workload_report import (
_redis_client,
run_key,
@@ -62,6 +63,12 @@ def _schema(**kwargs):
return SimpleNamespace(**defaults)
+def _patch_finalize():
+ # The real one writes the whole scheme through the ORM under a row lock; these tests drive the
+ # rewrite with SimpleNamespace schemas that have no row behind them.
+ return patch.object(repartition_module, "finalize_repartition_scheme", Mock(return_value=True))
+
+
def _make_table_ref(**kwargs):
# Stand-in for DeltaTableRef; untyped on purpose so callers can pass it to the real signature.
defaults = {
@@ -85,19 +92,25 @@ def _fake_s3(**kwargs):
return SimpleNamespace(**defaults)
-def _write_month_partitioned(path: str, rows: list[tuple[int, datetime.datetime]]) -> deltalake.DeltaTable:
+def _write_datetime_partitioned(
+ path: str, rows: list[tuple[int, datetime.datetime]], partition_format: PartitionFormat
+) -> deltalake.DeltaTable:
table = pa.table(
{
"id": pa.array([r[0] for r in rows], type=pa.int64()),
"created_at": pa.array([r[1] for r in rows], type=pa.timestamp("us")),
}
)
- result = append_partition_key_to_table(table, None, None, ["created_at"], "datetime", "month", logger)
+ result = append_partition_key_to_table(table, None, None, ["created_at"], "datetime", partition_format, logger)
assert result is not None
deltalake.write_deltalake(path, result.table, partition_by=PARTITION_KEY)
return deltalake.DeltaTable(path)
+def _write_month_partitioned(path: str, rows: list[tuple[int, datetime.datetime]]) -> deltalake.DeltaTable:
+ return _write_datetime_partitioned(path, rows, "month")
+
+
class TestSelectRepartitionTarget:
@parameterized.expand(
[
@@ -1453,6 +1466,7 @@ class TestResumeWithInvalidTemp:
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"),
+ _patch_finalize(),
):
result = asyncio.run(
repartition_table_in_place(
@@ -1470,6 +1484,153 @@ class TestResumeWithInvalidTemp:
assert result["outcome"] == "completed"
+class TestLiveMatchesScheme:
+ """Which scheme the data in S3 is bucketed under is otherwise only recorded in the schema row, and
+ a lost settings write is exactly what leaves that row stale — so the answer has to come from the
+ data. A wrong `True` here saves a scheme the table does not have, which is the corruption itself."""
+
+ def _live(self, tmp_path) -> str:
+ _write_month_partitioned(
+ str(tmp_path / "live"), [(1, datetime.datetime(2024, 1, 5)), (2, datetime.datetime(2024, 2, 2))]
+ )
+ return str(tmp_path / "live")
+
+ @pytest.mark.parametrize(
+ "partition_mode, partition_format, expected",
+ [
+ ("datetime", "month", True),
+ ("datetime", "day", False),
+ # A sample can auto-detect a different mode than the whole table did, so a mismatch would
+ # say nothing — and the only use of True is to skip a rebuild.
+ (None, None, None),
+ ],
+ ids=["the_scheme_the_keys_were_built_from", "a_finer_tier_of_the_same_mode", "an_auto_detect_target"],
+ )
+ def test_answers_from_the_live_rows(self, partition_mode, partition_format, expected, tmp_path):
+ target = RepartitionTarget(
+ partition_keys=["created_at"],
+ trigger_reason="resume",
+ partition_mode=partition_mode,
+ partition_format=partition_format,
+ )
+ assert (
+ asyncio.run(repartition_module._live_matches_scheme(self._live(tmp_path), {}, target, logger)) is expected
+ )
+
+
+class TestSwapSchemeIsRecorded:
+ """The swap re-buckets the data in S3; a separate write records the scheme it was bucketed under.
+ Between the two the schema row describes a layout the table no longer has, and the incremental
+ merge scopes its predicate to a partition that cannot exist — matching nothing and inserting every
+ fetched row instead of upserting it."""
+
+ STALE = RepartitionTarget(
+ partition_keys=["created_at"], trigger_reason="resume", partition_mode="datetime", partition_format="month"
+ )
+ STAGED = {
+ "partition_keys": ["created_at"],
+ "trigger_reason": "proactive_threshold",
+ "partition_mode": "datetime",
+ "partition_format": "day",
+ }
+
+ def _schema_resuming(self):
+ return _schema(
+ id="s1",
+ repartition_swap={
+ "state": "ready",
+ "temp_uri": "s3://bucket/live__repartitioned",
+ "live_uri": "s3://bucket/live",
+ "target": self.STAGED,
+ },
+ set_repartition_swap=Mock(),
+ clear_repartition_swap=Mock(),
+ clear_repartition_pending=Mock(),
+ stamp_last_repartition_at=Mock(),
+ )
+
+ def _table_ref(self, tmp_path, partition_format="month"):
+ live = _write_datetime_partitioned(
+ str(tmp_path / "live"),
+ [(1, datetime.datetime(2024, 1, 5)), (2, datetime.datetime(2024, 2, 2))],
+ partition_format,
+ )
+ return _make_table_ref(
+ get_table_uri=AsyncMock(return_value=str(tmp_path / "live")),
+ get_delta_table=AsyncMock(return_value=live),
+ )
+
+ def test_a_resume_saves_the_staged_scheme_not_the_schemas_own_settings(self, tmp_path):
+ # `target` is rebuilt from the schema's current settings whenever the pending marker is gone,
+ # and those still describe the pre-swap layout. Saving them once the new temp is swapped in
+ # leaves the data and the settings permanently disagreeing.
+ table_ref = self._table_ref(tmp_path)
+ schema = self._schema_resuming()
+
+ with (
+ patch.object(repartition_module, "_valid_delta_row_count", new=AsyncMock(return_value=2)),
+ patch.object(repartition_module, "_swap_temp_into_live", new=AsyncMock()),
+ patch.object(repartition_module, "_current_claim_token", return_value="tok"),
+ _patch_finalize() as finalize,
+ ):
+ result = asyncio.run(
+ repartition_table_in_place(
+ table_ref=table_ref, schema=schema, target=self.STALE, logger=logger, claim_token="tok"
+ )
+ )
+
+ assert result["outcome"] == "completed"
+ assert finalize.call_args.kwargs["partition_format"] == "day"
+
+ def test_a_swap_that_already_landed_is_finished_without_rewriting_the_table(self, tmp_path):
+ # temp is gone because the swap deleted it — only the scheme write was lost. Live is on the
+ # staged `day` keys already while the schema row still says `month`, so re-streaming the whole
+ # table would buy nothing the recorded scheme does not already describe.
+ table_ref = self._table_ref(tmp_path, "day")
+ schema = self._schema_resuming()
+
+ with (
+ patch.object(repartition_module, "_valid_delta_row_count", new=AsyncMock(return_value=None)),
+ patch.object(repartition_module, "_rewrite_into_temp", new=AsyncMock()) as rewrite,
+ patch.object(repartition_module, "_swap_temp_into_live", new=AsyncMock()) as swap,
+ patch.object(repartition_module, "_current_claim_token", return_value="tok"),
+ _patch_finalize() as finalize,
+ ):
+ result = asyncio.run(
+ repartition_table_in_place(
+ table_ref=table_ref, schema=schema, target=self.STALE, logger=logger, claim_token="tok"
+ )
+ )
+
+ assert result["recovered"] == "scheme_only"
+ rewrite.assert_not_awaited()
+ swap.assert_not_awaited()
+ assert finalize.call_args.kwargs["partition_format"] == "day"
+
+ def test_a_lost_scheme_write_raises_instead_of_reporting_success(self, tmp_path):
+ # The swap has already landed, so a database blip here is not the noise it looks like: every
+ # merge from now on duplicates its whole lookback window. The caller has to see a failure.
+ table_ref = self._table_ref(tmp_path)
+ schema = self._schema_resuming()
+
+ with (
+ patch.object(repartition_module, "_valid_delta_row_count", new=AsyncMock(return_value=2)),
+ patch.object(repartition_module, "_swap_temp_into_live", new=AsyncMock()),
+ patch.object(repartition_module, "_current_claim_token", return_value="tok"),
+ patch.object(
+ repartition_module,
+ "finalize_repartition_scheme",
+ Mock(side_effect=django.db.OperationalError("server conn crashed?")),
+ ),
+ pytest.raises(repartition_module.RepartitionSchemePersistError),
+ ):
+ asyncio.run(
+ repartition_table_in_place(
+ table_ref=table_ref, schema=schema, target=self.STALE, logger=logger, claim_token="tok"
+ )
+ )
+
+
class TestRewriteCheckpointResume:
"""A rewrite that runs out of activity budget checkpoints its half-built temp so the next attempt
resumes instead of re-streaming from row 0 — the loop that used to leave large tables giving up
@@ -1507,6 +1668,7 @@ class TestRewriteCheckpointResume:
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=1)),
patch.object(repartition_module, "save_repartition_checkpoint_if_claimed", return_value=True) as saved,
patch.object(
@@ -1560,6 +1722,7 @@ class TestRewriteCheckpointResume:
with (
patch.object(repartition_module, "_purge_stale_temp_tables", new=AsyncMock()) as purge,
patch.object(repartition_module, "_current_claim_token", return_value="tok"),
+ _patch_finalize(),
# First read validates the checkpoint temp (1 row); second validates the completed rewrite.
patch.object(repartition_module, "_valid_delta_row_count", new=AsyncMock(side_effect=[1, 3])),
patch.object(repartition_module, "_rewrite_into_temp", new=AsyncMock(return_value=(2, target))) as rewrite,
@@ -1601,6 +1764,7 @@ class TestRewriteCheckpointResume:
patch.object(repartition_module, "aget_s3_client", return_value=_FakeS3CM(_fake_s3())),
patch.object(repartition_module, "_purge_stale_temp_tables", new=AsyncMock()) as purge,
patch.object(repartition_module, "_current_claim_token", return_value="tok"),
+ _patch_finalize(),
patch.object(repartition_module, "_valid_delta_row_count", new=AsyncMock(side_effect=[1, 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()),
@@ -1868,6 +2032,7 @@ class TestClaimFencing:
patch.object(repartition_module, "_current_claim_token", return_value="tok-ours"),
patch.object(repartition_module, "_valid_delta_row_count", new=AsyncMock(return_value=2)) as valid,
patch.object(repartition_module, "_swap_temp_into_live", new=AsyncMock()) as swap,
+ _patch_finalize(),
):
result = asyncio.run(
repartition_table_in_place(
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 8223363eb746..665c59888c20 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
@@ -868,6 +868,60 @@ class TestRepartitionActivity:
# The claim check must be the mutate callback, evaluated against the row read under the lock.
assert locked_update.call_args.kwargs["mutate"] is not None
+ def test_finalizing_a_swap_saves_the_scheme_and_retires_every_marker_at_once(self, team):
+ # The swap has already re-bucketed the data in S3, so what is left is one write that has to be
+ # all-or-nothing. Landing the settings but keeping the swap marker holds the schema's imports
+ # forever; clearing the markers without the cooldown re-flags the table on the very next sync;
+ # keeping the operator pin re-applies it on a later reset.
+ schema = _make_schema(team, {"partition_mode": "md5", "partition_count": 4, "partition_count_override": 4})
+ schema.set_repartition_claim({"token": "live-claim", "job_id": "j1", "claimed_at": _days_ago_iso(0)})
+ schema.set_repartition_pending(
+ {"partition_mode": "md5", "partition_count": 8, "partition_keys": ["id"], "trigger_reason": "t"}
+ )
+ schema.set_repartition_swap({"state": "ready", "temp_uri": "s3://t", "live_uri": "s3://l"})
+ schema.set_repartition_rewrite({"temp_uri": "s3://t", "rows_written": 5})
+
+ wrote = external_data_schema.finalize_repartition_scheme(
+ schema,
+ partitioning_keys=["id"],
+ partition_count=8,
+ partition_size=None,
+ partition_mode="md5",
+ partition_format=None,
+ claim_token="live-claim",
+ )
+
+ schema.refresh_from_db()
+ assert wrote is True
+ assert schema.partitioning_enabled is True
+ assert schema.partition_count == 8
+ assert schema.partition_count_override is None
+ assert schema.repartition_swap is None
+ assert schema.repartition_pending is None
+ assert schema.repartition_rewrite is None
+ assert schema.last_repartition_at is not None
+
+ def test_finalizing_stands_down_when_a_newer_attempt_owns_the_claim(self, team):
+ # A zombie writing here would describe a layout the new claimant is in the middle of replacing.
+ schema = _make_schema(team, {"partition_mode": "md5", "partition_count": 4})
+ schema.set_repartition_claim({"token": "newer-claim", "job_id": "j2", "claimed_at": _days_ago_iso(0)})
+ schema.set_repartition_swap({"state": "ready", "temp_uri": "s3://t", "live_uri": "s3://l"})
+
+ wrote = external_data_schema.finalize_repartition_scheme(
+ schema,
+ partitioning_keys=["id"],
+ partition_count=8,
+ partition_size=None,
+ partition_mode="md5",
+ partition_format=None,
+ claim_token="stale-claim",
+ )
+
+ schema.refresh_from_db()
+ assert wrote is False
+ assert schema.partition_count == 4
+ assert schema.repartition_swap is not None
+
def test_a_staged_swap_is_never_abandoned_by_the_attempt_cap(self, team):
# An interrupted swap may already have deleted live, leaving temp the only intact copy. Giving
# up clears the marker that points at it, so the next sync would bootstrap an empty table.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/import_data_sync.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/import_data_sync.py
index 3a4b712085af..6d8ae0d86ef0 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/import_data_sync.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/import_data_sync.py
@@ -181,12 +181,43 @@ async def _warehouse_parent_reuse_available(
def _import_held_for_repartition(schema: ExternalDataSchema | None, logger: FilteringBoundLogger) -> bool:
"""Whether an in-flight repartition should pause this schema's import for one run.
- Both conditions have to hold: the schema opted into the hold, and a rewrite checkpoint is fresh
- enough to be worth waiting for. The flag is checked second so a schema without it never pays for
- the evaluation, and a flag lookup that throws leaves the import running — pausing a customer's
+ Two situations hold the import. A staged swap holds it unconditionally, because the table's
+ on-disk partition layout is mid-change and merging across that is data corruption, not staleness.
+ A converging rewrite holds it only when the schema opted in and its checkpoint is fresh enough to
+ be worth waiting for; the flag is checked second so a schema without it never pays for the
+ evaluation, and a flag lookup that throws leaves the import running — pausing a customer's
ingestion is the more expensive way to be wrong.
"""
- if schema is None or not schema.repartition_holds_import:
+ if schema is None:
+ return False
+
+ swap = schema.repartition_swap
+ if swap and swap.get("state") == "ready":
+ # The rewrite may already have re-bucketed the data in S3 while the schema row still holds the
+ # old settings. The merge computes each row's `_ph_partition_key` from those settings and
+ # scopes its predicate to `target._ph_partition_key = '<partition>'`, so under that mismatch
+ # nothing matches and every fetched row inserts instead of upserting — the whole incremental
+ # lookback window duplicated, with the job still reporting Completed. The repartition activity
+ # runs ahead of this one on every sync and resolves the marker, so waiting costs one run's
+ # freshness. Not behind the hold rollout flag: that flag trades freshness for a rewrite that
+ # can finish, and this trades it for not corrupting the table.
+ logger.warning(
+ "Holding import: a repartition swap is staged, so the table's partition layout is mid-change",
+ schema_id=str(schema.id),
+ temp_uri=swap.get("temp_uri"),
+ )
+ capture_repartition_event(
+ "warehouse_repartition_import_held",
+ {
+ "team_id": schema.team_id,
+ "schema_id": str(schema.id),
+ "resource_name": schema.name,
+ "reason": "swap_staged",
+ },
+ )
+ return True
+
+ if not schema.repartition_holds_import:
return False
try:
if not is_repartition_hold_enabled(schema):
@@ -208,6 +239,7 @@ def _import_held_for_repartition(schema: ExternalDataSchema | None, logger: Filt
"team_id": schema.team_id,
"schema_id": str(schema.id),
"resource_name": schema.name,
+ "reason": "rewrite_converging",
"rows_written": rewrite.get("rows_written"),
"held_at": rewrite.get("held_at"),
},
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 f9245ca69f80..48a1093e9297 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
@@ -4,9 +4,11 @@ Runs inside `ExternalDataJobWorkflow` after the pipeline lock is held and before
the sole writer for the schema (the schedule's OnlyOne overlap policy + the v3 pipeline lock guarantee
no concurrent sync). Acting on a pending target *before* the merge means the merge that follows in the
same run uses the new, memory-safe layout. A repartition failure never fails the workflow — the sync
-just proceeds on the old layout (status quo) and the table is retried on a later run. The one nuance:
-a transient infra error during an admin-staged rewrite re-raises retryable so the activity's retry
-policy re-runs it in this run (the workflow swallows the failure if retries exhaust).
+just proceeds on the old layout (status quo) and the table is retried on a later run. Two nuances: a
+transient infra error during an admin-staged rewrite re-raises retryable so the activity's retry
+policy re-runs it in this run (the workflow swallows the failure if retries exhaust); and a failure
+once the swap has landed leaves the `repartition_swap` marker set, which pauses the sync that follows
+rather than letting it merge against settings that no longer describe the data.
"""
import time
@@ -42,6 +44,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.del
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.repartition import (
RepartitionAttemptsExhausted,
RepartitionBudgetExceededError,
+ RepartitionSchemePersistError,
RepartitionSupersededError,
RepartitionTarget,
RepartitionUnpartitionableError,
@@ -136,8 +139,8 @@ def _rewrite_deadline(activity_started: float) -> float | None:
def _is_transient_infra_error(error: Exception) -> bool:
if isinstance(error, OperationalError | InterfaceError):
return True
- # A primary-DB failover briefly routes one of the rewrite's own writes (checkpoint, swap marker,
- # scheme persist) onto a connection that has become a read-only standby: Postgres raises
+ # A primary-DB failover briefly routes one of the rewrite's own writes (checkpoint, swap marker)
+ # onto a connection that has become a read-only standby: Postgres raises
# ReadOnlySqlTransaction (SQLSTATE 25006), which psycopg classifies under InternalError rather than
# OperationalError, so it needs its own check. Matched on the cause, not a bare InternalError
# isinstance, so real corruption errors sharing the base class are still reported. Mirrors the same
@@ -384,7 +387,15 @@ def _maybe_repartition_table(inputs: RepartitionActivityInputs, logger: Filterin
logger.debug("repartition: pre-extraction measurement found no repartition needed")
return
- target = RepartitionTarget.from_dict(pending) if pending is not None else _target_from_schema(schema)
+ # A pending marker carrying only bookkeeping (an attempt count written when nothing was queued)
+ # has no keys to rebuild a target from, and `from_dict` would raise before the rewrite even
+ # starts — every run, forever. Fall back to the schema's own settings, which is what a resume
+ # with no pending target uses anyway.
+ target = (
+ RepartitionTarget.from_dict(pending)
+ if pending is not None and pending.get("partition_keys") is not None
+ else _target_from_schema(schema)
+ )
trigger_reason = (pending or {}).get("trigger_reason", "resume")
# `_handle_failure` also gives up at the cap, but only for an attempt that survives to run it.
@@ -467,6 +478,20 @@ def _maybe_repartition_table(inputs: RepartitionActivityInputs, logger: Filterin
_refund_attempt(schema, charged_attempts, logger)
_capture_stood_down(schema, inputs, trigger_reason, "superseded", logger)
return
+ except RepartitionSchemePersistError as e:
+ # The rewrite worked and the swap landed; only the write recording the new scheme was lost. The
+ # table's data now carries partition keys the schema row does not describe, so this is never
+ # transient noise however transient the database error under it was: the merge that would run
+ # next scopes its predicate to a partition the table no longer has and inserts every fetched
+ # row instead of upserting it. Record it as a real failure and leave the swap marker set — it
+ # carries the scheme, so the next run finishes the write without rebuilding, and it holds this
+ # schema's imports until then (see `_import_held_for_repartition`).
+ logger.error("repartition: the swap landed but its scheme could not be saved; imports stay held", exc_info=True)
+ DELTA_REPARTITION_TOTAL.labels(
+ team_id=str(inputs.team_id),
+ outcome=_handle_failure(inputs, schema, pending, trigger_reason, e, claim_token, logger, charged_attempts),
+ ).inc()
+ return
except RepartitionUnpartitionableError as e:
# Terminal: the table can't be partitioned on its keys. Clear the flag AND engage the cooldown —
# clearing `repartition_pending` alone re-arms the loop, because detection re-flags on the very
@@ -808,7 +833,19 @@ def _handle_failure(
if attempts >= MAX_REPARTITION_ATTEMPTS:
props["final"] = True
schema.clear_repartition_pending()
- schema.clear_repartition_swap()
+ if schema.repartition_swap is not None:
+ # Giving up cannot include forgetting a staged swap. Until one completes, the table's
+ # on-disk layout is either the old scheme or the new one and the marker is the only record
+ # of which scheme was staged; dropping it would let the next merge run against settings
+ # that may no longer describe the data and duplicate the whole lookback window. Leaving it
+ # keeps this schema's imports held (see `_import_held_for_repartition`) and keeps the
+ # recovery available — stale beats silently corrupted.
+ props["swap_unresolved"] = True
+ logger.error(
+ f"repartition: giving up with a staged swap still unresolved; imports stay held for "
+ f"schema_id={schema.id}",
+ schema_id=str(schema.id),
+ )
# Drop any partial-rewrite checkpoint too: leaving it set would make the next flag cycle
# resume the same doomed temp instead of giving up, so the give-up would never take effect.
schema.clear_repartition_rewrite()
@@ -817,9 +854,11 @@ def _handle_failure(
# 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)
+ elif pending:
+ # Only when something was queued. A staged swap being driven to completion has no pending
+ # marker, and writing an attempt count onto an empty one invents a target with no partition
+ # keys — which the next run cannot rebuild a `RepartitionTarget` from.
+ schema.set_repartition_pending({**pending, "attempts": attempts})
capture_repartition_event("warehouse_repartition_failed", props)
capture_exception(error)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_import_data_sync.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_import_data_sync.py
index 0e61b4f6879d..28eda75db44f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_import_data_sync.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_import_data_sync.py
@@ -960,3 +960,34 @@ def test_the_customer_facing_message_matches_no_non_retryable_pattern(_name: str
f"These non-retryable patterns match {message_attr}, so an exhausted "
f"retry budget would disable the customer's schema: {offenders}"
)
+
+
+ [
+ ("swap_staged", {"state": "ready", "temp_uri": "s3://bucket/t__repartitioned"}, True),
+ ("no_swap_staged", None, False),
+ ]
+)
+def test_a_staged_repartition_swap_holds_the_import_whatever_the_rollout_flag_says(
+ _name: str, swap: dict | None, expected: bool
+) -> None:
+ # While a swap is staged the table's data may already be re-bucketed under the new scheme while
+ # the schema row still holds the old one. The merge derives each row's partition key from that
+ # row and scopes its predicate to it, so merging across the gap matches nothing and inserts every
+ # fetched row instead of upserting it. Unlike the converging-rewrite hold, this one is not behind
+ # the rollout flag: releasing it corrupts the table rather than merely restarting a rewrite.
+ schema = mock.MagicMock()
+ schema.id = uuid.uuid4()
+ schema.team_id = 1
+ schema.name = "public.usages"
+ schema.repartition_swap = swap
+ schema.repartition_holds_import = False
+
+ with (
+ mock.patch.object(module, "capture_repartition_event"),
+ mock.patch.object(module, "is_repartition_hold_enabled", return_value=False) as flag,
+ ):
+ held = module._import_held_for_repartition(schema, mock.MagicMock())
+
+ assert held is expected
+ flag.assert_not_called()
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 7e9eea269d87..2da2e98e4034 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
@@ -17,6 +17,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,
)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.repartition_controller import (
MAX_REPARTITION_ATTEMPTS,
@@ -636,6 +637,55 @@ class TestTransientObjectStoreFailure:
skip_calls = [c for c in mock_capture_event.call_args_list if c.args[0] == "warehouse_repartition_skipped"]
assert any(c.args[1].get("reason") == "transient_infra_error" for c in skip_calls)
+ @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_a_database_blip_after_the_swap_is_reported_not_shrugged_off(
+ self,
+ 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:
+ # The counterpart to the two cases above: the same class of database error, but raised once the
+ # swap has already re-bucketed the data in S3. Standing down there leaves the schema row
+ # describing a layout the table no longer has, and the merge that runs next in this very sync
+ # inserts every fetched row instead of upserting it. It has to be a reported failure.
+ # Spent attempts as well, so giving up is on the table: that is the one path that used to
+ # clear the marker, and clearing it is what would release the imports.
+ schema = _schema(
+ name="public.usages",
+ s3_folder_name="usages",
+ pending={**PENDING_TARGET, "attempts": MAX_REPARTITION_ATTEMPTS - 1},
+ swap={"state": "ready", "target": PENDING_TARGET},
+ )
+ mock_schema_model.objects.select_related.return_value.get.return_value = schema
+ mock_repartition.side_effect = RepartitionSchemePersistError(
+ "the swap landed but the new scheme could not be saved: server conn crashed?"
+ )
+
+ _maybe_repartition_table(
+ RepartitionActivityInputs(team_id=TEAM_ID, schema_id=SCHEMA_ID, job_id=JOB_ID, source_id=SOURCE_ID),
+ MagicMock(),
+ )
+
+ mock_capture_exception.assert_called_once()
+ emitted = [c.args[0] for c in mock_capture_event.call_args_list]
+ assert "warehouse_repartition_failed" in emitted
+ schema.clear_repartition_pending.assert_called_once()
+ # The marker records the staged scheme and holds this schema's imports; dropping it would let
+ # the next sync merge against settings that no longer describe the data.
+ schema.clear_repartition_swap.assert_not_called()
+
class TestFeatureFlagGate:
@parameterized.expand(