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): stop repartition failure loops and clear deploy/infra noise (#69602)

Tom Owersd5d822a704d6
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 057fcb57132a..e6ae71def0f8 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
@@ -129,6 +129,25 @@ 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.
+ """
+ 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 select_repartition_target(
schema: ExternalDataSchema,
partition_bytes: dict[str | None, int],
@@ -355,8 +374,7 @@ async def repartition_table_in_place(
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 _purge_s3_prefix(s3, temp_uri)
await asyncio.to_thread(schema.clear_repartition_swap)
resuming = False
@@ -534,8 +552,10 @@ async def _swap_temp_into_live(
temp_prefix = temp_uri.replace("s3://", "").rstrip("/")
async with aget_s3_client() as s3:
if await s3._exists(temp_uri):
- if await s3._exists(live_uri):
- await s3._rm(live_uri, recursive=True)
+ # Fully clear live before the copy. A leftover file from an incomplete recursive delete
+ # merges into the copied `_delta_log` and inflates the row count past `expected_rows`,
+ # tripping the verification below and looping the repartition forever.
+ await _purge_s3_prefix(s3, live_uri)
files = await s3._find(temp_uri)
for f in files:
rel = f[len(temp_prefix) :]
@@ -548,10 +568,4 @@ async def _swap_temp_into_live(
raise ValueError(f"repartition swap verification failed: live={live_rows} expected={expected_rows}")
async with aget_s3_client() as s3:
- # Delete the temp files explicitly (a recursive prefix delete can leave directory-marker
- # objects behind on some S3-compatible stores), then a best-effort recursive sweep.
- temp_files = await s3._find(temp_uri)
- if temp_files:
- await s3._rm([f"s3://{f.lstrip('/')}" for f in temp_files])
- if await s3._exists(temp_uri):
- await s3._rm(temp_uri, recursive=True)
+ await _purge_s3_prefix(s3, 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.py
index 67846ffa6155..949c26c1457f 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
@@ -395,6 +395,30 @@ class TestValidDeltaRowCount:
assert asyncio.run(repartition_module._valid_delta_row_count(str(path), {})) is None
+class TestPurgeS3Prefix:
+ """Robustly clearing an S3 prefix underpins every destructive repartition step (temp rebuild, swap
+ live-delete, temp cleanup). A lone recursive delete strands objects on S3-compatible stores, and
+ those strays corrupt a rebuilt temp or a swapped-in live — the DeltaError / row-count-mismatch loops
+ seen in prod."""
+
+ def test_enumerates_and_deletes_every_object(self):
+ # The fix: delete the listed objects explicitly, not only a recursive rm that can leave strays.
+ # A regression back to a bare `_rm(recursive=True)` would drop this list-delete.
+ s3 = SimpleNamespace(
+ _exists=AsyncMock(return_value=True),
+ _find=AsyncMock(return_value=["bucket/t/_delta_log/0.json", "bucket/t/part-0.parquet"]),
+ _rm=AsyncMock(),
+ )
+ asyncio.run(repartition_module._purge_s3_prefix(s3, "s3://bucket/t"))
+ s3._rm.assert_any_await(["s3://bucket/t/_delta_log/0.json", "s3://bucket/t/part-0.parquet"])
+
+ def test_noop_when_prefix_absent(self):
+ s3 = SimpleNamespace(_exists=AsyncMock(return_value=False), _find=AsyncMock(), _rm=AsyncMock())
+ asyncio.run(repartition_module._purge_s3_prefix(s3, "s3://bucket/gone"))
+ s3._find.assert_not_awaited()
+ s3._rm.assert_not_awaited()
+
+
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
@@ -442,7 +466,7 @@ class TestResumeWithInvalidTemp:
set_partitioning_enabled=Mock(),
stamp_last_repartition_at=Mock(),
)
- s3 = SimpleNamespace(_exists=AsyncMock(return_value=True), _rm=AsyncMock())
+ s3 = SimpleNamespace(_exists=AsyncMock(return_value=True), _rm=AsyncMock(), _find=AsyncMock(return_value=[]))
with (
patch.object(repartition_module, "aget_s3_client", return_value=_FakeS3CM(s3)),
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/test_repartition_controller.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/test_repartition_controller.py
index da22d68f36b1..4cf6892434e6 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/test_repartition_controller.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/test_repartition_controller.py
@@ -1,10 +1,13 @@
import uuid
+import asyncio
import datetime
import tempfile
import pytest
from unittest.mock import AsyncMock, patch
+from django.db import OperationalError
+
import pyarrow as pa
import deltalake as deltalake
import structlog
@@ -214,6 +217,13 @@ class TestRepartitionOOMHistoryTrigger:
assert schema.repartition_pending is None
+# An Exception-derived cancellation, named exactly `CancelledError`: models how `async_to_sync` can
+# surface a worker-shutdown cancel so it slips past a plain BaseException catch. `_is_cancellation`
+# keys on the type name, so this must be named `CancelledError`.
+class CancelledError(Exception):
+ pass
+
+
class TestRepartitionActivity:
def _inputs(self, team, schema: ExternalDataSchema) -> RepartitionActivityInputs:
job = _make_job(team, schema)
@@ -348,3 +358,55 @@ class TestRepartitionActivity:
self._run(self._inputs(team, schema), AsyncMock(side_effect=ValueError("boom")))
schema.refresh_from_db()
assert schema.repartition_pending is None
+
+ @pytest.mark.parametrize("cancel_exc", [asyncio.CancelledError(), CancelledError()])
+ def test_cancellation_propagates_and_is_not_recorded(self, team, cancel_exc):
+ # A worker-shutdown cancellation — whether it arrives as a real asyncio.CancelledError or wrapped
+ # Exception-derived through async_to_sync — must propagate so Temporal reschedules, and must never
+ # be recorded as a failure or consume an attempt. Otherwise every deploy floods error tracking
+ # with warehouse_repartition_failed and burns the table's finite attempt budget on non-failures.
+ schema = _make_schema(team, {})
+ schema.set_repartition_pending(
+ {
+ "partition_mode": "md5",
+ "partition_count": 4,
+ "partition_keys": ["id"],
+ "trigger_reason": "t",
+ "attempts": 0,
+ }
+ )
+ mocked = AsyncMock(side_effect=cancel_exc)
+ with (
+ patch.object(repartition_table, "HeartbeaterSync"),
+ patch.object(repartition_table, "repartition_table_in_place", new=mocked),
+ patch.object(repartition_table, "capture_repartition_event") as capture,
+ ):
+ with pytest.raises((asyncio.CancelledError, CancelledError)):
+ ActivityEnvironment().run(maybe_repartition_table_activity, self._inputs(team, schema))
+ assert "warehouse_repartition_failed" not in [c.args[0] for c in capture.call_args_list]
+ schema.refresh_from_db()
+ assert schema.repartition_pending is not None
+ assert schema.repartition_pending["attempts"] == 0
+
+ def test_transient_db_error_not_recorded_as_failure(self, team):
+ # A pooler drop mid-repartition (OperationalError) is infra noise, not a repartition bug: the swap
+ # is marker-idempotent and the next sync retries. It must not emit warehouse_repartition_failed or
+ # consume an attempt, else transient DB blips spam error tracking and exhaust the attempt budget.
+ schema = _make_schema(team, {})
+ schema.set_repartition_pending(
+ {
+ "partition_mode": "md5",
+ "partition_count": 4,
+ "partition_keys": ["id"],
+ "trigger_reason": "t",
+ "attempts": 0,
+ }
+ )
+ mocked = AsyncMock(side_effect=OperationalError("server closed the connection unexpectedly"))
+ capture = self._run(self._inputs(team, schema), mocked)
+ emitted = [c.args[0] for c in capture.call_args_list]
+ assert "warehouse_repartition_started" in emitted
+ assert "warehouse_repartition_failed" not in emitted
+ schema.refresh_from_db()
+ assert schema.repartition_pending is not None
+ assert schema.repartition_pending["attempts"] == 0
diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/repartition_table.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/repartition_table.py
index 801a3c3c3d29..d9815836fc0a 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
@@ -8,10 +8,11 @@ just proceeds on the old layout (status quo) and the table is retried on a later
"""
import time
+import asyncio
import dataclasses
from typing import Any
-from django.db import close_old_connections
+from django.db import InterfaceError, OperationalError, close_old_connections
from asgiref.sync import async_to_sync
from structlog.contextvars import bind_contextvars
@@ -57,6 +58,15 @@ class RepartitionActivityInputs:
source_id: str
+def _is_cancellation(error: BaseException) -> bool:
+ """Whether `error` is an activity cancellation, however it surfaced.
+
+ `async_to_sync` can wrap a worker-shutdown `asyncio.CancelledError` (a `BaseException` since 3.8) so
+ it arrives Exception-derived; match on the type name too so it's never mistaken for a real failure.
+ """
+ return isinstance(error, asyncio.CancelledError) or type(error).__name__ == "CancelledError"
+
+
def _target_from_schema(schema: ExternalDataSchema) -> RepartitionTarget:
"""Fallback target reconstructed from the schema's current settings (resume-with-no-pending)."""
return RepartitionTarget(
@@ -229,9 +239,28 @@ def _maybe_repartition_table(inputs: RepartitionActivityInputs, logger: Filterin
DELTA_REPARTITION_TOTAL.labels(team_id=str(inputs.team_id), outcome="skipped").inc()
capture_exception(e)
return
+ except asyncio.CancelledError:
+ # Worker shutdown / deploy interrupted the (possibly long) rewrite. Not a repartition failure —
+ # Temporal reschedules the activity — so propagate rather than record it, else every deploy fills
+ # error tracking with `warehouse_repartition_failed` noise and burns a repartition attempt.
+ logger.info("repartition: cancelled mid-run, will be retried")
+ raise
except Exception as e:
# Do NOT re-raise: a repartition failure must not block the sync — the table is retried on a
# later run, on the old layout in the meantime.
+ if _is_cancellation(e):
+ # Some cancellations surface through async_to_sync as an Exception-derived CancelledError.
+ # Treat identically to the branch above: propagate, never record it as a failure.
+ logger.info("repartition: cancelled mid-run, will be retried")
+ raise
+ if isinstance(e, OperationalError | InterfaceError):
+ # Transient app-DB pooler drop mid-repartition (not a repartition bug). The rewrite/swap is
+ # idempotent via the swap marker, so the next sync retries cleanly. Don't consume an attempt
+ # or emit a failure event over infra noise — capture for visibility and move on.
+ logger.warning("repartition: transient database error, will retry on next sync", exc_info=True)
+ capture_exception(e)
+ DELTA_REPARTITION_TOTAL.labels(team_id=str(inputs.team_id), outcome="transient").inc()
+ return
_handle_failure(inputs, schema, pending, trigger_reason, e)
DELTA_REPARTITION_TOTAL.labels(team_id=str(inputs.team_id), outcome="failed").inc()
return