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): fence concurrent repartition attempts and fix s3fs instance sharing (#69934)

Tom Owers3652f55a4524
diff --git a/products/data_warehouse/backend/s3.py b/products/data_warehouse/backend/s3.py
index bbb29df5ee3f..1d82e520a860 100644
--- a/products/data_warehouse/backend/s3.py
+++ b/products/data_warehouse/backend/s3.py
@@ -27,9 +27,19 @@ def get_s3_client():
@contextlib.asynccontextmanager
-async def aget_s3_client():
- # Defaults for localhost dev and test suites
+async def aget_s3_client(*, fresh_instance: bool = False):
+ # fresh_instance=True bypasses the fsspec instance cache: a new S3FileSystem bound to the current
+ # event loop, closed on context exit. The cached default hands every caller the same instance
+ # regardless of loop, so async_to_sync-driven code (each call runs on a fresh, short-lived loop)
+ # gets an aiobotocore client bound to an already-closed loop ("Event loop is closed") and a
+ # dircache that goes stale whenever delta-rs writes to S3 through its own object store behind
+ # s3fs's back. Reserve it for low-frequency, correctness-critical paths (repartition purge/swap):
+ # every fresh instance pays connection setup + credential resolution, so defaulting it on would
+ # hammer the credential provider from hot paths.
+ uncached = fresh_instance or settings.USE_LOCAL_SETUP
if settings.USE_LOCAL_SETUP:
+ # Defaults for localhost dev and test suites. skip_instance_cache avoids "Event loop is
+ # closed" errors when the loop changes between test modules.
s3 = s3fs.S3FileSystem(
key=settings.DATAWAREHOUSE_LOCAL_ACCESS_KEY,
secret=settings.DATAWAREHOUSE_LOCAL_ACCESS_SECRET,
@@ -38,11 +48,24 @@ async def aget_s3_client():
asynchronous=True,
)
else:
- s3 = s3fs.S3FileSystem(asynchronous=True)
+ s3 = s3fs.S3FileSystem(asynchronous=True, skip_instance_cache=fresh_instance)
await s3.set_session()
- yield s3
+ if not uncached:
+ yield s3
+ return
+
+ try:
+ yield s3
+ finally:
+ # Uncached instances aren't finalized by the fsspec registry, so close the aiobotocore client
+ # explicitly (s3fs's set_session docs: "to be closed later with await .close()") to avoid
+ # leaking HTTP connections in long-lived workers. Never close the shared cached instance —
+ # other callers hold references to it.
+ with contextlib.suppress(Exception):
+ if s3._s3 is not None:
+ await s3._s3.close()
def get_size_of_folder(path: str) -> float:
diff --git a/products/warehouse_sources/backend/models/external_data_schema.py b/products/warehouse_sources/backend/models/external_data_schema.py
index 9e7a617d1f74..182dec1be0d7 100644
--- a/products/warehouse_sources/backend/models/external_data_schema.py
+++ b/products/warehouse_sources/backend/models/external_data_schema.py
@@ -423,6 +423,21 @@ class ExternalDataSchema(ModelActivityMixin, CreatedMetaFields, UpdatedMetaField
return swap
return None
+ @property
+ def repartition_claim(self) -> dict[str, Any] | None:
+ """The fencing claim of the newest repartition attempt: {"token", "job_id", "claimed_at"}.
+
+ S3 has no locking, so this row is the coordination point between concurrent repartition
+ attempts (a heartbeat-timed-out zombie and its Temporal retry). The newest claimant owns the
+ table; older attempts compare their token against this and stand down. Never cleared — it is
+ only ever compared against a live attempt's token, so a stale claim is inert.
+ """
+ if self.sync_type_config:
+ claim = self.sync_type_config.get("repartition_claim", None)
+ if isinstance(claim, dict):
+ return claim
+ return None
+
def _save_sync_type_config(self) -> None:
# Internal bookkeeping write — skip the activity-log SELECT (see save()) since these run
# inside the sync/repartition activity where a dropped pooler connection would fail the run.
@@ -444,6 +459,10 @@ class ExternalDataSchema(ModelActivityMixin, CreatedMetaFields, UpdatedMetaField
self.sync_type_config["repartition_swap"] = swap
self._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 clear_repartition_swap(self) -> None:
self.sync_type_config.pop("repartition_swap", None)
self._save_sync_type_config()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/README.md b/products/warehouse_sources/backend/temporal/data_imports/README.md
index 2901ba81bdce..55c4dce3942e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/README.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/README.md
@@ -40,7 +40,7 @@ How 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. 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.
+- **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, and transient infra errors (DB pooler drops, S3 rate limits) don't count against that cap.
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.py
index e6ae71def0f8..bf38816f1eb0 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
@@ -19,6 +19,7 @@ import math
import asyncio
import dataclasses
from collections import defaultdict
+from collections.abc import Awaitable, Callable
from typing import TYPE_CHECKING, Any
import pyarrow as pa
@@ -58,6 +59,17 @@ class RepartitionUnpartitionableError(Exception):
"""The table has no column suitable for partitioning — repartition is skipped, not retried."""
+class RepartitionSupersededError(Exception):
+ """A newer repartition attempt has claimed this schema — this stale attempt must stop.
+
+ An activity that Temporal heartbeat-times-out keeps running as a zombie (heartbeat failures are
+ swallowed by HeartbeaterSync), so its retry starts while it is still rewriting. Two writers on the
+ same table corrupt each other's temp `_delta_log` and defeat the swap's row-count verification.
+ The schema row's `repartition_claim` is the fence: the newest claimant owns the table, and every
+ destructive step re-checks the claim and raises this to make older attempts stand down.
+ """
+
+
@dataclasses.dataclass(frozen=True)
class RepartitionTarget:
"""The partition scheme to rewrite a table into. `partition_mode=None` means auto-detect."""
@@ -138,7 +150,11 @@ async def _purge_s3_prefix(s3: Any, uri: str) -> None:
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)
@@ -148,6 +164,49 @@ async def _purge_s3_prefix(s3: Any, uri: str) -> None:
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.
+
+ Temp URIs are claim-scoped (`__repartitioned_<token>`), so a superseded or crashed attempt leaves
+ an orphaned temp folder under its own token. Sweeping by name prefix clears them all — including
+ the legacy unsuffixed `__repartitioned` — so orphans never accumulate S3 cost and a stale temp can
+ never be mistaken for (or interleave with) the one this attempt is about to build.
+ """
+ s3.invalidate_cache()
+ parent, _, table_dir = live_uri.rstrip("/").rpartition("/")
+ if not parent or not table_dir:
+ return
+ files = await s3._find(parent, prefix=f"{table_dir}{TEMP_URI_SUFFIX}")
+ if files:
+ await s3._rm([f"s3://{f.lstrip('/')}" for f in files])
+
+
+def _temp_uri_for(live_uri: str, claim_token: str | None) -> str:
+ suffix = f"{TEMP_URI_SUFFIX}_{claim_token[:8]}" if claim_token else TEMP_URI_SUFFIX
+ return f"{live_uri}{suffix}"
+
+
+def _current_claim_token(schema: ExternalDataSchema) -> str | None:
+ schema.refresh_from_db(fields=["sync_type_config"])
+ claim = schema.repartition_claim
+ return claim.get("token") if claim else None
+
+
+async def _ensure_claim(schema: ExternalDataSchema, claim_token: str | None) -> None:
+ """Raise `RepartitionSupersededError` if a newer attempt has claimed the schema.
+
+ Re-reads the schema row (the single, strongly-consistent coordination point — S3 has no locking)
+ and compares tokens. `claim_token=None` means the caller opted out of fencing (tests, ad-hoc use).
+ """
+ if claim_token is None:
+ return
+ current = await asyncio.to_thread(_current_claim_token, schema)
+ if current != claim_token:
+ raise RepartitionSupersededError(
+ f"repartition claim lost (ours={claim_token[:8]} current={str(current)[:8]}) schema_id={schema.id}"
+ )
+
+
def select_repartition_target(
schema: ExternalDataSchema,
partition_bytes: dict[str | None, int],
@@ -227,11 +286,14 @@ async def _rewrite_into_temp(
target: RepartitionTarget,
batch_size: int,
logger: FilteringBoundLogger,
+ ensure_claim: Callable[[], Awaitable[None]] | None = None,
) -> tuple[int, RepartitionTarget]:
"""Stream the live table into a fresh temp table under the new partition scheme.
Returns (rows_written, resolved_target). The first batch resolves any auto-detected mode/format/
keys so every subsequent batch is bucketed identically (a per-batch auto-detect could disagree).
+ `ensure_claim` runs before every batch write so a superseded attempt stops within one batch
+ instead of appending into (and corrupting) the newer attempt's rebuild.
"""
dataset = await asyncio.to_thread(old_delta.to_pyarrow_dataset)
reader = await asyncio.to_thread(lambda: dataset.scanner(batch_size=batch_size).to_reader())
@@ -240,6 +302,8 @@ async def _rewrite_into_temp(
rows_written = 0
while True:
+ if ensure_claim is not None:
+ await ensure_claim()
batch = await asyncio.to_thread(_read_next_batch, reader)
if batch is None:
break
@@ -297,6 +361,7 @@ async def repartition_table_in_place(
logger: FilteringBoundLogger,
*,
batch_size: int = DEFAULT_REPARTITION_BATCH_SIZE,
+ claim_token: str | None = None,
) -> dict[str, Any]:
"""Rewrite the schema's Delta table under `target`'s finer partition scheme, in place, from S3.
@@ -304,14 +369,26 @@ async def repartition_table_in_place(
`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. Returns a stats dict for
observability. Raises `RepartitionUnpartitionableError` (terminal) if no partition mode applies.
+
+ `claim_token` fences out zombie attempts: the temp table is scoped to the token so concurrent
+ writers can never share one, and the claim is re-checked before every batch write and every
+ destructive step (raising `RepartitionSupersededError` when a newer attempt has taken over).
"""
live_uri = await helper.get_table_uri()
- temp_uri = f"{live_uri}{TEMP_URI_SUFFIX}"
storage_options = helper.get_storage_options()
- # Resume path: a prior attempt already built + validated temp and recorded the swap marker.
+ async def ensure_claim() -> None:
+ await _ensure_claim(schema, claim_token)
+
+ # Resume path: a prior attempt already built + validated temp and recorded the swap marker. The
+ # marker's temp_uri is authoritative — it may be scoped to the attempt that built it.
swap = schema.repartition_swap
resuming = bool(swap and swap.get("state") == "ready")
+ temp_uri = (swap or {}).get("temp_uri") if resuming else None
+ if not temp_uri:
+ temp_uri = _temp_uri_for(live_uri, claim_token)
+
+ await ensure_claim()
try:
old_delta = await helper.get_delta_table()
@@ -342,6 +419,7 @@ async def repartition_table_in_place(
live_uri=live_uri,
storage_options=storage_options,
logger=logger,
+ ensure_claim=ensure_claim,
)
await logger.ainfo(f"repartition: no delta table, skipping schema_id={schema.id}", schema_id=str(schema.id))
return {"outcome": "skipped", "reason": "no_delta_table"}
@@ -373,16 +451,15 @@ async def repartition_table_in_place(
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:
- await _purge_s3_prefix(s3, temp_uri)
await asyncio.to_thread(schema.clear_repartition_swap)
resuming = False
+ # Rebuild under our own claim-scoped temp; the stale one is swept with the orphans below.
+ temp_uri = _temp_uri_for(live_uri, claim_token)
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):
- await s3._rm(temp_uri, recursive=True)
+ # Fresh build: sweep every stale/orphaned temp variant, then stream the live table into ours.
+ 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,
@@ -391,6 +468,7 @@ async def repartition_table_in_place(
target=target,
batch_size=batch_size,
logger=logger,
+ ensure_claim=ensure_claim,
)
# Validate before any destructive action — temp must hold every row.
@@ -402,6 +480,7 @@ async def repartition_table_in_place(
)
# Marker makes the swap idempotent: temp stays the source of truth until it's confirmed live.
+ await ensure_claim()
await asyncio.to_thread(
schema.set_repartition_swap, {"state": "ready", "temp_uri": temp_uri, "live_uri": live_uri}
)
@@ -413,6 +492,7 @@ async def repartition_table_in_place(
live_uri=live_uri,
storage_options=storage_options,
expected_rows=old_row_count,
+ ensure_claim=ensure_claim,
)
# Persist the new scheme and clear controller state. set_partitioning_enabled saves + pops overrides.
@@ -470,6 +550,7 @@ async def _resume_swap_with_missing_live(
live_uri: str,
storage_options: dict[str, str],
logger: FilteringBoundLogger,
+ ensure_claim: Callable[[], Awaitable[None]] | None = None,
) -> dict[str, Any]:
"""Finish a swap whose live table was already deleted by an interrupted prior run.
@@ -499,6 +580,7 @@ async def _resume_swap_with_missing_live(
live_uri=live_uri,
storage_options=storage_options,
expected_rows=expected_rows,
+ ensure_claim=ensure_claim,
)
await asyncio.to_thread(
@@ -528,6 +610,7 @@ async def _swap_temp_into_live(
live_uri: str,
storage_options: dict[str, str],
expected_rows: int,
+ ensure_claim: Callable[[], Awaitable[None]] | None = None,
) -> None:
"""Atomically-enough replace `live_uri` with the contents of `temp_uri`.
@@ -549,8 +632,12 @@ async def _swap_temp_into_live(
f"(rows={temp_rows} expected={expected_rows} temp_uri={temp_uri})"
)
+ # Deleting live is the point of no return — a superseded attempt must never reach it.
+ if ensure_claim is not None:
+ await ensure_claim()
+
temp_prefix = temp_uri.replace("s3://", "").rstrip("/")
- async with aget_s3_client() as s3:
+ async with aget_s3_client(fresh_instance=True) as s3:
if await s3._exists(temp_uri):
# 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`,
@@ -567,5 +654,5 @@ async def _swap_temp_into_live(
if live_rows != expected_rows:
raise ValueError(f"repartition swap verification failed: live={live_rows} expected={expected_rows}")
- async with aget_s3_client() as s3:
+ async with aget_s3_client(fresh_instance=True) as s3:
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 949c26c1457f..4fd5cab71821 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
@@ -15,6 +15,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline
)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.consts import PARTITION_KEY
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.repartition import (
+ RepartitionSupersededError,
RepartitionTarget,
_rewrite_into_temp,
measure_partition_bytes,
@@ -52,6 +53,18 @@ def _delta_helper(**kwargs):
return SimpleNamespace(**defaults)
+def _fake_s3(**kwargs):
+ defaults = {
+ "invalidate_cache": Mock(),
+ "_exists": AsyncMock(return_value=True),
+ "_find": AsyncMock(return_value=[]),
+ "_rm": AsyncMock(),
+ "_copy": AsyncMock(),
+ }
+ defaults.update(kwargs)
+ return SimpleNamespace(**defaults)
+
+
def _write_month_partitioned(path: str, rows: list[tuple[int, datetime.datetime]]) -> deltalake.DeltaTable:
table = pa.table(
{
@@ -403,28 +416,49 @@ class TestPurgeS3Prefix:
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(),
- )
+ # A regression back to a bare `_rm(recursive=True)` would drop this list-delete. The dircache
+ # must be dropped first — delta-rs writes bypass s3fs, so a cached listing misses its files.
+ s3 = _fake_s3(_find=AsyncMock(return_value=["bucket/t/_delta_log/0.json", "bucket/t/part-0.parquet"]))
asyncio.run(repartition_module._purge_s3_prefix(s3, "s3://bucket/t"))
+ s3.invalidate_cache.assert_called()
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())
+ s3 = _fake_s3(_exists=AsyncMock(return_value=False))
asyncio.run(repartition_module._purge_s3_prefix(s3, "s3://bucket/gone"))
s3._find.assert_not_awaited()
s3._rm.assert_not_awaited()
+class TestPurgeStaleTempTables:
+ def test_sweeps_every_repartitioned_variant(self):
+ # Temp URIs are claim-scoped, so orphans from superseded/crashed attempts live under other
+ # tokens (and the legacy unsuffixed name). A purge of only the current attempt's temp would
+ # leave those orphans to interleave with — and corrupt — the next rebuild.
+ s3 = _fake_s3(
+ _find=AsyncMock(
+ return_value=[
+ "bucket/dlt/team_1_src/t__repartitioned/_delta_log/0.json",
+ "bucket/dlt/team_1_src/t__repartitioned_ab12cd34/part-0.parquet",
+ ]
+ )
+ )
+ asyncio.run(repartition_module._purge_stale_temp_tables(s3, "s3://bucket/dlt/team_1_src/t"))
+ s3._find.assert_awaited_once_with("s3://bucket/dlt/team_1_src", prefix="t__repartitioned")
+ s3._rm.assert_awaited_once_with(
+ [
+ "s3://bucket/dlt/team_1_src/t__repartitioned/_delta_log/0.json",
+ "s3://bucket/dlt/team_1_src/t__repartitioned_ab12cd34/part-0.parquet",
+ ]
+ )
+
+
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())
+ s3 = _fake_s3()
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)),
@@ -466,7 +500,7 @@ class TestResumeWithInvalidTemp:
set_partitioning_enabled=Mock(),
stamp_last_repartition_at=Mock(),
)
- s3 = SimpleNamespace(_exists=AsyncMock(return_value=True), _rm=AsyncMock(), _find=AsyncMock(return_value=[]))
+ s3 = _fake_s3()
with (
patch.object(repartition_module, "aget_s3_client", return_value=_FakeS3CM(s3)),
@@ -482,6 +516,112 @@ class TestResumeWithInvalidTemp:
assert result["outcome"] == "completed"
+class TestClaimFencing:
+ """A heartbeat-timed-out attempt keeps running as a zombie while its Temporal retry starts; both
+ used to write into the same temp table and corrupt each other (headless `_delta_log`, inflated row
+ counts). The schema-row claim is the fence: a stale attempt must stop at the next check and never
+ reach a destructive step."""
+
+ @pytest.mark.parametrize(
+ "token_reads",
+ [
+ pytest.param(["other"], id="stolen_at_start"),
+ pytest.param(["tok-ours", "other"], id="stolen_before_marker"),
+ ],
+ )
+ def test_superseded_attempt_never_reaches_destructive_steps(self, token_reads, tmp_path):
+ 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="t", partition_mode="datetime", partition_format="day"
+ )
+ schema = _schema(id="s1", repartition_swap=None, set_repartition_swap=Mock())
+
+ with (
+ patch.object(repartition_module, "_current_claim_token", side_effect=token_reads),
+ patch.object(repartition_module, "_purge_stale_temp_tables", new=AsyncMock()),
+ patch.object(repartition_module, "_rewrite_into_temp", new=AsyncMock(return_value=(2, target))),
+ patch.object(repartition_module, "_valid_delta_row_count", new=AsyncMock(return_value=2)),
+ patch.object(repartition_module, "_swap_temp_into_live", new=AsyncMock()) as swap,
+ ):
+ with pytest.raises(RepartitionSupersededError):
+ asyncio.run(
+ repartition_table_in_place(
+ helper=helper, schema=schema, target=target, logger=logger, claim_token="tok-ours"
+ )
+ )
+
+ schema.set_repartition_swap.assert_not_called()
+ swap.assert_not_awaited()
+
+ def test_rewrite_stops_at_batch_boundary_when_claim_lost(self, tmp_path):
+ # The zombie's damage window is the rewrite loop, so the claim is re-checked before every batch
+ # write — a superseded writer must stop within one batch, not stream its whole table into (and
+ # corrupt) the newer attempt's rebuild.
+ live = _write_month_partitioned(
+ str(tmp_path / "live"), [(1, datetime.datetime(2024, 1, 5)), (2, datetime.datetime(2024, 2, 2))]
+ )
+ ensure = AsyncMock(side_effect=[None, RepartitionSupersededError("stolen")])
+ target = RepartitionTarget(
+ partition_keys=["created_at"], trigger_reason="t", partition_mode="datetime", partition_format="day"
+ )
+ with pytest.raises(RepartitionSupersededError):
+ asyncio.run(
+ _rewrite_into_temp(
+ old_delta=live,
+ temp_uri=str(tmp_path / "temp"),
+ storage_options={},
+ target=target,
+ batch_size=1,
+ logger=logger,
+ ensure_claim=ensure,
+ )
+ )
+ assert ensure.await_count == 2
+
+ def test_resume_targets_marker_temp_uri_not_claim_scoped(self, tmp_path):
+ # In-flight prod markers predate claim-scoped temp names; a resume must validate and swap the
+ # exact temp the marker records — deriving a fresh claim-scoped name instead would "lose" the
+ # built temp and, with live already deleted mid-swap, strand the recovery.
+ 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",
+ },
+ clear_repartition_swap=Mock(),
+ clear_repartition_pending=Mock(),
+ set_partitioning_enabled=Mock(),
+ stamp_last_repartition_at=Mock(),
+ )
+
+ with (
+ patch.object(repartition_module, "_current_claim_token", return_value="tok-ours"),
+ patch.object(repartition_module, "_valid_delta_row_count", new=AsyncMock(return_value=2)) as valid,
+ 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, claim_token="tok-ours"
+ )
+ )
+
+ assert result["outcome"] == "completed"
+ valid.assert_awaited_once_with("s3://bucket/live__repartitioned", {})
+ assert swap.await_args is not None
+ assert swap.await_args.kwargs["temp_uri"] == "s3://bucket/live__repartitioned"
+
+
@pytest.mark.parametrize(
"data",
[
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 4cf6892434e6..fc2ffb035def 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
@@ -21,6 +21,7 @@ from products.warehouse_sources.backend.models.oom_event import ExternalDataSche
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline import repartition_controller as ctrl
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.consts import PARTITION_KEY
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.repartition import (
+ RepartitionSupersededError,
RepartitionUnpartitionableError,
)
from products.warehouse_sources.backend.temporal.data_imports.workflow_activities import repartition_table
@@ -388,10 +389,20 @@ class TestRepartitionActivity:
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.
+ @pytest.mark.parametrize(
+ "error",
+ [
+ pytest.param(OperationalError("server closed the connection unexpectedly"), id="db_pooler_drop"),
+ pytest.param(OSError("[Errno 16] Please reduce your request rate."), id="s3_rate_limit"),
+ pytest.param(OSError("Kernel error -> an error occurred while loading credentials"), id="credentials"),
+ pytest.param(Exception("An HTTP Client raised an unhandled exception: Event loop is closed"), id="loop"),
+ ],
+ )
+ def test_transient_infra_error_not_recorded_as_failure(self, team, error):
+ # Infra noise mid-repartition (pooler drop, S3 throttle, credential timeout, dead-loop client) is
+ # 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 infra blips spam error tracking and
+ # exhaust the attempt budget.
schema = _make_schema(team, {})
schema.set_repartition_pending(
{
@@ -402,7 +413,7 @@ class TestRepartitionActivity:
"attempts": 0,
}
)
- mocked = AsyncMock(side_effect=OperationalError("server closed the connection unexpectedly"))
+ mocked = AsyncMock(side_effect=error)
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
@@ -410,3 +421,82 @@ class TestRepartitionActivity:
schema.refresh_from_db()
assert schema.repartition_pending is not None
assert schema.repartition_pending["attempts"] == 0
+
+ @pytest.mark.parametrize(
+ "error,still_claimant",
+ [
+ pytest.param(RepartitionSupersededError("claim lost"), True, id="clean_abort"),
+ pytest.param(ValueError("boom from clobbered temp"), False, id="collateral_failure"),
+ ],
+ )
+ def test_superseded_attempt_is_silent_and_burns_no_attempt(self, team, error, still_claimant):
+ # A zombie attempt (heartbeat-timed-out but still running) that either stands down cleanly or
+ # crashes on state its replacement clobbered must not emit warehouse_repartition_failed or
+ # consume an attempt — the newer claimant owns the run and reports for it. Without this, every
+ # superseded zombie double-reports and can burn the whole attempt budget on one bad table.
+ 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=error)
+ 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,
+ patch.object(repartition_table, "_still_claimant", return_value=still_claimant),
+ ):
+ 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
+ # The activity minted a fencing claim before starting the rewrite.
+ assert schema.repartition_claim is not None
+
+ def test_superseded_after_claim_check_blip_is_not_recorded_as_failure(self, team):
+ # _still_claimant is conservative and reports True on a transient DB read, so a zombie can reach
+ # the failure handler even after a newer attempt took the claim. _handle_failure's authoritative
+ # refresh is the fence that catches that: with _still_claimant forced True (the blip) but the DB
+ # claim changed by a newer attempt, the zombie must record no failure and re-queue no attempt —
+ # otherwise it double-reports and re-increments a run the newer claimant already owns.
+ schema = _make_schema(team, {})
+ schema.set_repartition_pending(
+ {
+ "partition_mode": "md5",
+ "partition_count": 4,
+ "partition_keys": ["id"],
+ "trigger_reason": "t",
+ "attempts": 0,
+ }
+ )
+
+ def _steal_claim_but_blip_reports_still_claimant(*args, **kwargs):
+ # Model the transient blip: a newer attempt has already taken the claim in the DB, yet the
+ # claim re-read here reports True anyway (conservative on doubt). The steal is written from
+ # here rather than inside the rewrite mock because _still_claimant runs in the activity's sync
+ # context, so its ORM write is safe — the rewrite runs under async_to_sync, where sync ORM
+ # raises SynchronousOnlyOperation.
+ other = ExternalDataSchema.objects.get(id=schema.id)
+ other.set_repartition_claim({"token": "newer-token", "job_id": "j2", "claimed_at": "later"})
+ return True
+
+ mocked = AsyncMock(side_effect=ValueError("boom from clobbered temp"))
+ 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,
+ patch.object(
+ repartition_table, "_still_claimant", side_effect=_steal_claim_but_blip_reports_still_claimant
+ ),
+ ):
+ 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
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 d9815836fc0a..f65ce78291fe 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,11 +8,13 @@ just proceeds on the old layout (status quo) and the table is retried on a later
"""
import time
+import uuid
import asyncio
import dataclasses
from typing import Any
from django.db import InterfaceError, OperationalError, close_old_connections
+from django.utils import timezone
from asgiref.sync import async_to_sync
from structlog.contextvars import bind_contextvars
@@ -29,6 +31,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline
DeltaTableHelper,
)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.repartition import (
+ RepartitionSupersededError,
RepartitionTarget,
RepartitionUnpartitionableError,
repartition_table_in_place,
@@ -67,6 +70,36 @@ def _is_cancellation(error: BaseException) -> bool:
return isinstance(error, asyncio.CancelledError) or type(error).__name__ == "CancelledError"
+# Infra noise observed escaping the rewrite as generic OSError/HTTPClientError — none of these are
+# repartition bugs, and the marker-idempotent swap means the next sync simply retries.
+_TRANSIENT_ERROR_SNIPPETS = (
+ "reduce your request rate", # S3 503 SlowDown surfaced by the delta kernel as OSError
+ "error occurred while loading credentials", # IMDS/credential-provider timeout inside the kernel
+ "event loop is closed", # s3fs client bound to an already-completed async_to_sync loop
+)
+
+
+def _is_transient_infra_error(error: Exception) -> bool:
+ if isinstance(error, OperationalError | InterfaceError):
+ return True
+ message = str(error).lower()
+ return any(snippet in message for snippet in _TRANSIENT_ERROR_SNIPPETS)
+
+
+def _still_claimant(schema: ExternalDataSchema, claim_token: str) -> bool:
+ """Whether this attempt still holds the schema's repartition claim.
+
+ Conservative on doubt: if the claim can't be read (DB blip), report True so a real failure is
+ never silently dropped.
+ """
+ try:
+ schema.refresh_from_db(fields=["sync_type_config"])
+ claim = schema.repartition_claim
+ return bool(claim and claim.get("token") == claim_token)
+ except Exception:
+ return True
+
+
def _target_from_schema(schema: ExternalDataSchema) -> RepartitionTarget:
"""Fallback target reconstructed from the schema's current settings (resume-with-no-pending)."""
return RepartitionTarget(
@@ -218,6 +251,15 @@ def _maybe_repartition_table(inputs: RepartitionActivityInputs, logger: Filterin
capture_repartition_event("warehouse_repartition_started", started_props)
logger.info(f"repartition: starting trigger_reason={trigger_reason}", trigger_reason=trigger_reason)
+ # Fencing claim: if we get heartbeat-timed-out mid-rewrite, this activity keeps running as a
+ # zombie (heartbeat failures are swallowed) while Temporal starts a retry. The retry's newer claim
+ # 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(
+ {"token": claim_token, "job_id": inputs.job_id, "claimed_at": timezone.now().isoformat()}
+ )
+
start = time.monotonic()
try:
# HeartbeaterSync heartbeats on a background thread while the (possibly long) rewrite streams,
@@ -228,7 +270,14 @@ def _maybe_repartition_table(inputs: RepartitionActivityInputs, logger: Filterin
schema=schema,
target=target,
logger=logger,
+ claim_token=claim_token,
)
+ except RepartitionSupersededError:
+ # A newer attempt claimed the schema and owns the table now. Stop quietly: recording a failure
+ # here would burn an attempt and double-report the run the newer claimant is already handling.
+ logger.info("repartition: superseded by a newer attempt, standing down")
+ DELTA_REPARTITION_TOTAL.labels(team_id=str(inputs.team_id), outcome="superseded").inc()
+ return
except RepartitionUnpartitionableError as e:
# Terminal: the table can't be partitioned. Clear the flag so we don't retry every run.
schema.refresh_from_db(fields=["sync_type_config"])
@@ -253,16 +302,24 @@ def _maybe_repartition_table(inputs: RepartitionActivityInputs, logger: Filterin
# 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)
+ if not _still_claimant(schema, claim_token):
+ # The error is almost certainly collateral from the newer claimant clobbering our S3 state
+ # (e.g. it swept our temp mid-write). It owns the retry; recording our wreckage as a
+ # failure would burn an attempt and pollute error tracking with self-inflicted noise.
+ logger.info("repartition: failed after being superseded, standing down", exc_info=True)
+ DELTA_REPARTITION_TOTAL.labels(team_id=str(inputs.team_id), outcome="superseded").inc()
+ return
+ if _is_transient_infra_error(e):
+ # Transient infra noise mid-repartition (app-DB pooler drop, S3 rate limit, credential
+ # timeout) — 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 —
+ # capture for visibility and move on.
+ logger.warning("repartition: transient infra 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()
+ failure_outcome = _handle_failure(inputs, schema, pending, trigger_reason, e, claim_token, logger)
+ DELTA_REPARTITION_TOTAL.labels(team_id=str(inputs.team_id), outcome=failure_outcome).inc()
return
duration = time.monotonic() - start
@@ -291,9 +348,22 @@ def _handle_failure(
pending: dict[str, Any] | None,
trigger_reason: str,
error: Exception,
-) -> None:
- """Record a failed attempt; give up (and clear the flag) after MAX_REPARTITION_ATTEMPTS."""
+ claim_token: str,
+ logger: FilteringBoundLogger,
+) -> str:
+ """Record a failed attempt; give up (and clear the flag) after MAX_REPARTITION_ATTEMPTS.
+
+ Returns the metric outcome: "failed" normally, or "superseded" when the authoritative post-refresh
+ read shows a newer attempt now owns the claim. `_still_claimant` is conservative and reports True on
+ a transient DB blip, so a zombie could reach here after a newer claimant already finished; the
+ refresh below is the authoritative read (the DB is reachable again), so re-checking the claim here
+ stops us recording a spurious failure and re-queueing `repartition_pending` the newer attempt cleared.
+ """
schema.refresh_from_db(fields=["sync_type_config"])
+ claim = schema.repartition_claim
+ if not (claim and claim.get("token") == claim_token):
+ logger.info("repartition: superseded (claim changed under us), standing down without recording failure")
+ return "superseded"
pending = schema.repartition_pending or pending or {}
attempts = int(pending.get("attempts", 0)) + 1
@@ -317,3 +387,4 @@ def _handle_failure(
capture_repartition_event("warehouse_repartition_failed", props)
capture_exception(error)
+ return "failed"