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(meta_ads): treat stale db connection lookup as recoverable (#63733)

Tom Owers9c71fa1271a5
diff --git a/posthog/temporal/data_imports/sources/meta_ads/meta_ads.py b/posthog/temporal/data_imports/sources/meta_ads/meta_ads.py
index ddaf1c8753ac..1c526c4f5ff2 100644
--- a/posthog/temporal/data_imports/sources/meta_ads/meta_ads.py
+++ b/posthog/temporal/data_imports/sources/meta_ads/meta_ads.py
@@ -5,6 +5,8 @@ import collections.abc
from dataclasses import dataclass
from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit
+from django.db import close_old_connections
+
from requests import Response
from posthog.models.integration import ERROR_TOKEN_REFRESH_FAILED, Integration, MetaAdsIntegration
@@ -91,6 +93,12 @@ def _clean_account_id(s: str | None) -> str | None:
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)
meta_ads_integration = MetaAdsIntegration(integration)
meta_ads_integration.refresh_access_token()
diff --git a/posthog/temporal/data_imports/sources/meta_ads/test_meta_ads.py b/posthog/temporal/data_imports/sources/meta_ads/test_meta_ads.py
index f73a0425a7f6..686d42eee24c 100644
--- a/posthog/temporal/data_imports/sources/meta_ads/test_meta_ads.py
+++ b/posthog/temporal/data_imports/sources/meta_ads/test_meta_ads.py
@@ -5,6 +5,7 @@ import pytest
from unittest import mock
from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.meta_ads import meta_ads
from posthog.temporal.data_imports.sources.meta_ads.meta_ads import (
META_AUTH_ERROR_MESSAGE,
PAGE_LIMIT_FALLBACK_SIZES,
@@ -814,3 +815,32 @@ class TestNonRetryableErrors:
)
def test_is_permanent_auth_error(self, body: dict, expected: bool) -> None:
assert _is_permanent_auth_error(_mock_response(400, body)) is expected
+
+
+class TestGetIntegration:
+ def test_refreshes_stale_db_connection_before_query(self, monkeypatch) -> None:
+ # 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(meta_ads, "close_old_connections", lambda: calls.append("close_old_connections"))
+
+ integration = mock.MagicMock()
+ integration.errors = None
+
+ def fake_get(*args: Any, **kwargs: Any) -> mock.MagicMock:
+ calls.append("Integration.objects.get")
+ return integration
+
+ monkeypatch.setattr(meta_ads.Integration.objects, "get", fake_get)
+ monkeypatch.setattr(meta_ads, "MetaAdsIntegration", lambda i: mock.MagicMock(integration=i))
+
+ config = mock.MagicMock()
+ config.meta_ads_integration_id = 1
+
+ result = meta_ads.get_integration(config, team_id=1)
+
+ assert calls == ["close_old_connections", "Integration.objects.get"]
+ assert result is integration