: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): don't crash the batch consumer on a failed startup recovery sweep (#87145)
Tom Owerse08b5a35fb8b
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 e1801a70ee5c..9b52e71eab2e 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@@ -453,7 +453,26 @@ class BatchConsumer:# scans the whole queue and can outlast the health server's startup# grace window, and a pod liveness-killed mid-sweep can never boot.self._heartbeat_task = asyncio.create_task(self._heartbeat_loop())- await self._recovery_sweep_with_timeout()+ try:+ await self._recovery_sweep_with_timeout()+ except psycopg.OperationalError as e:+ # Mirrors _recovery_loop's handling of the same call: a queue DB that+ # isn't reachable yet on startup must not crash the consumer, since the+ # periodic recovery loop tolerates the identical failure once running.+ if _is_dns_resolution_transient_error(e):+ logger.warning(self._event("startup_sweep_dns_unavailable"), error=str(e))+ elif _is_server_not_ready_error(e):+ logger.warning(self._event("startup_sweep_db_starting_up"), error=str(e))+ elif _is_connect_timeout_error(e):+ logger.warning(self._event("startup_sweep_connect_timeout"), error=str(e))+ elif _is_admin_shutdown_error(e):+ logger.warning(self._event("startup_sweep_admin_shutdown"), error=str(e))+ else:+ logger.exception(self._event("startup_sweep_error"))+ capture_exception(e)+ except Exception as e:+ logger.exception(self._event("startup_sweep_error"))+ capture_exception(e)self._recovery_task = asyncio.create_task(self._recovery_loop())while not self._shutdown.is_set():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 c1ba60aa4f3e..3db4aec438e5 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@@ -1018,6 +1018,54 @@ class TestQueueOperationTimeouts:consumer._shutdown.set()await asyncio.wait_for(run_task, timeout=5.0)+ @pytest.mark.asyncio+ async def test_startup_sweep_error_does_not_crash_consumer_and_polling_starts(self):+ # Reproduces the reported issue: a schema-level failure (e.g. the queue DB+ # missing its tables) during the one-time startup sweep used to propagate out+ # of run() uncaught, crashing the consumer -- even though the periodic+ # _recovery_loop already tolerates the identical failure from the same call.+ 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()++ async def raise_undefined_table(*args: Any, **kwargs: Any) -> list[PendingBatch]:+ raise psycopg.errors.UndefinedTable('relation "sourcebatch" does not exist')++ async def fetch(*args: Any, **kwargs: Any) -> list[PendingBatch]:+ polling_started.set()+ return []++ with (+ 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",+ side_effect=raise_undefined_table,+ ),+ 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,+ ),+ patch(f"{batch_consumer_module.__name__}.capture_exception") as mock_capture,+ ):+ run_task = asyncio.create_task(consumer.run())+ # Polling can only begin if the startup sweep error was contained 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)++ mock_capture.assert_called_once()+@pytest.mark.asyncioasync def test_poll_timeout_wrapped_as_operational_error_is_not_reported(self):# psycopg's async wait loop can catch the CancelledError that