: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(signals): guard select_repository activity against transient DB drops (#67042)
posthog[bot]59b31db26f61
diff --git a/posthog/temporal/common/utils.py b/posthog/temporal/common/utils.pyindex 03cf8358b641..7dc4b7c784c5 100644--- a/posthog/temporal/common/utils.py+++ b/posthog/temporal/common/utils.py@@ -146,6 +146,29 @@ def close_db_connections(fn: Callable[P, T]) -> Callable[P, T]:return sync_wrapper+async def aretry_on_db_connection_drop(operation: Callable[[], Coroutine[Any, Any, T]]) -> T:+ """Run an async DB read, retrying once on a transient connection drop.++ Long-lived Temporal workers pool their connections through pgbouncer, so a pool+ recycle, failover, or deploy can leave a stale pooled connection that raises+ ``OperationalError`` / ``InterfaceError`` the first time it's used. Evict the dead+ connection and retry once, so a transient blip at an activity's early connect-time+ reads succeeds on a fresh connection instead of escaping as error-tracking noise.+ A second failure propagates — that's a genuinely degraded DB, left to the caller's+ retry posture.++ Pass a zero-arg callable that *produces* the awaitable (not the awaitable itself),+ so the retry can issue a fresh query:++ team = await aretry_on_db_connection_drop(lambda: Team.objects.aget(pk=team_id))+ """+ try:+ return await operation()+ except (django.db.OperationalError, django.db.InterfaceError):+ await sync_to_async(_close_db_connections)()+ return await operation()++def get_scheduled_start_time():"""Return the start time of a workflow.diff --git a/products/signals/backend/temporal/agentic/select_repository.py b/products/signals/backend/temporal/agentic/select_repository.pyindex 872f8a4e2d1d..6ba792df4513 100644--- a/products/signals/backend/temporal/agentic/select_repository.py+++ b/products/signals/backend/temporal/agentic/select_repository.py@@ -11,7 +11,7 @@ from posthog.models.team.team import Teamfrom posthog.sync import database_sync_to_asyncfrom posthog.temporal.common.heartbeat import Heartbeaterfrom posthog.temporal.common.scoped import scoped_temporal-from posthog.temporal.common.utils import close_db_connections+from posthog.temporal.common.utils import aretry_on_db_connection_drop, close_db_connectionsfrom products.signals.backend.models import SignalReportArtefactfrom products.signals.backend.report_generation.select_repo import (@@ -104,8 +104,18 @@ def _load_previous_repo_selection(report_id: str) -> RepoSelectionResult | None:@scoped_temporal()@close_db_connectionsasync def select_repository_activity(input: SelectRepositoryInput) -> RepoSelectionResult:- """Select the most relevant repository for a report's signals."""- team = await Team.objects.select_related("organization").aget(pk=input.team_id)+ """Select the most relevant repository for a report's signals.++ The early connect-time reads (the team fetch and the previous-selection lookup) go+ through ``aretry_on_db_connection_drop``: the long-lived worker pools connections via+ pgbouncer, so a pool recycle / failover / deploy 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).+ """+ team = await aretry_on_db_connection_drop(+ lambda: Team.objects.select_related("organization").aget(pk=input.team_id)+ )_capture_repo_research_event("signals_repo_research_started",team,@@ -115,8 +125,8 @@ async def select_repository_activity(input: SelectRepositoryInput) -> RepoSelecttry:async with Heartbeater():# Check for a previous selection from an earlier run, if any- previous = await database_sync_to_async(_load_previous_repo_selection, thread_sensitive=False)(- input.report_id+ previous = await aretry_on_db_connection_drop(+ lambda: database_sync_to_async(_load_previous_repo_selection, thread_sensitive=False)(input.report_id))if previous is not None and previous.repository is not None:logger.info(diff --git a/products/signals/backend/test/test_agentic_report_activity.py b/products/signals/backend/test/test_agentic_report_activity.pyindex 957bbdb3d5bc..1cbb1c99eecd 100644--- a/products/signals/backend/test/test_agentic_report_activity.py+++ b/products/signals/backend/test/test_agentic_report_activity.py@@ -5,6 +5,8 @@ from datetime import UTC, datetimeimport pytestfrom unittest.mock import AsyncMock, Mock, patch+from django.db import OperationalError+import pytest_asynciofrom asgiref.sync import sync_to_async@@ -180,6 +182,35 @@ async def test_select_repository_activity_reuses_previous_selection(monkeypatch,assert not select_repo_called+async def test_select_repository_activity_retries_transient_db_drop(monkeypatch, ateam):+ # A pooled pgbouncer connection dropped mid-request raises OperationalError on the+ # activity's early 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.+ previous = RepoSelectionResult(repository="posthog/posthog", reason="Previously selected")+ attempts = {"n": 0}++ def flaky_load(report_id):+ attempts["n"] += 1+ if attempts["n"] == 1:+ raise OperationalError("server closed the connection unexpectedly")+ return previous++ monkeypatch.setattr(+ "products.signals.backend.temporal.agentic.select_repository._load_previous_repo_selection",+ flaky_load,+ )++ with patch("products.signals.backend.temporal.agentic.select_repository.Heartbeater"):+ result = await select_repository_activity(+ SelectRepositoryInput(team_id=ateam.id, report_id="test-report-id", signals=_build_signals())+ )++ assert result is previous+ assert attempts["n"] == 2++@pytest.mark.asyncio@pytest.mark.django_dbasync def test_select_repository_activity_no_repo(monkeypatch, ateam):