: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): v3 loader poll resilience — statement timeout and backoff (#68919)
estefania4a6a40136a81
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/batch_consumer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/batch_consumer.pyindex e98ce7026619..4ca07c41fb0c 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/batch_consumer.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/batch_consumer.py@@ -1,6 +1,7 @@from __future__ import annotationsimport time+import randomimport signalimport asynciofrom collections import defaultdict@@ -38,6 +39,10 @@ RECONCILE_LOOKBACK_SECONDS = 24 * 60 * 60 # wide enough to catch jobs orphanedSHUTDOWN_DRAIN_TIMEOUT_SECONDS = 30.0+# Cap on the exponential backoff between failed polls — flat retries make the+# whole fleet hammer a degraded queue DB in lockstep.+POLL_BACKOFF_MAX_SECONDS = 30.0+# Per-poll fetch cap multiplier: fetch at most (free slots x this) batches so a poll# never leases far more groups than it can dispatch. Runs average ~2 batches per# group (batch 0 + final), so x3 gives headroom for multi-batch runs without@@ -77,6 +82,9 @@ class BatchConsumerConfig:connect_timeout_seconds: int = 10poll_timeout_seconds: float | None = 180.0sweep_timeout_seconds: float | None = 300.0+ # Added to each connection's client ceiling to form its server-side+ # statement_timeout, so an abandoned poll or sweep can't keep burning DB CPU.+ statement_timeout_margin_seconds: float = 30.0# When set, the consumer stops reporting itself healthy once any single batch# has been executing longer than this, so a wedged sink connection turns into# a liveness-probe restart instead of an indefinite, invisible stall.@@ -252,11 +260,20 @@ class BatchConsumer:def _lease_ttl_seconds(self) -> int:return self._config.lease_ttl_seconds or self._config.recovery_grace_seconds or RECOVERY_GRACE_SECONDS- async def _connect(self) -> psycopg.AsyncConnection[Any]:+ def _statement_timeout_options(self, client_timeout_seconds: float | None) -> str | None:+ """libpq options for the server-side statement_timeout backstop; None when+ the client ceiling is disabled (same "0 disables" contract)."""+ if not client_timeout_seconds:+ return None+ timeout_ms = int((client_timeout_seconds + self._config.statement_timeout_margin_seconds) * 1000)+ return f"-c statement_timeout={timeout_ms}"++ async def _connect(self, *, statement_timeout_options: str | None = None) -> psycopg.AsyncConnection[Any]:return await psycopg.AsyncConnection.connect(self._config.database_url,autocommit=True,connect_timeout=self._config.connect_timeout_seconds,+ options=statement_timeout_options,)async def _drop_conn(self, attr: str) -> None:@@ -281,7 +298,9 @@ class BatchConsumer:async with self._poll_conn_lock:if self._poll_conn is None or self._poll_conn.closed or self._poll_conn.broken:logger.warning(self._event("queue_db_poll_connection_reconnecting"))- self._poll_conn = await self._connect()+ self._poll_conn = await self._connect(+ statement_timeout_options=self._statement_timeout_options(self._config.poll_timeout_seconds)+ )return self._poll_connasync def _ensure_recovery_conn(self) -> psycopg.AsyncConnection[Any]:@@ -291,7 +310,9 @@ class BatchConsumer:async with self._recovery_conn_lock:if self._recovery_conn is None or self._recovery_conn.closed or self._recovery_conn.broken:logger.warning(self._event("queue_db_recovery_connection_reconnecting"))- self._recovery_conn = await self._connect()+ self._recovery_conn = await self._connect(+ statement_timeout_options=self._statement_timeout_options(self._config.sweep_timeout_seconds)+ )return self._recovery_connasync def _wait_or_shutdown(self, timeout: float) -> None:@@ -303,8 +324,12 @@ class BatchConsumer:async def run(self) -> None:self._install_signal_handlers()- self._poll_conn = await self._connect()- self._recovery_conn = await self._connect()+ self._poll_conn = await self._connect(+ statement_timeout_options=self._statement_timeout_options(self._config.poll_timeout_seconds)+ )+ self._recovery_conn = await self._connect(+ statement_timeout_options=self._statement_timeout_options(self._config.sweep_timeout_seconds)+ )logger.info(self._event("batch_consumer_started"),@@ -353,13 +378,13 @@ class BatchConsumer:)self._note_poll_failure("timeout", duration=time.monotonic() - poll_start)await self._drop_conn("_poll_conn")- await self._wait_or_shutdown(self._config.poll_interval_seconds)+ await self._wait_or_shutdown(self._poll_retry_delay())continueexcept psycopg.OperationalError as e:logger.exception(self._event("poll_failed_queue_db_unreachable"))capture_exception(e)self._note_poll_failure("db_unreachable", duration=time.monotonic() - poll_start)- await self._wait_or_shutdown(self._config.poll_interval_seconds)+ await self._wait_or_shutdown(self._poll_retry_delay())continueself._consecutive_poll_failures = 0poll_duration = time.monotonic() - poll_start@@ -893,6 +918,14 @@ class BatchConsumer:self._metrics.poll_failures_total.labels(reason=reason).inc()self._metrics.poll_duration_seconds.observe(duration)+ def _poll_retry_delay(self) -> float:+ """Capped, jittered backoff before retrying a failed poll: a degraded queue DB+ gets exponentially less pressure and the fleet's retries desynchronize."""+ base = self._config.poll_interval_seconds+ failures = max(self._consecutive_poll_failures, 1)+ backoff = min(base * 2 ** (failures - 1), POLL_BACKOFF_MAX_SECONDS)+ return backoff + random.uniform(0, base)+def _report_health(self) -> None:"""Report liveness, unless the stuck-batch watchdog or the poll-failure trip fired.diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_consumer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_consumer.pyindex 355e4d9277f8..bdbaee461af7 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_consumer.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_consumer.py@@ -494,7 +494,9 @@ class TestQueueOperationTimeouts:return []with (- patch.object(consumer, "_connect", new_callable=AsyncMock, side_effect=lambda: _make_healthy_conn()),+ patch.object(+ consumer, "_connect", new_callable=AsyncMock, side_effect=lambda **kwargs: _make_healthy_conn()+ ),patch.object(consumer, "_install_signal_handlers"),patch("products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.get_stale_executing",@@ -536,7 +538,9 @@ class TestQueueOperationTimeouts:return []with (- patch.object(consumer, "_connect", new_callable=AsyncMock, side_effect=lambda: _make_healthy_conn()),+ patch.object(+ consumer, "_connect", new_callable=AsyncMock, side_effect=lambda **kwargs: _make_healthy_conn()+ ),patch.object(consumer, "_install_signal_handlers"),patch("products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.get_stale_executing",@@ -598,7 +602,9 @@ class TestPollFailureLiveness:return []with (- patch.object(consumer, "_connect", new_callable=AsyncMock, side_effect=lambda: _make_healthy_conn()),+ patch.object(+ consumer, "_connect", new_callable=AsyncMock, side_effect=lambda **kwargs: _make_healthy_conn()+ ),patch.object(consumer, "_install_signal_handlers"),patch("products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.get_stale_executing",@@ -621,6 +627,65 @@ class TestPollFailureLiveness:await asyncio.wait_for(run_task, timeout=5.0)+class TestStatementTimeoutBackstop:+ @pytest.mark.parametrize(+ "client_timeout,expected",+ [+ (180.0, "-c statement_timeout=210000"), # 180s + 30s margin, in ms+ (None, None), # disabled client ceiling disables the backstop too+ (0, None),+ ],+ )+ def test_option_string_tracks_client_timeout(self, client_timeout, expected):+ consumer = _make_consumer(statement_timeout_margin_seconds=30.0)+ assert consumer._statement_timeout_options(client_timeout) == expected++ @pytest.mark.asyncio+ async def test_poll_reconnect_applies_statement_timeout(self):+ # A reconnect that drops the backstop lets an abandoned query keep+ # burning queue-DB CPU — the exact failure the timeout guards against.+ consumer = _make_consumer(poll_timeout_seconds=180.0, statement_timeout_margin_seconds=30.0)+ consumer._poll_conn = _make_healthy_conn(closed=True) # force the reconnect branch+ captured: dict[str, Any] = {}++ async def fake_connect(*, statement_timeout_options: str | None = None) -> AsyncMock:+ captured["options"] = statement_timeout_options+ return _make_healthy_conn()++ with patch.object(consumer, "_connect", side_effect=fake_connect):+ await consumer._ensure_poll_conn()++ assert captured["options"] == "-c statement_timeout=210000"+++class TestPollBackoff:+ def test_delay_grows_exponentially_and_caps(self):+ # Losing the backoff means lockstep fleet retries; losing the cap means+ # unbounded delays.+ consumer = _make_consumer(poll_interval_seconds=2.0)+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.batch_consumer.random.uniform",+ return_value=0.0,+ ):+ consumer._consecutive_poll_failures = 1+ assert consumer._poll_retry_delay() == 2.0+ consumer._consecutive_poll_failures = 2+ assert consumer._poll_retry_delay() == 4.0+ consumer._consecutive_poll_failures = 3+ assert consumer._poll_retry_delay() == 8.0+ consumer._consecutive_poll_failures = 20 # far past the cap+ assert consumer._poll_retry_delay() == 30.0 # POLL_BACKOFF_MAX_SECONDS++ def test_jitter_is_added_within_one_interval(self):+ consumer = _make_consumer(poll_interval_seconds=2.0)+ consumer._consecutive_poll_failures = 1+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.batch_consumer.random.uniform",+ return_value=1.5,+ ):+ assert consumer._poll_retry_delay() == 3.5 # 2.0 backoff + 1.5 jitter++class TestFailRun:@pytest.mark.asyncioasync def test_does_not_raise_when_job_status_update_fails(self):@@ -835,7 +900,7 @@ class TestConnectionRecovery:consumer._poll_conn = _make_healthy_conn(closed=True)fresh = _make_healthy_conn()- async def slow_connect() -> AsyncMock:+ async def slow_connect(**kwargs: Any) -> AsyncMock:await asyncio.sleep(0) # yield so the other coroutines reach the check while we're "dialing"return fresh