: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(meta_ads): retry transient DB pool timeout when fetching integration (#66938)
Tom Owers3b25ce281c6e
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/meta_ads/meta_ads.py b/products/warehouse_sources/backend/temporal/data_imports/sources/meta_ads/meta_ads.pyindex a09a65437323..d6d3a18acf59 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/meta_ads/meta_ads.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/meta_ads/meta_ads.py@@ -1,11 +1,12 @@import json+import timeimport typingimport datetime as dtimport collections.abcfrom dataclasses import dataclassfrom urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit-from django.db import close_old_connections+from django.db import OperationalError, close_old_connectionsfrom requests import Response@@ -109,15 +110,42 @@ def _clean_account_id(s: str | None) -> str | None:return s+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 _fetch_integration_row(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, 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`` (e.g. ``the connection is closed``, ``query_wait_timeout``) 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 get_integration(config: MetaAdsSourceConfig, team_id: int) -> Integration:"""Get the Meta Ads integration."""- # 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, surfacing as- # `OperationalError: the connection is closed` — drop any stale connection first.- close_old_connections()- integration = Integration.objects.get(id=config.meta_ads_integration_id, team_id=team_id)+ integration = _fetch_integration_row(config.meta_ads_integration_id, team_id)meta_ads_integration = MetaAdsIntegration(integration)meta_ads_integration.refresh_access_token()diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/meta_ads/test_meta_ads.py b/products/warehouse_sources/backend/temporal/data_imports/sources/meta_ads/test_meta_ads.pyindex ab48a12dd78b..77e64d03c846 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/meta_ads/test_meta_ads.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/meta_ads/test_meta_ads.py@@ -6,6 +6,8 @@ import pytestfrom freezegun import freeze_timefrom unittest import mock+from django.db import OperationalError+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import MetaAdsSourceConfigfrom products.warehouse_sources.backend.temporal.data_imports.sources.meta_ads import meta_ads as meta_ads_module@@ -16,6 +18,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.meta_ads.mPAGE_LIMIT_FALLBACK_SIZES,MetaAdsResumeConfig,_earliest_supported_since,+ _fetch_integration_row,_is_permanent_auth_error,_iter_simple_pagination,_iter_time_range_pagination,@@ -1172,3 +1175,68 @@ class TestGetIntegration:assert calls == ["close_old_connections", "Integration.objects.get"]meta_ads_integration.refresh_access_token.assert_called_once()assert result is integration+++class TestFetchIntegrationRowDbResilience:+ def test_retries_on_dropped_connection_then_succeeds(self, monkeypatch) -> None:+ integration = object()+ get = mock.Mock(side_effect=[OperationalError("server closed the connection unexpectedly"), integration])+ close = mock.Mock()+ monkeypatch.setattr(meta_ads_module.Integration.objects, "get", get)+ monkeypatch.setattr(meta_ads_module, "close_old_connections", close)+ monkeypatch.setattr(meta_ads_module.time, "sleep", lambda _s: None)++ result = _fetch_integration_row(integration_id=1, team_id=2)++ assert result is integration+ assert get.call_count == 2+ # Evicted up front, then again after the failed query marked the connection unusable.+ assert close.call_count == 2++ def test_rides_out_pool_wait_timeout_then_succeeds(self, monkeypatch) -> None:+ integration = object()+ get = mock.Mock(+ side_effect=[+ OperationalError("query_wait_timeout"),+ OperationalError("query_wait_timeout"),+ integration,+ ]+ )+ sleeps: list[int] = []+ monkeypatch.setattr(meta_ads_module.Integration.objects, "get", get)+ monkeypatch.setattr(meta_ads_module, "close_old_connections", lambda: None)+ monkeypatch.setattr(meta_ads_module.time, "sleep", lambda s: sleeps.append(s))++ result = _fetch_integration_row(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 sleeps == [2, 4]++ def test_reraises_after_exhausting_attempts(self, monkeypatch) -> None:+ get = mock.Mock(side_effect=OperationalError("query_wait_timeout"))+ sleeps: list[int] = []+ monkeypatch.setattr(meta_ads_module.Integration.objects, "get", get)+ monkeypatch.setattr(meta_ads_module, "close_old_connections", lambda: None)+ monkeypatch.setattr(meta_ads_module.time, "sleep", lambda s: sleeps.append(s))++ with pytest.raises(OperationalError):+ _fetch_integration_row(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+ # Backed off between each attempt (2s, 4s, 6s) but not after the final attempt that re-raises.+ assert sleeps == [2, 4, 6]++ def test_missing_integration_is_not_retried(self, monkeypatch) -> None:+ get = mock.Mock(side_effect=meta_ads_module.Integration.DoesNotExist())+ monkeypatch.setattr(meta_ads_module.Integration.objects, "get", get)+ monkeypatch.setattr(meta_ads_module, "close_old_connections", lambda: None)+ monkeypatch.setattr(meta_ads_module.time, "sleep", lambda _s: None)++ with pytest.raises(meta_ads_module.Integration.DoesNotExist):+ _fetch_integration_row(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