: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_analytics): retry transient DB pool timeout when fetching integration (#66899)
Tom Owersd4a9869a3ff6
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/google_analytics/google_analytics.py b/products/warehouse_sources/backend/temporal/data_imports/sources/google_analytics/google_analytics.pyindex df01797c2402..bc2a84e7be09 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/google_analytics/google_analytics.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/google_analytics/google_analytics.py@@ -5,7 +5,7 @@ import collections.abcfrom typing import Anyfrom django.conf import settings-from django.db import close_old_connections+from django.db import OperationalError, close_old_connectionsimport requestsimport structlog@@ -70,12 +70,41 @@ class GoogleAnalyticsResumeConfig:offset: int # next row offset within that chunk+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 that never goes through Django's request+ cycle, so a pooled Postgres connection can be closed server-side while it sits idle, or the+ connection pooler can reject the query with a wait timeout when the pool is saturated. Both+ surface as a transient ``OperationalError`` and both clear 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 it is safe to repeat. ``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:- # Invoked lazily from inside `get_rows` on a worker thread, so the pooled- # Django connection has often been idle long enough for Postgres to close it- # server-side — drop any stale connection before the ORM read.- 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_analytics/tests/test_google_analytics.py b/products/warehouse_sources/backend/temporal/data_imports/sources/google_analytics/tests/test_google_analytics.pyindex 1821c417288a..61182bdcab8b 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/google_analytics/tests/test_google_analytics.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/google_analytics/tests/test_google_analytics.py@@ -5,8 +5,12 @@ from typing import Any, castimport pytestfrom unittest import mock+from django.db import OperationalError+import requests+from posthog.models.integration import Integration+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import (GoogleAnalyticsSourceConfig,)@@ -20,6 +24,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.google_anaGoogleAnalyticsResumeConfig,_convert_metric_value,_credentials,+ _get_integration,_initial_start_date,_is_quota_error,_is_retryable_server_error,@@ -206,6 +211,67 @@ def test_credentials_refreshes_stale_db_connection_before_query(monkeypatch):assert creds.refresh_token == "refresh-token"+_INTEGRATION_GET_PATH = (+ "products.warehouse_sources.backend.temporal.data_imports.sources.google_analytics.google_analytics."+ "Integration.objects.get"+)+_CLOSE_CONNECTIONS_PATH = (+ "products.warehouse_sources.backend.temporal.data_imports.sources.google_analytics.google_analytics."+ "close_old_connections"+)+_SLEEP_PATH = (+ "products.warehouse_sources.backend.temporal.data_imports.sources.google_analytics.google_analytics.time.sleep"+)+++class TestGetIntegrationDbResilience:+ def test_rides_out_pool_wait_timeout_then_succeeds(self):+ integration = object()+ get = mock.Mock(+ side_effect=[+ OperationalError("query_wait_timeout"),+ OperationalError("query_wait_timeout"),+ integration,+ ]+ )++ with (+ mock.patch(_INTEGRATION_GET_PATH, get),+ mock.patch(_CLOSE_CONNECTIONS_PATH),+ mock.patch(_SLEEP_PATH) as sleep,+ ):+ result = _get_integration(integration_id=1, team_id=2)++ assert result is integration+ assert get.call_count == 3+ # Backoff grows per attempt per `min(2 * attempt, 30)`: 2s after the 1st failure, 4s after the 2nd.+ assert sleep.call_args_list == [mock.call(2), mock.call(4)]++ def test_reraises_after_exhausting_attempts(self):+ get = mock.Mock(side_effect=OperationalError("query_wait_timeout"))++ with (+ mock.patch(_INTEGRATION_GET_PATH, get),+ mock.patch(_CLOSE_CONNECTIONS_PATH),+ mock.patch(_SLEEP_PATH),+ ):+ 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++ def test_missing_integration_is_not_retried(self):+ get = mock.Mock(side_effect=Integration.DoesNotExist())++ with mock.patch(_INTEGRATION_GET_PATH, get), mock.patch(_CLOSE_CONNECTIONS_PATH), mock.patch(_SLEEP_PATH):+ with pytest.raises(Integration.DoesNotExist):+ _get_integration(integration_id=1, team_id=2)++ # A deleted integration row is non-retryable — don't mask it as a transient drop.+ assert get.call_count == 1++def _fake_response(status_code: int, json_body: dict | None = None, headers: dict | None = None):resp = mock.MagicMock(spec=requests.Response)resp.status_code = status_code