: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): recover from corrupt repartition temp tables (#69322)
Tom Owersa949532f1e08
diff --git a/products/warehouse_sources/backend/temporal/data_imports/README.md b/products/warehouse_sources/backend/temporal/data_imports/README.mdindex 4fc580505bc5..2901ba81bdce 100644--- a/products/warehouse_sources/backend/temporal/data_imports/README.md+++ b/products/warehouse_sources/backend/temporal/data_imports/README.md@@ -39,7 +39,7 @@ The manual flow above re-pulls every row from the source. We also have an automaHow it works:- **Detection.** After each sync, the controller measures per-partition bytes from the Delta log (`get_add_actions` — no S3 LIST, no scan) and always records `max_partition_bytes` on the schema for observability. It records a `repartition_pending` target (the next finer tier — md5 count grows, numerical size shrinks, datetime `month` → `week` → `day` → `hour`) when **either** the largest partition is over the budget (`trigger_reason=proactive_threshold`) **or** the schema has repeatedly OOM'd recently (`trigger_reason=oom_history`). The OOM path catches tables whose compressed at-rest size looks safe but whose real merge working set is much larger (e.g. wide nested-JSON columns) — see `ExternalDataSchemaOOMEvent`, recorded per OOM occurrence at the heartbeat-timeout detection point.-- **Rewrite.** On the next run, a pre-extraction activity streams the live Delta table one record-batch at a time, recomputes `_ph_partition_key` under the finer scheme, and writes a sibling temp table. It then does a crash-safe swap: delete live → server-side copy temp → verify row count → delete temp. Memory is bounded by batch size, independent of partition size. Temp stays the source of truth until the swap is verified, so a worker death at any point loses wasted compute, never data.+- **Rewrite.** On the next run, a pre-extraction activity streams the live Delta table one record-batch at a time, recomputes `_ph_partition_key` under the finer scheme, and writes a sibling temp table. It then does a crash-safe swap: delete live → server-side copy temp → verify row count → delete temp. Memory is bounded by batch size, independent of partition size. Temp stays the source of truth until the swap is verified, so a worker death at any point loses wasted compute, never data. An interruption (OOM, worker restart) can leave the `__repartitioned` temp partial, so every step that could destroy live re-validates temp first: the swap opens temp and checks it holds the full row count before deleting live, and a resume re-validates the temp the `ready` marker points at — discarding it and rebuilding fresh from the intact live rather than copying a broken temp over live. A live table whose own log is unreadable is skipped (the import activity's revival handles it), not counted as a repartition failure.- **Safety.** The repartition is the sole writer (the schedule's `OnlyOne` overlap policy plus the v3 pipeline lock), so it needs no new locking. 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.Tuning and gating: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.pyindex 57c854981636..057fcb57132a 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@@ -23,6 +23,7 @@ from typing import TYPE_CHECKING, Anyimport pyarrow as paimport deltalake as deltalake+import deltalake.exceptionsfrom structlog.types import FilteringBoundLoggerfrom products.data_warehouse.backend.facade.api import aget_s3_client@@ -108,6 +109,26 @@ def _table_row_count(delta_table: deltalake.DeltaTable) -> int:return sum(n or 0 for n in actions.column("num_records").to_pylist())+async def _valid_delta_row_count(uri: str, storage_options: dict[str, str]) -> int | None:+ """Open `uri` and return its row count, or None if it isn't a readable, complete Delta table.++ None means the folder is absent, not a Delta table, or its `_delta_log` is inconsistent (a+ DeltaError / FileNotFoundError from an interrupted write or swap). Used to gate destructive swap+ steps on the temp/live tables actually being intact, so a partial `__repartitioned` temp can never+ be copied over a good live table.+ """+ try:+ is_delta = await asyncio.to_thread(+ deltalake.DeltaTable.is_deltatable, table_uri=uri, storage_options=storage_options+ )+ if not is_delta:+ return None+ dt = await asyncio.to_thread(deltalake.DeltaTable, table_uri=uri, storage_options=storage_options)+ return await asyncio.to_thread(_table_row_count, dt)+ except (deltalake.exceptions.DeltaError, FileNotFoundError):+ return None++def select_repartition_target(schema: ExternalDataSchema,partition_bytes: dict[str | None, int],@@ -273,7 +294,20 @@ async def repartition_table_in_place(swap = schema.repartition_swapresuming = bool(swap and swap.get("state") == "ready")- old_delta = await helper.get_delta_table()+ try:+ old_delta = await helper.get_delta_table()+ except (deltalake.exceptions.DeltaError, FileNotFoundError) as e:+ # Live's `_delta_log` is unreadable (an OOM-crashed merge or interrupted swap). If a swap was+ # already staged we can still recover from temp below; otherwise skip and let the import+ # activity's handle_corrupted_delta_log revive it — don't count this as a repartition failure.+ if not resuming:+ await logger.awarning(+ f"repartition: live table unreadable, skipping (will be revived) schema_id={schema.id}: {e}",+ schema_id=str(schema.id),+ )+ return {"outcome": "skipped", "reason": "live_unreadable"}+ old_delta = None+if old_delta is None:# Live table missing. If a swap was already in progress (temp built + marker recorded), an# interrupted prior run may have deleted live *after* recording the marker but before copying@@ -306,10 +340,27 @@ async def repartition_table_in_place(}if resuming:- resolved = target- rows_written = old_row_count- await logger.ainfo(f"repartition: resuming from swap marker schema_id={schema.id}", schema_id=str(schema.id))- else:+ # Validate the temp the marker points at is actually complete. An interrupted swap or cleanup can+ # leave it partial or corrupt; resuming from it would copy a broken table over live and loop+ # forever. When it's bad, discard it and fall through to a fresh rebuild — live is intact here.+ temp_rows = await _valid_delta_row_count(temp_uri, storage_options)+ if temp_rows == old_row_count:+ resolved = target+ rows_written = old_row_count+ await logger.ainfo(f"repartition: resuming from valid temp schema_id={schema.id}", schema_id=str(schema.id))+ else:+ await logger.awarning(+ f"repartition: resume marker points at an invalid temp (rows={temp_rows} "+ f"expected={old_row_count}), discarding and rebuilding fresh schema_id={schema.id}",+ schema_id=str(schema.id),+ )+ async with aget_s3_client() as s3:+ if await s3._exists(temp_uri):+ await s3._rm(temp_uri, recursive=True)+ await asyncio.to_thread(schema.clear_repartition_swap)+ resuming = False++ if not resuming:# Fresh build: clear any stale temp folder, then stream the live table into it.async with aget_s3_client() as s3:if await s3._exists(temp_uri):@@ -325,8 +376,7 @@ async def repartition_table_in_place()# Validate before any destructive action — temp must hold every row.- new_delta = await asyncio.to_thread(deltalake.DeltaTable, table_uri=temp_uri, storage_options=storage_options)- new_row_count = await asyncio.to_thread(_table_row_count, new_delta)+ new_row_count = await _valid_delta_row_count(temp_uri, storage_options)if new_row_count != old_row_count:raise ValueError(f"repartition row-count mismatch: temp={new_row_count} live={old_row_count} "@@ -410,21 +460,21 @@ async def _resume_swap_with_missing_live(source of truth, so its own row count is the swap's expectation. If temp is *also* gone there isnothing left to recover (both folders lost): clear the markers and skip so the next sync rebuilds."""- async with aget_s3_client() as s3:- temp_present = await s3._exists(temp_uri)- if not temp_present:+ expected_rows = await _valid_delta_row_count(temp_uri, storage_options)+ if expected_rows is None:+ # Both live and a usable temp are gone (temp missing or its `_delta_log` is corrupt) — nothing+ # left to recover. Clear the markers and skip so the next sync rebuilds the table from source.await asyncio.to_thread(schema.clear_repartition_swap)await asyncio.to_thread(schema.clear_repartition_pending)await logger.ainfo(- f"repartition: live and temp both missing, skipping schema_id={schema.id}", schema_id=str(schema.id)+ f"repartition: live missing and temp unrecoverable, skipping schema_id={schema.id}",+ schema_id=str(schema.id),)return {"outcome": "skipped", "reason": "no_delta_table"}await logger.ainfo(f"repartition: live missing mid-swap, resuming from temp schema_id={schema.id}", schema_id=str(schema.id))- temp_delta = await asyncio.to_thread(deltalake.DeltaTable, table_uri=temp_uri, storage_options=storage_options)- expected_rows = await asyncio.to_thread(_table_row_count, temp_delta)await _swap_temp_into_live(temp_uri=temp_uri,@@ -470,6 +520,17 @@ async def _swap_temp_into_live(Files are copied one at a time preserving their path relative to temp — a single recursive`copy(prefix, prefix)` trips over directory-marker objects on S3-compatible stores."""+ # Never destroy live for an incomplete temp: confirm temp is a readable Delta table holding every+ # expected row before deleting live. A partial/corrupt temp (from an interrupted rewrite or swap)+ # would otherwise be copied over live and leave both broken. Raising is safe — the caller+ # re-validates temp on the next run and rebuilds fresh from the still-intact live.+ temp_rows = await _valid_delta_row_count(temp_uri, storage_options)+ if temp_rows != expected_rows:+ raise ValueError(+ f"repartition swap: refusing to swap, temp is incomplete "+ f"(rows={temp_rows} expected={expected_rows} temp_uri={temp_uri})"+ )+temp_prefix = temp_uri.replace("s3://", "").rstrip("/")async with aget_s3_client() as s3:if await s3._exists(temp_uri):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.pyindex 4b6ce2cd8f18..67846ffa6155 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@@ -41,6 +41,17 @@ def _schema(**kwargs):return SimpleNamespace(**defaults)+def _delta_helper(**kwargs):+ # Stand-in for DeltaTableHelper; untyped on purpose so callers can pass it to the real signature.+ defaults = {+ "get_table_uri": AsyncMock(return_value="s3://bucket/live"),+ "get_storage_options": Mock(return_value={}),+ "get_delta_table": AsyncMock(return_value=None),+ }+ defaults.update(kwargs)+ return SimpleNamespace(**defaults)++def _write_month_partitioned(path: str, rows: list[tuple[int, datetime.datetime]]) -> deltalake.DeltaTable:table = pa.table({@@ -257,15 +268,8 @@ class TestResumeSwapWithMissingLive:intact. The repartition must finish the swap from temp, not take the `no_delta_table` early return(which would strand the markers forever and let the next sync bootstrap an empty table)."""- def _helper(self):- return SimpleNamespace(- get_table_uri=AsyncMock(return_value="s3://bucket/live"),- get_storage_options=Mock(return_value={}),- get_delta_table=AsyncMock(return_value=None),- )-def test_routes_to_recovery_when_swap_marker_present(self):- helper = self._helper()+ helper = _delta_helper()schema = _schema(id="s1",repartition_swap={@@ -286,7 +290,7 @@ class TestResumeSwapWithMissingLive:assert result == recovereddef test_skips_when_no_swap_marker(self):- helper = self._helper()+ helper = _delta_helper()schema = _schema(id="s1", repartition_swap=None)target = RepartitionTarget(partition_keys=["created_at"], trigger_reason="resume")@@ -296,15 +300,14 @@ class TestResumeSwapWithMissingLive:recover.assert_not_awaited()assert result == {"outcome": "skipped", "reason": "no_delta_table"}- def test_recovery_clears_markers_and_skips_when_temp_also_gone(self):- # Both live and temp lost: nothing left to recover, so clear the markers and skip rather than- # loop on a swap that can never complete.- helper = self._helper()+ def test_recovery_clears_markers_and_skips_when_temp_unrecoverable(self):+ # Both live and a usable temp are lost (temp missing OR its log is corrupt): nothing left to+ # recover, so clear the markers and skip rather than loop on a swap that can never complete.+ helper = _delta_helper()schema = _schema(id="s1", clear_repartition_swap=Mock(), clear_repartition_pending=Mock())target = RepartitionTarget(partition_keys=["created_at"], trigger_reason="resume")- s3 = SimpleNamespace(_exists=AsyncMock(return_value=False))- with patch.object(repartition_module, "aget_s3_client", return_value=_FakeS3CM(s3)):+ with patch.object(repartition_module, "_valid_delta_row_count", new=AsyncMock(return_value=None)):result = asyncio.run(repartition_module._resume_swap_with_missing_live(helper=helper,@@ -322,6 +325,139 @@ class TestResumeSwapWithMissingLive:assert result == {"outcome": "skipped", "reason": "no_delta_table"}+class TestLiveUnreadable:+ """`get_delta_table()` *raising* (a DeltaError/FileNotFoundError from an OOM-crashed merge or an+ interrupted swap) is distinct from it returning None. When not resuming we skip with a dedicated+ `live_unreadable` reason so the import activity's handle_corrupted_delta_log revives it — without+ counting it as a repartition failure. When a swap marker is set the raise must instead route to the+ missing-live recovery (temp is still the durable source of truth), exactly as a None live would."""++ @parameterized.expand(+ [+ ("delta_error", deltalake.exceptions.DeltaError("corrupt log")),+ ("file_not_found", FileNotFoundError("gone")),+ ]+ )+ def test_skips_with_live_unreadable_when_not_resuming(self, _name, exc):+ helper = _delta_helper(get_delta_table=AsyncMock(side_effect=exc))+ schema = _schema(id="s1", repartition_swap=None)+ target = RepartitionTarget(partition_keys=["created_at"], trigger_reason="resume")++ with patch.object(repartition_module, "_resume_swap_with_missing_live", new=AsyncMock()) as recover:+ result = asyncio.run(repartition_table_in_place(helper=helper, schema=schema, target=target, logger=logger))++ recover.assert_not_awaited()+ assert result == {"outcome": "skipped", "reason": "live_unreadable"}++ def test_routes_to_recovery_when_unreadable_while_resuming(self):+ # A "ready" swap marker means temp was already built and validated, so an unreadable live is the+ # interrupted-swap window: recover from temp rather than skipping (which would strand the marker).+ helper = _delta_helper(get_delta_table=AsyncMock(side_effect=deltalake.exceptions.DeltaError("corrupt log")))+ schema = _schema(+ id="s1",+ repartition_swap={+ "state": "ready",+ "temp_uri": "s3://bucket/live__repartitioned",+ "live_uri": "s3://bucket/live",+ },+ )+ target = RepartitionTarget(partition_keys=["created_at"], trigger_reason="resume")++ recovered = {"outcome": "completed", "recovered": True}+ with patch.object(+ repartition_module, "_resume_swap_with_missing_live", new=AsyncMock(return_value=recovered)+ ) as recover:+ result = asyncio.run(repartition_table_in_place(helper=helper, schema=schema, target=target, logger=logger))++ recover.assert_awaited_once()+ assert result == recovered+++class TestValidDeltaRowCount:+ """The gate the swap steps rely on: a real, complete table yields its row count; anything the swap+ must not trust (missing folder, corrupt `_delta_log`) yields None."""++ def test_returns_row_count_for_valid_table(self, tmp_path):+ _write_month_partitioned(+ str(tmp_path / "t"), [(1, datetime.datetime(2024, 1, 5)), (2, datetime.datetime(2024, 2, 2))]+ )+ assert asyncio.run(repartition_module._valid_delta_row_count(str(tmp_path / "t"), {})) == 2++ def test_none_for_missing_table(self, tmp_path):+ assert asyncio.run(repartition_module._valid_delta_row_count(str(tmp_path / "nope"), {})) is None++ def test_none_for_corrupt_log(self, tmp_path):+ # A `_delta_log` that lost a commit is exactly the partial-temp state the swap guard must catch+ # instead of trusting the table's row count.+ path = tmp_path / "c"+ _write_month_partitioned(str(path), [(1, datetime.datetime(2024, 1, 5))])+ next(iter(sorted((path / "_delta_log").glob("*.json")))).unlink()+ assert asyncio.run(repartition_module._valid_delta_row_count(str(path), {})) is None+++class TestSwapTempIntoLiveGuard:+ def test_refuses_incomplete_temp_without_deleting_live(self):+ # The core safety invariant: a temp that doesn't hold every expected row must never trigger the+ # destructive delete-of-live. The guard raises before any S3 op, so live stays intact and the+ # caller rebuilds fresh on the next run instead of copying a broken table over live.+ s3 = SimpleNamespace(_exists=AsyncMock(), _rm=AsyncMock(), _find=AsyncMock(), _copy=AsyncMock())+ with (+ patch.object(repartition_module, "_valid_delta_row_count", new=AsyncMock(return_value=5)),+ patch.object(repartition_module, "aget_s3_client", return_value=_FakeS3CM(s3)),+ ):+ with pytest.raises(ValueError, match="temp is incomplete"):+ asyncio.run(+ repartition_module._swap_temp_into_live(+ temp_uri="s3://b/live__repartitioned",+ live_uri="s3://b/live",+ storage_options={},+ expected_rows=10,+ )+ )+ s3._rm.assert_not_called()+++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+ # from it is the loop that kept failing in prod. The temp is discarded and rebuilt fresh from the+ # intact live instead. side_effect: temp invalid on resume (99 != live 2), valid after rebuild (2).+ live = _write_month_partitioned(+ str(tmp_path / "live"), [(1, datetime.datetime(2024, 1, 5)), (2, datetime.datetime(2024, 2, 2))]+ )+ helper = _delta_helper(get_delta_table=AsyncMock(return_value=live))+ target = RepartitionTarget(+ partition_keys=["created_at"], trigger_reason="resume", partition_mode="datetime", partition_format="day"+ )+ schema = _schema(+ id="s1",+ repartition_swap={+ "state": "ready",+ "temp_uri": "s3://bucket/live__repartitioned",+ "live_uri": "s3://bucket/live",+ },+ set_repartition_swap=Mock(),+ clear_repartition_swap=Mock(),+ clear_repartition_pending=Mock(),+ set_partitioning_enabled=Mock(),+ stamp_last_repartition_at=Mock(),+ )+ s3 = SimpleNamespace(_exists=AsyncMock(return_value=True), _rm=AsyncMock())++ with (+ patch.object(repartition_module, "aget_s3_client", return_value=_FakeS3CM(s3)),+ patch.object(repartition_module, "_valid_delta_row_count", new=AsyncMock(side_effect=[99, 2])),+ patch.object(repartition_module, "_rewrite_into_temp", new=AsyncMock(return_value=(2, target))) as rewrite,+ patch.object(repartition_module, "_swap_temp_into_live", new=AsyncMock()) as swap,+ ):+ result = asyncio.run(repartition_table_in_place(helper=helper, schema=schema, target=target, logger=logger))++ rewrite.assert_awaited_once() # fresh rebuild happened rather than trusting the bad temp+ swap.assert_awaited_once()+ schema.set_repartition_swap.assert_called_once() # fresh temp validated and re-marked+ assert result["outcome"] == "completed"++@pytest.mark.parametrize("data",[