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): record a native panic during repartitioning (#99083)

Tom Owers7574798eb58f
diff --git a/products/warehouse_sources/backend/temporal/data_imports/README.md b/products/warehouse_sources/backend/temporal/data_imports/README.md
index 631b3cd95d9a..5e11fed35d08 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/README.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/README.md
@@ -48,7 +48,7 @@ Week into month is the one transition that cannot be computed exactly, because I
- **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.
- **Keeping the data and the settings in step.** The swap re-buckets the data in S3, but the scheme it was re-bucketed under lives in the schema row, and the merge computes each incoming row's `_ph_partition_key` from that row. Between the two the table would be describing a layout it no longer has, and a merge there scopes its predicate to a partition the table cannot contain, matches nothing, and inserts every fetched row instead of upserting it — the whole incremental lookback window duplicated, with the job still reporting Completed. Three things keep that window shut. The `repartition_swap` marker records the resolved scheme before the swap starts, so the scheme survives a worker death. The settings, the markers and the cooldown are saved together in one row-locked write (`finalize_repartition_scheme`), so there is no half-applied state to observe. And while the marker is set the table's layout is mid-change by definition, so the import activity holds this schema's syncs — unconditionally, not behind the hold rollout flag, because the alternative is corruption rather than staleness. A run that finds the marker set and temp already gone recomputes a sample of live's keys under the marker's scheme (`_live_matches_scheme`): matching means the swap finished and only its scheme write was lost, so the run saves the scheme and stops instead of rewriting the table for a layout it already has. A swap whose scheme cannot be saved raises `RepartitionSchemePersistError`, which is never classified as transient noise however transient the database error under it was, and the attempt cap never clears an unresolved swap marker.
-- **Safety.** Concurrent _syncs_ are excluded (the schedule's `OnlyOne` overlap policy plus the v3 pipeline lock), but concurrent _repartition attempts_ are not: an attempt Temporal heartbeat-times-out keeps running as a zombie (heartbeat failures are swallowed) while its retry starts, and S3 has no locking. The schema row's `repartition_claim` is the fence — each attempt mints a claim token, temp tables are scoped to it (`__repartitioned_<token>`), and the claim is re-checked before every batch write and every destructive step (temp sweep, swap marker, live delete). A superseded attempt raises `RepartitionSupersededError` and stands down silently; orphaned temp variants from superseded or crashed attempts are swept by name prefix before each fresh rebuild. A repartition failure never fails the sync — it's swallowed, retried on a later run, and capped at `MAX_REPARTITION_ATTEMPTS` (3) consecutive failures before it gives up and alerts. Cancellations, superseded attempts, transient infra errors (DB pooler drops, S3 rate limits), and budget-exceeded attempts that advanced the rewrite checkpoint don't count against that cap — a table too large to rewrite in one activity budget converges across runs via the checkpoint, and only an attempt that made no forward progress is charged. An attempt killed outright (a SIGKILLed worker runs no `except` and no `finally`) records nothing at all, so the activity's own retries judge it on the checkpoint instead: a retry re-runs the rewrite only while the attempt it retries left the checkpoint further along than it found it, because repeating a rewrite that died in place holds the sync for another activity budget and the next sync resumes from the same checkpoint anyway. The stand-down reports `reason=attempt_killed_without_progress`, and the terminal give-up carries how far the rewrite got.
+- **Safety.** Concurrent _syncs_ are excluded (the schedule's `OnlyOne` overlap policy plus the v3 pipeline lock), but concurrent _repartition attempts_ are not: an attempt Temporal heartbeat-times-out keeps running as a zombie (heartbeat failures are swallowed) while its retry starts, and S3 has no locking. The schema row's `repartition_claim` is the fence — each attempt mints a claim token, temp tables are scoped to it (`__repartitioned_<token>`), and the claim is re-checked before every batch write and every destructive step (temp sweep, swap marker, live delete). A superseded attempt raises `RepartitionSupersededError` and stands down silently; orphaned temp variants from superseded or crashed attempts are swept by name prefix before each fresh rebuild. A repartition failure never fails the sync — it's swallowed, retried on a later run, and capped at `MAX_REPARTITION_ATTEMPTS` (3) consecutive failures before it gives up and alerts. Cancellations, superseded attempts, transient infra errors (DB pooler drops, S3 rate limits), and budget-exceeded attempts that advanced the rewrite checkpoint don't count against that cap — a table too large to rewrite in one activity budget converges across runs via the checkpoint, and only an attempt that made no forward progress is charged. A panic from the native delta stack (pyo3 raises those as `BaseException`, so they do not stop at an `except Exception`) is recorded as a failure too, rather than being left to fail the activity and spend the remaining retries re-reading a log that panics in the same place. An attempt killed outright (a SIGKILLed worker runs no `except` and no `finally`) records nothing at all, so the activity's own retries judge it on the checkpoint instead: a retry re-runs the rewrite only while the attempt it retries left the checkpoint further along than it found it, because repeating a rewrite that died in place holds the sync for another activity budget and the next sync resumes from the same checkpoint anyway. The stand-down reports `reason=attempt_killed_without_progress`, and the terminal give-up carries how far the rewrite got.
Tuning and gating:
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 96839c96b777..51b95f112cec 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
@@ -88,6 +88,16 @@ def _is_cancellation(error: BaseException) -> bool:
return isinstance(error, asyncio.CancelledError) or type(error).__name__ == "CancelledError"
+def _is_native_panic(error: BaseException) -> bool:
+ """Whether `error` is a panic that escaped the native Delta/Arrow stack.
+
+ pyo3 surfaces a Rust panic as `PanicException`, which derives from `BaseException`, so it passes
+ straight through an `except Exception` handler. Matched on the type name because the module that
+ defines it (`pyo3_runtime`) only exists once an extension module has loaded it.
+ """
+ return type(error).__name__ == "PanicException"
+
+
# 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 = (
@@ -587,6 +597,20 @@ def _maybe_repartition_table(inputs: RepartitionActivityInputs, logger: Filterin
)
DELTA_REPARTITION_TOTAL.labels(team_id=str(inputs.team_id), outcome=failure_outcome).inc()
return
+ except BaseException as e:
+ if not _is_native_panic(e):
+ raise
+ # Letting the panic escape records nothing: the attempt is charged but reports no outcome, so
+ # the cap is spent by attempts that read as worker deaths and the table ends up abandoned with
+ # `RepartitionAttemptsExhausted`, which carries none of the panic's detail. It is a property
+ # of the table too (the same read panics the same way), so failing the activity only spends
+ # the remaining retries on it and holds the sync behind a rewrite that cannot finish.
+ logger.error("repartition: the rewrite panicked inside the native delta stack", exc_info=True)
+ DELTA_REPARTITION_TOTAL.labels(
+ team_id=str(inputs.team_id),
+ outcome=_handle_failure(inputs, schema, pending, trigger_reason, e, claim_token, logger, charged_attempts),
+ ).inc()
+ return
duration = time.monotonic() - start
DELTA_REPARTITION_DURATION_SECONDS.labels(team_id=str(inputs.team_id), schema_id=inputs.schema_id).observe(duration)
@@ -876,7 +900,7 @@ def _handle_failure(
schema: ExternalDataSchema,
pending: dict[str, Any] | None,
trigger_reason: str,
- error: Exception,
+ error: BaseException,
claim_token: str,
logger: FilteringBoundLogger,
charged_attempts: int | None = None,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_repartition_table.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_repartition_table.py
index 4e99a7b6979d..4d4a8e4c213f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_repartition_table.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_repartition_table.py
@@ -55,6 +55,12 @@ def _read_only_transaction_error() -> InternalError:
return error
+def _panic_exception(message: str) -> BaseException:
+ # Stands in for pyo3's PanicException, which only exists once a rust extension module has loaded
+ # it. Matched by type name in the activity, so the name is what this has to reproduce.
+ return type("PanicException", (BaseException,), {})(message)
+
+
def _schema(
*,
name: str,
@@ -755,6 +761,76 @@ class TestTransientObjectStoreFailure:
# the next sync merge against settings that no longer describe the data.
schema.clear_repartition_swap.assert_not_called()
+ @patch(f"{MODULE}.capture_exception")
+ @patch(f"{MODULE}.capture_repartition_event")
+ @patch(f"{MODULE}.HeartbeaterSync")
+ @patch(f"{MODULE}.repartition_table_in_place", new_callable=AsyncMock)
+ @patch(f"{MODULE}.DeltaTableRef")
+ @patch(f"{MODULE}.is_auto_repartition_enabled", return_value=True)
+ @patch(f"{MODULE}.ExternalDataJob")
+ @patch(f"{MODULE}.ExternalDataSchema")
+ def test_a_native_panic_is_recorded_instead_of_escaping(
+ self,
+ mock_schema_model: MagicMock,
+ _mock_job_model: MagicMock,
+ _mock_enabled: MagicMock,
+ _mock_helper_cls: MagicMock,
+ mock_repartition: AsyncMock,
+ _mock_heartbeater: MagicMock,
+ mock_capture_event: MagicMock,
+ mock_capture_exception: MagicMock,
+ ) -> None:
+ # The rust side of the delta stack panics on tables whose log is large enough to overflow an
+ # arrow offset, and pyo3 raises that as a BaseException. Escaping the activity records no
+ # outcome, so the attempt is charged but never reported and the table ends up abandoned with
+ # an error carrying none of the panic's detail. The panic repeats on every read of the same
+ # table, so failing the activity only delays the sync that runs fine on the old layout.
+ schema = _schema(name="public.usages", s3_folder_name="usages")
+ mock_schema_model.objects.select_related.return_value.get.return_value = schema
+ mock_repartition.side_effect = _panic_exception("byte array offset overflow")
+
+ _maybe_repartition_table(
+ RepartitionActivityInputs(team_id=TEAM_ID, schema_id=SCHEMA_ID, job_id=JOB_ID, source_id=SOURCE_ID),
+ MagicMock(),
+ )
+
+ mock_capture_exception.assert_called_once()
+ failed = [c.args[1] for c in mock_capture_event.call_args_list if c.args[0] == "warehouse_repartition_failed"]
+ assert len(failed) == 1
+ assert failed[0]["error_type"] == "PanicException"
+ assert "byte array offset overflow" in failed[0]["error_message"]
+ assert schema.repartition_pending["attempts"] == 1
+
+ @patch(f"{MODULE}.capture_repartition_event")
+ @patch(f"{MODULE}.HeartbeaterSync")
+ @patch(f"{MODULE}.repartition_table_in_place", new_callable=AsyncMock)
+ @patch(f"{MODULE}.DeltaTableRef")
+ @patch(f"{MODULE}.is_auto_repartition_enabled", return_value=True)
+ @patch(f"{MODULE}.ExternalDataJob")
+ @patch(f"{MODULE}.ExternalDataSchema")
+ def test_a_worker_shutdown_still_propagates(
+ self,
+ mock_schema_model: MagicMock,
+ _mock_job_model: MagicMock,
+ _mock_enabled: MagicMock,
+ _mock_helper_cls: MagicMock,
+ mock_repartition: AsyncMock,
+ _mock_heartbeater: MagicMock,
+ _mock_capture_event: MagicMock,
+ ) -> None:
+ # The panic branch must not swallow the rest of the BaseException hierarchy: a worker being
+ # torn down has to keep unwinding, or a rewrite Temporal is about to reschedule is reported
+ # as a failure.
+ schema = _schema(name="public.usages", s3_folder_name="usages")
+ mock_schema_model.objects.select_related.return_value.get.return_value = schema
+ mock_repartition.side_effect = KeyboardInterrupt()
+
+ with pytest.raises(KeyboardInterrupt):
+ _maybe_repartition_table(
+ RepartitionActivityInputs(team_id=TEAM_ID, schema_id=SCHEMA_ID, job_id=JOB_ID, source_id=SOURCE_ID),
+ MagicMock(),
+ )
+
class TestFeatureFlagGate:
@parameterized.expand(