Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(data-warehouse): self-heal delta tables whose log references missing data files (#70237)

Tom Owers35db901e85bd
diff --git a/products/warehouse_sources/backend/models/external_data_schema.py b/products/warehouse_sources/backend/models/external_data_schema.py
index 182dec1be0d7..bddb314823e9 100644
--- a/products/warehouse_sources/backend/models/external_data_schema.py
+++ b/products/warehouse_sources/backend/models/external_data_schema.py
@@ -467,6 +467,23 @@ class ExternalDataSchema(ModelActivityMixin, CreatedMetaFields, UpdatedMetaField
self.sync_type_config.pop("repartition_swap", None)
self._save_sync_type_config()
+ @property
+ def delta_revive_required(self) -> dict[str, Any] | None:
+ """Set when the live Delta table is readable but hollow — its log references data files that
+ are gone from S3 (the terminal state an interrupted or interleaved repartition swap leaves).
+ `handle_corrupted_delta_log` honors this to reset + rebuild the table even though the log
+ itself opens fine. Shape: {"reason": str, "missing_path": str, "detected_at": iso8601 str}.
+ """
+ if self.sync_type_config:
+ marker = self.sync_type_config.get("delta_revive_required", None)
+ if isinstance(marker, dict):
+ return marker
+ return None
+
+ def set_delta_revive_required(self, info: dict[str, Any]) -> None:
+ self.sync_type_config["delta_revive_required"] = info
+ self._save_sync_type_config()
+
def stamp_last_repartition_at(self) -> None:
self.sync_type_config["last_repartition_at"] = timezone.now().isoformat()
self._save_sync_type_config()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/extract.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/extract.py
index a9abb96043d6..7846092714f4 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/extract.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/extract.py
@@ -306,10 +306,18 @@ async def handle_corrupted_delta_log(
delta_table_helper: DeltaTableHelper,
logger: FilteringBoundLogger,
) -> bool:
- """Detect and revive a Delta table whose `_delta_log` is unreadable, before extraction.
+ """Detect and revive a corrupt Delta table before extraction.
+
+ Two corruption signatures trigger it:
+
+ - `_delta_log` unreadable (open raises DeltaError / FileNotFoundError) — interrupted repartition
+ swaps and OOM-crashed merges leave this, after which every sync fails to open the table and
+ loops forever.
+ - The schema's `delta_revive_required` marker — set by the repartition activity when the log
+ opens fine but references data files that are gone from S3 (a hollow table an interleaved swap
+ left behind). Only a full scan discovers that state, so it arrives as a marker rather than a
+ check here.
- Interrupted repartition swaps and OOM-crashed merges can leave `_delta_log` inconsistent (open raises
- DeltaError / FileNotFoundError), after which every sync fails to open the table and loops forever.
Runs before extraction so the table self-heals in the same run:
- Salvage: an interrupted repartition swap that left a `ready` temp table is finished from temp (no
@@ -319,15 +327,18 @@ async def handle_corrupted_delta_log(
Returns True if a revive happened. Best-effort: any failure here must not block the sync.
"""
- try:
- if not await delta_table_helper.is_table_corrupted():
+ revive_marker = schema.delta_revive_required
+ if revive_marker is None:
+ try:
+ if not await delta_table_helper.is_table_corrupted():
+ return False
+ except Exception as e:
+ capture_exception(e)
return False
- except Exception as e:
- capture_exception(e)
- return False
await logger.awarning(
- f"handle_corrupted_delta_log: unreadable delta log detected, reviving schema_id={schema.id}",
+ f"handle_corrupted_delta_log: {'revive marker set' if revive_marker else 'unreadable delta log detected'}, "
+ f"reviving schema_id={schema.id}",
schema_id=str(schema.id),
)
@@ -360,6 +371,15 @@ async def handle_corrupted_delta_log(
logger=logger,
)
if result.get("outcome") == "completed":
+ from products.warehouse_sources.backend.models.external_data_schema import ( # noqa: PLC0415 — Django model import kept off this activity module's load path
+ update_sync_type_config_keys,
+ )
+
+ # The completed swap copied the full temp table over live, so any hollow-table
+ # marker is stale now.
+ await database_sync_to_async_pool(update_sync_type_config_keys)(
+ schema.id, schema.team_id, removes=["delta_revive_required"]
+ )
await logger.ainfo(
f"handle_corrupted_delta_log: salvaged from interrupted swap schema_id={schema.id}",
schema_id=str(schema.id),
@@ -378,7 +398,7 @@ async def handle_corrupted_delta_log(
await delta_table_helper.reset_table()
await database_sync_to_async_pool(schema.update_sync_type_config_for_reset_pipeline)()
await database_sync_to_async_pool(update_sync_type_config_keys)(
- schema.id, schema.team_id, removes=["repartition_pending", "repartition_swap"]
+ schema.id, schema.team_id, removes=["repartition_pending", "repartition_swap", "delta_revive_required"]
)
was_billable = bool(job.billable)
if job.billable:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/test/test_extract.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/test/test_extract.py
index 506a7a36c491..f3a9d9300d11 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/test/test_extract.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/test/test_extract.py
@@ -164,6 +164,28 @@ class TestHandleCorruptedDeltaLog:
assert ph.capture.call_args.kwargs["properties"]["outcome"] == "reset_rebuild"
assert ph.capture.call_args.kwargs["properties"]["made_non_billable"] is True
+ def test_revive_marker_resets_readable_table(self, team):
+ # A hollow table — log opens fine but references data files gone from S3 — is invisible to
+ # is_table_corrupted; the repartition scan marks it instead. The marker alone must trigger the
+ # reset + non-billable rebuild and be cleared so the revive can't loop.
+ schema, job = self._schema_and_job(team)
+ schema.sync_type_config = {
+ "delta_revive_required": {"reason": "repartition_scan_missing_data_file", "missing_path": "x/p.parquet"}
+ }
+ schema.save(update_fields=["sync_type_config"])
+ helper = MagicMock(is_table_corrupted=AsyncMock(return_value=False), reset_table=AsyncMock())
+
+ with patch(f"{_EXTRACT_MODULE}.posthoganalytics") as ph:
+ result = async_to_sync(handle_corrupted_delta_log)(schema, job, helper, self._logger())
+
+ assert result is True
+ helper.reset_table.assert_awaited_once()
+ job.refresh_from_db()
+ assert job.billable is False
+ schema.refresh_from_db()
+ assert "delta_revive_required" not in schema.sync_type_config
+ assert ph.capture.call_args.kwargs["properties"]["outcome"] == "reset_rebuild"
+
def test_corrupt_table_with_ready_swap_is_salvaged(self, team):
# A corrupt table whose interrupted repartition swap left a `ready` temp table is finished from temp
# rather than reset — the customer's data is recovered without a rebuild, so reset_table never runs
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/delta_table_helper.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/delta_table_helper.py
index f6b058e09046..f9c21df0002d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/delta_table_helper.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/delta_table_helper.py
@@ -51,6 +51,29 @@ DEFAULT_COMPACT_FILES_PER_PARTITION_THRESHOLD = 200
DEFAULT_COMPACT_TOTAL_FILES_THRESHOLD = 5000
+async def _purge_s3_prefix(s3: Any, uri: str) -> None:
+ """Delete every object under `uri`, resilient to S3 recursive-delete gaps.
+
+ A lone `_rm(uri, recursive=True)` can leave objects behind on S3-compatible stores (directory
+ markers, and — mid-write — partial `_delta_log` files). Strays are corrupting: a later
+ `write_deltalake` append onto a half-cleared temp then sees a malformed table ("No table metadata
+ or protocol found in delta log"), and a swap copy that lands on top of undeleted live files leaves
+ a merged `_delta_log` whose row count is wrong ("swap verification failed: live > expected").
+ Enumerate and delete explicitly first, then a best-effort recursive sweep.
+
+ The dircache is dropped first: delta-rs writes through its own Rust object store, so s3fs's
+ listing cache never learns about those files — a cached listing would leave exactly them behind.
+ """
+ s3.invalidate_cache()
+ if not await s3._exists(uri):
+ return
+ files = await s3._find(uri)
+ if files:
+ await s3._rm([f"s3://{f.lstrip('/')}" for f in files])
+ if await s3._exists(uri):
+ await s3._rm(uri, recursive=True)
+
+
def _write_deltalake(
table_or_uri: str | deltalake.DeltaTable,
table_data: pa.Table,
@@ -286,9 +309,12 @@ class DeltaTableHelper:
async def reset_table(self):
delta_uri = await self._get_delta_table_uri()
- async with aget_s3_client() as s3:
+ # Explicit purge on a fresh client: a stale dircache or an incomplete recursive delete can
+ # leave `_delta_log` strays behind, and the rebuild then commits version 0 into a log that
+ # still holds old commits — recreating exactly the corruption a reset is meant to clear.
+ async with aget_s3_client(fresh_instance=True) as s3:
try:
- await s3._rm(delta_uri, recursive=True)
+ await _purge_s3_prefix(s3, delta_uri)
except FileNotFoundError:
pass
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/repartition.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/repartition.py
index bf38816f1eb0..06497a7c2ee1 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/repartition.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/repartition.py
@@ -15,11 +15,13 @@ point loses at most wasted compute, never data. See the "Repartitioning" section
from __future__ import annotations
+import re
import math
import asyncio
import dataclasses
from collections import defaultdict
from collections.abc import Awaitable, Callable
+from datetime import UTC, datetime
from typing import TYPE_CHECKING, Any
import pyarrow as pa
@@ -31,6 +33,7 @@ from products.data_warehouse.backend.facade.api import aget_s3_client
from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.consts import PARTITION_KEY
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.delta_table_helper import (
+ _purge_s3_prefix,
_realign_decimal_buffers,
)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (
@@ -141,29 +144,6 @@ async def _valid_delta_row_count(uri: str, storage_options: dict[str, str]) -> i
return None
-async def _purge_s3_prefix(s3: Any, uri: str) -> None:
- """Delete every object under `uri`, resilient to S3 recursive-delete gaps.
-
- A lone `_rm(uri, recursive=True)` can leave objects behind on S3-compatible stores (directory
- markers, and — mid-write — partial `_delta_log` files). Strays are corrupting: a later
- `write_deltalake` append onto a half-cleared temp then sees a malformed table ("No table metadata
- or protocol found in delta log"), and a swap copy that lands on top of undeleted live files leaves
- a merged `_delta_log` whose row count is wrong ("swap verification failed: live > expected").
- Enumerate and delete explicitly first, then a best-effort recursive sweep.
-
- The dircache is dropped first: delta-rs writes through its own Rust object store, so s3fs's
- listing cache never learns about those files — a cached listing would leave exactly them behind.
- """
- s3.invalidate_cache()
- if not await s3._exists(uri):
- return
- files = await s3._find(uri)
- if files:
- await s3._rm([f"s3://{f.lstrip('/')}" for f in files])
- if await s3._exists(uri):
- await s3._rm(uri, recursive=True)
-
-
async def _purge_stale_temp_tables(s3: Any, live_uri: str) -> None:
"""Delete every `{live_uri}__repartitioned*` temp variant before a fresh rebuild.
@@ -207,6 +187,71 @@ async def _ensure_claim(schema: ExternalDataSchema, claim_token: str | None) ->
)
+# Message shapes delta-rs / pyarrow raise when a table's log references an object gone from S3.
+# "Object at location <path> not found" is the Rust `object_store` crate's NotFound display
+# (github.com/apache/arrow-rs-object-store), surfaced through delta-rs; "File not found: <path>"
+# is the datafusion/kernel scan variant. These are matched by exact wording, so a library upgrade
+# that rewords them would silently stop recognizing the hole (fails safe to today's stuck loop, not
+# data loss). `TestMissingLiveObjectRealError` provokes a real error from the installed deltalake and
+# fails the moment the wording drifts past these patterns, so the drift can't rot unnoticed.
+_MISSING_OBJECT_PATTERNS = (
+ re.compile(r"Object at location (\S+)"),
+ re.compile(r"File not found: (\S+)"),
+)
+
+
+def _missing_live_object_path(error: BaseException, live_uri: str) -> str | None:
+ """Bucket-relative path of the missing S3 object `error` names, when it's a live-table data file.
+
+ None for errors that don't name a missing object, name one outside the live table, or name one
+ under a `__repartitioned` temp — only a hole in the live table itself warrants a revive.
+ """
+ message = str(error)
+ path: str | None = None
+ for pattern in _MISSING_OBJECT_PATTERNS:
+ if match := pattern.search(message):
+ path = match.group(1).rstrip(":,.")
+ break
+ if path is None:
+ return None
+
+ # The kernel reports bucket-relative paths; live_uri is s3://bucket/prefix. Normalize both.
+ bucket, _, live_path = live_uri.split("://", 1)[-1].partition("/")
+ live_path = live_path.rstrip("/")
+ path = path.split("://", 1)[-1].lstrip("/")
+ if path.startswith(f"{bucket}/"):
+ path = path[len(bucket) + 1 :]
+ # The trailing slash excludes `{live_path}__repartitioned*` temp siblings.
+ if not live_path or not path.startswith(f"{live_path}/"):
+ return None
+ return path
+
+
+async def _live_missing_data_file(live_uri: str, storage_options: dict[str, str], missing_path: str) -> str | None:
+ """Absolute URI of `missing_path` when live's *current* log references it and the object is gone.
+
+ Guards the revive against a stale-snapshot race: a reader whose table handle predates a
+ legitimate rewrite also sees missing-object errors, but the current log no longer references
+ those files — reviving then would needlessly reset a healthy table. Matches on basename (part
+ file names embed a UUID, so they're unique) to sidestep the log's URL-encoded relative paths.
+ """
+ try:
+ live_delta = await asyncio.to_thread(deltalake.DeltaTable, table_uri=live_uri, storage_options=storage_options)
+ file_uris = await asyncio.to_thread(live_delta.file_uris)
+ except (deltalake.exceptions.DeltaError, FileNotFoundError):
+ # Live unreadable — the corrupted-log revive already covers that state.
+ return None
+ basename = missing_path.rsplit("/", 1)[-1]
+ referenced = next((uri for uri in file_uris if uri.rsplit("/", 1)[-1] == basename), None)
+ if referenced is None:
+ return None
+ async with aget_s3_client(fresh_instance=True) as s3:
+ if await s3._exists(referenced):
+ # The object exists after all — a transient read error, not a hollow table.
+ return None
+ return referenced
+
+
def select_repartition_target(
schema: ExternalDataSchema,
partition_bytes: dict[str | None, int],
@@ -461,15 +506,45 @@ async def repartition_table_in_place(
async with aget_s3_client(fresh_instance=True) as s3:
await _purge_stale_temp_tables(s3, live_uri)
- rows_written, resolved = await _rewrite_into_temp(
- old_delta=old_delta,
- temp_uri=temp_uri,
- storage_options=storage_options,
- target=target,
- batch_size=batch_size,
- logger=logger,
- ensure_claim=ensure_claim,
- )
+ try:
+ rows_written, resolved = await _rewrite_into_temp(
+ old_delta=old_delta,
+ temp_uri=temp_uri,
+ storage_options=storage_options,
+ target=target,
+ batch_size=batch_size,
+ logger=logger,
+ ensure_claim=ensure_claim,
+ )
+ except (RepartitionSupersededError, RepartitionUnpartitionableError):
+ raise
+ except Exception as e:
+ missing_path = _missing_live_object_path(e, live_uri)
+ if missing_path is None or await _live_missing_data_file(live_uri, storage_options, missing_path) is None:
+ raise
+ # Live is hollow: its log references a data file that's gone from S3 (the terminal state
+ # an interleaved or interrupted swap leaves). No repartition attempt can succeed — every
+ # rewrite re-reads the same missing file — and the sync can't detect it either (its
+ # incremental merges never touch the dead partition, while queries over it fail). Schedule
+ # a revive: the marker makes this run's handle_corrupted_delta_log reset the table and
+ # rebuild it from source, non-billable.
+ await ensure_claim()
+ await asyncio.to_thread(
+ schema.set_delta_revive_required,
+ {
+ "reason": "repartition_scan_missing_data_file",
+ "missing_path": missing_path,
+ "detected_at": datetime.now(UTC).isoformat(),
+ },
+ )
+ await asyncio.to_thread(schema.clear_repartition_pending)
+ await asyncio.to_thread(schema.clear_repartition_swap)
+ await logger.awarning(
+ f"repartition: live table references a missing data file, scheduling revive "
+ f"schema_id={schema.id} missing={missing_path}",
+ schema_id=str(schema.id),
+ )
+ return {"outcome": "revive_scheduled", "reason": "live_missing_data_files", "missing_path": missing_path}
# Validate before any destructive action — temp must hold every row.
new_row_count = await _valid_delta_row_count(temp_uri, storage_options)
@@ -644,6 +719,10 @@ async def _swap_temp_into_live(
# tripping the verification below and looping the repartition forever.
await _purge_s3_prefix(s3, live_uri)
files = await s3._find(temp_uri)
+ # Data files first, `_delta_log` last: a death mid-copy then leaves live without a
+ # readable log — a state the corrupted-log revive detects and heals — instead of a
+ # valid log referencing data files that never arrived.
+ files = sorted(files, key=lambda f: "/_delta_log/" in f)
for f in files:
rel = f[len(temp_prefix) :]
await s3._copy(f"s3://{f.lstrip('/')}", f"{live_uri}{rel}")
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/test_repartition.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/test_repartition.py
index 4fd5cab71821..55e3f488038e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/test_repartition.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/test_repartition.py
@@ -1,3 +1,4 @@
+import os
import asyncio
import datetime
from types import SimpleNamespace
@@ -475,6 +476,209 @@ class TestSwapTempIntoLiveGuard:
s3._rm.assert_not_called()
+class TestMissingLiveObjectPath:
+ """Classifying missing-object scan errors decides whether a table gets a destructive revive.
+ Under-matching leaves hollow tables looping repartition failures forever; over-matching (temp
+ siblings, other tables) resets healthy tables."""
+
+ LIVE = "s3://bucket/dlt/team_2_stripe_x/charge"
+
+ @parameterized.expand(
+ [
+ (
+ "object_at_location_with_trailing_detail",
+ FileNotFoundError(
+ "Object at location dlt/team_2_stripe_x/charge/_ph_partition_key=2020-w51/"
+ "part-00000-abc.parquet: The specified key does not exist."
+ ),
+ "dlt/team_2_stripe_x/charge/_ph_partition_key=2020-w51/part-00000-abc.parquet",
+ ),
+ (
+ "kernel_file_not_found",
+ Exception("Kernel error: File not found: dlt/team_2_stripe_x/charge/part-00001-def.parquet"),
+ "dlt/team_2_stripe_x/charge/part-00001-def.parquet",
+ ),
+ (
+ "arrow_external_wrapped",
+ Exception(
+ "Kernel error: Arrow error: External: Object at location "
+ "dlt/team_2_stripe_x/charge/part-2.parquet not found"
+ ),
+ "dlt/team_2_stripe_x/charge/part-2.parquet",
+ ),
+ (
+ "bucket_qualified_path_normalized",
+ FileNotFoundError("Object at location bucket/dlt/team_2_stripe_x/charge/part-3.parquet: gone"),
+ "dlt/team_2_stripe_x/charge/part-3.parquet",
+ ),
+ (
+ "temp_sibling_excluded",
+ FileNotFoundError(
+ "Object at location dlt/team_2_stripe_x/charge__repartitioned_ab12cd34/part-4.parquet: gone"
+ ),
+ None,
+ ),
+ (
+ "other_table_excluded",
+ FileNotFoundError("Object at location dlt/team_9_stripe_y/invoice/part-5.parquet: gone"),
+ None,
+ ),
+ ("no_path_in_message", FileNotFoundError("The specified key does not exist."), None),
+ ]
+ )
+ def test_classification(self, _name, error, expected):
+ assert repartition_module._missing_live_object_path(error, self.LIVE) == expected
+
+
+class TestMissingLiveObjectRealError:
+ """Drift guard: the cases above fixture message strings we author, so they can't catch delta-rs /
+ pyarrow rewording a missing-file error on a library upgrade — which would silently stop the
+ self-heal from ever firing. This provokes a real error from the installed deltalake by reading a
+ table whose data file is gone, and fails if `_missing_live_object_path` can no longer extract it."""
+
+ def test_real_missing_file_error_is_classified(self, tmp_path):
+ live = str(tmp_path / "live")
+ delta = _write_month_partitioned(live, [(1, datetime.datetime(2024, 1, 15))])
+ data_file = delta.file_uris()[0]
+ os.remove(data_file)
+
+ with pytest.raises(Exception) as exc_info:
+ # Same read path the repartition scan takes; surfaces the missing-file error.
+ delta.to_pyarrow_dataset().scanner().to_reader().read_all()
+
+ matched = repartition_module._missing_live_object_path(exc_info.value, live)
+ assert matched is not None, f"error wording drifted past _MISSING_OBJECT_PATTERNS: {exc_info.value!r}"
+ assert matched.endswith(data_file.rsplit("/", 1)[-1])
+
+
+class TestLiveMissingDataFile:
+ """The verification step behind a revive: only a file the *current* log references and that is
+ truly absent counts. Without it, a stale-snapshot race (a reader whose handle predates a
+ legitimate rewrite) would reset a healthy table."""
+
+ def test_returns_uri_when_referenced_and_absent(self, tmp_path):
+ live = str(tmp_path / "live")
+ _write_month_partitioned(live, [(1, datetime.datetime(2024, 1, 15))])
+ referenced = deltalake.DeltaTable(live).file_uris()[0]
+ basename = referenced.rsplit("/", 1)[-1]
+
+ s3 = _fake_s3(_exists=AsyncMock(return_value=False))
+ with patch.object(repartition_module, "aget_s3_client", return_value=_FakeS3CM(s3)):
+ result = asyncio.run(repartition_module._live_missing_data_file(live, {}, f"dlt/x/live/{basename}"))
+ assert result is not None and result.endswith(basename)
+
+ def test_none_when_current_log_no_longer_references_it(self, tmp_path):
+ live = str(tmp_path / "live")
+ _write_month_partitioned(live, [(1, datetime.datetime(2024, 1, 15))])
+ result = asyncio.run(
+ repartition_module._live_missing_data_file(live, {}, "dlt/x/live/part-00000-not-referenced.parquet")
+ )
+ assert result is None
+
+ def test_none_when_object_actually_exists(self, tmp_path):
+ live = str(tmp_path / "live")
+ _write_month_partitioned(live, [(1, datetime.datetime(2024, 1, 15))])
+ basename = deltalake.DeltaTable(live).file_uris()[0].rsplit("/", 1)[-1]
+
+ s3 = _fake_s3(_exists=AsyncMock(return_value=True))
+ with patch.object(repartition_module, "aget_s3_client", return_value=_FakeS3CM(s3)):
+ result = asyncio.run(repartition_module._live_missing_data_file(live, {}, f"dlt/x/live/{basename}"))
+ assert result is None
+
+ def test_none_when_live_unreadable(self, tmp_path):
+ result = asyncio.run(
+ repartition_module._live_missing_data_file(str(tmp_path / "absent"), {}, "dlt/x/absent/part.parquet")
+ )
+ assert result is None
+
+
+class TestReviveScheduling:
+ """A live table whose log references data files gone from S3 can never repartition (every rewrite
+ re-reads the missing file) and the sync can't see it either. The repartition must convert that
+ error into a revive marker instead of burning attempts forever."""
+
+ def _run(self, tmp_path, verified_uri):
+ live = str(tmp_path / "live")
+ _write_month_partitioned(live, [(1, datetime.datetime(2024, 1, 15))])
+ helper = _delta_helper(
+ get_table_uri=AsyncMock(return_value="s3://bucket/dlt/x/live"),
+ get_delta_table=AsyncMock(return_value=deltalake.DeltaTable(live)),
+ )
+ schema = _schema(
+ id="s1",
+ repartition_swap=None,
+ set_delta_revive_required=Mock(),
+ clear_repartition_pending=Mock(),
+ clear_repartition_swap=Mock(),
+ )
+ target = RepartitionTarget(
+ partition_keys=["created_at"], trigger_reason="oom", partition_mode="datetime", partition_format="day"
+ )
+ scan_error = FileNotFoundError(
+ "Object at location dlt/x/live/_ph_partition_key=2024-01/part-00000-abc.parquet: "
+ "The specified key does not exist."
+ )
+ with (
+ patch.object(repartition_module, "_rewrite_into_temp", new=AsyncMock(side_effect=scan_error)),
+ patch.object(repartition_module, "_live_missing_data_file", new=AsyncMock(return_value=verified_uri)),
+ patch.object(repartition_module, "aget_s3_client", return_value=_FakeS3CM(_fake_s3())),
+ ):
+ return (
+ asyncio.run(repartition_table_in_place(helper=helper, schema=schema, target=target, logger=logger)),
+ schema,
+ )
+
+ def test_verified_missing_live_file_schedules_revive(self, tmp_path):
+ result, schema = self._run(tmp_path, verified_uri="s3://bucket/dlt/x/live/part-00000-abc.parquet")
+ assert result["outcome"] == "revive_scheduled"
+ marker = schema.set_delta_revive_required.call_args.args[0]
+ assert marker["reason"] == "repartition_scan_missing_data_file"
+ assert marker["missing_path"] == "dlt/x/live/_ph_partition_key=2024-01/part-00000-abc.parquet"
+ schema.clear_repartition_pending.assert_called_once()
+ schema.clear_repartition_swap.assert_called_once()
+
+ def test_unverified_missing_file_propagates_without_marking(self, tmp_path):
+ with pytest.raises(FileNotFoundError):
+ self._run(tmp_path, verified_uri=None)
+
+
+class TestSwapCopyOrder:
+ def test_delta_log_copied_after_every_data_file(self):
+ # Crash-safety ordering: a death mid-copy must leave live without a readable log (the
+ # corrupted-log revive heals that) — never a valid log referencing data files that never
+ # arrived, which is stable, undetectable corruption.
+ copied: list[str] = []
+ s3 = _fake_s3(
+ _find=AsyncMock(
+ return_value=[
+ "bucket/live__repartitioned/_delta_log/00000000000000000000.json",
+ "bucket/live__repartitioned/_ph_partition_key=a/part-1.parquet",
+ "bucket/live__repartitioned/_delta_log/00000000000000000001.json",
+ "bucket/live__repartitioned/_ph_partition_key=b/part-2.parquet",
+ ]
+ ),
+ _copy=AsyncMock(side_effect=lambda src, dst: copied.append(dst)),
+ )
+ with (
+ patch.object(repartition_module, "aget_s3_client", return_value=_FakeS3CM(s3)),
+ patch.object(repartition_module, "_valid_delta_row_count", new=AsyncMock(return_value=4)),
+ patch.object(repartition_module.deltalake, "DeltaTable", return_value=Mock()),
+ patch.object(repartition_module, "_table_row_count", return_value=4),
+ ):
+ asyncio.run(
+ repartition_module._swap_temp_into_live(
+ temp_uri="s3://bucket/live__repartitioned",
+ live_uri="s3://bucket/live",
+ storage_options={},
+ expected_rows=4,
+ )
+ )
+ log_positions = [i for i, dst in enumerate(copied) if "/_delta_log/" in dst]
+ data_positions = [i for i, dst in enumerate(copied) if "/_delta_log/" not in dst]
+ assert log_positions and data_positions
+ assert min(log_positions) > max(data_positions)
+
+
class TestResumeWithInvalidTemp:
def test_discards_invalid_temp_and_rebuilds_fresh(self, tmp_path):
# A "ready" swap marker pointing at an incomplete/corrupt temp must NOT be trusted — resuming