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(hubspot): retry transient DB pool timeout when fetching OAuth integration (#66896)

Tom Owersba79d703abfd
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/mixins.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/mixins.py
index 7980cfb94647..08cacb2db873 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/mixins.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/mixins.py
@@ -1,7 +1,10 @@
+import time
import socket
from collections.abc import Callable, Generator
from contextlib import _GeneratorContextManager, contextmanager
+from django.db import OperationalError, close_old_connections
+
import structlog
from posthog.cloud_utils import is_cloud
@@ -166,18 +169,45 @@ class SSHTunnelMixin:
return True, None
+_MAX_INTEGRATION_FETCH_ATTEMPTS = 4
+
+
+def _integration_fetch_backoff_sleep(attempt: int) -> None:
+ """Sleep before the next integration-fetch retry: linear growth capped at 30s (2s, 4s, 6s, ...)."""
+ time.sleep(min(2 * attempt, 30))
+
+
class OAuthMixin:
"""Mixin for OAuth-based sources"""
def get_oauth_integration(self, integration_id: int, team_id: int) -> Integration:
- """Get OAuth integration from integration ID"""
+ """Get OAuth integration from integration ID.
+
+ Temporal activities run in a long-lived worker outside Django's request cycle, so a pooled
+ Postgres connection can be closed server-side while idle, or the connection pooler can
+ reject the query with a wait timeout when the pool is saturated. Both surface as a transient
+ ``OperationalError`` that clears on a healthy connection, so this idempotent lookup is
+ retried with backoff before failing the whole import on a momentary blip. A failed query
+ marks its connection unusable, so ``close_old_connections()`` evicts it between attempts and
+ the next attempt runs on a fresh one; the sleep lets a saturated pool drain. A genuinely
+ missing integration is surfaced as the stable, non-retryable ``ValueError`` and is not
+ retried.
+ """
if not integration_id:
raise ValueError(f"Missing integration ID")
- if not Integration.objects.filter(id=integration_id, team_id=team_id).exists():
- raise ValueError(f"Integration not found: {integration_id}")
-
- return Integration.objects.get(id=integration_id, team_id=team_id)
+ attempt = 0
+ while True:
+ try:
+ return Integration.objects.get(id=integration_id, team_id=team_id)
+ except Integration.DoesNotExist:
+ raise ValueError(f"Integration not found: {integration_id}") from None
+ except OperationalError:
+ attempt += 1
+ if attempt >= _MAX_INTEGRATION_FETCH_ATTEMPTS:
+ raise
+ close_old_connections()
+ _integration_fetch_backoff_sleep(attempt)
class ValidateDatabaseHostMixin:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/test_mixins.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/test_mixins.py
index 0741fbd3df8b..a46ca7cdc88b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/test_mixins.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/test_mixins.py
@@ -1,17 +1,25 @@
from dataclasses import dataclass
+import pytest
+from unittest import mock
from unittest.mock import patch
+from django.db import OperationalError
from django.test import SimpleTestCase, override_settings
from parameterized import parameterized
+from posthog.models.integration import Integration
+
from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import (
+ OAuthMixin,
SSHTunnelMixin,
ValidateDatabaseHostMixin,
_is_host_safe,
)
+_MIXINS_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins"
+
class TestIsHostSafe(SimpleTestCase):
@parameterized.expand(
@@ -226,3 +234,92 @@ class TestSSHTunnelHostValidation(SimpleTestCase):
config = FakeConfig(ssh_tunnel=FakeSSHTunnelConfig(enabled=True, host=host))
valid, _ = mixin.ssh_tunnel_is_valid(config, team_id=999)
assert not valid
+
+
+class TestOAuthMixinIntegrationFetchResilience(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("pool_wait_timeout", "query_wait_timeout"),
+ ("dropped_connection", "server closed the connection unexpectedly"),
+ ]
+ )
+ def test_retries_transient_db_error_then_succeeds(self, _name: str, message: str):
+ integration = object()
+ get = mock.Mock(side_effect=[OperationalError(message), OperationalError(message), integration])
+
+ with (
+ patch(f"{_MIXINS_MODULE}.Integration.objects.get", get),
+ patch(f"{_MIXINS_MODULE}.close_old_connections") as close,
+ patch(f"{_MIXINS_MODULE}.time.sleep") as sleep,
+ ):
+ result = OAuthMixin().get_oauth_integration(integration_id=1, team_id=2)
+
+ assert result is integration
+ assert get.call_count == 3
+ # The poisoned connection is evicted before each retry, but not on the successful attempt.
+ assert close.call_count == 2
+ # Backoff grows per `min(2 * attempt, 30)`: 2s after the 1st failure, 4s after the 2nd.
+ assert sleep.call_args_list == [mock.call(2), mock.call(4)]
+
+ def test_success_does_not_evict_connection(self):
+ # Closing the connection on the happy path would tear down the caller's open transaction
+ # (e.g. inside a transactional test), so eviction must only happen between retries.
+ integration = object()
+
+ with (
+ patch(f"{_MIXINS_MODULE}.Integration.objects.get", return_value=integration),
+ patch(f"{_MIXINS_MODULE}.close_old_connections") as close,
+ patch(f"{_MIXINS_MODULE}.time.sleep") as sleep,
+ ):
+ result = OAuthMixin().get_oauth_integration(integration_id=1, team_id=2)
+
+ assert result is integration
+ close.assert_not_called()
+ sleep.assert_not_called()
+
+ def test_reraises_after_exhausting_attempts(self):
+ get = mock.Mock(side_effect=OperationalError("query_wait_timeout"))
+
+ with (
+ patch(f"{_MIXINS_MODULE}.Integration.objects.get", get),
+ patch(f"{_MIXINS_MODULE}.close_old_connections"),
+ patch(f"{_MIXINS_MODULE}.time.sleep") as sleep,
+ ):
+ with pytest.raises(OperationalError):
+ OAuthMixin().get_oauth_integration(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 attempts (2s, 4s, 6s) but not after the final attempt that re-raises.
+ assert sleep.call_args_list == [mock.call(2), mock.call(4), mock.call(6)]
+
+ def test_missing_integration_is_not_retried(self):
+ get = mock.Mock(side_effect=Integration.DoesNotExist())
+
+ with (
+ patch(f"{_MIXINS_MODULE}.Integration.objects.get", get),
+ patch(f"{_MIXINS_MODULE}.close_old_connections"),
+ patch(f"{_MIXINS_MODULE}.time.sleep") as sleep,
+ ):
+ # A deleted integration is non-retryable — surfaced as the stable "Integration not found"
+ # message the sources classify as non-retryable, not masked as a transient drop.
+ with pytest.raises(ValueError, match="Integration not found"):
+ OAuthMixin().get_oauth_integration(integration_id=1, team_id=2)
+
+ assert get.call_count == 1
+ sleep.assert_not_called()
+
+ def test_deletion_during_retry_is_surfaced_as_not_found(self):
+ # The row vanishes after a transient failure: the retry must convert DoesNotExist into the
+ # stable non-retryable ValueError rather than letting raw DoesNotExist escape and be retried.
+ get = mock.Mock(side_effect=[OperationalError("query_wait_timeout"), Integration.DoesNotExist()])
+
+ with (
+ patch(f"{_MIXINS_MODULE}.Integration.objects.get", get),
+ patch(f"{_MIXINS_MODULE}.close_old_connections"),
+ patch(f"{_MIXINS_MODULE}.time.sleep"),
+ ):
+ with pytest.raises(ValueError, match="Integration not found"):
+ OAuthMixin().get_oauth_integration(integration_id=1, team_id=2)
+
+ assert get.call_count == 2