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): never split append tables in the repartition controller (#117898)

Daniel RCfafffc66c2bf
diff --git a/products/warehouse_sources/backend/models/external_data_schema.py b/products/warehouse_sources/backend/models/external_data_schema.py
index 6ac7a269ef3f..9de070267e01 100644
--- a/products/warehouse_sources/backend/models/external_data_schema.py
+++ b/products/warehouse_sources/backend/models/external_data_schema.py
@@ -1032,7 +1032,7 @@ class ExternalDataSchema( # nosemgrep: semgrep.rules.security.prefer-uuid7-djan
)
return self.sync_type_config.get("repartition_claim") == claim
- def abandon_repartition_if_claimed(self, claim_token: str) -> bool:
+ def abandon_repartition_if_claimed(self, claim_token: str, *, stamp_cooldown: bool = True) -> bool:
from posthog.temporal.common.utils import retry_on_db_connection_drop # noqa: PLC0415
def _write(config: dict[str, Any]) -> None:
@@ -1043,7 +1043,8 @@ class ExternalDataSchema( # nosemgrep: semgrep.rules.security.prefer-uuid7-djan
return
for key in ("repartition_pending", "repartition_swap", "repartition_rewrite"):
config.pop(key, None)
- config["last_repartition_at"] = timezone.now().isoformat()
+ if stamp_cooldown:
+ config["last_repartition_at"] = timezone.now().isoformat()
self.sync_type_config = retry_on_db_connection_drop(
lambda: update_sync_type_config_keys(schema_id=self.id, team_id=self.team_id, mutate=_write)
@@ -1961,6 +1962,27 @@ def release_repartition_hold_if_claimed(schema: ExternalDataSchema, *, claim_tok
schema.sync_type_config = update_sync_type_config_keys(schema_id=schema.id, team_id=schema.team_id, mutate=_write)
+def mark_repartition_dropping_if_claimed(schema: ExternalDataSchema, *, claim_token: str) -> int | None:
+ """Count one failed drop of the pending target while `claim_token` still owns the schema.
+
+ Returns the drop attempts so far, or None when a newer attempt owns the schema. A target marked
+ `dropping` is never promoted by a reset (see `pending_scheme_for_table_replacement`).
+ """
+ drop_attempts: int | None = None
+
+ def _write(config: dict[str, Any]) -> None:
+ nonlocal drop_attempts
+ claim = config.get("repartition_claim")
+ pending = config.get("repartition_pending")
+ if not (claim and claim.get("token") == claim_token) or not isinstance(pending, dict):
+ return
+ drop_attempts = int(pending.get("drop_attempts", 0)) + 1
+ pending.update({"dropping": True, "drop_attempts": drop_attempts})
+
+ schema.sync_type_config = update_sync_type_config_keys(schema_id=schema.id, team_id=schema.team_id, mutate=_write)
+ return drop_attempts
+
+
def clear_repartition_checkpoint_if_claimed(schema: ExternalDataSchema, *, claim_token: str, temp_uri: str) -> bool:
"""Remove the rewrite checkpoint for `temp_uri` while `claim_token` still owns the schema.
@@ -2127,10 +2149,11 @@ def pending_scheme_for_table_replacement(config: dict[str, Any]) -> dict[str, An
None while a swap is staged, because the temp table can then be the only intact copy and the
swap recovery owns the scheme. None when an operator pinned a scheme, because that pin is the
- newer decision. A marker with no keys holds bookkeeping only and describes no scheme.
+ newer decision. A marker with no keys holds bookkeeping only and describes no scheme. A target that
+ the activity is dropping (`dropping`) describes no table either.
"""
pending = config.get("repartition_pending")
- if not isinstance(pending, dict) or not pending.get("partition_keys"):
+ if not isinstance(pending, dict) or not pending.get("partition_keys") or pending.get("dropping"):
return None
if config.get("repartition_swap") is not None:
return None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/README.md b/products/warehouse_sources/backend/temporal/data_imports/README.md
index cef517f09b2b..121a544f83b8 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/README.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/README.md
@@ -65,6 +65,7 @@ Tuning and gating:
- The split floor and the coarsening trigger are both derived from the budget rather than tuned separately (`COARSEN_TRIGGER_DIVISOR`), so the two directions stay consistent by construction.
- The coarsening gate's own tunables are `COARSEN_OOM_FREE_DAYS` (default 14, deliberately longer than the split window) and `DATA_WAREHOUSE_COARSEN_BLOCK_MERGE_PEAK_BYTES` (default 1 MB), the peak above which a merge-phase death blocks regardless of how the classification rules explained it. `DELTA_COARSEN_DECLINE_TOTAL` records which gate declined, labelled by reason.
- CDC tables are excluded for now.
+- Append tables are never split. The budget bounds the working set of a merge, and an append sync never merges, so a split only rewrites every row. Coarsening still applies to them. A split that detection queued for an append table is dropped by the next run, with the temp table of its rewrite (`reason=append_never_merges`). An operator target still runs.
Observability: `warehouse_repartition_flagged` / `started` / `completed` / `failed` / `skipped` PostHog events (with full team/schema/source/table context, before→after scheme, sizes, durations, and trigger reason) plus `DELTA_REPARTITION_*` Prometheus metrics.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/repartition_controller.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/repartition_controller.py
index 094d5e896bb5..39915a5980d8 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/repartition_controller.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/repartition_controller.py
@@ -175,7 +175,8 @@ def pre_extraction_measurement_is_redundant(schema: ExternalDataSchema, job: Ext
if measurement.get("budget") != target_partition_bytes():
return False
if (
- ExternalDataSchemaOOMEvent.recent_count(schema, days=repartition_oom_window_days())
+ not schema.is_append
+ and ExternalDataSchemaOOMEvent.recent_count(schema, days=repartition_oom_window_days())
>= repartition_oom_threshold()
):
return False
@@ -190,6 +191,14 @@ def pre_extraction_measurement_is_redundant(schema: ExternalDataSchema, job: Ext
return partition_measurement_holds(measurement, earlier_jobs)
+AUTOMATIC_SPLIT_TRIGGERS = frozenset({"proactive_threshold", "oom_history"})
+
+
+def is_automatic_split_of_append_table(schema: ExternalDataSchema, trigger_reason: str) -> bool:
+ """Whether a queued target is an automatic split of an append table. An operator target is not."""
+ return schema.is_append and trigger_reason in AUTOMATIC_SPLIT_TRIGGERS
+
+
def repartition_activity_has_work(schema: ExternalDataSchema) -> bool:
"""Whether the pre-extraction repartition activity would do more than log and return.
@@ -462,7 +471,12 @@ async def maybe_flag_for_repartition(
max_bytes = max(partition_bytes.values())
budget = target_partition_bytes()
- over_budget = max_bytes > budget
+ # The budget bounds the working set of a merge, and an append sync never merges: it adds new
+ # files and reads no partition. So neither split trigger applies to an append table, and a
+ # split only rewrites every row for no gain. Coarsening still applies, because fewer files
+ # make reads of the table cheaper.
+ split_applies = not schema.is_append
+ over_budget = split_applies and max_bytes > budget
# Hybrid trigger: a table that has actually OOM'd repeatedly is repartitioned even when its
# largest partition looks within budget — the compressed at-rest size under-counts the merge's
@@ -470,7 +484,7 @@ async def maybe_flag_for_repartition(
# Only query the OOM log when the size check didn't already trip: an over-budget table
# repartitions regardless, so the count would only feed observability props there — skip the
# per-sync indexed COUNT for it and report 0.
- if over_budget:
+ if over_budget or not split_applies:
oom_count = 0
oom_triggered = False
else:
@@ -497,8 +511,9 @@ async def maybe_flag_for_repartition(
)
if not over_budget and not oom_triggered:
+ verdict = "within budget and no repeated OOMs" if split_applies else "append table, a split does not apply"
await logger.adebug(
- f"repartition: not needed, within budget and no repeated OOMs schema_id={schema.id} "
+ f"repartition: not needed, {verdict} schema_id={schema.id} "
f"max_partition_bytes={max_bytes} budget_bytes={budget} recent_oom_count={oom_count} "
f"partition_count={len(partition_bytes)}",
schema_id=str(schema.id),
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 5a9bc109949d..6bcdb2b4df74 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
@@ -283,6 +283,40 @@ class TestRepartitionDetection:
assert schema.repartition_pending["partition_mode"] is None
assert schema.repartition_pending["partition_keys"] == ["id"]
+ @pytest.mark.parametrize("trigger", ["over_budget", "oom_history"])
+ def test_an_append_table_is_never_split(self, team, trigger):
+ schema = _make_schema(
+ team,
+ {
+ "partitioning_enabled": True,
+ "partition_mode": "datetime",
+ "partition_format": "day",
+ "partitioning_keys": ["ts"],
+ },
+ )
+ schema.sync_type = ExternalDataSchema.SyncType.APPEND
+ schema.save()
+ if trigger == "oom_history":
+ for _ in range(3):
+ ExternalDataSchemaOOMEvent.objects.for_team(schema.team_id).create(
+ team_id=schema.team_id, schema=schema
+ )
+
+ with tempfile.TemporaryDirectory() as d:
+ delta = _write_partitioned_delta(f"{d}/t", ["2026-10-01", "2026-10-01", "2026-10-02"])
+ with (
+ patch.object(ctrl, "target_partition_bytes", return_value=1 if trigger == "over_budget" else 10**12),
+ patch.object(ctrl, "repartition_oom_threshold", return_value=3),
+ patch.object(ctrl, "min_splittable_partition_bytes", return_value=1),
+ patch.object(ctrl, "capture_repartition_event") as capture,
+ ):
+ self._detect(team, schema, delta)
+
+ schema.refresh_from_db()
+ assert schema.repartition_pending is None
+ assert schema.last_repartition_at is None
+ assert capture.call_count == 0
+
class TestPartitionMeasurementRecord:
@pytest.mark.parametrize(
@@ -1294,6 +1328,113 @@ class TestRepartitionActivity:
# The cooldown stamp is what actually stops the flag → start → skip churn every 5 minutes.
assert schema.last_repartition_at is not None
+ @pytest.mark.parametrize(
+ "trigger_reason,dropped",
+ [("proactive_threshold", True), ("oom_history", True), ("admin", False), ("coarsening", False)],
+ )
+ def test_an_automatic_split_queued_on_an_append_table_is_dropped(self, team, trigger_reason, dropped):
+ schema = _make_schema(team, {})
+ schema.sync_type = ExternalDataSchema.SyncType.APPEND
+ schema.save()
+ schema.set_repartition_pending(
+ {
+ "partition_mode": "md5",
+ "partition_count": 4,
+ "partition_keys": ["id"],
+ "trigger_reason": trigger_reason,
+ "attempts": 0,
+ }
+ )
+ schema.set_repartition_rewrite({"temp_uri": "s3://bucket/t__repartitioned_x", "rows_written": 10})
+ mocked = AsyncMock(return_value={"outcome": "completed", "row_count": 6, "partition_mode_after": "md5"})
+ purge = AsyncMock(return_value=True)
+ with patch.object(repartition_table, "purge_abandoned_rewrite_temp", new=purge):
+ capture = self._run(self._inputs(team, schema), mocked)
+
+ schema.refresh_from_db()
+ if dropped:
+ mocked.assert_not_called()
+ assert purge.await_args is not None
+ assert purge.await_args.args[2] == "s3://bucket/t__repartitioned_x"
+ assert schema.repartition_pending is None
+ assert schema.repartition_rewrite is None
+ skipped = [c.args[1] for c in capture.call_args_list if c.args[0] == "warehouse_repartition_skipped"]
+ assert [props["reason"] for props in skipped] == ["append_never_merges"]
+ else:
+ mocked.assert_awaited_once()
+ purge.assert_not_called()
+
+ @pytest.mark.parametrize("prior_attempts, gives_up", [(0, False), (MAX_REPARTITION_ATTEMPTS - 1, True)])
+ def test_an_append_split_whose_temp_cannot_be_deleted_is_retried_a_bounded_number_of_times(
+ self, team, prior_attempts, gives_up
+ ):
+ schema = _make_schema(team, {})
+ schema.sync_type = ExternalDataSchema.SyncType.APPEND
+ schema.save()
+ schema.set_repartition_pending(
+ {
+ "partition_mode": "md5",
+ "partition_count": 4,
+ "partition_keys": ["id"],
+ "trigger_reason": "proactive_threshold",
+ "drop_attempts": prior_attempts,
+ }
+ )
+ schema.set_repartition_rewrite(
+ {"temp_uri": "s3://bucket/t__repartitioned_x", "rows_written": 10, "held_at": "2026-01-01T00:00:00+00:00"}
+ )
+ mocked = AsyncMock()
+ with (
+ patch.object(repartition_table, "purge_abandoned_rewrite_temp", new=AsyncMock(side_effect=OSError("s3"))),
+ patch.object(repartition_table, "capture_exception") as captured,
+ ):
+ self._run(self._inputs(team, schema), mocked)
+
+ schema.refresh_from_db()
+ mocked.assert_not_called()
+ if gives_up:
+ assert schema.repartition_pending is None
+ assert schema.repartition_rewrite is None
+ assert any("dropped append split" in str(c.args[0]) for c in captured.call_args_list)
+ else:
+ assert schema.repartition_pending is not None
+ assert schema.repartition_pending["dropping"] is True
+ assert schema.repartition_pending["drop_attempts"] == 1
+ # The checkpoint stays as the record of the temp table, and no longer holds the import.
+ assert schema.repartition_rewrite == {"temp_uri": "s3://bucket/t__repartitioned_x", "rows_written": 10}
+ # A dropped split changes no layout, so it must not start the cooldown or age the layout.
+ assert schema.last_repartition_at is None
+
+ def test_a_failed_append_split_drop_never_overwrites_a_newer_claim(self, team):
+ schema = _make_schema(team, {})
+ schema.sync_type = ExternalDataSchema.SyncType.APPEND
+ schema.save()
+ schema.set_repartition_pending(
+ {"partition_mode": "md5", "partition_keys": ["id"], "trigger_reason": "proactive_threshold"}
+ )
+ schema.set_repartition_rewrite({"temp_uri": "s3://bucket/t__repartitioned_x", "rows_written": 10})
+ newer_claim = {"token": "newer", "job_id": "other", "claimed_at": "2999-01-01T00:00:00+00:00"}
+
+ async def newer_attempt_claims_then_delete_fails(*_args, **_kwargs):
+ await asyncio.to_thread(
+ external_data_schema.update_sync_type_config_keys,
+ schema_id=schema.id,
+ team_id=schema.team_id,
+ updates={"repartition_claim": newer_claim},
+ )
+ raise OSError("s3")
+
+ with patch.object(
+ repartition_table,
+ "purge_abandoned_rewrite_temp",
+ new=AsyncMock(side_effect=newer_attempt_claims_then_delete_fails),
+ ):
+ self._run(self._inputs(team, schema), AsyncMock())
+
+ schema.refresh_from_db()
+ assert schema.repartition_claim == newer_claim
+ assert "dropping" not in (schema.repartition_pending or {})
+
def test_failure_increments_attempts_without_clearing(self, team):
schema = _make_schema(team, {})
schema.set_repartition_pending(
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/test_pipeline.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/test_pipeline.py
index 6133df89e0d6..0fc20ee2fb87 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/test_pipeline.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/test_pipeline.py
@@ -643,12 +643,14 @@ class TestResetLoadWritesTheQueuedScheme:
{"partition_count_override": 11},
),
({"repartition_pending": {"attempts": 2}, "repartition_rewrite": {"temp_uri": "x"}}, {}),
+ ({"repartition_pending": {**_PENDING_SCHEME, "dropping": True}}, {}),
({}, {}),
],
ids=[
"queued_target_becomes_the_scheme",
"operator_pin_stays",
"bookkeeping_only_marker_goes",
+ "target_being_dropped_goes",
"nothing_queued",
],
)
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 1b33f177363c..7e607f0c09fa 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
@@ -40,6 +40,7 @@ from products.warehouse_sources.backend.models.external_data_job import External
from products.warehouse_sources.backend.models.external_data_schema import (
ExternalDataSchema,
clear_repartition_checkpoint_if_claimed,
+ mark_repartition_dropping_if_claimed,
release_repartition_hold_if_claimed,
)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.common.extract import import_replaces_table
@@ -66,6 +67,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.rep
MAX_REPARTITION_ATTEMPTS,
base_event_props,
capture_repartition_event,
+ is_automatic_split_of_append_table,
is_repartition_hold_enabled,
maybe_flag_for_repartition,
needs_pre_extraction_detection,
@@ -472,6 +474,11 @@ def _maybe_repartition_table(inputs: RepartitionActivityInputs, logger: Filterin
)
trigger_reason = (pending or {}).get("trigger_reason", "resume")
+ # Before the reset deferral too, because a reset would write this split into the new table.
+ if swap is None and is_automatic_split_of_append_table(schema, trigger_reason):
+ _drop_append_split(inputs, schema, table_ref, trigger_reason, logger)
+ return
+
# Never while a swap is staged: live may already be deleted, and temp is then the only intact copy.
if replaces_table:
if schema.sync_type == ExternalDataSchema.SyncType.FULL_REFRESH:
@@ -889,15 +896,15 @@ def _purge_abandoned_temp(
logger: FilteringBoundLogger,
*,
clear_checkpoint: bool = False,
-) -> None:
- """Delete the temp table that the rewrite checkpoint names. Best effort.
+) -> bool:
+ """Delete the temp table that the rewrite checkpoint names. Best effort; returns whether it is gone.
A failure leaves the checkpoint in place when this function owns its removal, so the next run
tries the delete again. It must not block the sync.
"""
temp_uri = _rewrite_checkpoint_id(schema)
if not temp_uri:
- return
+ return True
try:
# A large temp table takes longer to delete than the heartbeat timeout.
with HeartbeaterSync(logger=logger):
@@ -906,6 +913,7 @@ def _purge_abandoned_temp(
)
if purged and clear_checkpoint:
clear_repartition_checkpoint_if_claimed(schema, claim_token=claim_token, temp_uri=temp_uri)
+ return purged
except RepartitionSupersededError:
logger.info("repartition: temp cleanup superseded by a newer claim")
except Exception as e:
@@ -914,6 +922,7 @@ def _purge_abandoned_temp(
if not _is_transient_infra_error(e):
capture_exception(e)
logger.warning("repartition: could not delete the temp table of an abandoned rewrite", exc_info=True)
+ return False
def _capture_stood_down(
@@ -1204,6 +1213,62 @@ def _give_up(
DELTA_REPARTITION_TOTAL.labels(outcome="failed").inc()
+def _drop_append_split(
+ inputs: RepartitionActivityInputs,
+ schema: ExternalDataSchema,
+ table_ref: DeltaTableRef,
+ trigger_reason: str,
+ logger: FilteringBoundLogger,
+) -> None:
+ """Discard an automatic split queued for an append table, with the temp table of its rewrite.
+
+ Same order as `_give_up`: the fresh claim fences out a predecessor that may still run as a
+ zombie, and the temp table goes before the checkpoint that records where it is.
+ """
+ claim_token = str(uuid.uuid4())
+ if not schema.set_repartition_claim(
+ {"token": claim_token, "job_id": inputs.job_id, "claimed_at": timezone.now().isoformat()}
+ ):
+ logger.info("repartition: append split drop superseded by a newer claim")
+ return
+ # A predecessor can stage a swap before the claim above fences it out. Temp is then the only
+ # intact copy, so the swap must finish, and the next run drops nothing. The claim write reloaded
+ # the config under the row lock, so this reads the current markers.
+ if schema.repartition_swap is not None:
+ logger.info("repartition: a swap is staged, so the append split stays until it lands")
+ return
+ rewrite_rows = _rewrite_rows_written(schema)
+ # First, so that a delete that keeps failing cannot hold the import of a rewrite that never resumes.
+ release_repartition_hold_if_claimed(schema, claim_token=claim_token)
+ if not _purge_abandoned_temp(schema, table_ref, claim_token, logger):
+ # The checkpoint is the only record of the temp table, and an append table rarely runs the fresh
+ # rebuild that sweeps orphans, so the drop retries on later runs, up to the attempt cap.
+ drop_attempts = mark_repartition_dropping_if_claimed(schema, claim_token=claim_token)
+ if drop_attempts is None:
+ logger.info("repartition: append split drop superseded by a newer claim")
+ return
+ if drop_attempts < MAX_REPARTITION_ATTEMPTS:
+ logger.info(f"repartition: append split drop waits for the temp table delete, attempt {drop_attempts}")
+ return
+ capture_exception(
+ Exception(f"repartition: could not delete the temp table of a dropped append split schema_id={schema.id}")
+ )
+ if not schema.abandon_repartition_if_claimed(claim_token, stamp_cooldown=False):
+ logger.info("repartition: append split drop superseded by a newer claim")
+ return
+ logger.info(
+ f"repartition: dropped the queued split of an append table, which never merges "
+ f"schema_id={schema.id} trigger_reason={trigger_reason} rewrite_rows={rewrite_rows}",
+ schema_id=str(schema.id),
+ trigger_reason=trigger_reason,
+ rewrite_rows=rewrite_rows,
+ )
+ DELTA_REPARTITION_TOTAL.labels(outcome="skipped").inc()
+ props = base_event_props(schema, schema.source, inputs.job_id)
+ props.update({"trigger_reason": trigger_reason, "reason": "append_never_merges", "rewrite_rows": rewrite_rows})
+ capture_repartition_event("warehouse_repartition_skipped", props)
+
+
def _charge_attempt(
schema: ExternalDataSchema, pending: dict[str, Any] | None, job_id: str, logger: FilteringBoundLogger
) -> int | None:
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 9a457cfc4da0..cc0f469112d7 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
@@ -62,6 +62,7 @@ PENDING_TARGET = {
"trigger_reason": "proactive_threshold",
"attempts": 0,
}
+ADMIN_TARGET = {**PENDING_TARGET, "trigger_reason": "admin"}
def _read_only_transaction_error() -> InternalError:
@@ -93,6 +94,7 @@ def _schema(
schema.resolved_s3_folder_name = s3_folder_name
schema.team_id = TEAM_ID
schema.delta_revive_required = None
+ schema.is_append = False
schema.sync_frequency_interval = None
schema.repartition_swap = swap
schema.repartition_pending = pending
@@ -1517,8 +1519,10 @@ class TestFullRefreshDeferral:
# The next full refresh deletes the table and writes it again, so a rewrite only copies rows
# that sync throws away, and the sync moves the live version under any checkpoint it saves.
mock_schema_model.SyncType.FULL_REFRESH = "full_refresh"
- schema = _schema(name="contacts", s3_folder_name="contacts", swap=swap)
+ pending = ADMIN_TARGET if sync_type == "append" else PENDING_TARGET
+ schema = _schema(name="contacts", s3_folder_name="contacts", pending=pending, swap=swap)
schema.sync_type = sync_type
+ schema.is_append = sync_type == "append"
if swap_after_refresh is not None:
schema.refresh_from_db.side_effect = lambda **_kwargs: setattr(
schema, "repartition_swap", swap_after_refresh
@@ -1554,6 +1558,7 @@ def _reset_schema(
) -> MagicMock:
schema = _schema(name="contacts", s3_folder_name="contacts", pending=pending, swap=swap, rewrite=rewrite)
schema.sync_type = sync_type
+ schema.is_append = sync_type == "append"
schema.is_webhook = sync_type == "webhook"
schema.sync_type_config = {"reset_pipeline": True} if config_reset else {}
schema.initial_sync_complete = initial_sync_complete
@@ -1611,7 +1616,10 @@ class TestResetDeferral:
expect_rewrite: bool,
) -> None:
mock_schema_model.SyncType.FULL_REFRESH = "full_refresh"
- schema = _reset_schema(sync_type=sync_type, config_reset=config_reset, swap=swap, rewrite=dict(CHECKPOINT))
+ pending = ADMIN_TARGET if sync_type == "append" else PENDING_TARGET
+ schema = _reset_schema(
+ sync_type=sync_type, config_reset=config_reset, pending=pending, swap=swap, rewrite=dict(CHECKPOINT)
+ )
mock_schema_model.objects.select_related.return_value.get.return_value = schema
mock_repartition.return_value = {"outcome": "completed"}
mock_purge.return_value = True
@@ -1629,7 +1637,7 @@ class TestResetDeferral:
mock_purge.assert_not_awaited()
return
# The queued target stays for the reset to write, and for a later rewrite if no reset happens.
- assert schema.repartition_pending == PENDING_TARGET
+ assert schema.repartition_pending == pending
schema.set_repartition_pending.assert_not_called()
schema.clear_repartition_pending.assert_not_called()
schema.stamp_last_repartition_at.assert_not_called()
@@ -1640,6 +1648,42 @@ class TestResetDeferral:
assert mock_capture.call_args.args[0] == "warehouse_repartition_skipped"
assert mock_capture.call_args.args[1]["reason"] == "reset_replaces_the_table"
+ @patch(f"{MODULE}.release_repartition_hold_if_claimed")
+ @patch(f"{MODULE}.purge_abandoned_rewrite_temp", new_callable=AsyncMock)
+ @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_an_automatic_split_on_an_append_table_is_dropped_before_a_reset_can_write_it(
+ self,
+ mock_schema_model: MagicMock,
+ _mock_job_model: MagicMock,
+ _mock_helper_cls: MagicMock,
+ mock_repartition: AsyncMock,
+ _mock_heartbeater: MagicMock,
+ mock_capture: MagicMock,
+ mock_purge: AsyncMock,
+ _mock_release: MagicMock,
+ ) -> None:
+ mock_schema_model.SyncType.FULL_REFRESH = "full_refresh"
+ schema = _reset_schema(sync_type="append", config_reset=True, rewrite=dict(CHECKPOINT))
+ mock_schema_model.objects.select_related.return_value.get.return_value = schema
+ mock_purge.return_value = True
+
+ _maybe_repartition_table(
+ RepartitionActivityInputs(team_id=TEAM_ID, schema_id=SCHEMA_ID, job_id=JOB_ID, source_id=SOURCE_ID),
+ MagicMock(),
+ )
+
+ mock_repartition.assert_not_awaited()
+ assert mock_purge.await_args is not None
+ assert mock_purge.await_args.args[2] == TEMP_URI
+ schema.abandon_repartition_if_claimed.assert_called_once()
+ reasons = [c.args[1].get("reason") for c in mock_capture.call_args_list]
+ assert reasons == ["append_never_merges"]
+
@patch(f"{MODULE}.capture_repartition_event")
@patch(f"{MODULE}.HeartbeaterSync")
@patch(f"{MODULE}.repartition_table_in_place", new_callable=AsyncMock)