: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(google_search_console): retry transient DB pool timeouts when fetching integration (#66895)
Tom Owers9d70c010b0e9
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/google_search_console/google_search_console.py b/products/warehouse_sources/backend/temporal/data_imports/sources/google_search_console/google_search_console.pyindex c2e7f646561f..837e1efdc227 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/google_search_console/google_search_console.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/google_search_console/google_search_console.py@@ -7,7 +7,7 @@ from typing import Anyfrom urllib.parse import parse_qs, quote, unquote, urlparse, urlunparsefrom django.conf import settings-from django.db import close_old_connections+from django.db import OperationalError, close_old_connectionsimport requestsimport structlog@@ -166,13 +166,42 @@ def suggest_registered_site(site_url: str, registered: collections.abc.Iterable[return None+def _backoff_sleep(attempt: int) -> None:+ """Sleep before the next retry: linear growth capped at 30s (2s, 4s, 6s, ...)."""+ time.sleep(min(2 * attempt, 30))+++_MAX_INTEGRATION_FETCH_ATTEMPTS = 4+++def _get_integration(integration_id: int, team_id: int) -> Integration:+ """Fetch the OAuth ``Integration`` row, retrying a transient DB failure with backoff.++ Temporal activities run in a long-lived worker outside Django's request cycle, and this+ read happens lazily inside `get_rows` after the connection has often sat idle for minutes.+ A pooled Postgres connection can be closed server-side while idle, or the connection pooler+ can reject the query with a wait timeout (`query_wait_timeout`) when the pool is saturated.+ Both surface as a transient ``OperationalError`` that clears once a healthy connection is+ used. ``close_old_connections()`` evicts connections already known to be stale (and, after a+ failed query marks one unusable, drops it), so each attempt runs on a fresh connection; the+ short backoff also gives a saturated pool time to drain rather than retrying straight back+ into the same wait timeout. This read is idempotent, so repeating it is safe.+ ``Integration.DoesNotExist`` is left to propagate.+ """+ attempt = 0+ while True:+ close_old_connections()+ try:+ return Integration.objects.get(id=integration_id, team_id=team_id)+ except OperationalError:+ attempt += 1+ if attempt >= _MAX_INTEGRATION_FETCH_ATTEMPTS:+ raise+ _backoff_sleep(attempt)++def _credentials(integration_id: int, team_id: int) -> OAuthCredentials:- # Temporal activities run in a thread pool where Django DB connections can go- # stale between uses (Postgres closes the connection server-side). This is- # invoked lazily from inside `get_rows`, so the connection has often been idle- # for minutes by the time we reach it — drop any stale connection first.- close_old_connections()- integration = Integration.objects.get(id=integration_id, team_id=team_id)+ integration = _get_integration(integration_id, team_id)return OAuthCredentials(token=None,refresh_token=integration.refresh_token,diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/google_search_console/tests/test_google_search_console.py b/products/warehouse_sources/backend/temporal/data_imports/sources/google_search_console/tests/test_google_search_console.pyindex 466d3042fc4e..4596624629e0 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/google_search_console/tests/test_google_search_console.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/google_search_console/tests/test_google_search_console.py@@ -3,6 +3,8 @@ import datetime as dtimport pytestfrom unittest import mock+from django.db import OperationalError+import requestsfrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import (@@ -18,6 +20,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.google_seaGoogleSearchConsoleQuotaExceededError,GoogleSearchConsoleResumeConfig,_credentials,+ _get_integration,_initial_start_date,_is_daily_quota_error,_is_quota_error,@@ -140,6 +143,46 @@ def test_credentials_refreshes_stale_db_connection_before_query(monkeypatch):assert creds.refresh_token == "refresh-token"+def test_get_integration_rides_out_pool_wait_timeout_then_succeeds(monkeypatch):+ # A saturated connection pooler rejects the query with `query_wait_timeout`; the short+ # backoff lets the pool drain so a later attempt on a fresh connection succeeds.+ integration = mock.MagicMock()+ get = mock.Mock(+ side_effect=[+ OperationalError("query_wait_timeout"),+ OperationalError("query_wait_timeout"),+ integration,+ ]+ )++ monkeypatch.setattr(gsc, "close_old_connections", lambda: None)+ monkeypatch.setattr(gsc.Integration.objects, "get", get)+ sleeps: list[float] = []+ monkeypatch.setattr(gsc.time, "sleep", lambda seconds: sleeps.append(seconds))++ result = _get_integration(integration_id=1, team_id=2)++ assert result is integration+ assert get.call_count == 3+ assert sleeps == [2, 4]+++def test_get_integration_reraises_after_exhausting_attempts(monkeypatch):+ get = mock.Mock(side_effect=OperationalError("query_wait_timeout"))++ monkeypatch.setattr(gsc, "close_old_connections", lambda: None)+ monkeypatch.setattr(gsc.Integration.objects, "get", get)+ sleeps: list[float] = []+ monkeypatch.setattr(gsc.time, "sleep", lambda seconds: sleeps.append(seconds))++ with pytest.raises(OperationalError):+ _get_integration(integration_id=1, team_id=2)++ # Bounded attempts: it gives up rather than looping forever, leaving Temporal to retry the activity.+ assert get.call_count == 4+ assert sleeps == [2, 4, 6]++def _make_response(config: GoogleSearchConsoleSourceConfig, rows_per_call: list[list[dict]]):"""Build a SourceResponse where _query_search_analytics returns the given pages in order."""inputs = mock.MagicMock()