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(google_ads): retry import on dropped Postgres connection (#66350)

Tom Owers7ef2429598db
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/google_ads.py b/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/google_ads.py
index 50ffccc88d53..cb0c4e9e5174 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/google_ads.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/google_ads.py
@@ -4,7 +4,7 @@ import datetime as dt
import collections.abc
from django.conf import settings
-from django.db import close_old_connections
+from django.db import OperationalError, close_old_connections
import grpc
import pyarrow as pa
@@ -102,17 +102,31 @@ def _load_client_with_transient_retry(
time.sleep(min(2 * attempt, 30))
+def _get_integration(integration_id: int, team_id: int) -> Integration:
+ """Fetch the OAuth ``Integration`` row, retrying once if the DB connection was dropped.
+
+ 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.
+ ``close_old_connections()`` evicts connections already known to be stale, but one can still
+ die in the window before the query runs and surface as a transient ``OperationalError``
+ ("server closed the connection unexpectedly"). The failed query marks the connection
+ unusable, so a second eviction drops it and the retry runs on a fresh connection. This read
+ is idempotent, so it is safe to repeat. ``Integration.DoesNotExist`` is left to propagate.
+ """
+ close_old_connections()
+ try:
+ return Integration.objects.get(id=integration_id, team_id=team_id)
+ except OperationalError:
+ close_old_connections()
+ return Integration.objects.get(id=integration_id, team_id=team_id)
+
+
def google_ads_client(config: GoogleAdsSourceConfigUnion, team_id: int) -> GoogleAdsClient:
"""Initialize a `GoogleAdsClient` with provided config."""
_ensure_grpc_receive_limit()
if isinstance(config, GoogleAdsSourceConfig):
- # Temporal activities run in a thread pool where Django DB connections can go
- # stale between uses (Postgres closes the connection server-side). This
- # function is invoked lazily from inside `get_rows` after the schema fetch,
- # so the connection has often been idle for minutes by the time we reach it.
- close_old_connections()
- integration = Integration.objects.get(id=config.google_ads_integration_id, team_id=team_id)
+ integration = _get_integration(config.google_ads_integration_id, team_id)
login_customer_id: str | None = None
if config.is_mcc_account and config.is_mcc_account.enabled:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/tests/test_google_ads_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/tests/test_google_ads_source.py
index e25cf015fc2a..6c504712290a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/tests/test_google_ads_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/tests/test_google_ads_source.py
@@ -3,6 +3,8 @@ from types import SimpleNamespace
import pytest
from unittest import mock
+from django.db import OperationalError
+
import grpc
from google.ads.googleads.errors import GoogleAdsException
from google.ads.googleads.v23.enums import types as ga_enums
@@ -21,6 +23,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.google_ads
from products.warehouse_sources.backend.temporal.data_imports.sources.google_ads.google_ads import (
GoogleAdsColumn,
GoogleAdsTable,
+ _get_integration,
_is_invalid_page_token_error,
_is_transient_grpc_error,
_load_client_with_transient_retry,
@@ -682,3 +685,56 @@ class TestSearchTransientRetry:
# First call raises and propagates immediately — no retry, no backoff.
assert service.calls == 1
assert sleep.call_count == 0
+
+
+_INTEGRATION_GET_PATH = (
+ "products.warehouse_sources.backend.temporal.data_imports.sources.google_ads.google_ads.Integration.objects.get"
+)
+_CLOSE_CONNECTIONS_PATH = (
+ "products.warehouse_sources.backend.temporal.data_imports.sources.google_ads.google_ads.close_old_connections"
+)
+
+
+class TestGetIntegrationDbResilience:
+ def test_retries_once_on_dropped_connection_then_succeeds(self):
+ integration = object()
+ get = mock.Mock(side_effect=[OperationalError("server closed the connection unexpectedly"), integration])
+
+ with mock.patch(_INTEGRATION_GET_PATH, get), mock.patch(_CLOSE_CONNECTIONS_PATH) as close:
+ result = _get_integration(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_reraises_when_retry_also_fails(self):
+ get = mock.Mock(side_effect=OperationalError("server closed the connection unexpectedly"))
+
+ with mock.patch(_INTEGRATION_GET_PATH, get), mock.patch(_CLOSE_CONNECTIONS_PATH):
+ with pytest.raises(OperationalError):
+ _get_integration(integration_id=1, team_id=2)
+
+ # One retry only — the second failure propagates so Temporal still retries the activity.
+ assert get.call_count == 2
+
+ 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):
+ with pytest.raises(Integration.DoesNotExist):
+ _get_integration(integration_id=1, team_id=2)
+
+ # A deleted connection row is non-retryable elsewhere — don't mask it as a transient drop.
+ assert get.call_count == 1
+
+ def test_no_retry_on_success(self):
+ integration = object()
+ get = mock.Mock(return_value=integration)
+
+ with mock.patch(_INTEGRATION_GET_PATH, get), mock.patch(_CLOSE_CONNECTIONS_PATH) as close:
+ result = _get_integration(integration_id=1, team_id=2)
+
+ assert result is integration
+ assert get.call_count == 1
+ assert close.call_count == 1