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(linkedin_ads): refresh stale db connection before integration read (#63799)

Tom Owers6adb015f7348
diff --git a/posthog/temporal/data_imports/sources/linkedin_ads/linkedin_ads.py b/posthog/temporal/data_imports/sources/linkedin_ads/linkedin_ads.py
index d340a97f9c1c..f86d834f3593 100644
--- a/posthog/temporal/data_imports/sources/linkedin_ads/linkedin_ads.py
+++ b/posthog/temporal/data_imports/sources/linkedin_ads/linkedin_ads.py
@@ -3,6 +3,8 @@ import datetime as dt
import collections.abc
from dataclasses import dataclass
+from django.db import close_old_connections
+
import pyarrow as pa
import structlog
from structlog.types import FilteringBoundLogger
@@ -100,6 +102,12 @@ def get_schemas() -> dict[str, LinkedinAdsSchema]:
def linkedin_ads_client(config: LinkedinAdsSourceConfig, team_id: int) -> LinkedinAdsClient:
"""Initialize a LinkedIn Ads client with provided config."""
+ # 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, else
+ # the read surfaces as `OperationalError: the connection is closed`.
+ close_old_connections()
integration = Integration.objects.get(id=config.linkedin_ads_integration_id, team_id=team_id)
if not integration.access_token:
raise ValueError("LinkedIn Ads integration does not have an access token")
diff --git a/posthog/temporal/data_imports/sources/linkedin_ads/tests/test_linkedin_ads.py b/posthog/temporal/data_imports/sources/linkedin_ads/tests/test_linkedin_ads.py
index dc1fe7f38f2e..1292f58370a1 100644
--- a/posthog/temporal/data_imports/sources/linkedin_ads/tests/test_linkedin_ads.py
+++ b/posthog/temporal/data_imports/sources/linkedin_ads/tests/test_linkedin_ads.py
@@ -361,6 +361,32 @@ class TestLinkedinAdsClientFunction:
with pytest.raises(ValueError, match="LinkedIn Ads integration does not have an access token"):
linkedin_ads_client(config, team_id=789)
+ def test_linkedin_ads_client_refreshes_stale_db_connection_before_query(self, mock_integration_model, 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(
+ "posthog.temporal.data_imports.sources.linkedin_ads.linkedin_ads.close_old_connections",
+ lambda: calls.append("close_old_connections"),
+ )
+
+ mock_integration = mock.MagicMock()
+ mock_integration.access_token = "token"
+
+ def fake_get(*args, **kwargs):
+ calls.append("Integration.objects.get")
+ return mock_integration
+
+ mock_integration_model.objects.get.side_effect = fake_get
+
+ config = LinkedinAdsSourceConfig(linkedin_ads_integration_id=123, account_id="456")
+ linkedin_ads_client(config, team_id=789)
+
+ assert calls == ["close_old_connections", "Integration.objects.get"]
+
@mock.patch("posthog.temporal.data_imports.sources.linkedin_ads.linkedin_ads.linkedin_ads_client")
class TestLinkedinAdsSource: