: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-imports): retry a startup DNS blip instead of crashing the queue consumer (#114288)
Tom Owersae6f60b3e1cc
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 d5a63c3a5629..09ddc558aa01 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@@ -1362,6 +1362,59 @@ class TestQueueOperationTimeouts:mock_capture.assert_called_once()+ @pytest.mark.asyncio+ async def test_startup_connect_retries_a_dns_blip_instead_of_crashing(self):+ # Reproduces the reported issue: the queue DB being unreachable for a DNS blip when+ # this process starts used to raise straight out of run() uncaught -- crashing the+ # whole consumer -- even though every other connect path here (the poll loop, the+ # recovery loop, _ensure_poll_conn/_ensure_recovery_conn) already redials through the+ # identical error instead of giving up.+ config = ConsumerConfig(+ database_url="postgres://unused:unused@localhost/unused",+ poll_interval_seconds=0.01,+ )+ consumer = BatchConsumer(config=config, process_batch=AsyncMock())++ polling_started = asyncio.Event()+ connect_attempts = 0++ async def flaky_connect(**kwargs: Any) -> Any:+ nonlocal connect_attempts+ connect_attempts += 1+ if connect_attempts == 1:+ raise psycopg.OperationalError("[Errno -3] Temporary failure in name resolution")+ return _make_healthy_conn()++ async def fetch(*args: Any, **kwargs: Any) -> list[PendingBatch]:+ polling_started.set()+ return []++ with (+ patch.object(consumer, "_connect", side_effect=flaky_connect),+ patch(f"{batch_consumer_module.__name__}._queue_retry_delay", return_value=0),+ patch.object(consumer, "_install_signal_handlers"),+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.get_stale_executing",+ new_callable=AsyncMock,+ return_value=[],+ ),+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.get_unprocessed_and_lock",+ side_effect=fetch,+ ),+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.release_all_owned_leases",+ new_callable=AsyncMock,+ ),+ ):+ run_task = asyncio.create_task(consumer.run())+ # Polling can only begin if the startup DNS blip was retried instead of crashing run().+ await asyncio.wait_for(polling_started.wait(), timeout=2.0)+ consumer._shutdown.set()+ await asyncio.wait_for(run_task, timeout=5.0)++ assert connect_attempts >= 2+@pytest.mark.asyncioasync def test_poll_timeout_wrapped_as_operational_error_is_not_reported(self):# psycopg's async wait loop can catch the CancelledError thatdiff --git a/products/warehouse_sources_queue/backend/core/batch_consumer.py b/products/warehouse_sources_queue/backend/core/batch_consumer.pyindex 90d631aa7af9..48cdccb83dd4 100644--- a/products/warehouse_sources_queue/backend/core/batch_consumer.py+++ b/products/warehouse_sources_queue/backend/core/batch_consumer.py@@ -559,6 +559,31 @@ class BatchConsumer:raisereturn conn+ async def _connect_with_startup_retry(+ self, *, statement_timeout_seconds: float | None, event: str+ ) -> psycopg.AsyncConnection[Any]:+ """Dial the queue DB at startup, retrying a self-healing blip indefinitely.++ `_connect` only retries QUEUE_RETRY_MAX_ATTEMPTS times before raising -- enough for a+ blip mid-run, where the poll and recovery loops simply redial on the next cycle, but+ not for the queue DB still being unreachable the moment this process starts. Raising+ here crashes the whole consumer before `_poll_conn`/`_recovery_conn` even exist, for+ the same DNS, server-not-ready, connect-timeout, and admin-shutdown shapes the running+ consumer already treats as self-healing everywhere else.+ """+ attempt = 0+ while True:+ attempt += 1+ try:+ return await self._connect(statement_timeout_seconds=statement_timeout_seconds)+ except Exception as error:+ if not _is_transient_queue_db_error(error):+ raise+ logger.warning(self._event(event), attempt=attempt, error=str(error))+ await self._wait_or_shutdown(_queue_retry_delay(min(attempt, QUEUE_RETRY_MAX_ATTEMPTS)))+ if self._shutdown.is_set():+ raise+async def _drop_conn(self, attr: str) -> None:"""Close and forget a connection after a timed-out operation.@@ -692,8 +717,14 @@ class BatchConsumer:async def run(self) -> None:self._install_signal_handlers()- self._poll_conn = await self._connect(statement_timeout_seconds=self._config.poll_timeout_seconds)- self._recovery_conn = await self._connect(statement_timeout_seconds=self._config.sweep_timeout_seconds)+ self._poll_conn = await self._connect_with_startup_retry(+ statement_timeout_seconds=self._config.poll_timeout_seconds,+ event="startup_poll_connect_retrying",+ )+ self._recovery_conn = await self._connect_with_startup_retry(+ statement_timeout_seconds=self._config.sweep_timeout_seconds,+ event="startup_recovery_connect_retrying",+ )logger.info(self._event("batch_consumer_started"),