: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(data-warehouse): stream the repartition rewrite with bounded memory (#111992)
Tom Owers4daf847fd855
diff --git a/products/warehouse_sources/backend/models/external_data_schema.py b/products/warehouse_sources/backend/models/external_data_schema.pyindex 76a865a15c7d..0bd1978d2055 100644--- a/products/warehouse_sources/backend/models/external_data_schema.py+++ b/products/warehouse_sources/backend/models/external_data_schema.py@@ -896,9 +896,52 @@ class ExternalDataSchema( # nosemgrep: semgrep.rules.security.prefer-uuid7-djanself.sync_type_config["repartition_swap"] = swapself._save_sync_type_config()- def set_repartition_claim(self, claim: dict[str, Any]) -> None:- self.sync_type_config["repartition_claim"] = claim- self._save_sync_type_config()+ def set_repartition_claim(self, claim: dict[str, Any]) -> bool:+ from posthog.temporal.common.utils import retry_on_db_connection_drop # noqa: PLC0415++ # A timed-out activity may still be running when its retry stakes a newer claim. Merge under+ # the row lock so the older activity's stale model copy cannot overwrite that newer token (or+ # any unrelated config written while it was running) and accidentally reclaim the table.+ def _write(config: dict[str, Any]) -> None:+ current = config.get("repartition_claim")+ if isinstance(current, dict):+ current_claimed_at = current.get("claimed_at")+ claimed_at = claim.get("claimed_at")+ if isinstance(current_claimed_at, str) and isinstance(claimed_at, str):+ if current_claimed_at > claimed_at:+ return+ config["repartition_claim"] = claim++ 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)+ )+ return self.sync_type_config.get("repartition_claim") == claim++ def abandon_repartition_if_claimed(self, claim_token: str) -> bool:+ from posthog.temporal.common.utils import retry_on_db_connection_drop # noqa: PLC0415++ def _write(config: dict[str, Any]) -> None:+ claim = config.get("repartition_claim")+ if not (isinstance(claim, dict) and claim.get("token") == claim_token):+ return+ if config.get("repartition_swap") is not None:+ return+ for key in ("repartition_pending", "repartition_swap", "repartition_rewrite"):+ config.pop(key, None)+ 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)+ )+ claim = self.sync_type_config.get("repartition_claim")+ return (+ isinstance(claim, dict)+ and claim.get("token") == claim_token+ and not any(+ key in self.sync_type_config+ for key in ("repartition_pending", "repartition_swap", "repartition_rewrite")+ )+ )def clear_repartition_swap(self) -> None:self.sync_type_config.pop("repartition_swap", None)@@ -1672,6 +1715,58 @@ def finalize_repartition_scheme(return wrote+def stage_partition_scheme_for_full_refresh(+ 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:+ """Pin a new partition scheme for the next full refresh to write, and retire the repartition markers.++ A full-refresh sync deletes the table and writes it again, so it can lay out the new scheme with+ no rewrite at all. The scheme goes in as the `*_override` keys because the reset at the start of+ that sync removes the plain partition settings, and the overrides are the keys it keeps for the+ sync to consume (see `update_sync_type_config_for_reset_pipeline` and `set_partitioning_enabled`).+ `partition_format` survives the reset on its own.+ """+ overrides: dict[str, Any] = {+ "partitioning_keys_override": partitioning_keys or None,+ "partition_count_override": partition_count,+ "partition_size_override": partition_size,+ "partition_mode_override": partition_mode,+ }++ 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+ if config.get("repartition_swap") is not None:+ return+ for key, value in overrides.items():+ if value is None:+ config.pop(key, None)+ else:+ config[key] = value+ if partition_format is not None:+ config["partition_format"] = partition_format+ # The cooldown stops detection from flagging the old layout again before the sync rewrites it.+ config["last_repartition_at"] = timezone.now().isoformat()+ for key in ("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 mark_schema_running_unless_halted(schema: ExternalDataSchema) -> bool:"""Paint a schema Running at the start of a run, unless a CDC halt marker holds.diff --git a/products/warehouse_sources/backend/temporal/data_imports/README.md b/products/warehouse_sources/backend/temporal/data_imports/README.mdindex 9a2a36b4e31e..beedefb3c222 100644--- a/products/warehouse_sources/backend/temporal/data_imports/README.md+++ b/products/warehouse_sources/backend/temporal/data_imports/README.md@@ -46,7 +46,9 @@ 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. Batches coalesce into one commit per buffer, and the buffer also commits once it has been held for the checkpoint interval, so a scan too slow to fill it inside one worker's life still leaves resumable progress behind. 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.+- **Rewrite.** On the next run, a pre-extraction activity copies the live Delta table into a sibling temp table under the new scheme, recomputing `_ph_partition_key` for every row. It then does a crash-safe swap: delete live → server-side copy temp → verify row count → delete temp. The copy (`pipelines/core/repartition_stream.py`) never opens a dataset over the whole table, because a dataset keeps the parquet footer of every file it has scanned and its memory grows with each file. It plans from the add actions of the loaded version and reads one source file at a time: small files whole, a few ahead on worker threads, large files by row group. It writes through a capped set of open parquet files, one per target partition, and commits them as add actions with stats. One memory-governor slot sizes every buffer, so memory depends on that budget, not on the table's size, its file count or the rows already written. Commits land on source-file boundaries, at least once per checkpoint interval, and each records the source files it completes.+- **Resume.** A rewrite cut short (deadline, OOM, worker restart) resumes from the source files its temp commits record, not from a row count. Delta data files never change, so the resume stays valid after the sync commits to live, as long as every copied file is still live, live has no new column, and temp's row count matches the copied files (`resume_blocker`). Files the sync appended are copied with the rest. Otherwise the checkpoint is discarded and the rewrite starts again. A temp written before source files were recorded is rebuilt the same way.+- **Full-refresh tables are not rewritten.** Their next sync deletes the table and writes it again, so a rewrite would only copy rows that sync throws away. The activity stages the target as the `*_override` partition keys, which survive that sync's reset, plus `partition_format`, and the sync writes the new layout (`stage_partition_scheme_for_full_refresh`). It also rotates the claim, so a rewrite still running as a zombie cannot swap its copy back over live. It leaves claim-scoped temp tables alone because a wildcard S3 sweep cannot stay fenced against a newer recovery attempt while awaiting storage. The event is `warehouse_repartition_skipped` with `outcome=deferred`. A staged swap still completes first. 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. A panic from the native delta stack (pyo3 raises those as `BaseException`, so they do not stop at an `except Exception`) is recorded as a failure too, rather than being left to fail the activity and spend the remaining retries re-reading a log that panics in the same place. An attempt killed outright (a SIGKILLed worker runs no `except` and no `finally`) records nothing at all, so the activity's own retries judge it on the checkpoint instead: a retry re-runs the rewrite only while the attempt it retries left the checkpoint further along than it found it, because repeating a rewrite that died in place holds the sync for another activity budget and the next sync resumes from the same checkpoint anyway. The stand-down reports `reason=attempt_killed_without_progress`. The cap applies that same test across syncs, since a killed attempt is the one shape it cannot read an outcome for: a spent count is reset when the last attempt still moved the checkpoint on, so a table converging one worker death per sync keeps its progress, and the give-up fires only once the checkpoint stops moving. The terminal give-up carries how far the rewrite got.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.pyindex 3d4630d9da5d..94ce1d6c0c85 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@@ -28,7 +28,6 @@ from typing import TYPE_CHECKING, Anyimport pyarrow as paimport deltalake as deltalakeimport pyarrow.compute as pc-import pyarrow.dataset as padsimport deltalake.exceptionsfrom structlog.types import FilteringBoundLogger@@ -39,20 +38,33 @@ from products.warehouse_sources.backend.models.external_data_schema import (ExternalDataSchema,finalize_repartition_scheme,save_repartition_checkpoint_if_claimed,+ stage_partition_scheme_for_full_refresh,)from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrow_utils import (evolve_pyarrow_schema,normalize_column_name,realign_decimal_buffers,)-from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.batcher import DEFAULT_MAX_TABLE_BYTESfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.core.consts import PARTITION_KEY+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.memory_governor import get_governorfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.table import _purge_s3_prefixfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.core.partitioning import (NULL_NUMERICAL_PARTITION,append_partition_key_to_table,)-from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.table_stats import table_payload_bytes+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.repartition_stream import (+ PartitionedFileWriter,+ SourceReader,+ StreamBudget,+ TempTableCommitter,+ UnsupportedSourceTableError,+ arrow_schema_of,+ check_source_supported,+ copied_source_files,+ plan_source_files,+ resume_blocker,+ storage_filesystem,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import (PartitionFormat,PartitionMode,@@ -66,17 +78,16 @@ if TYPE_CHECKING:# Coarse → fine. A datetime table that's OOMing steps one tier finer each repartition cycle.DATETIME_FORMAT_TIERS: list[PartitionFormat] = ["month", "week", "day", "hour"]-# Rows per scanned record-batch. A row count cannot bound memory on its own — the same count is a few-# MB of a narrow table and gigabytes of nested records — so this is deliberately low rather than-# tuned, the way `MAX_FETCH_PAGE_ROWS` is in `sources/common/sql/batching.py`. It bounds the window-# that is still unmeasured when the scan hands a batch over; `REWRITE_BUFFER_MAX_BYTES` bounds what-# is materialised, from real measurements. Low is cheap here: the parquet row group is read either-# way, and the coalescing buffer merges small batches back before any commit.-DEFAULT_REPARTITION_BATCH_SIZE = 1_000+# Memory one rewrite may use when the pod's memory governor cannot size a slot (no cgroup limit).+DEFAULT_REWRITE_BUDGET_BYTES = 512 * 1024 * 1024+# A slot smaller than this cannot hold one decoded batch and a few open files; a slot larger than this+# buys no throughput, because the rewrite is bound by object-store reads, not by its buffers.+MIN_REWRITE_BUDGET_BYTES = 256 * 1024 * 1024+MAX_REWRITE_BUDGET_BYTES = 2 * 1024 * 1024 * 1024-# Minimum gap between claim re-reads during the rewrite loop. The loop yields at least one batch per+# Minimum gap between claim re-reads during the rewrite loop. The loop reads at least one batch per# source *file*, so an over-fragmented table (the exact kind being repartitioned) produces one batch-# per partition regardless of `DEFAULT_REPARTITION_BATCH_SIZE` — a few thousand rows spread over a few+# per partition however small the budget makes the batches — a few thousand rows spread over a few# thousand hour-partitions is a few thousand batches. Re-reading the claim on every one turns a small# rewrite into thousands of Postgres round-trips, and any single failure discards the whole rewrite.# Throttling is safe because the rewrite writes only to a temp table scoped to our own claim token@@ -91,28 +102,10 @@ CLAIM_RECHECK_INTERVAL_SECONDS = 10.0# on committed progress instead means an attempt converges across runs whatever kills it. Throttled# because it costs a claim check and a row write per checkpoint, and bounds re-done work to this# interval rather than to the whole rewrite. A checkpoint only records committed rows, so this also-# bounds how long the coalescing buffer may be held before it commits — a buffer that fills slower-# than this would otherwise leave the rewrite with nothing to resume from.+# bounds how long the rewrite may go between commits — one that fills its buffers slower than this+# would otherwise leave the rewrite with nothing to resume from.CHECKPOINT_INTERVAL_SECONDS = 30.0-# Arrow payload the rewrite may hold in its coalescing buffer. Half the package's per-table cap-# deliberately: the batch that triggers a flush is already materialised and stays resident while the-# buffer drains, so the true peak is buffer + one incoming batch. Budgeting half keeps that sum inside-# one `DEFAULT_MAX_TABLE_BYTES` instead of letting it reach twice the cap. Coalescing loses nothing-# that matters — the win comes from merging thousands of KB-sized batches, not from filling the cap.-REWRITE_BUFFER_MAX_BYTES = DEFAULT_MAX_TABLE_BYTES // 2--# Rows the coalescing buffer may hold before it commits. Deliberately not the scan batch size: one-# number for both caps the buffer at a single batch, so nothing coalesces and every batch becomes its-# own Delta commit. Each commit is a transaction-log write, so that puts a floor under throughput that-# no table large enough to need repartitioning can finish above.-REWRITE_BUFFER_MAX_ROWS = 50_000--# Arrow's default 16-batch readahead keeps memory in flight that never reaches the coalescing buffer,-# so no buffer budget bounds it. Fragment readahead is left at its default: serialising file reads-# would cost the most on the many-small-files tables this module rewrites.-REWRITE_BATCH_READAHEAD = 1-TEMP_URI_SUFFIX = "__repartitioned"@@ -877,61 +870,6 @@ def select_coarsen_target(return None, "unsupported_mode"-def _rows_per_source_file(old_delta: deltalake.DeltaTable) -> dict[str, int]:- """Row count per data file, keyed by file name, read from the Delta log (metadata only)."""- actions = old_delta.get_add_actions(flatten=True)- names = actions.schema.names- if "path" not in names or "num_records" not in names:- return {}- paths = actions.column("path").to_pylist()- counts = actions.column("num_records").to_pylist()- return {path.rsplit("/", 1)[-1]: count or 0 for path, count in zip(paths, counts) if path}---def _drop_copied_source_files(- old_delta: deltalake.DeltaTable, dataset: pads.Dataset, skip_rows: int-) -> tuple[pads.Dataset, int]:- """Trim the source files a resumed rewrite already copied, returning the rows left to skip.-- The scan hands batches over one file at a time in the order `get_fragments` lists them, so the- `skip_rows` prefix temp already holds is exactly the leading whole files whose row counts sum- under it, plus part of the file that straddles the boundary. Dropping those files costs one- Delta-log read; discarding their rows batch by batch costs a full decode of every one of them, on- the same activity budget as the rows the attempt still has to write. So on a table that needs- several budgets the prefix grows until re-reading it fills a budget on its own, and an attempt that- appends nothing is what the controller counts against its give-up cap.-- Only whole files are dropped, so the boundary file is still skipped row by row.- """- if not isinstance(dataset, pads.FileSystemDataset):- return dataset, skip_rows-- per_file = _rows_per_source_file(old_delta)- fragments = list(dataset.get_fragments())- copied = 0- boundary = 0- for fragment in fragments:- rows = per_file.get(fragment.path.rsplit("/", 1)[-1])- if rows is None:- rows = fragment.count_rows()- if copied + rows > skip_rows:- break- copied += rows- boundary += 1-- if boundary == 0:- return dataset, skip_rows- trimmed = pads.FileSystemDataset(fragments[boundary:], dataset.schema, dataset.format, dataset.filesystem)- return trimmed, skip_rows - copied---def _read_next_batch(reader: pa.RecordBatchReader) -> pa.RecordBatch | None:- try:- return reader.read_next_batch()- except StopIteration:- return None--def _format_scheme(target: RepartitionTarget) -> str:"""`datetime/month`, `md5/64`, `numerical/1000000` — the scheme in one readable token."""knob = target.partition_format or target.partition_count or target.partition_size@@ -942,79 +880,125 @@ def _format_fields(fields: dict[str, Any]) -> str:return " ".join(f"{key}={value}" for key, value in fields.items() if value is not None)+def rewrite_budget() -> StreamBudget:+ """The rewrite's byte budget: one memory-governor slot, the same share a concurrent upsert gets."""+ slot_mb = get_governor().slot_budget_mb()+ budget = int(slot_mb * 1024 * 1024) if slot_mb else DEFAULT_REWRITE_BUDGET_BYTES+ return StreamBudget.from_budget(min(max(budget, MIN_REWRITE_BUDGET_BYTES), MAX_REWRITE_BUDGET_BYTES))+++async def _delete_uncommitted(temp_uri: str, storage_options: dict[str, str], paths: list[str]) -> None:+ """Best effort: files no commit references are invisible, but the swap copies the whole prefix."""+ if not paths:+ return++ def delete() -> None:+ filesystem = storage_filesystem(temp_uri, storage_options)+ for path in paths:+ try:+ filesystem.delete_file(path)+ except Exception:+ pass++ await asyncio.to_thread(delete)++async def _rewrite_into_temp(*,old_delta: deltalake.DeltaTable,temp_uri: str,storage_options: dict[str, str],target: RepartitionTarget,- batch_size: int,logger: FilteringBoundLogger,+ budget: StreamBudget | None = None,ensure_claim: Callable[[], Awaitable[None]] | None = None,claim_recheck_interval_seconds: float = CLAIM_RECHECK_INTERVAL_SECONDS,save_checkpoint: Callable[[int, RepartitionTarget], Awaitable[None]] | None = None,checkpoint_interval_seconds: float = CHECKPOINT_INTERVAL_SECONDS,deadline: float | None = None,total_rows: int | None = None,- skip_rows: int = 0,+ copied_files: frozenset[str] = frozenset(),) -> tuple[int, RepartitionTarget]:"""Stream the live table into a temp table under the new partition scheme.- Returns (rows_written, resolved_target) — `rows_written` counts only the rows written by *this*+ Returns (rows_written, resolved_target) — `rows_written` counts only the rows committed by *this*call. The first processed batch resolves any auto-detected mode/format/keys so every subsequentbatch is bucketed identically (a per-batch auto-detect could disagree). `ensure_claim` runs beforethe first batch and then at most once per `claim_recheck_interval_seconds`, so a superseded attemptstops within that window rather than paying a database round-trip per batch (see`CLAIM_RECHECK_INTERVAL_SECONDS`).+ Memory is bounded by `budget` alone (see `repartition_stream`): the rewrite plans from the log of+ the loaded version, reads one source file at a time by row group, and writes through a capped set+ of open files. It commits only at a source-file boundary, and each commit records the source+ files it completes.+`deadline` is a `time.monotonic()` value past which the rewrite gives up with`RepartitionBudgetExceededError` rather than run until Temporal kills it. None runs unbounded.`total_rows` is the source row count, used only to report progress as a percentage and an ETA.- `skip_rows` resumes a prior attempt that ran out of budget: temp already holds a scan-ordered- prefix of `skip_rows` rows, so this call skips that many source rows (the source is immutable- during the rewrite, so the scan order is stable) and appends only the remainder. Whole source files- inside the prefix are dropped from the scan on their recorded row counts, so only the file that- straddles the boundary is read-and-discarded. The rewrite writes in `append` mode, so resuming- builds on the existing temp rather than replacing it.+ `copied_files` resumes a prior attempt: temp already holds every row of these source files (see+ `copied_source_files`), so this call skips them and appends only the rest."""+ budget = budget or rewrite_budget()await logger.ainfo(f"repartition: rewrite starting target_scheme={_format_scheme(target)} total_rows={total_rows} "- f"batch_size={batch_size} temp_uri={temp_uri}",+ f"batch_bytes={budget.batch_bytes} max_open_files={budget.max_open_files} temp_uri={temp_uri}",target_scheme=_format_scheme(target),total_rows=total_rows,- batch_size=batch_size,temp_uri=temp_uri,+ **budget.to_dict(),)+ try:+ check_source_supported(old_delta)+ except UnsupportedSourceTableError as e:+ raise RepartitionUnpartitionableError(str(e)) from e+# The live table's properties travel with its rows. A buffered CDC lane reads its resume# point from a statistic one of them declares, and a rebuilt table that lost it would report# no position at all.- table_configuration = dict(old_delta.metadata().configuration or {}) or None- dataset = await asyncio.to_thread(old_delta.to_pyarrow_dataset)- if skip_rows:- dataset, skip_rows = await asyncio.to_thread(_drop_copied_source_files, old_delta, dataset, skip_rows)+ table_configuration = dict(old_delta.metadata().configuration or {})+ live_schema = await asyncio.to_thread(old_delta.schema)+ live_arrow_schema = arrow_schema_of(live_schema)+ plan = await asyncio.to_thread(plan_source_files, old_delta)+ inherited_rows = 0+ if copied_files:+ inherited_rows = sum(source.num_records or 0 for source in plan if source.path in copied_files)+ plan = [source for source in plan if source.path not in copied_files]await logger.ainfo(- f"repartition: resume dropped the source files already copied, {skip_rows} rows left to skip",- rows_to_skip=skip_rows,+ f"repartition: resume skips the {len(copied_files)} source files already copied, {len(plan)} left to copy",+ files_already_copied=len(copied_files),+ files_left=len(plan),)- reader = await asyncio.to_thread(- lambda: dataset.scanner(- batch_size=batch_size,- batch_readahead=REWRITE_BATCH_READAHEAD,- ).to_reader()++ reader = SourceReader(+ filesystem=storage_filesystem(+ old_delta.table_uri, storage_options, known_sizes={source.path: source.size for source in plan}+ ),+ schema=live_arrow_schema,+ batch_bytes=budget.batch_bytes,)- live_schema = await asyncio.to_thread(old_delta.schema)+ committer = TempTableCommitter(+ temp_uri=temp_uri, storage_options=storage_options, configuration=table_configuration+ )+ writer: PartitionedFileWriter | None = None++ async def run_io(function: Callable[..., Any], *args: Any) -> Any:+ """Do not let task cancellation abandon a native I/O call that still owns these objects."""+ task = asyncio.create_task(asyncio.to_thread(function, *args))+ try:+ return await asyncio.shield(task)+ except asyncio.CancelledError:+ try:+ await asyncio.shield(task)+ except BaseException:+ pass+ raiseresolved: RepartitionTarget | None = Nonerows_written = 0-- buffered: list[pa.Table] = []- buffered_rows = 0- buffered_bytes = 0- buffer_opened_at: float | None = None-started_at = time.monotonic()commits = 0@@ -1058,76 +1042,30 @@ async def _rewrite_into_temp(except Exception:await logger.awarning("repartition: could not save rewrite checkpoint", exc_info=True)- async def flush() -> None:- """Write the buffered batches as one Delta commit, then report progress."""- nonlocal buffered, buffered_rows, buffered_bytes, rows_written, commits, buffer_opened_at- if not buffered:+ completed_sources: list[str] = []+ last_commit_at = time.monotonic()++ async def commit() -> None:+ """Close the open files and commit them, with the source files whose rows they now hold."""+ nonlocal rows_written, commits, completed_sources, last_commit_at+ await write_staged()+ last_commit_at = time.monotonic()+ if writer is None or not completed_sources:return- buffer_opened_at = None- # Every buffered table was already aligned to `live_schema`, so they concat without promotion.- combined = buffered[0] if len(buffered) == 1 else pa.concat_tables(buffered)- buffered = []- buffered_rows = 0- buffered_bytes = 0- await asyncio.to_thread(- deltalake.write_deltalake,- temp_uri,- combined,- partition_by=PARTITION_KEY,- mode="append",- schema_mode="merge",- storage_options=storage_options,- configuration=table_configuration,- )- rows_written += combined.num_rows+ written = await run_io(writer.finish)+ await run_io(committer.commit, written, completed_sources)+ completed_sources = []+ rows_written += sum(file.num_records for file in written)commits += 1report_buffer_bytes(0)await maybe_checkpoint()fields = progress()await logger.ainfo(f"repartition: rewrite progress {_format_fields(fields)}", **fields)- last_claim_check: float | None = None- source_rows_read = 0-- while True:- if ensure_claim is not None:- now = time.monotonic()- if last_claim_check is None or now - last_claim_check >= claim_recheck_interval_seconds:- await ensure_claim()- last_claim_check = now- batch = await asyncio.to_thread(_read_next_batch, reader)- if batch is None:- break- # Deliberately after the read, so exhausting the reader always beats the deadline. Checking- # first would let a rewrite that has already copied every row be discarded and charged an- # attempt because it happened to cross the deadline on the iteration that would have hit- # EOF, which is likeliest for a table whose rewrite lands near the budget: exactly the ones- # this deadline exists to rescue.- if deadline is not None and time.monotonic() >= deadline:- raise RepartitionBudgetExceededError(- f"rewrite exceeded its activity budget after {rows_written} rows written to {temp_uri}",- rows_written=rows_written,- resolved=resolved,- resumed_from=skip_rows,- )-- # Resume: temp already holds the first `skip_rows` rows in scan order, so read past them and- # only append the remainder. The boundary batch is sliced so no row is written twice or lost.- if source_rows_read < skip_rows:- to_skip = min(batch.num_rows, skip_rows - source_rows_read)- source_rows_read += batch.num_rows- if to_skip == batch.num_rows:- continue- batch = batch.slice(to_skip)- else:- source_rows_read += batch.num_rows-- table = pa.Table.from_batches([batch])- if table.num_rows == 0:- continue+ def prepare(table: pa.Table) -> pa.Table:+ nonlocal resolvedif PARTITION_KEY in table.column_names:table = table.drop([PARTITION_KEY])-# After the first batch resolves, later batches must use the *resolved* keys too: datetime# auto-detect swaps the key from the primary key to the detected timestamp column, and pairing# the resolved mode with the original (e.g. UUID) key would fail to parse it as a date.@@ -1142,8 +1080,6 @@ async def _rewrite_into_temp()if result is None:raise RepartitionUnpartitionableError(f"No supported partition mode for keys={target.partition_keys}")-- partitioned_table = result.tableif resolved is None:resolved = dataclasses.replace(target,@@ -1151,48 +1087,93 @@ async def _rewrite_into_temp(partition_format=result.partition_format,partition_keys=result.partition_keys,)-# Align each batch against the live table's own declared schema before writing. Without- # this, whichever batch happens to build temp's schema on the first write fixes its- # nullability from what that one batch's data looked like. So if a column the live schema- # already declares non-nullable slips through with a real null (e.g. a source NOT NULL- # constraint later relaxed upstream), the write aborts with "declared as non-nullable but- # contains null values" partway through the rewrite. Every other Delta write path in this- # pipeline runs incoming data through this same alignment first, so the rewrite must too.- partitioned_table = evolve_pyarrow_schema(partitioned_table, live_schema)- partitioned_table = realign_decimal_buffers(partitioned_table)-- # Coalesce before writing, so commits scale with data size rather than source file count- # (see `CLAIM_RECHECK_INTERVAL_SECONDS`). Bound the buffer by bytes as well as rows: a row- # count says nothing about width once `evolve_pyarrow_schema` has flattened struct and list- # columns into JSON strings. Flush *before* appending whatever would overflow, never after,- # or a nearly-full buffer could still take a further full-sized batch. Peak residency is this- # buffer plus the batch in hand, which `REWRITE_BUFFER_MAX_BYTES` budgets for.- table_bytes = table_payload_bytes(partitioned_table)- # Age closes the buffer as well as size. The scan yields at least one batch per source file,- # so on an over-fragmented table — the kind a coarsening rewrite exists to fix — filling the- # buffer can take longer than the worker survives. Nothing commits, so nothing checkpoints,- # and every attempt resumes from the same row until the attempt cap abandons the table.- buffer_held_too_long = (- buffer_opened_at is not None and time.monotonic() - buffer_opened_at >= checkpoint_interval_seconds- )- if buffered and (- buffered_rows + partitioned_table.num_rows > REWRITE_BUFFER_MAX_ROWS- or buffered_bytes + table_bytes > REWRITE_BUFFER_MAX_BYTES- or buffer_held_too_long- ):- await flush()- if save_checkpoint is not None and buffer_opened_at is None:- # Only tracked when there is a checkpoint to protect, so a caller that cannot resume- # keeps the size-only commits it had.- buffer_opened_at = time.monotonic()- buffered.append(partitioned_table)- buffered_rows += partitioned_table.num_rows- buffered_bytes += table_bytes+ # this, a column the live schema already declares non-nullable that slips through with a+ # real null (e.g. a source NOT NULL constraint later relaxed upstream) reaches the temp+ # table as a null in a non-nullable column. Every other Delta write path in this pipeline+ # runs incoming data through this same alignment first, so the rewrite must too.+ return realign_decimal_buffers(evolve_pyarrow_schema(result.table, live_schema))++ # Over-fragmented sources hand over a few rows per file. Partitioning, aligning and routing+ # each of those on its own costs more than the copy, so the reads are coalesced up to one batch+ # budget first.+ staged: list[pa.Table] = []+ staged_bytes = 0++ async def write_staged() -> None:+ nonlocal writer, staged, staged_bytes+ if not staged:+ return+ combined = staged[0] if len(staged) == 1 else pa.concat_tables(staged)+ staged = []+ staged_bytes = 0+ prepared = await run_io(prepare, combined)+ if writer is None:+ file_schema = await run_io(committer.open_or_create, prepared.schema)+ writer = PartitionedFileWriter(+ filesystem=storage_filesystem(temp_uri, storage_options),+ schema=file_schema,+ budget=budget,+ configuration=table_configuration,+ )+ await run_io(writer.write, prepared)# Feeds the workload reporter bound by the repartition activity; no-op everywhere else.- report_buffer_bytes(buffered_bytes)+ report_buffer_bytes(writer.buffered_bytes)- await flush()+ last_claim_check: float | None = None+ sources = reader.iter_sources(plan)+ try:+ while True:+ entry = await run_io(next, sources, None)+ if entry is None:+ break+ source, tables = entry+ while True:+ if ensure_claim is not None:+ now = time.monotonic()+ if last_claim_check is None or now - last_claim_check >= claim_recheck_interval_seconds:+ await ensure_claim()+ last_claim_check = now+ table = await run_io(next, tables, None)+ if table is None:+ break+ # Deliberately after the read, so exhausting the last file always beats the deadline.+ # Checking first would let a rewrite that has already copied every row be discarded+ # and charged an attempt because it happened to cross the deadline on the iteration+ # that would have hit EOF, which is likeliest for a table whose rewrite lands near the+ # budget: exactly the ones this deadline exists to rescue.+ if deadline is not None and time.monotonic() >= deadline:+ raise RepartitionBudgetExceededError(+ f"rewrite exceeded its activity budget after {rows_written} rows written to {temp_uri}",+ rows_written=rows_written,+ resolved=resolved,+ resumed_from=inherited_rows,+ )+ staged.append(table)+ staged_bytes += table.nbytes+ if staged_bytes >= budget.batch_bytes:+ await write_staged()+ completed_sources.append(source.path)+ if (+ (writer is not None and writer.bytes_since_commit >= budget.commit_bytes)+ or len(completed_sources) >= budget.max_source_files_per_commit+ or time.monotonic() - last_commit_at >= checkpoint_interval_seconds+ ):+ await commit()+ await commit()+ except BaseException:+ if writer is not None:+ try:+ paths = await run_io(writer.abort)+ await _delete_uncommitted(temp_uri, storage_options, paths)+ except BaseException:+ await logger.awarning("repartition: could not clean up uncommitted files", exc_info=True)+ raise+ finally:+ try:+ await run_io(sources.close)+ except BaseException:+ await logger.awarning("repartition: could not close the source reader", exc_info=True)if resolved is None:# Empty source table — nothing to rewrite.@@ -1206,6 +1187,13 @@ async def _rewrite_into_temp(return rows_written, resolved+async def _copied_source_files(temp_uri: str, storage_options: dict[str, str]) -> frozenset[str] | None:+ try:+ return await asyncio.to_thread(copied_source_files, temp_uri, storage_options)+ except (deltalake.exceptions.DeltaError, FileNotFoundError, ValueError):+ return None++def _restart_would_run_out_of_budget(checkpoint: dict[str, Any], live_rows: int) -> bool:"""Whether re-streaming this table from row 0 would run out of budget the way the last attempt did.@@ -1220,19 +1208,58 @@ def _restart_would_run_out_of_budget(checkpoint: dict[str, Any], live_rows: int)return 0 < covered < live_rows+async def defer_repartition_to_full_refresh(+ table_ref: DeltaTableRef,+ schema: ExternalDataSchema,+ target: RepartitionTarget,+ logger: FilteringBoundLogger,+ *,+ claim_token: str | None = None,+) -> dict[str, Any]:+ """Apply `target` through the next full refresh instead of rewriting the table.++ A full-refresh sync deletes the table and writes every row again, so a rewrite only copies data+ the next sync throws away. Its live version also moves on every sync. The scheme is staged for+ that sync to write (see `stage_partition_scheme_for_full_refresh`). Temp tables are not swept+ here: a newer claimant can begin a recovery while this activity awaits S3, and wildcard cleanup+ cannot be fenced by the database claim for the duration of that operation.+ """++ def _write() -> bool:+ return stage_partition_scheme_for_full_refresh(+ schema,+ partitioning_keys=target.partition_keys,+ partition_count=target.partition_count,+ partition_size=target.partition_size,+ partition_mode=target.partition_mode,+ partition_format=target.partition_format,+ claim_token=claim_token,+ )++ if not await asyncio.to_thread(retry_on_db_connection_drop, _write):+ raise RepartitionSupersededError(f"repartition claim lost before full-refresh deferral schema_id={schema.id}")+ await logger.ainfo(+ f"repartition: full-refresh table, staged scheme={_format_scheme(target)} for the next sync to write "+ f"schema_id={schema.id}",+ scheme=_format_scheme(target),+ schema_id=str(schema.id),+ )+ return {"outcome": "deferred", "reason": "full_refresh_rewrites_the_table"}++async def repartition_table_in_place(table_ref: DeltaTableRef,schema: ExternalDataSchema,target: RepartitionTarget,logger: FilteringBoundLogger,*,- batch_size: int = DEFAULT_REPARTITION_BATCH_SIZE,+ budget: StreamBudget | None = None,claim_token: str | None = None,deadline: float | None = None,) -> dict[str, Any]:"""Rewrite the schema's Delta table under `target`'s finer partition scheme, in place, from S3.- Memory is bounded by `batch_size`; the source is never re-read. Crash-safe via the+ Memory is bounded by `budget` (one memory-governor slot by default); the source is read once. 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 in one row-locked write.Returns a stats dict for observability. Raises `RepartitionUnpartitionableError` (terminal) if no@@ -1368,20 +1395,50 @@ async def repartition_table_in_place(if not resuming:skip_rows = 0+ copied: frozenset[str] = frozenset()rewrite_target = targetif resuming_rewrite:- # A prior attempt ran out of budget with temp holding a scan-ordered prefix of the table.- # Resuming skips that prefix and appends the rest, which is only correct while live is- # byte-identical to when the checkpoint was written: the sync's merge runs after a- # swallowed repartition failure, so on any run where that merge committed, live has grown- # and the recorded prefix no longer lines up with the current scan. The Delta version is- # the fence — equal means no commit has touched live since, so the prefix still holds.- # A checkpoint whose temp is unreadable, larger than live, or built against a different- # live version is unusable: discard it and rebuild fresh from the still-intact live table.+ # A prior attempt stopped with temp holding every row of some source files, which its+ # commits record. Resuming skips those files and copies the rest. The sync's merge runs+ # after a swallowed repartition failure, so live may have moved on since the checkpoint.+ # That only matters when the move removed a copied file or added a column (see+ # `resume_blocker`); appended files are simply copied with the rest. A temp that is+ # unreadable, larger than live, or out of step with its record is unusable: discard it+ # and rebuild fresh from the still-intact live table.live_version = await asyncio.to_thread(old_delta.version)checkpoint_version = (rewrite_checkpoint or {}).get("live_version")temp_rows = await _valid_delta_row_count(temp_uri, storage_options)- if temp_rows is None or temp_rows > old_row_count or checkpoint_version != live_version:+ recorded = await _copied_source_files(temp_uri, storage_options) if temp_rows is not None else None+ blocker: str | None+ if temp_rows is None:+ blocker = "temp_unreadable"+ elif temp_rows > old_row_count:+ blocker = "temp_larger_than_live"+ elif recorded is None:+ blocker = None+ else:+ live_sources = await asyncio.to_thread(plan_source_files, old_delta)+ blocker = await asyncio.to_thread(+ resume_blocker,+ live_sources=live_sources,+ live_schema=arrow_schema_of(old_delta.schema()),+ temp_uri=temp_uri,+ storage_options=storage_options,+ copied=recorded,+ temp_rows=temp_rows,+ )+ if blocker is None and recorded is None:+ # A temp an older rewrite wrote records rows, not source files, so it cannot be+ # resumed. That says nothing about the budget, so rebuild without the give-up check.+ await logger.awarning(+ f"repartition: rewrite checkpoint does not record its source files, rebuilding fresh "+ f"schema_id={schema.id}",+ schema_id=str(schema.id),+ )+ await asyncio.to_thread(schema.clear_repartition_rewrite)+ resuming_rewrite = False+ temp_uri = _temp_uri_for(live_uri, claim_token)+ elif blocker is not None:if _restart_would_run_out_of_budget(rewrite_checkpoint or {}, old_row_count):raise RepartitionTooLargeForBudgetError(f"a full activity budget covered {(rewrite_checkpoint or {}).get('rows_written')} of "@@ -1389,16 +1446,18 @@ async def repartition_table_in_place(f"cannot finish either (schema_id={schema.id})")await logger.awarning(- f"repartition: rewrite checkpoint is unusable (temp_rows={temp_rows} live={old_row_count} "- f"checkpoint_version={checkpoint_version} live_version={live_version}), discarding and "- f"rebuilding fresh schema_id={schema.id}",+ f"repartition: rewrite checkpoint is unusable reason={blocker} (temp_rows={temp_rows} "+ f"live={old_row_count} checkpoint_version={checkpoint_version} live_version={live_version}), "+ f"discarding and rebuilding fresh schema_id={schema.id}",schema_id=str(schema.id),+ reason=blocker,)await asyncio.to_thread(schema.clear_repartition_rewrite)resuming_rewrite = Falsetemp_uri = _temp_uri_for(live_uri, claim_token)else:- skip_rows = temp_rows+ skip_rows = temp_rows or 0+ copied = recorded or frozenset()checkpoint_target = (rewrite_checkpoint or {}).get("target")if checkpoint_target:# Pin the scheme the prior attempt resolved, so a resumed auto-detect can't pick a@@ -1451,12 +1510,12 @@ async def repartition_table_in_place(storage_options=storage_options,target=rewrite_target,save_checkpoint=save_checkpoint,- batch_size=batch_size,+ budget=budget,logger=logger,ensure_claim=ensure_claim,deadline=deadline,total_rows=old_row_count,- skip_rows=skip_rows,+ copied_files=copied,)except RepartitionBudgetExceededError as e:# Only a checkpoint this attempt could build on marks a restart. One the resume pathdiff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/repartition_stream.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/repartition_stream.pynew file mode 100644index 000000000000..338ea3f74abc--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/repartition_stream.py@@ -0,0 +1,753 @@+"""Bounded-memory building blocks for the repartition rewrite.++The rewrite copies every row of a live Delta table into a temp table under a new partition scheme.+Its memory must depend on the byte budget only, not on the table's size, its file count or the rows+already written. This module holds the three parts that make that true:++* `SourceReader` reads one source parquet file at a time, by row group, in batches sized from a+ byte budget. Nothing is held for a file after its last batch, so the parquet footer and schema of+ each file are freed before the next file opens. A `pyarrow.dataset` over the whole table keeps+ each fragment's footer once it has scanned it, which grows with every file read.+* `PartitionedFileWriter` routes rows to one parquet file per target partition. It caps the open+ files and the rows they buffer, and it rolls a file over at a target size.+* `TempTableCommitter` commits the closed files as Add actions, with no data rewrite. Each commit+ also records which source files it completes, so a resumed rewrite skips whole source files+ instead of counting rows.++The module has no Django imports, so the local reproduction can drive it directly.+"""++from __future__ import annotations++import re+import json+import math+import time+import uuid+import decimal+import hashlib+import datetime+from collections import OrderedDict, deque+from collections.abc import Generator, Iterator, Mapping, Sequence+from concurrent.futures import Future, ThreadPoolExecutor+from typing import Any, cast++import pyarrow as pa+import deltalake+import pyarrow.fs as pa_fs+import pyarrow.compute as pc+import pyarrow.parquet as pq+from deltalake.fs import DeltaStorageHandler+from deltalake.transaction import AddAction, CommitProperties++from posthog.dataclasses import frozen++from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.consts import PARTITION_KEY++MB = 1024 * 1024++# Commit metadata key that lists the source files a temp commit completes.+SOURCE_FILES_METADATA_KEY = "repartition_source_files"++# Delta-rs truncates string statistics at this many UTF-8 bytes. The same bound keeps the stats of a+# column of large JSON strings small, both in the log and while a file is open.+STRING_STATS_MAX_BYTES = 64++# Delta's default for `delta.dataSkippingNumIndexedCols`.+DEFAULT_NUM_INDEXED_COLS = 32++# The object-store output stream buffers this much before it uploads a multipart part, and the+# parquet writer keeps per-column state too. Counted per open file when the open-file cap is sized.+_OPEN_FILE_OVERHEAD_BYTES = 8 * MB++# Reader features this path cannot honour. A deletion vector hides rows that the parquet file still+# holds, and column mapping renames physical columns, so reading the files directly would be wrong.+UNSUPPORTED_READER_FEATURES = frozenset({"deletionVectors", "columnMapping"})++_SAFE_PARTITION_DIR = re.compile(r"^[A-Za-z0-9_.\-]+$")+++class UnsupportedSourceTableError(Exception):+ """The live table uses a Delta feature that a file-by-file copy would get wrong."""+++@frozen+class StreamBudget:+ """Byte limits for one rewrite. Every in-memory term of the rewrite is bounded by one of these."""++ batch_bytes: int+ buffer_bytes: int+ row_group_bytes: int+ max_open_files: int+ target_file_bytes: int+ commit_bytes: int+ max_source_files_per_commit: int++ @staticmethod+ def from_budget(budget_bytes: int, *, target_file_bytes: int = 128 * MB) -> StreamBudget:+ """Divide one byte budget across the read batch, the write buffers and the open files.++ Half goes to buffered rows, a quarter to open-file overhead, and an eighth to the decoded+ read batch. The rest covers the batch copies that routing and casting make.+ """+ budget_bytes = max(budget_bytes, 64 * MB)+ buffer_bytes = budget_bytes // 2+ return StreamBudget(+ batch_bytes=max(budget_bytes // 8, 1 * MB),+ buffer_bytes=buffer_bytes,+ row_group_bytes=max(min(64 * MB, buffer_bytes // 4), 1 * MB),+ max_open_files=max(2, min(64, (budget_bytes // 4) // _OPEN_FILE_OVERHEAD_BYTES)),+ target_file_bytes=target_file_bytes,+ commit_bytes=max(8 * target_file_bytes, 1024 * MB),+ max_source_files_per_commit=2_000,+ )++ def to_dict(self) -> dict[str, int]:+ return {+ "batch_bytes": self.batch_bytes,+ "buffer_bytes": self.buffer_bytes,+ "row_group_bytes": self.row_group_bytes,+ "max_open_files": self.max_open_files,+ "target_file_bytes": self.target_file_bytes,+ }+++@frozen+class SourceFile:+ path: str+ size: int+ num_records: int | None+ partition_values: Mapping[str, str | None]+++@frozen+class WrittenFile:+ action: AddAction+ num_records: int+++def check_source_supported(delta_table: deltalake.DeltaTable) -> None:+ protocol = delta_table.protocol()+ features = set(protocol.reader_features or []) & UNSUPPORTED_READER_FEATURES+ if features:+ raise UnsupportedSourceTableError(f"the live table uses reader features {sorted(features)}")+++def plan_source_files(delta_table: deltalake.DeltaTable) -> list[SourceFile]:+ """The live data files of the loaded version, from the log only, in a stable order.++ Path order makes the plan the same for every attempt against the same version.+ """+ actions = pa.table(delta_table.get_add_actions(flatten=False))+ names = actions.schema.names+ paths = actions.column("path").to_pylist()+ sizes = actions.column("size_bytes").to_pylist()+ counts = actions.column("num_records").to_pylist() if "num_records" in names else [None] * len(paths)+ partitions = actions.column("partition_values").to_pylist() if "partition_values" in names else [None] * len(paths)+ files = [+ SourceFile(path=path, size=size or 0, num_records=count, partition_values=dict(values or {}))+ for path, size, count, values in zip(paths, sizes, counts, partitions)+ if path+ ]+ files.sort(key=lambda f: f.path)+ return files+++def copied_source_files(temp_uri: str, storage_options: dict[str, str]) -> frozenset[str] | None:+ """The source files the temp table already holds in full, read from its commit metadata.++ None means the record cannot be trusted: a commit without it (a temp table that an older+ rewrite wrote), or a history that does not reach back to the table's creation.+ """+ temp = deltalake.DeltaTable(temp_uri, storage_options=storage_options)+ copied: set[str] = set()+ versions: set[int] = set()+ for entry in temp.history():+ version = entry.get("version")+ if isinstance(version, int):+ versions.add(version)+ if entry.get("operation") == "CREATE TABLE":+ continue+ raw = entry.get(SOURCE_FILES_METADATA_KEY)+ if raw is None:+ return None+ copied.update(json.loads(raw))+ if versions != set(range(temp.version() + 1)):+ return None+ return frozenset(copied)+++def resume_blocker(+ *,+ live_sources: Sequence[SourceFile],+ live_schema: pa.Schema,+ temp_uri: str,+ storage_options: dict[str, str],+ copied: frozenset[str],+ temp_rows: int,+) -> str | None:+ """Why temp cannot be resumed against the live table as it is now, or None when it can.++ Delta data files never change, so a copied file that is still live still holds exactly the rows+ temp took from it. A sync that committed since the checkpoint only blocks the resume when it+ removed a copied file (a merge rewrote it) or added a column temp does not have.+ """+ by_path = {source.path: source for source in live_sources}+ if any(path not in by_path for path in copied):+ return "copied_file_no_longer_live"+ temp = deltalake.DeltaTable(temp_uri, storage_options=storage_options)+ if not set(live_schema.names) - {PARTITION_KEY} <= set(arrow_schema_of(temp.schema()).names):+ return "live_schema_changed"+ counts = [by_path[path].num_records for path in copied]+ if all(count is not None for count in counts) and sum(count or 0 for count in counts) != temp_rows:+ return "temp_rows_do_not_match_copied_files"+ return None+++def arrow_schema_of(delta_schema: deltalake.Schema) -> pa.Schema:+ # `to_arrow` returns an arro3 schema; pyarrow imports it through the Arrow C interface, which+ # the stubs do not model.+ return pa.schema(delta_schema.to_arrow()) # type: ignore[arg-type]+++def storage_filesystem(table_uri: str, storage_options: dict[str, str], **kwargs: Any) -> pa_fs.FileSystem:+ """A pyarrow filesystem rooted at the table, on the same object store client delta-rs uses."""+ return pa_fs.PyFileSystem(DeltaStorageHandler(table_uri, storage_options, **kwargs))+++class SourceReader:+ """Reads source files as tables aligned to the live table's schema, in plan order.++ A small file is fetched whole on a worker thread, a few files ahead, under a cap on the bytes+ fetched and not yet consumed. Decoding stays on the consumer so prefetched files cannot retain+ whole decoded tables. Over-fragmented tables are made of such files, and reading them one at a+ time pays one round trip per file. A large file is read by row group, in batches sized from the+ byte budget, and is never prefetched.+ """++ def __init__(+ self,+ *,+ filesystem: pa_fs.FileSystem,+ schema: pa.Schema,+ batch_bytes: int,+ max_batch_rows: int = 100_000,+ prefetch_bytes: int | None = None,+ max_prefetch_files: int = 64,+ read_threads: int = 8,+ ) -> None:+ self._filesystem = filesystem+ self._schema = schema+ self._batch_bytes = batch_bytes+ self._max_batch_rows = max_batch_rows+ # Compressed bytes. A file decodes to a few times its size, so this stays well under the batch+ # budget, and one file larger than this is streamed instead of prefetched.+ self._prefetch_bytes = prefetch_bytes if prefetch_bytes is not None else max(batch_bytes // 8, 1 * MB)+ self._max_prefetch_files = max_prefetch_files+ self._read_threads = read_threads+ # Decoded rows can be wider than the parquet footer says (dictionary pages expand), so the+ # widest row seen so far also sizes the next file's batches.+ self._observed_row_bytes = 0.0++ def batch_rows_for(self, metadata: pq.FileMetaData) -> int:+ row_bytes = self._observed_row_bytes+ for index in range(metadata.num_row_groups):+ group = metadata.row_group(index)+ if group.num_rows:+ row_bytes = max(row_bytes, group.total_byte_size / group.num_rows)+ if row_bytes <= 0:+ return self._max_batch_rows+ return max(1, min(self._max_batch_rows, int(self._batch_bytes // row_bytes)))++ def iter_sources(self, sources: Sequence[SourceFile]) -> Generator[tuple[SourceFile, Iterator[pa.Table]]]:+ """Each source with an iterator over its tables, in order. Consume each before the next."""+ pool = ThreadPoolExecutor(max_workers=self._read_threads, thread_name_prefix="repartition-read")+ pending: deque[tuple[SourceFile, Future[bytes] | None]] = deque()+ in_flight = 0+ position = 0+ try:+ while position < len(sources) or pending:+ while position < len(sources) and len(pending) < self._max_prefetch_files:+ source = sources[position]+ if source.size > self._prefetch_bytes:+ pending.append((source, None))+ elif pending and in_flight + source.size > self._prefetch_bytes:+ break+ else:+ pending.append((source, pool.submit(self._fetch_small, source)))+ in_flight += source.size+ position += 1+ source, future = pending.popleft()+ if future is None:+ yield source, self.iter_tables(source)+ else:+ data = future.result()+ in_flight -= source.size+ yield source, self._iter_buffer(data, source)+ finally:+ pool.shutdown(wait=True, cancel_futures=True)++ def iter_tables(self, source: SourceFile) -> Iterator[pa.Table]:+ with self._filesystem.open_input_file(source.path) as handle:+ yield from self._iter_parquet(pq.ParquetFile(handle, pre_buffer=True), source)++ def _fetch_small(self, source: SourceFile) -> bytes:+ with self._filesystem.open_input_file(source.path) as handle:+ return handle.read()++ def _iter_buffer(self, data: bytes, source: SourceFile) -> Iterator[pa.Table]:+ yield from self._iter_parquet(pq.ParquetFile(pa.BufferReader(data)), source)++ def _iter_parquet(self, parquet: pq.ParquetFile, source: SourceFile) -> Iterator[pa.Table]:+ batch_rows = self.batch_rows_for(parquet.metadata)+ for batch in parquet.iter_batches(batch_size=batch_rows, use_threads=False):+ if batch.num_rows == 0:+ continue+ yield self._conform(pa.Table.from_batches([batch]), source)++ def _conform(self, table: pa.Table, source: SourceFile) -> pa.Table:+ conformed = conform_to_schema(table, self._schema, source.partition_values)+ self._observed_row_bytes = max(self._observed_row_bytes, conformed.nbytes / conformed.num_rows)+ return conformed+++def conform_to_schema(table: pa.Table, schema: pa.Schema, partition_values: Mapping[str, str | None]) -> pa.Table:+ """Give one file's rows the table schema, the way a dataset scan over the table does.++ A file written before a column was added lacks it, so it reads as nulls. Partition columns are+ not stored in the file, so they come from the Add action's partition values.+ """+ if table.schema.names == schema.names and table.schema.types == schema.types:+ return pa.Table.from_arrays(table.columns, schema=schema)+ num_rows = table.num_rows+ columns: list[pa.ChunkedArray | pa.Array] = []+ for field in schema:+ index = table.schema.get_field_index(field.name)+ column: pa.ChunkedArray | pa.Array+ if index >= 0:+ column = table.column(index)+ if column.type != field.type:+ column = column.cast(field.type)+ elif field.name in partition_values and partition_values[field.name] is not None:+ column = pa.array([partition_values[field.name]] * num_rows, pa.string()).cast(field.type)+ else:+ column = pa.nulls(num_rows, field.type)+ columns.append(column)+ return pa.Table.from_arrays(columns, schema=schema)+++def _stats_columns(schema: pa.Schema, configuration: Mapping[str, str | None]) -> list[str]:+ """The columns whose stats an Add action carries: the table's selection, without nested columns.++ Delta nests the stats of a struct column field by field, and a flat value there is a log that+ delta-rs refuses to commit. The pipeline flattens nested values to JSON strings before they+ reach a table, so a nested column here is rare and loses only its pruning.+ """+ data_columns = [name for name in schema.names if name != PARTITION_KEY]+ named = configuration.get("delta.dataSkippingStatsColumns")+ if named:+ wanted = {part.strip().strip("`") for part in named.split(",") if part.strip()}+ selected = [name for name in data_columns if name in wanted]+ else:+ raw_count = configuration.get("delta.dataSkippingNumIndexedCols")+ count = int(raw_count) if raw_count else DEFAULT_NUM_INDEXED_COLS+ selected = data_columns if count < 0 else data_columns[:count]+ return [name for name in selected if not pa.types.is_nested(schema.field(name).type)]+++def _truncate_utf8(value: str, max_bytes: int) -> str:+ encoded = value.encode("utf-8")+ if len(encoded) <= max_bytes:+ return value+ return encoded[:max_bytes].decode("utf-8", errors="ignore")+++def _string_upper_bound(value: str) -> str | None:+ """The smallest string up to `STRING_STATS_MAX_BYTES` that is not less than `value`.++ A truncated prefix sorts below the value, so its last character is raised by one. None when no+ character can be raised, which leaves the column without a max.+ """+ prefix = _truncate_utf8(value, STRING_STATS_MAX_BYTES)+ if prefix == value:+ return value+ chars = list(prefix)+ while chars:+ code = ord(chars.pop()) + 1+ if 0xD800 <= code <= 0xDFFF:+ code = 0xE000+ if code <= 0x10FFFF:+ candidate = "".join(chars) + chr(code)+ if len(candidate.encode("utf-8")) <= STRING_STATS_MAX_BYTES:+ return candidate+ return None+++@frozen+class StatBounds:+ """JSON-ready min and max for one column. None means the bound is left out."""++ low: Any+ high: Any+++class _ColumnStats:+ """Running min, max and null count of one column across the batches of one output file.++ A reader skips a file whose min/max rule out its filter, so a bound that misses one value loses+ that row from reads and turns its merge into a duplicate insert. Each bound is exact or looser,+ and matches what delta-rs writes where delta-rs is safe.++ A bound is left out only where JSON cannot hold it (infinity). That is not free: delta-rs's+ pyarrow reader turns a missing bound into a null guarantee and skips the file for every filter+ on the column, the same as it does for delta-rs's own stats in that case.+ """++ __slots__ = ("kind", "minimum", "maximum", "null_count", "min_unbounded", "max_unbounded")++ def __init__(self, data_type: pa.DataType) -> None:+ self.kind = _stats_kind(data_type)+ self.minimum: Any = None+ self.maximum: Any = None+ self.null_count = 0+ self.min_unbounded = False+ self.max_unbounded = False++ def update(self, column: pa.ChunkedArray) -> None:+ self.null_count += column.null_count+ if self.kind is None or column.null_count == len(column):+ return+ if self.kind == "float":+ # Same as delta-rs and the parquet footer: NaN is left out of the bounds. JSON has no+ # infinity, so a file holding one has no bound on that side.+ self.min_unbounded = self.min_unbounded or bool(+ pc.any(pc.equal(column, pa.scalar(-math.inf, column.type))).as_py()+ )+ self.max_unbounded = self.max_unbounded or bool(+ pc.any(pc.equal(column, pa.scalar(math.inf, column.type))).as_py()+ )+ column = pc.filter(column, pc.is_finite(column))+ if len(column) == 0:+ return+ result = pc.min_max(column)+ low, high = result["min"].as_py(), result["max"].as_py()+ if low is None or high is None:+ return+ if self.kind == "string":+ low = _truncate_utf8(low, STRING_STATS_MAX_BYTES)+ # With no short upper bound the exact value is kept, as delta-rs does.+ high = _string_upper_bound(high) or high+ self.minimum = low if self.minimum is None or low < self.minimum else self.minimum+ self.maximum = high if self.maximum is None or high > self.maximum else self.maximum++ def json_values(self) -> StatBounds:+ if self.kind is None or self.minimum is None:+ return StatBounds(low=None, high=None)+ return StatBounds(+ low=None if self.min_unbounded else _json_stat(self.minimum),+ high=None if self.max_unbounded else _json_stat(self.maximum),+ )+++def _stats_kind(data_type: pa.DataType) -> str | None:+ if pa.types.is_integer(data_type):+ return "int"+ if pa.types.is_floating(data_type):+ return "float"+ if pa.types.is_decimal(data_type):+ return "decimal"+ if pa.types.is_string(data_type) or pa.types.is_large_string(data_type):+ return "string"+ if pa.types.is_boolean(data_type):+ return "bool"+ if pa.types.is_date32(data_type):+ return "date"+ if pa.types.is_timestamp(data_type) and data_type.unit == "us":+ return "timestamp"+ return None+++def _json_stat(value: Any) -> Any:+ # Same text forms delta-rs writes, so readers that parse its stats parse these too. A decimal+ # stays a `Decimal` until `_dumps_stats` writes it as an exact JSON number.+ if isinstance(value, datetime.datetime):+ if value.tzinfo is None:+ return str(value)+ return value.astimezone(datetime.UTC).isoformat().replace("+00:00", "Z")+ if isinstance(value, datetime.date):+ return value.isoformat()+ return value+++def _dumps_stats(stats: dict[str, Any]) -> str:+ """JSON for an Add action's stats, with each decimal written as its exact JSON number.++ delta-rs writes a decimal bound through a float. The float can round to the inner side of the+ real bound, and from about 1e16 delta-rs's own reader parses it as null. The exact number text+ is valid JSON and parses back to the exact value.+ """+ # A random token, so no string value in the stats can look like a placeholder.+ token = uuid.uuid4().hex+ numbers: list[str] = []++ def default(value: Any) -> str:+ if isinstance(value, decimal.Decimal) and value.is_finite():+ numbers.append(format(value, "f"))+ return f"{token}{len(numbers) - 1}"+ raise TypeError(f"cannot write {type(value).__name__} into Delta stats")++ text = json.dumps(stats, default=default)+ return re.sub(f'"{token}(\\d+)"', lambda match: numbers[int(match.group(1))], text)+++class _OpenFile:+ """One parquet file in the temp table, open for one target partition."""++ def __init__(+ self,+ *,+ filesystem: pa_fs.FileSystem,+ path: str,+ partition_value: str | None,+ file_schema: pa.Schema,+ stats_columns: Sequence[str],+ ) -> None:+ self.path = path+ self.partition_value = partition_value+ self._sink = filesystem.open_output_stream(path)+ self._writer = pq.ParquetWriter(self._sink, file_schema, compression="snappy")+ self._stats = {name: _ColumnStats(file_schema.field(name).type) for name in stats_columns}+ self.pending: list[pa.Table] = []+ self.pending_bytes = 0+ self.num_records = 0++ @property+ def written_bytes(self) -> int:+ return self._sink.tell()++ def append(self, table: pa.Table) -> None:+ self.pending.append(table)+ self.pending_bytes += table.nbytes+ self.num_records += table.num_rows+ for name, stats in self._stats.items():+ stats.update(table.column(name))++ def flush_row_group(self) -> None:+ if not self.pending:+ return+ combined = self.pending[0] if len(self.pending) == 1 else pa.concat_tables(self.pending)+ self.pending = []+ self.pending_bytes = 0+ self._writer.write_table(combined, row_group_size=max(combined.num_rows, 1))++ def close(self) -> WrittenFile:+ self.flush_row_group()+ self._writer.close()+ size = self._sink.tell()+ self._sink.close()+ stats: dict[str, Any] = {"numRecords": self.num_records, "minValues": {}, "maxValues": {}, "nullCount": {}}+ for name, column_stats in self._stats.items():+ stats["nullCount"][name] = column_stats.null_count+ bounds = column_stats.json_values()+ if bounds.low is not None:+ stats["minValues"][name] = bounds.low+ if bounds.high is not None:+ stats["maxValues"][name] = bounds.high+ action = AddAction(+ self.path,+ size,+ {PARTITION_KEY: self.partition_value},+ int(time.time() * 1000),+ True,+ _dumps_stats(stats),+ )+ return WrittenFile(action=action, num_records=self.num_records)++ def abort(self) -> None:+ try:+ self._writer.close()+ finally:+ self._sink.close()+++def _partition_dir(value: str | None) -> str:+ # The Add action carries the partition value, so the directory name only has to be unique and+ # safe. A value with characters that need URI encoding gets a hashed name instead, because the+ # log stores paths encoded and a literal `%` in an object key would not round-trip.+ if value is None:+ return f"{PARTITION_KEY}=__HIVE_DEFAULT_PARTITION__"+ if _SAFE_PARTITION_DIR.match(value):+ return f"{PARTITION_KEY}={value}"+ digest = hashlib.md5(value.encode("utf-8"), usedforsecurity=False).hexdigest()+ return f"{PARTITION_KEY}=__h{digest[:16]}"+++def split_by_partition(table: pa.Table) -> Iterator[tuple[str | None, pa.Table]]:+ keys = table.column(PARTITION_KEY)+ if keys.null_count == 0:+ first = keys[0].as_py()+ if pc.all(pc.equal(keys, first)).as_py():+ yield first, table+ return+ encoded = cast(pa.DictionaryArray, pc.dictionary_encode(keys.combine_chunks()))+ dictionary = encoded.dictionary.to_pylist()+ indices = encoded.indices+ for position, value in enumerate(dictionary):+ yield value, table.filter(pc.equal(indices, pa.scalar(position, indices.type)))+ if keys.null_count:+ yield None, table.filter(pc.is_null(indices))+++class PartitionedFileWriter:+ """Writes rows into one parquet file per target partition, inside a fixed memory budget.++ Three limits bound memory however many target partitions the rows spread over:++ * at most `max_open_files` files are open; opening one more closes the least recently used;+ * one file's buffered rows become a row group at `row_group_bytes`;+ * the buffered rows of all open files never exceed `buffer_bytes`; the largest buffer is+ written out first.++ A file closes at `target_file_bytes`, on eviction, or at `finish`. Closed files wait in+ `finish`'s result until the caller commits them.+ """++ def __init__(+ self,+ *,+ filesystem: pa_fs.FileSystem,+ schema: pa.Schema,+ budget: StreamBudget,+ configuration: Mapping[str, str | None],+ ) -> None:+ self._filesystem = filesystem+ self._schema = schema+ self._file_schema = pa.schema([field.with_nullable(True) for field in schema if field.name != PARTITION_KEY])+ self._stats_columns = _stats_columns(schema, configuration)+ self._budget = budget+ self._open: OrderedDict[str | None, _OpenFile] = OrderedDict()+ self._closed: list[WrittenFile] = []+ self._buffered_bytes = 0+ self.bytes_since_commit = 0+ self.max_open_seen = 0++ @property+ def schema(self) -> pa.Schema:+ return self._schema++ @property+ def buffered_bytes(self) -> int:+ return self._buffered_bytes++ def write(self, table: pa.Table) -> None:+ """Route `table` (which holds `PARTITION_KEY`) to its partitions' files."""+ unknown = set(table.column_names) - set(self._schema.names)+ if unknown:+ # Selecting the known columns would silently drop these values from the rebuilt table.+ raise ValueError(f"rows carry columns the temp table does not have: {sorted(unknown)}")+ table = table.select(self._schema.names).cast(self._schema)+ for value, rows in split_by_partition(table):+ data = rows.drop([PARTITION_KEY]).cast(self._file_schema)+ open_file = self._file_for(value)+ open_file.append(data)+ self._buffered_bytes += data.nbytes+ if open_file.pending_bytes >= self._budget.row_group_bytes:+ self._flush(open_file)+ while self._buffered_bytes > self._budget.buffer_bytes:+ self._flush(max(self._open.values(), key=lambda f: f.pending_bytes))++ def finish(self) -> list[WrittenFile]:+ """Close every open file and hand over all files closed since the last call."""+ while self._open:+ _, open_file = self._open.popitem(last=False)+ self._close(open_file)+ closed, self._closed = self._closed, []+ self.bytes_since_commit = 0+ return closed++ def abort(self) -> list[str]:+ """Drop every open and uncommitted file. Returns their paths so the caller can delete them."""+ paths = [written.action.path for written in self._closed]+ while self._open:+ _, open_file = self._open.popitem(last=False)+ paths.append(open_file.path)+ open_file.abort()+ self._closed = []+ self._buffered_bytes = 0+ return paths++ def _file_for(self, value: str | None) -> _OpenFile:+ open_file = self._open.get(value)+ if open_file is not None:+ self._open.move_to_end(value)+ return open_file+ if len(self._open) >= self._budget.max_open_files:+ _, oldest = self._open.popitem(last=False)+ self._close(oldest)+ open_file = _OpenFile(+ filesystem=self._filesystem,+ path=f"{_partition_dir(value)}/part-{uuid.uuid4()}-c000.snappy.parquet",+ partition_value=value,+ file_schema=self._file_schema,+ stats_columns=self._stats_columns,+ )+ self._open[value] = open_file+ self.max_open_seen = max(self.max_open_seen, len(self._open))+ return open_file++ def _flush(self, open_file: _OpenFile) -> None:+ before = open_file.written_bytes+ self._buffered_bytes -= open_file.pending_bytes+ open_file.flush_row_group()+ self.bytes_since_commit += open_file.written_bytes - before+ if open_file.written_bytes >= self._budget.target_file_bytes:+ self._open.pop(open_file.partition_value, None)+ self._close(open_file)++ def _close(self, open_file: _OpenFile) -> None:+ before = open_file.written_bytes+ self._buffered_bytes -= open_file.pending_bytes+ written = open_file.close()+ self.bytes_since_commit += written.action.size - before+ self._closed.append(written)+++class TempTableCommitter:+ """Commits written files to the temp table as Add actions, with the source files they complete."""++ def __init__(+ self, *, temp_uri: str, storage_options: dict[str, str], configuration: Mapping[str, str | None] | None+ ) -> None:+ self._temp_uri = temp_uri+ self._storage_options = storage_options+ self._configuration = dict(configuration or {}) or None+ self._table: deltalake.DeltaTable | None = None++ def open_or_create(self, schema: pa.Schema) -> pa.Schema:+ """Open temp, creating it with `schema` when absent. Returns the schema files must use."""+ if self._table is None:+ if deltalake.DeltaTable.is_deltatable(self._temp_uri, storage_options=self._storage_options):+ self._table = deltalake.DeltaTable(self._temp_uri, storage_options=self._storage_options)+ else:+ self._table = deltalake.DeltaTable.create(+ self._temp_uri,+ schema=schema,+ partition_by=[PARTITION_KEY],+ configuration=self._configuration,+ storage_options=self._storage_options,+ )+ return arrow_schema_of(self._table.schema())++ def commit(self, files: Sequence[WrittenFile], source_paths: Sequence[str]) -> None:+ if self._table is None:+ raise RuntimeError("commit before the temp table was opened")+ self._table.create_write_transaction(+ [written.action for written in files],+ mode="append",+ schema=self._table.schema(),+ partition_by=[PARTITION_KEY],+ commit_properties=CommitProperties(+ custom_metadata={SOURCE_FILES_METADATA_KEY: json.dumps(list(source_paths))}+ ),+ )+ self._table.update_incremental()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.pyindex 167d25875c24..329324bc3ddb 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@@ -1,9 +1,13 @@import os+import globimport json+import mathimport asyncio+import decimalimport datetimeimport itertoolsfrom types import SimpleNamespace+from typing import castimport pytestfrom unittest.mock import AsyncMock, Mock, patch@@ -12,7 +16,10 @@ import django.dbimport pyarrow as paimport deltalake as deltalake+import deltaliteimport structlog+import pyarrow.parquet as pq+from deltalake.transaction import AddActionfrom parameterized import parameterizedfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.core import repartition as repartition_module@@ -24,7 +31,6 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.parappend_partition_key_to_table,)from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.repartition import (- REWRITE_BATCH_READAHEAD,RepartitionBudgetExceededError,RepartitionSupersededError,RepartitionTarget,@@ -35,6 +41,14 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.repselect_coarsen_target,select_repartition_target,)+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.repartition_stream import (+ SOURCE_FILES_METADATA_KEY,+ SourceFile,+ SourceReader,+ StreamBudget,+ TempTableCommitter,+ copied_source_files,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import PartitionFormatfrom products.warehouse_sources.backend.temporal.data_imports.workload_report import (_redis_client,@@ -113,6 +127,29 @@ def _write_month_partitioned(path: str, rows: list[tuple[int, datetime.datetime]return _write_datetime_partitioned(path, rows, "month")+def _budget(**overrides) -> StreamBudget:+ # A one-byte batch budget reads one row per batch, so every test sees many batches per file.+ values = {+ "batch_bytes": 1,+ "buffer_bytes": 64 * 1024 * 1024,+ "row_group_bytes": 8 * 1024 * 1024,+ "max_open_files": 8,+ "target_file_bytes": 128 * 1024 * 1024,+ "commit_bytes": 1 << 40,+ "max_source_files_per_commit": 10_000,+ }+ values.update(overrides)+ return StreamBudget(**values)+++def _patch_copied(files: frozenset[str] | None = frozenset({"part-0.parquet"})):+ return patch.object(repartition_module, "_copied_source_files", new=AsyncMock(return_value=files))+++def _patch_blocker(reason: str | None = None):+ return patch.object(repartition_module, "resume_blocker", return_value=reason)++class TestSelectRepartitionTarget:@parameterized.expand([@@ -603,7 +640,7 @@ class TestRewriteIntoTemp:partition_mode="datetime",partition_format="day",),- batch_size=2, # force multiple streamed batches+ budget=_budget(),logger=logger,))@@ -644,7 +681,7 @@ class TestRewriteIntoTemp:partition_mode="datetime",partition_format="day",),- batch_size=1,+ budget=_budget(),logger=logger,))@@ -671,7 +708,7 @@ class TestRewriteIntoTemp:partition_mode="datetime",partition_format="day",),- batch_size=1,+ budget=_budget(),logger=logger,))@@ -681,20 +718,14 @@ class TestRewriteIntoTemp:sample = json.loads(redis.get(run_key("repartition:rw-test")))assert sample["peak_buffer_bytes"] > 0- def test_scanner_bounds_readahead_so_the_scan_cannot_outrun_the_buffer(self, tmp_path):- # The default 16-batch prefetch is invisible to the coalescing buffer.- rows = [(i, datetime.datetime(2024, 1, 1 + (i % 28))) for i in range(40)]+ def test_reads_source_files_without_a_whole_table_dataset(self, tmp_path):+ # A dataset over the live table keeps every scanned fragment's parquet footer until the scan+ # ends, so its memory grows with each file read and OOM-killed workers on many-file tables.+ rows = [(i, datetime.datetime(2024, 1 + (i % 12), 1 + (i % 28))) for i in range(40)]old_delta = _write_month_partitioned(str(tmp_path / "src"), rows)- captured: dict = {}- real_scanner = old_delta.to_pyarrow_dataset().scanner-- def spy(**kwargs):- captured.update(kwargs)- return real_scanner(**kwargs)- with patch.object(deltalake.DeltaTable, "to_pyarrow_dataset") as dataset:- dataset.return_value = SimpleNamespace(scanner=spy)- asyncio.run(+ with patch.object(deltalake.DeltaTable, "to_pyarrow_dataset", side_effect=AssertionError("dataset scan")):+ rows_written, _ = asyncio.run(_rewrite_into_temp(old_delta=old_delta,temp_uri=str(tmp_path / "tmp"),@@ -705,13 +736,12 @@ class TestRewriteIntoTemp:partition_mode="datetime",partition_format="day",),- batch_size=10,+ budget=_budget(),logger=logger,))- assert captured["batch_readahead"] == REWRITE_BATCH_READAHEAD- assert "fragment_readahead" not in captured+ assert rows_written == len(rows)def test_progress_is_checkpointed_before_any_deadline(self, tmp_path):# The deadline handler is the only other place a checkpoint is written, and an OOM-killed@@ -734,7 +764,7 @@ class TestRewriteIntoTemp:partition_mode="datetime",partition_format="day",),- batch_size=1,+ budget=_budget(),logger=logger,save_checkpoint=save_checkpoint,checkpoint_interval_seconds=0,@@ -747,18 +777,18 @@ class TestRewriteIntoTemp:assert saved[-1][1] == "day"def test_a_slow_scan_checkpoints_before_the_buffer_is_full(self, tmp_path):- # An over-fragmented table yields one small batch per source file, so the buffer can take+ # An over-fragmented table yields one small batch per source file, so the buffers can take# longer to fill than the worker survives. With no commit there is no checkpoint either, and- # every attempt then resumes from the same row until the attempt cap abandons the table.- rows = [(i, datetime.datetime(2024, 1, 1 + i)) for i in range(4)]+ # every attempt then resumes from the same file until the attempt cap abandons the table.+ rows = [(i, datetime.datetime(2024, 1 + i, 1)) for i in range(4)]old_delta = _write_month_partitioned(str(tmp_path / "src"), rows)saved: list[int] = []async def save_checkpoint(rows_so_far, _resolved_target):saved.append(rows_so_far)- # Every clock read lands a minute later, so the buffer is always older than the checkpoint- # interval while holding far less than REWRITE_BUFFER_MAX_ROWS/BYTES.+ # Every clock read lands a minute later, so each source file boundary is past the checkpoint+ # interval while the buffers hold far less than their byte bounds.clock = Mock(side_effect=itertools.count(0.0, 60.0))with patch.object(repartition_module, "time", Mock(monotonic=clock)):@@ -773,7 +803,7 @@ class TestRewriteIntoTemp:partition_mode="datetime",partition_format="day",),- batch_size=1,+ budget=_budget(),logger=logger,save_checkpoint=save_checkpoint,)@@ -803,7 +833,7 @@ class TestRewriteIntoTemp:partition_mode="datetime",partition_format="day",),- batch_size=1,+ budget=_budget(),logger=logger,save_checkpoint=exploding_checkpoint,checkpoint_interval_seconds=0,@@ -813,25 +843,16 @@ class TestRewriteIntoTemp:assert rows_written == len(rows)def test_stops_mid_stream_once_the_deadline_passes(self, tmp_path):- rows = [- (1, datetime.datetime(2024, 1, 5)),- (2, datetime.datetime(2024, 1, 20)),- (3, datetime.datetime(2024, 1, 25)),- (4, datetime.datetime(2024, 2, 2)),- ]+ # One row per month, so one source file per row and a commit after each file.+ rows = [(i, datetime.datetime(2024, 1 + i, 5)) for i in range(4)]old_delta = _write_month_partitioned(str(tmp_path / "src"), rows)temp_uri = str(tmp_path / "tmp")- # Batches coalesce into a commit rather than writing one each, so the deadline has to fall- # after the buffer has flushed at least once for any row to be observable in temp at all.- # The rewrite also samples this clock for its own progress timing, so the prefix stays under- # the deadline for the early reads and every later read is over it.+ # The rewrite also samples this clock for its own progress and commit timing, so the prefix+ # stays under the deadline until the first file has committed and every later read is over it.clock = Mock(side_effect=itertools.chain([0.0] * 4, itertools.repeat(100.0)))- with (- patch.object(repartition_module, "time", Mock(monotonic=clock)),- patch.object(repartition_module, "REWRITE_BUFFER_MAX_ROWS", 2),- ):+ with patch.object(repartition_module, "time", Mock(monotonic=clock)):with pytest.raises(RepartitionBudgetExceededError):asyncio.run(_rewrite_into_temp(@@ -844,7 +865,7 @@ class TestRewriteIntoTemp:partition_mode="datetime",partition_format="day",),- batch_size=2,+ budget=_budget(max_source_files_per_commit=1),logger=logger,deadline=50.0,)@@ -852,30 +873,37 @@ class TestRewriteIntoTemp:# Some rows landed but not all: the deadline is checked per batch inside the streaming loop,# so the rewrite gives up partway instead of either draining the reader (no bound at all) or- # bailing before it starts. The exact count is not asserted because the reader yields at- # least one batch per source file, so batch boundaries follow the source layout.+ # bailing before it starts.written = deltalake.DeltaTable(temp_uri).to_pyarrow_table().num_rowsassert 0 < written < len(rows)- def test_resume_from_a_prefix_completes_the_table_exactly_once(self, tmp_path):- # A budget-exceeded rewrite leaves temp holding a scan-ordered prefix. Resuming with- # skip_rows=<prefix length> must append exactly the remaining rows: every source row present- # once, none duplicated, none dropped. This is the fix's core guarantee, and it also guards the- # assumption the skip relies on — that the scan order is stable across the two passes. A- # reordering would re-write rows already in temp and skip others, which this catches.- rows = [(i, datetime.datetime(2024, 1, 1) + datetime.timedelta(days=3 * i)) for i in range(8)]+ @pytest.mark.parametrize(+ "files_per_commit,rows_per_month",+ [+ pytest.param(1, 1, id="one_file_per_commit"),+ pytest.param(2, 1, id="two_files_per_commit"),+ pytest.param(1, 3, id="rows_spread_over_several_target_days"),+ ],+ )+ def test_resume_after_an_interruption_completes_the_table_exactly_once(+ self, files_per_commit, rows_per_month, tmp_path+ ):+ # A rewrite stopped mid-way leaves temp holding whole source files, which its commits record.+ # Resuming from that record must append exactly the other files: every source row present+ # once, none duplicated, none dropped.+ rows = [+ (month * rows_per_month + day, datetime.datetime(2024, 1 + month, 1 + day))+ for month in range(6)+ for day in range(rows_per_month)+ ]live = _write_month_partitioned(str(tmp_path / "live"), rows)temp_uri = str(tmp_path / "tmp")target = RepartitionTarget(partition_keys=["created_at"], trigger_reason="t", partition_mode="datetime", partition_format="day")- # Stop the first pass after the buffer has flushed once, so temp holds a partial prefix.- clock = Mock(side_effect=itertools.chain([0.0] * 4, itertools.repeat(100.0)))- with (- patch.object(repartition_module, "time", Mock(monotonic=clock)),- patch.object(repartition_module, "REWRITE_BUFFER_MAX_ROWS", 2),- ):+ clock = Mock(side_effect=itertools.chain([0.0] * (4 + 3 * rows_per_month), itertools.repeat(100.0)))+ with patch.object(repartition_module, "time", Mock(monotonic=clock)):with pytest.raises(RepartitionBudgetExceededError):asyncio.run(_rewrite_into_temp(@@ -883,103 +911,66 @@ class TestRewriteIntoTemp:temp_uri=temp_uri,storage_options={},target=target,- batch_size=2,+ budget=_budget(max_source_files_per_commit=files_per_commit),logger=logger,deadline=50.0,))partial = deltalake.DeltaTable(temp_uri).to_pyarrow_table().num_rowsassert 0 < partial < len(rows)+ copied = copied_source_files(temp_uri, {})+ assert copied is not None+ assert len(copied) * rows_per_month == partial- asyncio.run(- _rewrite_into_temp(- old_delta=live,- temp_uri=temp_uri,- storage_options={},- target=target,- batch_size=2,- logger=logger,- skip_rows=partial,- )- )-- final = deltalake.DeltaTable(temp_uri).to_pyarrow_table()- # Count plus set: every source id present exactly once (equal count rules out duplicates).- assert final.num_rows == len(rows)- assert set(final.column("id").to_pylist()) == set(range(len(rows)))-- def test_resume_does_not_re_read_the_source_files_it_already_copied(self, tmp_path):- # The prefix temp already holds is charged to the resumed attempt's own budget when it is- # skipped row by row, so on a table that needs several budgets the re-read grows until it fills- # a budget on its own and the attempt appends nothing — which is what the controller counts- # against its give-up cap before abandoning the table. One row per month means one source file- # per row, so a copied prefix is a whole number of files and the scan must never open them.- rows = [(i, datetime.datetime(2024, 1, 1) + datetime.timedelta(days=40 * i)) for i in range(6)]- live = _write_month_partitioned(str(tmp_path / "live"), rows)- temp_uri = str(tmp_path / "tmp")- target = RepartitionTarget(- partition_keys=["created_at"], trigger_reason="t", partition_mode="datetime", partition_format="day"- )-- clock = Mock(side_effect=itertools.chain([0.0] * 8, itertools.repeat(100.0)))- with (- patch.object(repartition_module, "time", Mock(monotonic=clock)),- patch.object(repartition_module, "REWRITE_BUFFER_MAX_ROWS", 1),- ):- with pytest.raises(RepartitionBudgetExceededError):- asyncio.run(- _rewrite_into_temp(- old_delta=live,- temp_uri=temp_uri,- storage_options={},- target=target,- batch_size=1,- logger=logger,- deadline=50.0,- )- )- copied = deltalake.DeltaTable(temp_uri).to_pyarrow_table().num_rows- assert 0 < copied < len(rows)-- reads = 0- read_batch = repartition_module._read_next_batch+ opened: list[str] = []+ iter_sources = SourceReader.iter_sources- def counting_read(reader):- nonlocal reads- reads += 1- return read_batch(reader)+ def recording_iter_sources(reader, sources):+ opened.extend(source.path for source in sources)+ return iter_sources(reader, sources)- with patch.object(repartition_module, "_read_next_batch", counting_read):+ with patch.object(SourceReader, "iter_sources", recording_iter_sources):rows_written, _ = asyncio.run(_rewrite_into_temp(old_delta=live,temp_uri=temp_uri,storage_options={},target=target,- batch_size=1,+ budget=_budget(),logger=logger,- skip_rows=copied,+ copied_files=copied,))- # One read per uncopied file, plus the read that exhausts the scan.- assert reads == (len(rows) - copied) + 1- assert rows_written == len(rows) - copied+ # The copied files are never read again, so a resume does not re-read its prefix.+ assert opened and not copied & set(opened)+ assert rows_written == len(rows) - partialfinal = deltalake.DeltaTable(temp_uri).to_pyarrow_table()assert final.num_rows == len(rows)- assert set(final.column("id").to_pylist()) == set(range(len(rows)))+ assert sorted(cast(list[int], final.column("id").to_pylist())) == [row[0] for row in rows]+ assert copied_source_files(temp_uri, {}) == frozenset(+ f.path for f in repartition_module.plan_source_files(live)+ )++ def test_a_temp_without_source_file_records_cannot_be_resumed(self, tmp_path):+ # An older rewrite appended rows with plain writes. Its temp says how many rows it holds but+ # not which files, so treating it as resumable would skip the wrong rows.+ rows = [(1, datetime.datetime(2024, 1, 5)), (2, datetime.datetime(2024, 2, 2))]+ _write_month_partitioned(str(tmp_path / "legacy"), rows)++ assert copied_source_files(str(tmp_path / "legacy"), {}) is Nonedef test_a_finished_rewrite_beats_the_deadline(self, tmp_path):- # One source file, one batch, so the reader is exhausted on the second loop iteration. The- # clock is over the deadline by then: a rewrite that has already copied every row must still- # reach the swap rather than be thrown away and charged a failed attempt.+ # One source file, one batch, so the reader is exhausted on the second read. The clock is+ # over the deadline by then: a rewrite that has already copied every row must still reach the+ # swap rather than be thrown away and charged a failed attempt.rows = [(1, datetime.datetime(2024, 1, 5)), (2, datetime.datetime(2024, 1, 20))]old_delta = _write_month_partitioned(str(tmp_path / "src"), rows)temp_uri = str(tmp_path / "tmp")# Every deadline check must land under the deadline for the rewrite to reach the swap; the# later readings only feed progress timing, so they are free to be past it.- clock = Mock(side_effect=itertools.chain([0.0] * 2, itertools.repeat(100.0)))+ clock = Mock(side_effect=itertools.chain([0.0] * 3, itertools.repeat(100.0)))with patch.object(repartition_module, "time", Mock(monotonic=clock)):rows_written, _ = asyncio.run(@@ -993,7 +984,7 @@ class TestRewriteIntoTemp:partition_mode="datetime",partition_format="day",),- batch_size=2,+ budget=_budget(batch_bytes=64 * 1024 * 1024),logger=logger,deadline=50.0,)@@ -1014,7 +1005,7 @@ class TestRewriteIntoTemp:temp_uri=temp_uri,storage_options={},target=RepartitionTarget(partition_keys=["created_at"], trigger_reason="test", partition_mode=None),- batch_size=3,+ budget=_budget(),logger=logger,))@@ -1044,7 +1035,7 @@ class TestRewriteIntoTemp:temp_uri=str(tmp_path / "tmp"),storage_options={},target=RepartitionTarget(partition_keys=["id"], trigger_reason="test", partition_mode=None),- batch_size=3, # force batches after the resolving first one+ budget=_budget(),logger=logger,))@@ -1077,7 +1068,7 @@ class TestRewriteIntoTemp:target=RepartitionTarget(partition_keys=["id"], trigger_reason="test", partition_mode=None, partition_count=4),- batch_size=3,+ budget=_budget(),logger=logger,))@@ -1111,7 +1102,7 @@ class TestRewriteIntoTemp:target=RepartitionTarget(partition_keys=["id"], trigger_reason="test", partition_mode=None, partition_count=4),- batch_size=3,+ budget=_budget(),logger=logger,))@@ -1131,40 +1122,41 @@ class TestRewriteIntoTemp:pa.field("real_model", pa.string(), nullable=False),])- # Bypasses delta-rs's own write-time validation (which would reject this) to stand in for- # a batch scanned off a live table whose data no longer matches its declared schema. The- # scanned batch's own field still says non-nullable too, matching the live table's.- batch_table = pa.Table.from_arrays(- [pa.array([1, 2], type=pa.int64()), pa.array(["gpt-4", None], type=pa.string())],- schema=live_pa_schema,+ # Bypasses delta-rs's own write-time validation (which would reject this): the parquet file+ # is written directly and committed as an Add action, so the live table really holds a null+ # its declared schema forbids.+ live_uri = str(tmp_path / "live")+ live = deltalake.DeltaTable.create(live_uri, schema=live_pa_schema)+ file_schema = pa.schema([field.with_nullable(True) for field in live_pa_schema])+ pq.write_table(+ pa.table({"id": [1, 2], "real_model": ["gpt-4", None]}, schema=file_schema),+ os.path.join(live_uri, "part-0.parquet"),)-- class _FakeReader:- def __init__(self, table):- self._batches = table.to_batches()-- def read_next_batch(self):- if not self._batches:- raise StopIteration- return self._batches.pop(0)-- old_delta = SimpleNamespace(- metadata=lambda: SimpleNamespace(configuration={}),- to_pyarrow_dataset=lambda: SimpleNamespace(- scanner=lambda **kwargs: SimpleNamespace(to_reader=lambda: _FakeReader(batch_table))- ),- schema=lambda: deltalake.Schema.from_arrow(live_pa_schema),+ live.create_write_transaction(+ [+ AddAction(+ "part-0.parquet",+ os.path.getsize(os.path.join(live_uri, "part-0.parquet")),+ {},+ 0,+ True,+ json.dumps({"numRecords": 2}),+ )+ ],+ mode="append",+ schema=live.schema(),)+ old_delta = deltalake.DeltaTable(live_uri)rows_written, _ = asyncio.run(_rewrite_into_temp(- old_delta=old_delta, # type: ignore[arg-type]+ old_delta=old_delta,temp_uri=str(tmp_path / "tmp"),storage_options={},target=RepartitionTarget(partition_keys=["id"], trigger_reason="test", partition_mode="md5", partition_count=1),- batch_size=10,+ budget=_budget(),logger=logger,))@@ -1175,6 +1167,474 @@ class TestRewriteIntoTemp:assert new_table.column("real_model").to_pylist() == ["gpt-4", ""]+class TestStreamingRewrite:+ """The rewrite reads source files one at a time and writes through a capped set of open files,+ so its memory follows the byte budget, not the table. These cases pin the limits and the data+ the limits must not change."""++ def test_prefetched_small_file_is_decoded_in_batches(self, tmp_path):+ path = str(tmp_path / "small.parquet")+ table = pa.table({"id": [1, 2, 3, 4, 5]})+ pq.write_table(table, path)+ source = SourceFile(path=path, size=os.path.getsize(path), num_records=5, partition_values={})+ reader = SourceReader(+ filesystem=pa.fs.LocalFileSystem(),+ schema=table.schema,+ batch_bytes=1024,+ max_batch_rows=2,+ prefetch_bytes=1024 * 1024,+ )++ [(read_source, tables)] = reader.iter_sources([source])+ batches = list(tables)++ assert read_source is source+ assert [batch.num_rows for batch in batches] == [2, 2, 1]+ assert pa.concat_tables(batches).equals(table)++ @staticmethod+ def _day_target() -> RepartitionTarget:+ return RepartitionTarget(+ partition_keys=["created_at"], trigger_reason="t", partition_mode="datetime", partition_format="day"+ )++ @pytest.mark.parametrize(+ "max_open_files,buffer_bytes,target_file_bytes",+ [+ pytest.param(1, 64 * 1024 * 1024, 128 * 1024 * 1024, id="one_open_file"),+ pytest.param(4, 64 * 1024 * 1024, 128 * 1024 * 1024, id="fewer_open_files_than_partitions"),+ pytest.param(64, 64 * 1024 * 1024, 128 * 1024 * 1024, id="more_open_files_than_partitions"),+ pytest.param(64, 2048, 128 * 1024 * 1024, id="tiny_shared_buffer"),+ pytest.param(4, 2048, 1, id="every_row_group_closes_its_file"),+ ],+ )+ def test_many_target_partitions_keep_every_row_inside_the_writer_limits(+ self, max_open_files, buffer_bytes, target_file_bytes, tmp_path+ ):+ # Rows for 30 target days arrive interleaved, so every batch moves to another partition.+ # Without the open-file cap, a table spread over many target partitions keeps one open file+ # (and its upload buffer) per partition.+ rows = [(i, datetime.datetime(2024, 1 + i % 3, 1 + i % 28, i % 24)) for i in range(240)]+ live = _write_month_partitioned(str(tmp_path / "live"), rows)+ temp_uri = str(tmp_path / "temp")+ writers: list = []+ buffered: list[int] = []++ class SpyWriter(repartition_module.PartitionedFileWriter):+ def __init__(self, **kwargs):+ super().__init__(**kwargs)+ writers.append(self)++ def write(self, table):+ super().write(table)+ buffered.append(self.buffered_bytes)++ budget = _budget(+ max_open_files=max_open_files,+ buffer_bytes=buffer_bytes,+ row_group_bytes=min(buffer_bytes, 8 * 1024 * 1024),+ target_file_bytes=target_file_bytes,+ )+ with patch.object(repartition_module, "PartitionedFileWriter", SpyWriter):+ rows_written, _ = asyncio.run(+ _rewrite_into_temp(+ old_delta=live,+ temp_uri=temp_uri,+ storage_options={},+ target=self._day_target(),+ budget=budget,+ logger=logger,+ )+ )++ assert writers[0].max_open_seen <= max_open_files+ assert max(buffered) <= buffer_bytes+ temp = deltalake.DeltaTable(temp_uri)+ table = temp.to_pyarrow_table()+ assert rows_written == table.num_rows == len(rows)+ assert sorted(cast(list[int], table.column("id").to_pylist())) == [row[0] for row in rows]+ expected_keys = {created.strftime("%Y-%m-%d") for _, created in rows}+ assert set(table.column(PARTITION_KEY).to_pylist()) == expected_keys+ # Every row sits in the partition its own timestamp maps to.+ for created, key in zip(table.column("created_at").to_pylist(), table.column(PARTITION_KEY).to_pylist()):+ assert isinstance(created, datetime.datetime)+ assert created.strftime("%Y-%m-%d") == key++ def test_files_written_before_a_column_was_added_read_as_nulls(self, tmp_path):+ # A file-by-file read sees each file's own schema. The rewrite must fill a column an older+ # file lacks, the way a scan of the whole table does, instead of failing the write.+ live_uri = str(tmp_path / "live")+ first = pa.table(+ {+ "id": pa.array([1], pa.int64()),+ "created_at": pa.array([datetime.datetime(2024, 1, 5)], pa.timestamp("us")),+ }+ )+ second = pa.table(+ {+ "id": pa.array([2], pa.int64()),+ "created_at": pa.array([datetime.datetime(2024, 2, 5)], pa.timestamp("us")),+ "added_later": pa.array(["v"], pa.string()),+ }+ )+ for chunk in (first, second):+ result = append_partition_key_to_table(chunk, None, None, ["created_at"], "datetime", "month", logger)+ assert result is not None+ deltalake.write_deltalake(+ live_uri, result.table, partition_by=PARTITION_KEY, mode="append", schema_mode="merge"+ )+ temp_uri = str(tmp_path / "temp")++ rows_written, _ = asyncio.run(+ _rewrite_into_temp(+ old_delta=deltalake.DeltaTable(live_uri),+ temp_uri=temp_uri,+ storage_options={},+ target=self._day_target(),+ budget=_budget(),+ logger=logger,+ )+ )++ table = deltalake.DeltaTable(temp_uri).to_pyarrow_table().sort_by("id")+ assert rows_written == 2+ assert table.column("added_later").to_pylist() == [None, "v"]++ @pytest.mark.parametrize(+ "partition_count",+ [pytest.param(1, id="one_bucket"), pytest.param(7, id="several_buckets")],+ )+ def test_hashed_buckets_keep_every_row_and_key(self, partition_count, tmp_path):+ rows = 50+ table = pa.table(+ {+ "id": pa.array([f"key-{i}" for i in range(rows)], type=pa.string()),+ "payload": pa.array(["p" * 200] * rows, type=pa.string()),+ }+ )+ deltalake.write_deltalake(str(tmp_path / "live"), table)+ temp_uri = str(tmp_path / "temp")++ rows_written, resolved = asyncio.run(+ _rewrite_into_temp(+ old_delta=deltalake.DeltaTable(str(tmp_path / "live")),+ temp_uri=temp_uri,+ storage_options={},+ target=RepartitionTarget(+ partition_keys=["id"], trigger_reason="t", partition_mode="md5", partition_count=partition_count+ ),+ budget=_budget(max_open_files=2),+ logger=logger,+ )+ )++ rebuilt = deltalake.DeltaTable(temp_uri).to_pyarrow_table()+ assert resolved.partition_mode == "md5"+ assert rows_written == rebuilt.num_rows == rows+ assert sorted(cast(list[str], rebuilt.column("id").to_pylist())) == sorted(f"key-{i}" for i in range(rows))+ assert len(set(rebuilt.column(PARTITION_KEY).to_pylist())) <= partition_count+++_D = decimal.Decimal+_CUT_IN_A_CHARACTER = "a" * 63 + "é" + "zz"+_MAX_CODE_POINT = "\U0010ffff" * 20+++def _write_streamed(uri: str, chunks: list[pa.Table]) -> None:+ # One commit, and so one file, per chunk.+ committer = TempTableCommitter(temp_uri=uri, storage_options={}, configuration=None)+ file_schema = committer.open_or_create(chunks[0].schema)+ for chunk in chunks:+ writer = repartition_module.PartitionedFileWriter(+ filesystem=repartition_module.storage_filesystem(uri, {}),+ schema=file_schema,+ budget=_budget(),+ configuration={},+ )+ writer.write(chunk)+ committer.commit(writer.finish(), [f"source-{chunk.column('id')[0].as_py()}"])+++def _raw_add_stats(uri: str) -> list[dict]:+ # Decimals parse exactly, so a bound that is off in its last digit cannot pass as equal.+ stats = []+ for log in sorted(glob.glob(os.path.join(uri, "_delta_log", "*.json"))):+ with open(log) as handle:+ for line in handle:+ action = json.loads(line)+ if "add" in action:+ stats.append(json.loads(action["add"]["stats"], parse_float=decimal.Decimal))+ return stats+++def _typed(value, data_type: pa.DataType):+ if pa.types.is_decimal(data_type):+ return _D(value)+ if pa.types.is_date32(data_type):+ return datetime.date.fromisoformat(value)+ if pa.types.is_timestamp(data_type):+ return datetime.datetime.fromisoformat(value)+ if pa.types.is_floating(data_type):+ return pa.scalar(float(value), data_type).as_py()+ return value+++class TestAddActionStats:+ """The rewrite writes its own Add-action stats. Readers skip files on them, so a bound that misses+ one value loses that row from reads and turns its merge into a duplicate insert."""++ @pytest.mark.parametrize(+ "values,data_type,differs",+ [+ pytest.param([-128, 5, None, 127], pa.int8(), {}, id="int8"),+ pytest.param([-32768, 1, 32767], pa.int16(), {}, id="int16"),+ pytest.param([-(2**31), 0, 2**31 - 1], pa.int32(), {}, id="int32"),+ pytest.param([-(2**63), 0, 2**63 - 1], pa.int64(), {}, id="int64"),+ pytest.param([1.5, -2.25, 0.1, None], pa.float32(), {}, id="float32"),+ pytest.param([0.1, -1e300, 5e-324, -0.0], pa.float64(), {}, id="float64"),+ pytest.param([1.5, float("nan"), -2.25], pa.float32(), {}, id="float32_with_nan"),+ pytest.param([float("nan"), float("nan")], pa.float64(), {}, id="float64_all_nan"),+ pytest.param([float("inf"), 0.1], pa.float64(), {}, id="float64_with_inf"),+ pytest.param([float("-inf"), 0.1], pa.float64(), {}, id="float64_with_negative_inf"),+ pytest.param(+ [_D("0.10"), _D("2.50"), None], pa.decimal128(20, 2), {}, id="decimal_held_exactly_by_a_float"+ ),+ pytest.param(+ [_D("0.10"), _D("12345678901234567.89")],+ pa.decimal128(20, 2),+ {"max": "exact"},+ id="decimal_max_a_float_cannot_hold",+ ),+ pytest.param(+ [_D("12345678901234567.89"), _D("12345678901234599.99")],+ pa.decimal128(20, 2),+ {"min": "exact", "max": "exact"},+ id="decimal_bounds_a_float_cannot_hold",+ ),+ pytest.param(+ [_D("-1234567890123456789012345678.0123456789"), _D("1E-10")],+ pa.decimal128(38, 10),+ {"min": "exact"},+ id="decimal_at_full_precision",+ ),+ pytest.param([_CUT_IN_A_CHARACTER, "b" * 100, "c"], pa.string(), {}, id="long_string_cut_in_a_character"),+ pytest.param(["é" * 40, "ab", None], pa.string(), {}, id="long_multibyte_string"),+ pytest.param([_MAX_CODE_POINT, "a"], pa.string(), {}, id="string_whose_prefix_cannot_be_raised"),+ pytest.param(["", "", ""], pa.string(), {}, id="empty_strings"),+ pytest.param(["", "x"], pa.string(), {}, id="empty_and_short_strings"),+ pytest.param([None, None, None], pa.string(), {}, id="all_null_strings"),+ pytest.param([None, None], pa.int64(), {}, id="all_null_ints"),+ pytest.param([True, None, False], pa.bool_(), {}, id="bool"),+ pytest.param([True, True], pa.bool_(), {}, id="bool_one_value"),+ pytest.param([datetime.date(2024, 1, 1), datetime.date(1970, 1, 1), None], pa.date32(), {}, id="date32"),+ pytest.param(+ [datetime.datetime(2024, 1, 1, 1, 2, 3, 456789), datetime.datetime(1999, 12, 31), None],+ pa.timestamp("us"),+ {},+ id="timestamp_naive",+ ),+ pytest.param(+ [+ datetime.datetime(2024, 1, 1, 1, 2, 3, 456789, tzinfo=datetime.UTC),+ datetime.datetime(1999, 12, 31, tzinfo=datetime.UTC),+ None,+ ],+ pa.timestamp("us", tz="UTC"),+ {},+ id="timestamp_utc",+ ),+ pytest.param(+ [{"x": 1, "y": "q"}, None, {"x": 3, "y": "r"}],+ pa.struct([("x", pa.int64()), ("y", pa.string())]),+ {"min": "omitted", "max": "omitted", "nullCount": "omitted"},+ id="struct",+ ),+ ],+ )+ def test_stats_match_delta_rs_unless_delta_rs_is_unsafe(self, values, data_type, differs, tmp_path):+ # `differs` names each stat that deliberately does not match delta-rs: "exact" where delta-rs+ # rounds a decimal through a float, "omitted" where the writer leaves the stat out.+ table = pa.table(+ {+ "id": pa.array(range(len(values)), pa.int64()),+ "v": pa.array(values, data_type),+ PARTITION_KEY: pa.array(["p"] * len(values)),+ }+ )+ deltalake.write_deltalake(str(tmp_path / "reference"), table, partition_by=PARTITION_KEY)+ _write_streamed(str(tmp_path / "streamed"), [table])+ (reference,) = _raw_add_stats(str(tmp_path / "reference"))+ (streamed,) = _raw_add_stats(str(tmp_path / "streamed"))+ present = [+ value for value in values if value is not None and value == value and value not in (math.inf, -math.inf)+ ]++ assert streamed["numRecords"] == reference["numRecords"]+ assert streamed["nullCount"]["id"] == reference["nullCount"]["id"]+ for key, name, true_value in (+ ("nullCount", "nullCount", None),+ ("minValues", "min", min),+ ("maxValues", "max", max),+ ):+ ours = streamed.get(key, {}).get("v")+ theirs = reference.get(key, {}).get("v")+ expectation = differs.get(name)+ if expectation == "omitted":+ assert ours is None+ elif expectation == "exact":+ assert callable(true_value)+ assert _typed(ours, data_type) == true_value(present)+ assert _typed(theirs, data_type) != true_value(present)+ elif key == "nullCount" or ours is None or theirs is None:+ assert ours == theirs+ else:+ assert _typed(ours, data_type) == _typed(theirs, data_type)++ if streamed.get("minValues", {}).get("v") is not None:+ assert _typed(streamed["minValues"]["v"], data_type) <= min(present)+ if streamed.get("maxValues", {}).get("v") is not None:+ assert _typed(streamed["maxValues"]["v"], data_type) >= max(present)++ @staticmethod+ def _typed_table() -> pa.Table:+ rows = range(12)+ base = datetime.datetime(2024, 1, 1, 0, 0, 0, 456789)+ return pa.table(+ {+ "id": pa.array(rows, pa.int64()),+ "i8": pa.array([None if i == 3 else i * 10 - 60 for i in rows], pa.int8()),+ "f32": pa.array([i * 1.5 - 3.0 for i in rows], pa.float32()),+ "f64": pa.array([i * 0.1 for i in rows], pa.float64()),+ "f64_nan": pa.array([float("nan") if i == 5 else float(i) for i in rows], pa.float64()),+ "f64_inf": pa.array([float("inf") if i == 9 else float(i) for i in rows], pa.float64()),+ "dec": pa.array([(_D(i) / 4).quantize(_D("0.01")) for i in rows], pa.decimal128(20, 2)),+ "dec_big": pa.array([_D("12345678901234567.89") + i for i in rows], pa.decimal128(20, 2)),+ "s": pa.array(["é" * 40 + chr(ord("a") + i) for i in rows], pa.string()),+ "b": pa.array([i % 2 == 0 for i in rows], pa.bool_()),+ "d": pa.array(+ [None if i == 7 else datetime.date(2024, 1, 1) + datetime.timedelta(days=i) for i in rows]+ ),+ "ts": pa.array([base + datetime.timedelta(hours=i) for i in rows], pa.timestamp("us")),+ "tz": pa.array(+ [(base + datetime.timedelta(hours=i)).replace(tzinfo=datetime.UTC) for i in rows],+ pa.timestamp("us", tz="UTC"),+ ),+ PARTITION_KEY: pa.array(["p"] * 12),+ }+ )++ @staticmethod+ def _boundaries(table: pa.Table, column: str) -> list:+ values = []+ for start in range(0, table.num_rows, 4):+ chunk = [v for v in table.column(column).to_pylist()[start : start + 4] if v is not None and v == v]+ values.extend([min(chunk), max(chunk)])+ return values++ @staticmethod+ def _sql_literal(value, data_type: pa.DataType) -> str:+ if pa.types.is_decimal(data_type):+ return f"CAST('{value}' AS DECIMAL({data_type.precision},{data_type.scale}))"+ if pa.types.is_string(data_type):+ return "'" + value.replace("'", "''") + "'"+ if pa.types.is_boolean(data_type):+ return "true" if value else "false"+ if pa.types.is_date32(data_type):+ return f"DATE '{value.isoformat()}'"+ if pa.types.is_timestamp(data_type):+ if data_type.tz is None:+ return f"TIMESTAMP '{value.isoformat(sep=' ')}'"+ return f"CAST('{value.isoformat().replace('+00:00', 'Z')}' AS TIMESTAMP)"+ if pa.types.is_floating(data_type):+ return f"CAST('{value!r}' AS DOUBLE)" if math.isinf(value) else repr(float(value))+ return str(value)++ _OPS = {+ "=": lambda a, b: a == b,+ "<": lambda a, b: a < b,+ ">": lambda a, b: a > b,+ "<=": lambda a, b: a <= b,+ ">=": lambda a, b: a >= b,+ }++ @pytest.mark.parametrize(+ "column", ["id", "i8", "f32", "f64", "f64_nan", "dec", "dec_big", "s", "b", "d", "ts", "tz"]+ )+ def test_filtered_pyarrow_reads_at_each_file_bound_keep_every_matching_row(self, column, tmp_path):+ # delta-rs turns each file's stats into a pyarrow guarantee, so a bound off by one value drops+ # that file from a filtered read. The infinity column is not listed: JSON cannot hold its+ # bound, and delta-rs's pyarrow reader reads a missing bound as null and drops the file,+ # for delta-rs's own stats too. NaN rows are not compared, because readers disagree on how+ # NaN orders.+ table = self._typed_table()+ uri = str(tmp_path / "temp")+ _write_streamed(uri, [table.slice(start, 4) for start in range(0, 12, 4)])+ delta = deltalake.DeltaTable(uri)+ assert len(delta.file_uris()) == 3+ values = table.column(column).to_pylist()+ nan_rows = {i for i, value in enumerate(values) if isinstance(value, float) and math.isnan(value)}++ for bound in self._boundaries(table, column):+ for op, holds in self._OPS.items():+ expected = sorted(+ i+ for i, value in enumerate(values)+ if value is not None and i not in nan_rows and holds(value, bound)+ )+ read = delta.to_pyarrow_table(filters=[(column, op, bound)])+ read_ids = set(cast(list[int], read.column("id").to_pylist()))+ assert sorted(read_ids - nan_rows) == expected, (column, op, bound)++ @pytest.mark.parametrize(+ "column",+ ["id", "i8", "f32", "f64", "f64_nan", "f64_inf", "dec", "dec_big", "s", "b", "d", "ts", "tz"],+ )+ def test_datafusion_reads_at_each_file_bound_keep_every_matching_row(self, column, tmp_path):+ # DataFusion prunes files on the same stats during delta-rs merges and SQL reads. NaN rows are+ # not compared: DataFusion orders NaN above every number when it evaluates a filter, but the+ # parquet footer and delta-rs's own stats both leave NaN out, so pruning drops them for any+ # writer.+ table = self._typed_table()+ uri = str(tmp_path / "temp")+ _write_streamed(uri, [table.slice(start, 4) for start in range(0, 12, 4)])+ query = deltalake.QueryBuilder().register("t", deltalake.DeltaTable(uri))+ data_type = table.schema.field(column).type+ values = table.column(column).to_pylist()+ nan_rows = {i for i, value in enumerate(values) if isinstance(value, float) and math.isnan(value)}++ for bound in self._boundaries(table, column):+ for op, holds in self._OPS.items():+ expected = sorted(+ i+ for i, value in enumerate(values)+ if value is not None and i not in nan_rows and holds(value, bound)+ )+ sql = f"SELECT id FROM t WHERE {column} {op} {self._sql_literal(bound, data_type)}"+ read = pa.table(query.execute(sql).read_all())+ read_ids = set(cast(list[int], read.column("id").to_pylist()))+ assert sorted(read_ids - nan_rows) == expected, sql++ @pytest.mark.parametrize("key", ["id", "s", "dec", "dec_big", "ts", "tz"])+ def test_a_stats_pruned_upsert_at_each_file_bound_updates_instead_of_inserting(self, key, tmp_path):+ # deltalite skips files whose stats on the first primary key rule out a match. A bound that+ # misses the key inserts the row again, so the table keeps a duplicate.+ table = self._typed_table()+ uri = str(tmp_path / "temp")+ _write_streamed(uri, [table.slice(start, 4) for start in range(0, 12, 4)])+ keys = table.column(key).to_pylist()+ rows = sorted({keys.index(bound) for bound in self._boundaries(table, key)})+ changed = table.take(rows).set_column(+ table.schema.get_field_index("i8"), "i8", pa.array([99] * len(rows), pa.int8())+ )++ stats = deltalite.DeltaLiteTable.open(uri).upsert(changed, [key], PARTITION_KEY, prune_strategy="stats")++ after = deltalake.DeltaTable(uri).to_pyarrow_table().sort_by("id")+ assert stats.rows_inserted == 0+ assert after.num_rows == table.num_rows+ assert [after.column("i8")[i].as_py() for i in rows] == [99] * len(rows)++class _FakeS3CM:"""Minimal async-context-manager stand-in for `aget_s3_client()`."""@@ -1909,6 +2369,8 @@ 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_copied(),+ _patch_blocker(),_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,@@ -1939,8 +2401,8 @@ class TestRewriteCheckpointResume:assert checkpoint["temp_uri"].endswith("__repartitioned_tok")def test_resumes_when_the_live_version_still_matches(self, tmp_path):- # Version matches → resume: append from the recorded offset into the checkpoint's own temp,- # without sweeping temps (a fresh rebuild would discard the prefix).+ # Version matches → resume: skip the source files temp records into the checkpoint's own+ # temp, without sweeping temps (a fresh rebuild would discard them).live = _write_month_partitioned(str(tmp_path / "live"),[@@ -1965,6 +2427,8 @@ 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_copied(),+ _patch_blocker(),_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])),@@ -1979,7 +2443,7 @@ class TestRewriteCheckpointResume:purge.assert_not_awaited() # the prefix must not be sweptassert rewrite.await_args_list[0].kwargs["temp_uri"] == "s3://bucket/live__repartitioned_old"- assert rewrite.await_args_list[0].kwargs["skip_rows"] == 1+ assert rewrite.await_args_list[0].kwargs["copied_files"] == {"part-0.parquet"}schema.clear_repartition_rewrite.assert_called_once() # obsolete once temp is completeassert result["outcome"] == "completed"@@ -2017,6 +2481,8 @@ class TestRewriteCheckpointResume:with (patch.object(repartition_module, "_purge_stale_temp_tables", new=AsyncMock()),patch.object(repartition_module, "_current_claim_token", return_value="tok"),+ _patch_copied(),+ _patch_blocker(),_patch_finalize(),patch.object(repartition_module, "_valid_delta_row_count", new=AsyncMock(side_effect=[1, 3])),patch.object(repartition_module, "save_repartition_checkpoint_if_claimed", return_value=True) as saved,@@ -2031,10 +2497,10 @@ class TestRewriteCheckpointResume:assert saved.call_args.kwargs["checkpoint"]["rows_written"] == 3- def test_discards_the_checkpoint_when_the_live_version_moved_on(self, tmp_path):- # Version moved on (a merge committed between attempts) → the recorded prefix no longer lines up- # with the current scan. The checkpoint must be discarded and a fresh rebuild started into our- # own claim-scoped temp, never resumed — resuming would swap misaligned data over live.+ def test_discards_the_checkpoint_when_a_copied_file_is_no_longer_live(self, 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.live = _write_month_partitioned(str(tmp_path / "live"), [(1, datetime.datetime(2024, 1, 5)), (2, datetime.datetime(2024, 2, 2))])@@ -2055,6 +2521,8 @@ 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_copied(),+ _patch_blocker("copied_file_no_longer_live"),_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,@@ -2069,17 +2537,18 @@ class TestRewriteCheckpointResume:schema.clear_repartition_rewrite.assert_called() # stale checkpoint droppedpurge.assert_awaited_once() # fresh rebuild sweeps orphansassert rewrite.await_args_list[0].kwargs["temp_uri"].endswith("__repartitioned_tok")- assert rewrite.await_args_list[0].kwargs["skip_rows"] == 0+ assert rewrite.await_args_list[0].kwargs["copied_files"] == frozenset()@pytest.mark.parametrize(- "version_offset,expected_restart",+ "version_offset,blocker,expected_restart",[- pytest.param(0, True, id="resumed_checkpoint_is_a_restart"),- pytest.param(999, False, id="rejected_checkpoint_is_not_a_restart"),+ pytest.param(0, None, True, id="resumed_checkpoint_is_a_restart"),+ pytest.param(999, None, True, id="checkpoint_resumed_after_live_moved_is_a_restart"),+ pytest.param(999, "copied_file_no_longer_live", False, id="rejected_checkpoint_is_not_a_restart"),],)def test_only_a_usable_checkpoint_makes_an_over_budget_attempt_a_restart(- self, version_offset, expected_restart, tmp_path+ self, version_offset, blocker, expected_restart, tmp_path):# `had_prior_checkpoint` decides whether the activity charges this attempt against the cap.# A checkpoint the resume path rejected was left by an attempt killed at an arbitrary point@@ -2106,6 +2575,8 @@ 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_copied(),+ _patch_blocker(blocker),_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),@@ -2125,6 +2596,121 @@ class TestRewriteCheckpointResume:assert raised.value.had_prior_checkpoint is expected_restartassert raised.value.checkpoint_saved is True+ @staticmethod+ def _append_month(live_uri: str) -> None:+ table = pa.table(+ {+ "id": pa.array([100], pa.int64()),+ "created_at": pa.array([datetime.datetime(2025, 3, 3)], pa.timestamp("us")),+ }+ )+ result = append_partition_key_to_table(table, None, None, ["created_at"], "datetime", "month", logger)+ assert result is not None+ deltalake.write_deltalake(live_uri, result.table, partition_by=PARTITION_KEY, mode="append")++ @staticmethod+ def _rewrite_a_copied_file(live_uri: str) -> None:+ deltalake.DeltaTable(live_uri).delete("id = 0")++ @staticmethod+ def _add_a_column(live_uri: str) -> None:+ table = pa.table(+ {+ "id": pa.array([101], pa.int64()),+ "created_at": pa.array([datetime.datetime(2025, 4, 4)], pa.timestamp("us")),+ "added_later": pa.array(["v"], pa.string()),+ }+ )+ result = append_partition_key_to_table(table, None, None, ["created_at"], "datetime", "month", logger)+ assert result is not None+ deltalake.write_deltalake(+ live_uri, result.table, partition_by=PARTITION_KEY, mode="append", schema_mode="merge"+ )++ @pytest.mark.parametrize(+ "move_live,expect_resume",+ [+ pytest.param(None, True, id="live_unchanged"),+ pytest.param("_append_month", True, id="live_gained_a_file"),+ pytest.param("_rewrite_a_copied_file", False, id="live_rewrote_a_copied_file"),+ pytest.param("_add_a_column", False, id="live_gained_a_column"),+ ],+ )+ def test_a_resume_survives_a_live_version_move_that_keeps_the_copied_files(+ self, move_live, expect_resume, tmp_path+ ):+ # Full-refresh and frequently merged tables move their live version between almost every two+ # attempts. Discarding a checkpoint for that alone threw away every long rewrite's progress.+ live_uri = str(tmp_path / "live")+ rows = [(i, datetime.datetime(2024, 1 + i, 5)) for i in range(6)]+ live = _write_month_partitioned(live_uri, rows)+ target = RepartitionTarget(+ partition_keys=["created_at"], trigger_reason="t", partition_mode="datetime", partition_format="day"+ )+ prior_temp = str(tmp_path / "live__repartitioned_old")+ clock = Mock(side_effect=itertools.chain([0.0] * 7, itertools.repeat(100.0)))+ with patch.object(repartition_module, "time", Mock(monotonic=clock)):+ with pytest.raises(RepartitionBudgetExceededError):+ asyncio.run(+ _rewrite_into_temp(+ old_delta=live,+ temp_uri=prior_temp,+ storage_options={},+ target=target,+ budget=_budget(max_source_files_per_commit=1),+ logger=logger,+ deadline=50.0,+ )+ )+ copied = copied_source_files(prior_temp, {})+ assert copied+ prior_rows = deltalake.DeltaTable(prior_temp).to_pyarrow_table().num_rows++ if move_live is not None:+ getattr(self, move_live)(live_uri)+ moved = deltalake.DeltaTable(live_uri)+ schema = self._base_schema(+ repartition_rewrite={+ "temp_uri": prior_temp,+ "rows_written": prior_rows,+ "target": target.to_dict(),+ "live_version": live.version(),+ },+ )+ table_ref = _make_table_ref(+ get_table_uri=AsyncMock(return_value=live_uri), get_delta_table=AsyncMock(return_value=moved)+ )++ 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.object(repartition_module, "save_repartition_checkpoint_if_claimed", return_value=True),+ _patch_finalize(),+ patch.object(repartition_module, "_swap_temp_into_live", new=AsyncMock()) as swap,+ ):+ result = asyncio.run(+ repartition_table_in_place(+ table_ref=table_ref,+ schema=schema,+ target=target,+ logger=logger,+ claim_token="tok",+ budget=_budget(),+ )+ )++ assert result["outcome"] == "completed"+ assert swap.await_args is not None+ swapped = swap.await_args.kwargs["temp_uri"]+ assert (swapped == prior_temp) is expect_resume+ rebuilt = deltalake.DeltaTable(swapped).to_pyarrow_table()+ live_now = moved.to_pyarrow_table()+ assert rebuilt.num_rows == live_now.num_rows+ assert sorted(cast(list[int], rebuilt.column("id").to_pylist())) == sorted(+ cast(list[int], live_now.column("id").to_pylist())+ )+def test_refuses_to_restart_a_table_one_budget_already_failed_to_cover(self, tmp_path):# The discarded checkpoint above is only harmless while a restart can finish. Once a full# budget has been spent covering fewer rows than live holds, re-streaming from row 0 runs out@@ -2151,6 +2737,8 @@ 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_copied(),+ _patch_blocker("copied_file_no_longer_live"),_patch_finalize(),patch.object(repartition_module, "_valid_delta_row_count", new=AsyncMock(return_value=1)),patch.object(repartition_module, "_rewrite_into_temp", new=AsyncMock()) as rewrite,@@ -2223,7 +2811,7 @@ class TestClaimFencing:temp_uri=str(tmp_path / "temp"),storage_options={},target=target,- batch_size=1,+ budget=_budget(),logger=logger,ensure_claim=ensure,claim_recheck_interval_seconds=0,@@ -2247,7 +2835,7 @@ class TestClaimFencing:temp_uri=str(tmp_path / "temp"),storage_options={},target=target,- batch_size=1,+ budget=_budget(),logger=logger,ensure_claim=ensure,claim_recheck_interval_seconds=3600,@@ -2256,12 +2844,20 @@ class TestClaimFencing:assert rows_written == 24assert ensure.await_count == 1- @pytest.mark.parametrize("batch_size", [50_000, 2])- def test_rewrite_coalesces_batches_into_one_commit(self, batch_size, tmp_path):- # Commits must scale with data size, not source file count or scan batch count: under one- # buffer's worth of rows the whole rewrite lands as a single commit, losing no rows. A scan- # batch size the buffer bound is derived from would cap the buffer at one batch and commit- # per batch instead, which is a throughput floor, not just extra versions.+ @pytest.mark.parametrize(+ "batch_bytes,files_per_commit,expected_commits",+ [+ pytest.param(64 * 1024 * 1024, 10_000, 1, id="whole_files_per_batch"),+ pytest.param(1, 10_000, 1, id="one_row_per_batch"),+ pytest.param(1, 4, 3, id="four_source_files_per_commit"),+ pytest.param(1, 1, 12, id="one_source_file_per_commit"),+ ],+ )+ def test_commits_follow_the_commit_budget_not_the_batch_count(+ self, batch_bytes, files_per_commit, expected_commits, tmp_path+ ):+ # Each commit is a transaction-log write, so one per scan batch or per source file puts a+ # floor under throughput that no table large enough to need repartitioning finishes above.rows = [(i, datetime.datetime(2024, 1 + (i % 12), 5)) for i in range(1, 37)]live = _write_month_partitioned(str(tmp_path / "live"), rows)assert len(measure_partition_bytes(live)) == 12@@ -2276,22 +2872,19 @@ class TestClaimFencing:temp_uri=temp_uri,storage_options={},target=target,- batch_size=batch_size,+ budget=_budget(batch_bytes=batch_bytes, max_source_files_per_commit=files_per_commit),logger=logger,))temp = deltalake.DeltaTable(temp_uri)assert rows_written == 36- assert temp.to_pyarrow_dataset().count_rows() == 36- # Version 0 is the sole commit; one-per-source-file would leave version 11, and- # one-per-scan-batch would leave version 17 at batch_size=2.- assert temp.version() == 0+ assert temp.to_pyarrow_table().num_rows == 36+ # Version 0 creates the table; every later version is one data commit.+ assert temp.version() == expected_commits+ assert all(SOURCE_FILES_METADATA_KEY in entry for entry in temp.history() if entry["version"] > 0)def test_rewrite_of_empty_source_writes_nothing(self, tmp_path):- # The post-loop drain always runs, so flush() has to tolerate an empty buffer — an empty- # source, or a loop that flushed exactly on the bound. Without the guard it indexes an empty- # list and raises instead of completing with nothing written.live_uri = str(tmp_path / "live")empty = pa.table({@@ -2311,74 +2904,13 @@ class TestClaimFencing:temp_uri=str(tmp_path / "temp"),storage_options={},target=target,- batch_size=50_000,+ budget=_budget(),logger=logger,))assert rows_written == 0assert resolved == target- def test_rewrite_flushes_on_byte_bound_before_row_bound(self, tmp_path):- # A row count says nothing about width once struct/list columns are flattened into JSON- # strings, so a row-only bound lets wide rows buffer arbitrarily many bytes and OOM the- # worker — the failure this module exists to prevent. Rows stay far under batch_size here,- # so only the byte bound can force the extra commits.- rows = [(i, datetime.datetime(2024, 1 + (i % 4), 5)) for i in range(1, 25)]- live = _write_month_partitioned(str(tmp_path / "live"), rows)-- target = RepartitionTarget(- partition_keys=["created_at"], trigger_reason="t", partition_mode="datetime", partition_format="day"- )- temp_uri = str(tmp_path / "temp")- with patch.object(repartition_module, "REWRITE_BUFFER_MAX_BYTES", 100):- rows_written, _ = asyncio.run(- _rewrite_into_temp(- old_delta=live,- temp_uri=temp_uri,- storage_options={},- target=target,- batch_size=50_000,- logger=logger,- )- )-- temp = deltalake.DeltaTable(temp_uri)- assert rows_written == 24- assert temp.to_pyarrow_dataset().count_rows() == 24- assert temp.version() > 0-- def test_rewrite_never_buffers_beyond_its_row_bound(self, tmp_path):- # Appending before the size check lets a nearly-full buffer take another full-sized batch, so- # peak memory reaches ~2x the bound, in the module that exists because oversized in-memory- # data OOMs the worker. Four 6-row source files against a 10-row bound catch it: flushing- # after the append writes commits of 12 rows, flushing before it keeps every commit within- # the bound.- rows = [(i, datetime.datetime(2024, 1 + (i % 4), 5)) for i in range(1, 25)]- live = _write_month_partitioned(str(tmp_path / "live"), rows)- assert len(measure_partition_bytes(live)) == 4-- target = RepartitionTarget(- partition_keys=["created_at"], trigger_reason="t", partition_mode="datetime", partition_format="day"- )- temp_uri = str(tmp_path / "temp")- with patch.object(repartition_module, "REWRITE_BUFFER_MAX_ROWS", 10):- rows_written, _ = asyncio.run(- _rewrite_into_temp(- old_delta=live,- temp_uri=temp_uri,- storage_options={},- target=target,- batch_size=2,- logger=logger,- )- )-- temp = deltalake.DeltaTable(temp_uri)- assert rows_written == 24- assert temp.to_pyarrow_dataset().count_rows() == 24- per_commit = [e["operationMetrics"]["num_added_rows"] for e in temp.history()]- assert max(per_commit) <= 10-def test_claim_token_read_retries_dropped_connection(self):# pgbouncer recycling a pooled connection surfaces as OperationalError on first use. Treating# that as a lost claim discarded rewrites that were tens of minutes in, so the read retries.@@ -2430,6 +2962,37 @@ class TestClaimFencing:assert swap.await_args.kwargs["temp_uri"] == "s3://bucket/live__repartitioned"+class TestDeferToFullRefresh:+ def test_stages_the_target_without_sweeping_claim_scoped_temps(self):+ # A wildcard S3 sweep cannot remain claim-fenced while it awaits storage, so a stale deferral+ # must leave claim-scoped recovery tables alone rather than race a newer attempt.+ target = RepartitionTarget(+ partition_keys=["created_at"], trigger_reason="t", partition_mode="datetime", partition_format="month"+ )+ schema = _schema(id="s1")+ with (+ patch.object(repartition_module, "_purge_stale_temp_tables", new=AsyncMock()) as purge,+ patch.object(repartition_module, "stage_partition_scheme_for_full_refresh") as stage,+ ):+ result = asyncio.run(+ repartition_module.defer_repartition_to_full_refresh(+ table_ref=_make_table_ref(), schema=schema, target=target, logger=logger+ )+ )++ purge.assert_not_awaited()+ stage.assert_called_once()+ assert stage.call_args.kwargs == {+ "partitioning_keys": ["created_at"],+ "partition_count": None,+ "partition_size": None,+ "partition_mode": "datetime",+ "partition_format": "month",+ "claim_token": None,+ }+ assert result["outcome"] == "deferred"++@pytest.mark.parametrize("data",[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.pyindex a95d642974d3..a3b85cfb1bf1 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@@ -949,6 +949,109 @@ class TestRepartitionActivity:assert schema.repartition_rewrite is Noneassert schema.last_repartition_at is not None+ @pytest.mark.parametrize(+ "target,expected",+ [+ pytest.param(+ {"partitioning_keys": ["id"], "partition_count": 8, "partition_size": None, "partition_mode": "md5"},+ {"partition_count": 8, "partition_size": None, "partition_mode": "md5", "partitioning_keys": ["id"]},+ id="fewer_hash_buckets",+ ),+ pytest.param(+ {+ "partitioning_keys": ["created_at"],+ "partition_count": None,+ "partition_size": None,+ "partition_mode": "datetime",+ "partition_format": "month",+ },+ {"partition_mode": "datetime", "partitioning_keys": ["created_at"], "partition_format": "month"},+ id="coarser_datetime_format",+ ),+ pytest.param(+ {+ "partitioning_keys": ["id"],+ "partition_count": None,+ "partition_size": 4096,+ "partition_mode": "numerical",+ },+ {"partition_size": 4096, "partition_mode": "numerical", "partitioning_keys": ["id"]},+ id="wider_numerical_ranges",+ ),+ ],+ )+ def test_a_scheme_staged_for_a_full_refresh_survives_that_syncs_reset(self, team, target, expected):+ # A full-refresh sync starts by wiping the plain partition settings, so a scheme saved as+ # plain settings would be discarded and the sync would write the old layout again.+ schema = _make_schema(+ team,+ {"partition_mode": "md5", "partition_count": 64, "partitioning_keys": ["id"], "partition_format": "hour"},+ )+ schema.set_repartition_pending({"partition_mode": "md5", "partition_keys": ["id"], "trigger_reason": "t"})+ schema.set_repartition_rewrite({"temp_uri": "s3://t", "rows_written": 5})++ external_data_schema.stage_partition_scheme_for_full_refresh(schema, **{"partition_format": None, **target})+ schema.refresh_from_db()+ schema.update_sync_type_config_for_reset_pipeline(clear_initial_sync_complete=False)+ schema.refresh_from_db()++ resolved = {+ "partition_count": schema.partition_count_override,+ "partition_size": schema.partition_size_override,+ "partition_mode": schema.partition_mode_override,+ "partitioning_keys": schema.partitioning_keys_override,+ "partition_format": schema.partition_format,+ }+ for key, value in expected.items():+ assert resolved[key] == value+ assert schema.repartition_pending is None+ assert schema.repartition_rewrite is None+ assert schema.last_repartition_at is not None++ def test_full_refresh_staging_stands_down_when_a_newer_attempt_owns_the_claim(self, team):+ 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_pending(+ {"partition_mode": "md5", "partition_count": 8, "partition_keys": ["id"], "trigger_reason": "t"}+ )++ wrote = external_data_schema.stage_partition_scheme_for_full_refresh(+ schema,+ partitioning_keys=["id"],+ partition_count=8,+ partition_size=None,+ partition_mode="md5",+ partition_format=None,+ claim_token="superseded-claim",+ )++ schema.refresh_from_db()+ assert wrote is False+ assert schema.partition_count_override is None+ assert schema.repartition_pending is not None+ assert schema.repartition_claim is not None+ assert schema.repartition_claim["token"] == "newer-claim"++ def test_full_refresh_staging_preserves_a_swap_that_appeared_after_claiming(self, team):+ schema = _make_schema(team, {"partition_mode": "md5", "partition_count": 4})+ schema.set_repartition_claim({"token": "ours", "job_id": "j1", "claimed_at": _days_ago_iso(0)})+ schema.set_repartition_swap({"state": "ready", "temp_uri": "s3://t", "live_uri": "s3://l"})++ wrote = external_data_schema.stage_partition_scheme_for_full_refresh(+ schema,+ partitioning_keys=["id"],+ partition_count=8,+ partition_size=None,+ partition_mode="md5",+ partition_format=None,+ claim_token="ours",+ )++ schema.refresh_from_db()+ assert wrote is False+ assert schema.partition_count_override is None+ assert schema.repartition_swap 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})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.pyindex ab4b07e3e806..3171349a86c6 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@@ -16,7 +16,6 @@ import uuidimport socketimport asyncioimport datetime as dt-import dataclassesfrom typing import Anyfrom django.db import InterfaceError, InternalError, OperationalError, close_old_connections@@ -29,6 +28,7 @@ from structlog.types import FilteringBoundLoggerfrom temporalio import activityfrom temporalio.exceptions import ApplicationError+from posthog.dataclasses import frozenfrom posthog.exceptions_capture import capture_exceptionfrom posthog.temporal.common.activity_context import current_activity_attemptfrom posthog.temporal.common.heartbeat_sync import HeartbeaterSync@@ -50,6 +50,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.repRepartitionTarget,RepartitionTooLargeForBudgetError,RepartitionUnpartitionableError,+ defer_repartition_to_full_refresh,repartition_table_in_place,)from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.repartition_controller import (@@ -70,7 +71,7 @@ from products.warehouse_sources.backend.temporal.data_imports.workload_report imLOGGER = get_logger(__name__)+@frozenclass RepartitionActivityInputs:team_id: intschema_id: str@@ -365,6 +366,14 @@ def _maybe_repartition_table(inputs: RepartitionActivityInputs, logger: Filterinlogger.debug("repartition: pre-extraction measurement found no repartition needed")return+ if swap is None and schema.sync_type == ExternalDataSchema.SyncType.FULL_REFRESH:+ # The marker snapshot predates the job fetch and Delta-log work above. A heartbeat-timed-out+ # predecessor can stage a swap in that window, making temp the only intact copy; deferring+ # from the stale snapshot would purge that temp and erase its recovery marker.+ schema.refresh_from_db(fields=["sync_type_config"])+ swap = schema.repartition_swap+ pending = schema.repartition_pending or pending+# 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@@ -376,6 +385,11 @@ def _maybe_repartition_table(inputs: RepartitionActivityInputs, logger: Filterin)trigger_reason = (pending or {}).get("trigger_reason", "resume")+ # Never while a swap is staged: live may already be deleted, and temp is then the only intact copy.+ if swap is None and schema.sync_type == ExternalDataSchema.SyncType.FULL_REFRESH:+ _defer_to_full_refresh(inputs, schema, table_ref, target, trigger_reason, logger)+ return+# `_handle_failure` also gives up at the cap, but only for an attempt that survives to run it.# A rewrite whose worker is OOM-killed never reaches it, so the count has to be read here too.# Never while a swap is staged: an interrupted swap may already have deleted live, leaving temp@@ -419,9 +433,11 @@ def _maybe_repartition_table(inputs: RepartitionActivityInputs, logger: Filterin# the predecessor is only heartbeat-timed-out, and that one keeps running as a zombie holding# the claim it minted; standing down without rotating it would leave the zombie free to swap# the live table while the sync this run releases merges into it.- schema.set_repartition_claim(+ if not schema.set_repartition_claim({"token": str(uuid.uuid4()), "job_id": inputs.job_id, "claimed_at": timezone.now().isoformat()}- )+ ):+ logger.info("repartition: killed-attempt stand-down superseded by a newer claim")+ returnlogger.warning(f"repartition: the attempt this run retries wrote nothing before it stopped, standing "f"down until the next sync schema_id={schema.id}",@@ -441,9 +457,12 @@ def _maybe_repartition_table(inputs: RepartitionActivityInputs, logger: Filterin# makes every claim re-check inside the rewrite/swap raise RepartitionSupersededError in the# zombie, so exactly one writer ever touches the table's S3 state.claim_token = str(uuid.uuid4())- schema.set_repartition_claim(+ if not schema.set_repartition_claim({"token": claim_token, "job_id": inputs.job_id, "claimed_at": timezone.now().isoformat()}- )+ ):+ logger.info("repartition: rewrite superseded before it claimed the schema")+ _capture_stood_down(schema, inputs, trigger_reason, "claim_superseded", logger)+ return# Charged before the rewrite and refunded on the stand-down paths below. Charging on failure# instead bounds nothing: a worker killed mid-rewrite records no outcome, so the cap never moves.@@ -635,6 +654,53 @@ def _maybe_repartition_table(inputs: RepartitionActivityInputs, logger: Filterin)+def _defer_to_full_refresh(+ inputs: RepartitionActivityInputs,+ schema: ExternalDataSchema,+ table_ref: DeltaTableRef,+ target: RepartitionTarget,+ trigger_reason: str,+ logger: FilteringBoundLogger,+) -> None:+ """Hand the new scheme to the full refresh that runs next, instead of rewriting the table.++ The fresh claim fences out a rewrite attempt that may still run as a zombie. Without it, that+ attempt could finish its swap after the full refresh and put its stale copy back over live.+ """+ try:+ 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: full-refresh deferral superseded before it claimed the schema")+ return+ result = async_to_sync(defer_repartition_to_full_refresh)(+ table_ref=table_ref, schema=schema, target=target, logger=logger, claim_token=claim_token+ )+ except RepartitionSupersededError:+ logger.info("repartition: full-refresh deferral superseded by a newer claim")+ return+ except Exception as e:+ # `async_to_sync` can surface cancellation as an Exception-derived wrapper. It must retain+ # Temporal's cancellation semantics rather than being swallowed as a failed deferral.+ if _is_cancellation(e):+ raise+ # Like a failed rewrite, this must not block the sync: the table keeps its layout and the+ # next run tries again.+ transient = _is_transient_infra_error(e)+ if not transient:+ capture_exception(e)+ logger.warning("repartition: could not stage the scheme for the next full refresh", exc_info=True)+ DELTA_REPARTITION_TOTAL.labels(+ team_id=str(inputs.team_id), outcome="transient" if transient else "failed"+ ).inc()+ return+ DELTA_REPARTITION_TOTAL.labels(team_id=str(inputs.team_id), outcome="deferred").inc()+ props = base_event_props(schema, schema.source, inputs.job_id)+ props.update({"trigger_reason": trigger_reason, **result})+ capture_repartition_event("warehouse_repartition_skipped", props)++def _capture_stood_down(schema: ExternalDataSchema,inputs: RepartitionActivityInputs,@@ -887,13 +953,12 @@ def _give_up(# Stake a fresh claim before clearing anything. This runs before the activity mints its own, so a# timed-out predecessor may still be running and still hold the old token; leaving it valid would# let it pass `ensure_claim` and go on mutating live after we declared the rewrite abandoned.- schema.set_repartition_claim(- {"token": str(uuid.uuid4()), "job_id": inputs.job_id, "claimed_at": timezone.now().isoformat()}- )- schema.clear_repartition_pending()- schema.clear_repartition_swap()- schema.clear_repartition_rewrite()- schema.stamp_last_repartition_at()+ claim_token = str(uuid.uuid4())+ if not schema.set_repartition_claim(+ {"token": claim_token, "job_id": inputs.job_id, "claimed_at": timezone.now().isoformat()}+ ) or not schema.abandon_repartition_if_claimed(claim_token):+ logger.info("repartition: give-up superseded by a newer claim")+ returnerror = RepartitionAttemptsExhausted(f"repartition gave up after {MAX_REPARTITION_ATTEMPTS} attempts that did not survive to record "f"an outcome, with the rewrite stuck at {rewrite_rows} rows (trigger_reason={trigger_reason})"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.pyindex 1a487e141852..04c4a767e91c 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@@ -28,6 +28,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.rep)from products.warehouse_sources.backend.temporal.data_imports.workflow_activities.repartition_table import (RepartitionActivityInputs,+ _defer_to_full_refresh,_maybe_flag_pre_extraction,_maybe_repartition_table,_rewrite_deadline,@@ -85,9 +86,14 @@ def _schema(schema.repartition_swap = swapschema.repartition_pending = pendingschema.repartition_rewrite = rewrite+# The failure bookkeeping re-reads the claim to check it still owns the schema, so the mock has# to actually remember the token the activity just staked.- schema.set_repartition_claim.side_effect = lambda claim: setattr(schema, "repartition_claim", claim)+ def set_repartition_claim(claim: dict) -> bool:+ schema.repartition_claim = claim+ return True++ schema.set_repartition_claim.side_effect = set_repartition_claim# Same for the pending marker: the attempt is charged before the rewrite and refunded after, and# the refund only fires when it reads back the count it wrote.schema.set_repartition_pending.side_effect = lambda p: setattr(schema, "repartition_pending", p)@@ -660,8 +666,7 @@ class TestKilledAttemptRetry:assert len(failed) == 1assert failed[0]["final"] is Trueassert failed[0]["error_type"] == "RepartitionAttemptsExhausted"- schema.clear_repartition_pending.assert_called_once()- schema.stamp_last_repartition_at.assert_called_once()+ schema.abandon_repartition_if_claimed.assert_called_once()@patch(f"{MODULE}.capture_exception")@patch(f"{MODULE}.capture_repartition_event")@@ -1150,3 +1155,103 @@ class TestMaybeFlagPreExtraction:assert result is Nonemock_capture.assert_called_once_with(error)+++class TestFullRefreshDeferral:+ @patch(f"{MODULE}.defer_repartition_to_full_refresh", new_callable=AsyncMock)+ def test_rejected_claim_stops_before_storage_work(self, mock_defer: AsyncMock) -> None:+ schema = _schema(name="contacts", s3_folder_name="contacts")+ schema.set_repartition_claim.side_effect = None+ schema.set_repartition_claim.return_value = False++ _defer_to_full_refresh(+ RepartitionActivityInputs(team_id=TEAM_ID, schema_id=SCHEMA_ID, job_id=JOB_ID, source_id=SOURCE_ID),+ schema,+ MagicMock(),+ MagicMock(),+ "proactive_threshold",+ MagicMock(),+ )++ mock_defer.assert_not_awaited()++ @patch(f"{MODULE}.defer_repartition_to_full_refresh", new_callable=AsyncMock)+ def test_wrapped_cancellation_is_propagated(self, mock_defer: AsyncMock) -> None:+ wrapped_cancelled_error = type("CancelledError", (Exception,), {})+ mock_defer.side_effect = wrapped_cancelled_error()++ with pytest.raises(wrapped_cancelled_error):+ _defer_to_full_refresh(+ RepartitionActivityInputs(team_id=TEAM_ID, schema_id=SCHEMA_ID, job_id=JOB_ID, source_id=SOURCE_ID),+ _schema(name="contacts", s3_folder_name="contacts"),+ MagicMock(),+ MagicMock(),+ "proactive_threshold",+ MagicMock(),+ )++ @pytest.mark.parametrize(+ "sync_type, swap, swap_after_refresh, expect_deferred",+ [+ ("full_refresh", None, None, True),+ ("incremental", None, None, False),+ ("append", None, None, False),+ ("full_refresh", {"state": "ready", "temp_uri": TEMP_URI}, None, False),+ ("full_refresh", None, {"state": "ready", "temp_uri": TEMP_URI}, False),+ ],+ ids=[+ "full_refresh_defers",+ "incremental_rewrites",+ "append_rewrites",+ "staged_swap_still_completes",+ "swap_staged_during_evaluation_still_completes",+ ],+ )+ @patch(f"{MODULE}.capture_repartition_event")+ @patch(f"{MODULE}.HeartbeaterSync")+ @patch(f"{MODULE}.defer_repartition_to_full_refresh", new_callable=AsyncMock)+ @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_full_refresh_table_takes_its_new_scheme_from_the_next_sync(+ self,+ mock_schema_model: MagicMock,+ _mock_job_model: MagicMock,+ _mock_helper_cls: MagicMock,+ mock_repartition: AsyncMock,+ mock_defer: AsyncMock,+ _mock_heartbeater: MagicMock,+ mock_capture: MagicMock,+ sync_type: str,+ swap: dict | None,+ swap_after_refresh: dict | None,+ expect_deferred: bool,+ ) -> None:+ # 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)+ schema.sync_type = sync_type+ if swap_after_refresh is not None:+ schema.refresh_from_db.side_effect = lambda **_kwargs: setattr(+ schema, "repartition_swap", swap_after_refresh+ )+ mock_schema_model.objects.select_related.return_value.get.return_value = schema+ mock_repartition.return_value = {"outcome": "completed"}+ mock_defer.return_value = {"outcome": "deferred", "reason": "full_refresh_rewrites_the_table"}++ _maybe_repartition_table(+ RepartitionActivityInputs(team_id=TEAM_ID, schema_id=SCHEMA_ID, job_id=JOB_ID, source_id=SOURCE_ID),+ MagicMock(),+ )++ assert mock_defer.await_count == (1 if expect_deferred else 0)+ assert mock_repartition.await_count == (0 if expect_deferred else 1)+ if expect_deferred:+ await_args = mock_defer.await_args+ assert await_args is not None+ assert await_args.kwargs["target"].partition_format == PENDING_TARGET["partition_format"]+ # A fresh claim fences out a rewrite attempt that may still be running as a zombie.+ schema.set_repartition_claim.assert_called_once()+ assert mock_capture.call_args.args[0] == "warehouse_repartition_skipped"diff --git a/products/warehouse_sources/backend/tests/test_models.py b/products/warehouse_sources/backend/tests/test_models.pyindex c254f710eb15..56a906305c8a 100644--- a/products/warehouse_sources/backend/tests/test_models.py+++ b/products/warehouse_sources/backend/tests/test_models.py@@ -356,6 +356,51 @@ class TestPartitionMeasurementPreservesConcurrentKeys(BaseTest):assert schema.sync_type_config["max_partition_bytes"] == 4096assert schema.sync_type_config["incremental_field"] == "updated_at"+ def test_repartition_claims_are_ordered_and_preserve_concurrent_keys(self) -> None:+ schema = ExternalDataSchema.objects.create(+ team_id=self.team.pk, source=self.source, name="orders", sync_type_config={"repartition_pending": {}}+ )+ stale = ExternalDataSchema.objects.get(id=schema.id)++ update_sync_type_config_keys(+ schema.id,+ self.team.pk,+ updates={+ "repartition_claim": {"token": "newer", "claimed_at": "2026-10-05T12:01:00+00:00"},+ "last_full_run_at": "2026-10-05T12:00:00+00:00",+ },+ )+ assert not stale.set_repartition_claim({"token": "zombie", "claimed_at": "2026-10-05T11:59:00+00:00"})++ schema.refresh_from_db()+ assert schema.sync_type_config["repartition_claim"] == {+ "token": "newer",+ "claimed_at": "2026-10-05T12:01:00+00:00",+ }+ assert schema.sync_type_config["repartition_pending"] == {}+ assert schema.sync_type_config["last_full_run_at"] == "2026-10-05T12:00:00+00:00"++ assert stale.set_repartition_claim({"token": "latest", "claimed_at": "2026-10-05T12:02:00+00:00"})+ schema.refresh_from_db()+ assert schema.sync_type_config["repartition_claim"]["token"] == "latest"++ update_sync_type_config_keys(+ schema.id,+ self.team.pk,+ updates={"repartition_swap": {"state": "ready"}, "repartition_rewrite": {"rows_written": 1}},+ )+ assert not stale.abandon_repartition_if_claimed("newer")+ assert not stale.abandon_repartition_if_claimed("latest")+ schema.refresh_from_db()+ assert schema.repartition_swap == {"state": "ready"}+ assert schema.repartition_rewrite == {"rows_written": 1}++ update_sync_type_config_keys(schema.id, self.team.pk, removes=["repartition_swap"])+ assert stale.abandon_repartition_if_claimed("latest")+ schema = ExternalDataSchema.objects.get(id=schema.id)+ assert schema.repartition_rewrite is None+ assert schema.last_repartition_at is not None+@parameterized.expand([("reset", lambda schema: schema.update_sync_type_config_for_reset_pipeline()),