: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(tasks): guard sandbox event ingest DB reads against stale connections (#67765)
posthog[bot]61d3ec9d18c6
diff --git a/products/tasks/backend/logic/stream/event_ingest.py b/products/tasks/backend/logic/stream/event_ingest.pyindex b1b31b2f8312..4e243bb18ced 100644--- a/products/tasks/backend/logic/stream/event_ingest.py+++ b/products/tasks/backend/logic/stream/event_ingest.py@@ -7,6 +7,7 @@ from dataclasses import dataclassfrom typing import castfrom django.conf import settings+from django.db import InterfaceError, OperationalError, close_old_connectionsimport structlogimport posthoganalytics@@ -296,6 +297,14 @@ async def _heartbeat_workflow_if_needed(redis_stream: TaskRunRedisStream, run_iddef _heartbeat_workflow(run_id: str, agent_active: bool) -> None:+ # This runs on a sync_to_async thread that Django never health-checks (the ASGI wrapper+ # intercepts the request before Django's connection lifecycle runs), so a pooled connection+ # Postgres has since closed can be reused. Mirror push_dispatcher/custom_prompt_internals and+ # clear stale connections first. Gated on `not settings.TEST` since it trips pytest-django's+ # DB-access guard when the ORM read is patched.+ if not settings.TEST:+ close_old_connections()+try:task_run = TaskRun.objects.get(id=run_id)except TaskRun.DoesNotExist:@@ -311,6 +320,9 @@ async def _dispatch_awaiting_input_if_interactive(run_id: str) -> None:def _dispatch_awaiting_input_if_interactive_sync(run_id: str) -> None:+ if not settings.TEST:+ close_old_connections()+try:task_run = TaskRun.objects.select_related("task__created_by", "team").get(id=run_id)except TaskRun.DoesNotExist:@@ -360,11 +372,22 @@ def _is_session_update(event: dict) -> bool:def _task_run_exists_sync(run_id: str, task_id: str, team_id: int) -> bool:+ if not settings.TEST:+ close_old_connections()return TaskRun.objects.filter(id=run_id, task_id=task_id, team_id=team_id).exists()-def _task_run_exists(run_id: str, task_id: str, team_id: int) -> Awaitable[bool]:- return sync_to_async(_task_run_exists_sync, thread_sensitive=True)(run_id, task_id, team_id)+async def _task_run_exists(run_id: str, task_id: str, team_id: int) -> bool:+ """Existence check on a sync_to_async thread whose pooled connection Django never+ health-checks. `close_old_connections()` clears a stale connection before the read; a+ single retry recovers a transparent reconnect since this is a side-effect-free read.+ An uncaught OperationalError here would otherwise crash the whole ingest request."""+ run_check = sync_to_async(_task_run_exists_sync, thread_sensitive=True)+ try:+ return await run_check(run_id, task_id, team_id)+ except (OperationalError, InterfaceError):+ logger.warning("task_run_event_ingest_exists_db_reconnect", run_id=run_id, exc_info=True)+ return await run_check(run_id, task_id, team_id)def _get_bearer_token(scope: ASGIMessage) -> str | None:diff --git a/products/tasks/backend/tests/test_event_ingest.py b/products/tasks/backend/tests/test_event_ingest.pyindex 5f68a9988167..b2be80084c9b 100644--- a/products/tasks/backend/tests/test_event_ingest.py+++ b/products/tasks/backend/tests/test_event_ingest.py@@ -5,6 +5,7 @@ from collections.abc import Sequencefrom unittest.mock import patch+from django.db import OperationalErrorfrom django.test import TestCase, override_settingsfrom asgiref.sync import async_to_sync@@ -593,6 +594,29 @@ class TestTaskRunEventIngest(TestCase):self.assertEqual(status, 401)self.assertEqual(body["error"], "Invalid event ingest token")+ @override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)+ def test_stale_db_connection_during_authorization_retries(self) -> None:+ # A stale pooled connection makes the run-existence check raise OperationalError.+ # Without the retry this crashes the ingest mid-stream; the reconnect must recover it.+ token = self._create_token()++ real_exists = TaskRun.objects.filter(id=self.task_run.id).exists()+ self.assertTrue(real_exists)++ with patch(+ "products.tasks.backend.logic.stream.event_ingest._task_run_exists_sync",+ side_effect=[OperationalError("server closed the connection unexpectedly"), True],+ ) as exists_sync:+ status, body = self._call_ingest(+ token,+ [{"seq": 1, "event": {"type": "notification", "notification": {"method": "session/update"}}}],+ )++ self.assertEqual(exists_sync.call_count, 2)+ self.assertEqual(status, 200)+ self.assertEqual(body["accepted"], 1)+ self.assertEqual(self._read_notification_methods(), ["session/update"])+@parameterized.expand([("single_oversized_line", False, 0, []),