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(tasks): guard credential-refresh DB read against transient DB drops (#73445)

posthog[bot]080c2466ceaf
diff --git a/posthog/temporal/common/utils.py b/posthog/temporal/common/utils.py
index 7dc4b7c784c5..28461ad9feb9 100644
--- a/posthog/temporal/common/utils.py
+++ b/posthog/temporal/common/utils.py
@@ -169,6 +169,28 @@ async def aretry_on_db_connection_drop(operation: Callable[[], Coroutine[Any, An
return await operation()
+def retry_on_db_connection_drop(operation: Callable[[], T]) -> T:
+ """Run a sync DB read, retrying once on a transient connection drop.
+
+ The sync sibling of ``aretry_on_db_connection_drop``, for activities that run sync
+ Django ORM code (e.g. under ``@asyncify``). See that function for the full rationale:
+ a long-lived worker pools connections through pgbouncer, so a pool recycle / failover
+ / deploy can leave a stale pooled connection that raises ``OperationalError`` /
+ ``InterfaceError`` on first use. Evict the dead connection and retry once; a second
+ failure propagates, left to the caller's retry posture.
+
+ Pass a zero-arg callable that *produces* the result, so the retry can issue a fresh
+ query:
+
+ task = retry_on_db_connection_drop(lambda: Task.objects.get(id=task_id))
+ """
+ try:
+ return operation()
+ except (django.db.OperationalError, django.db.InterfaceError):
+ _close_db_connections()
+ return operation()
+
+
def get_scheduled_start_time():
"""Return the start time of a workflow.
diff --git a/products/tasks/backend/temporal/process_task/activities/refresh_sandbox_credentials.py b/products/tasks/backend/temporal/process_task/activities/refresh_sandbox_credentials.py
index 9adab94feea9..a15d61618158 100644
--- a/products/tasks/backend/temporal/process_task/activities/refresh_sandbox_credentials.py
+++ b/products/tasks/backend/temporal/process_task/activities/refresh_sandbox_credentials.py
@@ -3,7 +3,7 @@ from dataclasses import dataclass, field
from temporalio import activity
from posthog.temporal.common.logger import get_logger
-from posthog.temporal.common.utils import asyncify
+from posthog.temporal.common.utils import asyncify, retry_on_db_connection_drop
from products.tasks.backend.exceptions import (
CredentialUnavailableError,
@@ -92,8 +92,16 @@ def refresh_sandbox_credentials(input: RefreshSandboxCredentialsInput) -> Refres
**ctx.to_log_context(),
):
try:
- task = Task.objects.select_related("created_by", "github_integration", "github_user_integration").get(
- id=ctx.task_id
+ # The early connect-time read goes through retry_on_db_connection_drop: the
+ # long-lived worker pools connections via pgbouncer, so a pool recycle / failover
+ # / transient DNS blip can leave a stale pooled connection that raises
+ # OperationalError on first use. Retrying once on a fresh connection keeps a
+ # transient blip from escaping as error-tracking noise (Temporal still retries
+ # the activity if the DB is genuinely degraded).
+ task = retry_on_db_connection_drop(
+ lambda: Task.objects.select_related("created_by", "github_integration", "github_user_integration").get(
+ id=ctx.task_id
+ )
)
except Task.DoesNotExist as e:
raise TaskNotFoundError(f"Task {ctx.task_id} not found", {"task_id": ctx.task_id}, cause=e)
diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_refresh_sandbox_credentials.py b/products/tasks/backend/temporal/process_task/activities/tests/test_refresh_sandbox_credentials.py
index 248061c91385..4448b1c44bd5 100644
--- a/products/tasks/backend/temporal/process_task/activities/tests/test_refresh_sandbox_credentials.py
+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_refresh_sandbox_credentials.py
@@ -1,12 +1,15 @@
import pytest
from unittest.mock import MagicMock, patch
+from django.db import OperationalError
+
from asgiref.sync import async_to_sync
from posthog.models.integration import Integration
from products.tasks.backend.exceptions import SandboxExecutionError, SandboxNotFoundError, SandboxNotRunningError
from products.tasks.backend.logic.services.sandbox import ExecutionResult
+from products.tasks.backend.models import Task
from products.tasks.backend.temporal.process_task.activities.refresh_sandbox_credentials import (
RefreshSandboxCredentialsInput,
refresh_sandbox_credentials,
@@ -58,6 +61,38 @@ class TestRefreshSandboxCredentialsActivity:
assert event_name == "sandbox_credentials_refreshed"
assert track_event.call_args.kwargs["properties"]["refreshed_kinds"] == ["github"]
+ def test_retries_transient_db_connection_drop(self, activity_environment, task_context, test_task, sandbox):
+ # A pooled pgbouncer connection dropped mid-request raises OperationalError on the
+ # activity's early Task read. The retry-once guard must evict the dead connection and
+ # succeed on the second attempt rather than letting it escape as error-tracking noise.
+ with (
+ patch(
+ "products.tasks.backend.temporal.process_task.activities.refresh_sandbox_credentials.Task"
+ ) as mock_task,
+ patch(
+ "products.tasks.backend.temporal.process_task.activities.refresh_sandbox_credentials.Sandbox.get_by_id",
+ return_value=sandbox,
+ ),
+ patch(
+ "products.tasks.backend.temporal.process_task.sandbox_credentials.get_sandbox_github_token",
+ return_value="ghs_fresh",
+ ),
+ patch("products.tasks.backend.temporal.process_task.activities.refresh_sandbox_credentials.track_event"),
+ ):
+ mock_task.DoesNotExist = Task.DoesNotExist
+ mock_task.objects.select_related.return_value.get.side_effect = [
+ OperationalError("server closed the connection unexpectedly"),
+ test_task,
+ ]
+
+ output = async_to_sync(activity_environment.run)(
+ refresh_sandbox_credentials,
+ RefreshSandboxCredentialsInput(context=task_context, sandbox_id="sandbox-abc"),
+ )
+
+ assert mock_task.objects.select_related.return_value.get.call_count == 2
+ assert output.refreshed_kinds == ["github"]
+
def test_credential_failure_is_non_fatal(self, activity_environment, task_context, test_task, sandbox):
with (
patch(