: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): retry admin repartition in-run on transient errors (#75530)
Daniel RC4ca537f58aec
diff --git a/posthog/temporal/common/posthog_client.py b/posthog/temporal/common/posthog_client.pyindex 53255e422cc1..080bc8b3f415 100644--- a/posthog/temporal/common/posthog_client.py+++ b/posthog/temporal/common/posthog_client.py@@ -24,8 +24,9 @@ from posthog.temporal.common.shutdown import WorkerShuttingDownErrorlogger = get_write_only_logger()# ApplicationError types that are expected control flow (e.g. activity-retry-as-poll-# probes), not defects — same reasoning as the EgressBudgetExhausted exemption below.-EXPECTED_CONTROL_FLOW_ERROR_TYPES = frozenset({"trace_not_settled"})+# probes, retryable transient-infra re-raises), not defects — same reasoning as the+# EgressBudgetExhausted exemption below.+EXPECTED_CONTROL_FLOW_ERROR_TYPES = frozenset({"trace_not_settled", "TransientRepartitionError"})def _tag_team_id_on_current_span(input: ExecuteActivityInput | ExecuteWorkflowInput) -> None:diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test_repartition_controller.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test_repartition_controller.pyindex 3efceab0d936..ee81a2bb154c 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test_repartition_controller.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test_repartition_controller.py@@ -12,6 +12,7 @@ import pyarrow as paimport deltalake as deltalakeimport structlogfrom asgiref.sync import async_to_sync+from temporalio.exceptions import ApplicationErrorfrom temporalio.testing import ActivityEnvironmentfrom products.warehouse_sources.backend.models.external_data_job import ExternalDataJob@@ -583,6 +584,37 @@ class TestRepartitionActivity:assert schema.repartition_pending is not Noneassert schema.repartition_pending["attempts"] == 0+ def test_admin_transient_infra_error_reraises_for_activity_retry(self, team):+ # An operator staged this rewrite (trigger_reason "admin") because syncing on the old layout is+ # pathological — deferring a transient blip to the next sync runs that crawl first. The activity+ # must re-raise retryable so Temporal re-runs the rewrite in this run, while still emitting no+ # failure event and consuming no attempt (in-run retries must not exhaust the budget on infra+ # noise). ActivityEnvironment bypasses the worker interceptor chain, so this does NOT cover the+ # error-tracking exemption for the re-raise — that lives in EXPECTED_CONTROL_FLOW_ERROR_TYPES+ # (posthog_client.py), keyed on the ApplicationError's type string.+ schema = _make_schema(team, {})+ schema.set_repartition_pending(+ {+ "partition_mode": "md5",+ "partition_count": 4,+ "partition_keys": ["id"],+ "trigger_reason": "admin",+ "attempts": 0,+ }+ )+ mocked = AsyncMock(side_effect=OperationalError("server closed the connection unexpectedly"))+ 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(ApplicationError):+ 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+@pytest.mark.parametrize("error,still_claimant",[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.pyindex a7bc22706173..f0163aa3acba 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@@ -4,7 +4,9 @@ Runs inside `ExternalDataJobWorkflow` after the pipeline lock is held and beforethe sole writer for the schema (the schedule's OnlyOne overlap policy + the v3 pipeline lock guaranteeno concurrent sync). Acting on a pending target *before* the merge means the merge that follows in thesame run uses the new, memory-safe layout. A repartition failure never fails the workflow — the sync-just proceeds on the old layout (status quo) and the table is retried on a later run.+just proceeds on the old layout (status quo) and the table is retried on a later run. The one nuance:+a transient infra error during an admin-staged rewrite re-raises retryable so the activity's retry+policy re-runs it in this run (the workflow swallows the failure if retries exhaust)."""import time@@ -20,6 +22,7 @@ from asgiref.sync import async_to_syncfrom structlog.contextvars import bind_contextvarsfrom structlog.types import FilteringBoundLoggerfrom temporalio import activity+from temporalio.exceptions import ApplicationErrorfrom posthog.exceptions_capture import capture_exceptionfrom posthog.temporal.common.heartbeat_sync import HeartbeaterSync@@ -331,11 +334,25 @@ def _maybe_repartition_table(inputs: RepartitionActivityInputs, logger: Filterinif _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.+ # retrying is always safe. Don't consume an attempt or emit a failure event.+ DELTA_REPARTITION_TOTAL.labels(team_id=str(inputs.team_id), outcome="transient").inc()+ if trigger_reason == "admin":+ # An operator staged this rewrite precisely because syncing on the old layout is+ # pathological (e.g. a badly over-partitioned table merging one commit per partition+ # for hours). Deferring to the next sync would run that crawl first, so re-raise+ # retryable and let the activity's retry policy re-run the rewrite now; the claim+ # fencing handles any zombie, and if attempts exhaust the workflow still swallows the+ # failure and syncs on the old layout. No capture_exception here and the error type is+ # exempted in EXPECTED_CONTROL_FLOW_ERROR_TYPES: retries are expected control flow,+ # and error-tracking events here would spam (and can trigger automated remediation);+ # the log line and the transient metric carry the visibility.+ logger.warning("repartition: transient infra error, re-raising for activity retry", exc_info=True)+ raise ApplicationError(+ f"Transient infra error during admin-staged repartition: {e}",+ type="TransientRepartitionError",+ ) from elogger.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()returnfailure_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()