: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 poll_for_turn ORM reads against dropped DB connections (#65345)
posthog[bot]9d69381e09b4
diff --git a/products/tasks/backend/logic/services/custom_prompt_internals.py b/products/tasks/backend/logic/services/custom_prompt_internals.pyindex 3b32665025ee..16ac8ad57c6c 100644--- a/products/tasks/backend/logic/services/custom_prompt_internals.py+++ b/products/tasks/backend/logic/services/custom_prompt_internals.py@@ -8,6 +8,9 @@ from collections.abc import Callablefrom dataclasses import dataclassfrom typing import TYPE_CHECKING, Any+from django.conf import settings+from django.db import InterfaceError, OperationalError, close_old_connections+from asgiref.sync import sync_to_asyncfrom posthog.models.team.team import Team@@ -151,6 +154,36 @@ async def create_task_and_trigger(return task, task_run+async def _refresh_task_run(task_run_id) -> TaskRun:+ """Re-read a ``TaskRun`` mid-poll, tolerating a dropped pooled DB connection.++ ``poll_for_turn`` runs for many minutes while the activity's threadpool connection+ sits idle; pgbouncer can drop it underneath us. The activity's ``@close_db_connections``+ decorator only resets connections at the activity boundaries, not inside this loop, so+ without this guard the next ORM read raises ``OperationalError``/``InterfaceError`` and+ aborts the whole report run. ``close_old_connections()`` clears any stale/errored+ connection before the read, and we retry once so a transparent reconnect recovers the+ drop instead of failing the run. Mirrors the handling in ``push_dispatcher``.+ """++ def _read() -> TaskRun:+ # Guarded like push_dispatcher: close_old_connections() health-checks live connections,+ # which trips pytest-django's DB-access guard in unit tests that patch the ORM read.+ if not settings.TEST:+ close_old_connections()+ return TaskRun.objects.get(id=task_run_id)++ try:+ return await sync_to_async(_read)()+ except (OperationalError, InterfaceError):+ logger.warning(+ "custom_prompt - poll_for_turn: DB connection dropped during TaskRun refresh, reconnecting, run=%s",+ task_run_id,+ exc_info=True,+ )+ return await sync_to_async(_read)()++async def poll_for_turn(task_run,*,@@ -251,7 +284,7 @@ async def poll_for_turn(# prior poll; without the clamp we'd re-parse old lines. Doubles as the line-count high-water# mark handed to salvage: every line up to here was seen (and watched go quiet) during polling.skip_lines = max(skip_lines, total_lines)- refreshed = await sync_to_async(TaskRun.objects.get)(id=task_run.id)+ refreshed = await _refresh_task_run(task_run.id)if refreshed.status in {TaskRun.Status.COMPLETED,TaskRun.Status.FAILED,@@ -278,7 +311,7 @@ async def poll_for_turn()# Poll budget exhausted. A run already terminal here was marked by something else (cancel,# relay-detected crash) — drain it; otherwise try to salvage below.- refreshed = await sync_to_async(TaskRun.objects.get)(id=task_run.id)+ refreshed = await _refresh_task_run(task_run.id)if refreshed.status in {TaskRun.Status.COMPLETED,TaskRun.Status.FAILED,diff --git a/products/tasks/backend/tests/test_multi_turn_session.py b/products/tasks/backend/tests/test_multi_turn_session.pyindex 32f9b4608261..f028b83aa9e2 100644--- a/products/tasks/backend/tests/test_multi_turn_session.py+++ b/products/tasks/backend/tests/test_multi_turn_session.py@@ -5,6 +5,8 @@ from pathlib import Pathimport pytestfrom unittest.mock import AsyncMock, MagicMock, patch+from django.db import OperationalError+from asgiref.sync import sync_to_asyncfrom parameterized import parameterizedfrom pydantic import BaseModel@@ -1410,3 +1412,55 @@ class TestMultiTurnSessionStartFallback:fallback.assert_not_called()session.end.assert_awaited_once() # type: ignore[attr-defined]+++class TestPollForTurnConnectionDrop:+ """poll_for_turn runs for many minutes while the activity's pooled DB connection sits idle;+ pgbouncer can drop it underneath the in-loop `TaskRun.objects.get` refreshes. Those reads must+ reconnect transparently instead of aborting the whole report run with an OperationalError."""++ @pytest.mark.asyncio+ async def test_in_loop_refresh_reconnects_after_dropped_connection(self):+ # First poll has an agent_message but no end_turn -> falls through to the in-loop TaskRun+ # refresh, whose first ORM read hits a dropped pooled connection. The retry must reconnect+ # and observe the now-terminal status so the run drains cleanly instead of crashing.+ log = "\n".join([_agent_message_line("connection-drop summary"), _usage_update_line()])+ completed = FakeTaskRun(status=TaskRun.Status.COMPLETED)+ get_mock = MagicMock(side_effect=[OperationalError("server closed the connection unexpectedly"), completed])++ # settings.TEST gates the close_old_connections() call (it health-checks live+ # connections, which trips the test DB-access guard), so flip it off to exercise+ # the real reconnect path.+ with (+ patch("posthog.storage.object_storage.read", return_value=log),+ patch("asyncio.sleep", new=AsyncMock()),+ patch("products.tasks.backend.logic.services.custom_prompt_internals.POLL_INTERVAL_SECONDS", 0),+ patch("products.tasks.backend.logic.services.custom_prompt_internals.settings.TEST", False),+ patch("products.tasks.backend.logic.services.custom_prompt_internals.close_old_connections") as close_conns,+ patch("products.tasks.backend.models.TaskRun.objects.get", new=get_mock),+ ):+ last_message, _, _, _ = await poll_for_turn(FakeTaskRun(), skip_lines=0)++ assert last_message == "connection-drop summary"+ # Read was retried after the drop, and the staleness guard ran before each attempt.+ assert get_mock.call_count == 2+ assert close_conns.call_count == 2++ @pytest.mark.asyncio+ async def test_persistent_connection_failure_propagates(self):+ # A genuinely dead pool (both attempts fail) must still surface — the guard retries once,+ # it is not an infinite reconnect loop that masks a real outage.+ log = "\n".join([_agent_message_line("partial"), _usage_update_line()])+ get_mock = MagicMock(side_effect=OperationalError("server closed the connection unexpectedly"))++ with (+ patch("posthog.storage.object_storage.read", return_value=log),+ patch("asyncio.sleep", new=AsyncMock()),+ patch("products.tasks.backend.logic.services.custom_prompt_internals.POLL_INTERVAL_SECONDS", 0),+ patch("products.tasks.backend.logic.services.custom_prompt_internals.close_old_connections"),+ patch("products.tasks.backend.models.TaskRun.objects.get", new=get_mock),+ ):+ with pytest.raises(OperationalError):+ await poll_for_turn(FakeTaskRun(), skip_lines=0)++ assert get_mock.call_count == 2