: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): handle transient Postgres drops in scout activity (#65344)
posthog[bot]0237f76b95dc
diff --git a/products/signals/backend/temporal/agentic/scout_scheduler.py b/products/signals/backend/temporal/agentic/scout_scheduler.pyindex 47576bcd2922..4d00238f766b 100644--- a/products/signals/backend/temporal/agentic/scout_scheduler.py+++ b/products/signals/backend/temporal/agentic/scout_scheduler.py@@ -4,11 +4,14 @@ from dataclasses import dataclassfrom datetime import timedeltafrom typing import TYPE_CHECKING+from django.db import InterfaceError, OperationalError+import structlogimport temporaliofrom temporalio.common import RetryPolicyfrom posthog.temporal.common.heartbeat import Heartbeater+from posthog.temporal.common.utils import close_db_connectionsfrom products.signals.backend.scout_harness.limits import WORKFLOW_HARD_CEILING_Sfrom products.signals.backend.temporal import metrics@@ -53,24 +56,54 @@ def _to_output(result: RunResult) -> RunSignalsScoutOutput:@temporalio.activity.defn+@close_db_connectionsasync def run_signals_scout_activity(input: RunSignalsScoutInput) -> RunSignalsScoutOutput:"""One scheduled scout run for a (team, skill) pair.The activity itself never raises — failures are persisted on the run row and theworkflow sees a `status='failed'` outcome. This matches the spec's "fail safe andsilent" rule: a bad run does not retry blindly.++ The long-lived worker pools its DB connections through pgbouncer, so a pool recycle,+ failover, or deploy can leave a stale pooled connection that raises `OperationalError`+ the next time it's used. `@close_db_connections` evicts stale connections around the+ activity, and the `(OperationalError, InterfaceError)` guard below catches a blip that+ lands mid-run — including the runner's early guards and its own except-handler reads,+ which run outside the run-row try/except — so a transient drop is reported as a failed+ run rather than escaping the activity and breaching the "never raises" contract."""# Deferred to break the runner <-> temporal import cycle (see the TYPE_CHECKING note# above): importing the runner at module load leaves RunResult undefined when runner# is the import entry point. Imported here at call time, after both modules are loaded.from products.signals.backend.scout_harness.runner import arun_signals_scout # noqa: PLC0415- async with Heartbeater():- result = await arun_signals_scout(+ try:+ async with Heartbeater():+ result = await arun_signals_scout(+ team_id=input.team_id,+ skill_name=input.skill_name,+ skill_version=input.skill_version,+ repository=input.repository,+ )+ except (OperationalError, InterfaceError):+ # Transient DB connection drop (pgbouncer pool recycle / failover / deploy). Stay+ # fail-safe and silent: report a failed run for this tick rather than raising. The+ # decorator already evicted the dead connection; the next scheduled tick retries on+ # a fresh one. `"failed"` mirrors `TaskRun.Status.FAILED.value`.+ metrics.increment_scout_run("failed")+ logger.warning(+ "signals_scout activity: transient DB connection failure, reporting failed run",team_id=input.team_id,skill_name=input.skill_name,- skill_version=input.skill_version,- repository=input.repository,+ exc_info=True,+ )+ return RunSignalsScoutOutput(+ run_id=None,+ task_run_id=None,+ status="failed",+ runtime_s=0.0,+ skill_name=input.skill_name,+ skill_version=input.skill_version or 0,)metrics.increment_scout_run(result.status or "unknown")logger.info(diff --git a/products/signals/backend/test/test_scout_harness.py b/products/signals/backend/test/test_scout_harness.pyindex 92543f999f8b..ae624823de9f 100644--- a/products/signals/backend/test/test_scout_harness.py+++ b/products/signals/backend/test/test_scout_harness.py@@ -10,6 +10,7 @@ from posthog.test.base import BaseTestfrom unittest.mock import AsyncMock, MagicMock, patchfrom django.apps import apps+from django.db import OperationalErrorimport pytest_asynciofrom asgiref.sync import sync_to_async@@ -761,6 +762,32 @@ async def test_activity_returns_skip_outcome_when_already_running(ateam):assert output.skip_reason is not None+async def test_activity_swallows_transient_db_connection_drop(ateam):+ # A pgbouncer pool recycle / failover can surface as OperationalError from the runner's+ # synchronous DB access, outside the run-row try/except. The activity's "never raises"+ # contract must hold: report a failed run instead of letting it escape.+ async def fake_arun(**_kwargs):+ raise OperationalError("server closed the connection unexpectedly")++ with patch(+ "products.signals.backend.scout_harness.runner.arun_signals_scout",+ side_effect=fake_arun,+ ):+ env = ActivityEnvironment()+ output = await env.run(+ run_signals_scout_activity,+ RunSignalsScoutInput(team_id=ateam.id, skill_name="signals-scout-errors"),+ )++ assert output.run_id is None+ assert output.task_run_id is None+ assert output.status == "failed"+ assert output.skill_name == "signals-scout-errors"+ assert output.skip_reason is None++# ── Tasks-UI cross-link: SignalScoutRun ─→ TaskRun ────────────────────────────## Status, timestamps, and the task-id pair all live on the linked `TaskRun` now.