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_search_console): refresh stale db connection before integration lookup (#63170)

Tom Owers839a763d2a7a
diff --git a/posthog/temporal/data_imports/sources/google_search_console/google_search_console.py b/posthog/temporal/data_imports/sources/google_search_console/google_search_console.py
index 4bc9df4b59df..899ae9391a9c 100644
--- a/posthog/temporal/data_imports/sources/google_search_console/google_search_console.py
+++ b/posthog/temporal/data_imports/sources/google_search_console/google_search_console.py
@@ -7,6 +7,7 @@ from typing import Any
from urllib.parse import quote
from django.conf import settings
+from django.db import close_old_connections
import requests
import structlog
@@ -104,6 +105,11 @@ class GoogleSearchConsoleResumeConfig:
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)
return OAuthCredentials(
token=None,
diff --git a/posthog/temporal/data_imports/sources/google_search_console/tests/test_google_search_console.py b/posthog/temporal/data_imports/sources/google_search_console/tests/test_google_search_console.py
index 4b9c5a0d5adc..acff8363ae66 100644
--- a/posthog/temporal/data_imports/sources/google_search_console/tests/test_google_search_console.py
+++ b/posthog/temporal/data_imports/sources/google_search_console/tests/test_google_search_console.py
@@ -13,6 +13,7 @@ from posthog.temporal.data_imports.sources.google_search_console.google_search_c
QUOTA_MAX_RETRIES,
GoogleSearchConsoleQuotaExceededError,
GoogleSearchConsoleResumeConfig,
+ _credentials,
_initial_start_date,
_is_daily_quota_error,
_is_quota_error,
@@ -108,6 +109,30 @@ def test_row_to_dict_prefers_api_date_over_iter_date():
assert out["date"] == dt.date(2026, 4, 15)
+def test_credentials_refreshes_stale_db_connection_before_query(monkeypatch):
+ # The ORM read runs lazily inside `get_rows` on a worker thread whose pooled
+ # Django connection may have been closed server-side, surfacing as
+ # `OperationalError: the connection is closed`. We must drop the stale
+ # connection before querying, so the read happens on a fresh connection.
+ calls: list[str] = []
+
+ monkeypatch.setattr(gsc, "close_old_connections", lambda: calls.append("close_old_connections"))
+
+ integration = mock.MagicMock()
+ integration.refresh_token = "refresh-token"
+
+ def fake_get(*args, **kwargs):
+ calls.append("Integration.objects.get")
+ return integration
+
+ monkeypatch.setattr(gsc.Integration.objects, "get", fake_get)
+
+ creds = _credentials(integration_id=1, team_id=1)
+
+ assert calls == ["close_old_connections", "Integration.objects.get"]
+ assert creds.refresh_token == "refresh-token"
+
+
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()