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-imports): classify queue-db connect timeouts as transient (#81543)

Tom Owersa1ef953d13da
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.py
index ffb1fd068922..46ddb6f922a5 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
@@ -92,6 +92,17 @@ def _is_server_not_ready_error(error: BaseException) -> bool:
return any(substring in message for substring in _SERVER_NOT_READY_ERROR_SUBSTRINGS)
+# psycopg raises ConnectionTimeout only while *establishing* a connection, never mid-query. Every
+# caller here reconnects to a queue DB it (or a sibling pod) was already talking to moments earlier,
+# so a connect-time timeout is the queue DB being momentarily slow to accept, not a config problem —
+# the same self-healing shape as the DNS and server-not-ready refusals above. Mirrors the source-side
+# `_is_dropped_or_connect_timeout` in sources/postgres/postgres.py, which treats a connect timeout on
+# its read/sync path the same way (as opposed to schema discovery, where a timeout usually means a
+# now-unreachable host and is deliberately left to fail fast).
+def _is_connect_timeout_error(error: BaseException) -> bool:
+ return isinstance(error, psycopg.errors.ConnectionTimeout)
+
+
class OwnershipLostError(Exception):
"""Raised when the group lease for a (team_id, schema_id) is no longer held by this consumer."""
@@ -476,6 +487,8 @@ class BatchConsumer:
logger.warning(self._event("poll_failed_queue_db_dns_unavailable"), error=str(e))
elif _is_server_not_ready_error(e):
logger.warning(self._event("poll_failed_queue_db_starting_up"), error=str(e))
+ elif _is_connect_timeout_error(e):
+ logger.warning(self._event("poll_failed_queue_db_connect_timeout"), error=str(e))
else:
logger.exception(self._event("poll_failed_queue_db_unreachable"))
capture_exception(e)
@@ -1073,6 +1086,8 @@ class BatchConsumer:
logger.warning(self._event("recovery_sweep_dns_unavailable"), error=str(e))
elif _is_server_not_ready_error(e):
logger.warning(self._event("recovery_sweep_db_starting_up"), error=str(e))
+ elif _is_connect_timeout_error(e):
+ logger.warning(self._event("recovery_sweep_connect_timeout"), error=str(e))
else:
logger.exception(self._event("recovery_sweep_error"))
capture_exception(e)
@@ -1097,6 +1112,8 @@ class BatchConsumer:
logger.warning(self._event("reconcile_sweep_dns_unavailable"), error=str(e))
elif _is_server_not_ready_error(e):
logger.warning(self._event("reconcile_sweep_db_starting_up"), error=str(e))
+ elif _is_connect_timeout_error(e):
+ logger.warning(self._event("reconcile_sweep_connect_timeout"), error=str(e))
else:
logger.exception(self._event("reconcile_sweep_error"))
capture_exception(e)
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.py
index 03fc7baa885d..fd477bb5f41f 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
@@ -15,6 +15,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline
)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.batch_consumer import (
OwnershipLostError,
+ _is_connect_timeout_error,
_is_dns_resolution_transient_error,
_is_server_not_ready_error,
)
@@ -635,6 +636,126 @@ class TestDnsResolutionTransientErrorClassification:
mock_capture.assert_not_called()
+class TestConnectTimeoutErrorClassification:
+ def test_classifies_connection_timeout(self) -> None:
+ assert _is_connect_timeout_error(psycopg.errors.ConnectionTimeout("connection timeout expired")) is True
+
+ def test_ignores_other_operational_errors(self) -> None:
+ # A generic OperationalError carrying similar wording is not the same as psycopg's
+ # dedicated connect-time ConnectionTimeout class and must not be misclassified.
+ assert _is_connect_timeout_error(psycopg.OperationalError("connection timeout expired")) is False
+
+ @pytest.mark.asyncio
+ async def test_recovery_loop_does_not_report_connect_timeout_error(self):
+ # Reproduces the reported issue: the recovery connection times out while
+ # reconnecting for the periodic reconcile sweep. This is a connect-time-only
+ # failure (psycopg never raises ConnectionTimeout mid-query), and the sweep
+ # already retries every interval, so it must not be sent to error tracking.
+ config = ConsumerConfig(
+ database_url="postgres://unused:unused@localhost/unused",
+ recovery_interval_seconds=0.01,
+ reconcile_interval_seconds=0,
+ )
+ consumer = BatchConsumer(config=config, process_batch=AsyncMock())
+ consumer._recovery_conn = _make_healthy_conn()
+
+ second_reconcile_started = asyncio.Event()
+ call_count = 0
+
+ async def flaky_reconcile() -> None:
+ nonlocal call_count
+ call_count += 1
+ if call_count == 1:
+ raise psycopg.errors.ConnectionTimeout("connection timeout expired")
+ second_reconcile_started.set()
+
+ with (
+ patch.object(consumer, "_recovery_sweep_with_timeout", new_callable=AsyncMock),
+ patch.object(consumer, "_reconcile_failed_runs", side_effect=flaky_reconcile),
+ patch(f"{batch_consumer_module.__name__}.capture_exception") as mock_capture,
+ ):
+ loop_task = asyncio.create_task(consumer._recovery_loop())
+ await asyncio.wait_for(second_reconcile_started.wait(), timeout=2.0)
+ consumer._shutdown.set()
+ await asyncio.wait_for(loop_task, timeout=5.0)
+
+ mock_capture.assert_not_called()
+
+ @pytest.mark.asyncio
+ async def test_poll_failure_does_not_report_connect_timeout_error(self):
+ # Same self-healing connect-time timeout as above, but hit directly by the main
+ # poll loop's own OperationalError branch rather than the recovery loop.
+ config = ConsumerConfig(
+ database_url="postgres://unused:unused@localhost/unused",
+ poll_interval_seconds=0.01,
+ )
+ consumer = BatchConsumer(config=config, process_batch=AsyncMock())
+
+ second_poll_started = asyncio.Event()
+ fetch_calls = 0
+
+ async def flaky_fetch(*args: Any, **kwargs: Any) -> list[PendingBatch]:
+ nonlocal fetch_calls
+ fetch_calls += 1
+ if fetch_calls == 1:
+ raise psycopg.errors.ConnectionTimeout("connection timeout expired")
+ second_poll_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",
+ 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=flaky_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())
+ await asyncio.wait_for(second_poll_started.wait(), timeout=2.0)
+ consumer._shutdown.set()
+ await asyncio.wait_for(run_task, timeout=5.0)
+
+ mock_capture.assert_not_called()
+
+ @pytest.mark.asyncio
+ async def test_recovery_sweep_does_not_report_connect_timeout_error(self):
+ # Same self-healing connect-time timeout, but hit by the periodic recovery
+ # sweep's own OperationalError branch rather than the reconcile sweep.
+ consumer = _make_consumer(recovery_interval_seconds=0.01)
+ swept = asyncio.Event()
+
+ async def raise_connect_timeout(*args: Any, **kwargs: Any) -> list[PendingBatch]:
+ swept.set()
+ raise psycopg.errors.ConnectionTimeout("connection timeout expired")
+
+ with (
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.get_stale_executing",
+ side_effect=raise_connect_timeout,
+ ),
+ patch.object(consumer, "_reconcile_failed_runs", new_callable=AsyncMock),
+ patch(f"{batch_consumer_module.__name__}.capture_exception") as mock_capture,
+ ):
+ loop_task = asyncio.create_task(consumer._recovery_loop())
+ await asyncio.wait_for(swept.wait(), timeout=2.0)
+ consumer._shutdown.set()
+ await asyncio.wait_for(loop_task, timeout=5.0)
+
+ mock_capture.assert_not_called()
+
+
class TestStartupLiveness:
@pytest.mark.asyncio
async def test_heartbeat_reports_liveness_while_startup_sweep_runs(self):