: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): evict stale DB connections mid-activity and meter swallowed push failures (#62693)
Alessandro Pogliaghi0336769cc52a
diff --git a/products/tasks/backend/metrics.py b/products/tasks/backend/metrics.pyindex 1953b03b8ebc..9fcb085b8c24 100644--- a/products/tasks/backend/metrics.py+++ b/products/tasks/backend/metrics.py@@ -107,6 +107,12 @@ TASK_RUN_STREAM_RESUME_GAP_TOTAL = Counter(labelnames=["origin_product"],)+PUSH_DISPATCHER_FAILURES_TOTAL = Counter(+ "posthog_tasks_push_dispatcher_failures_total",+ "Push-notification dispatch attempts that failed and were swallowed by the best-effort dispatcher",+ labelnames=["kind", "reason"],+)+def _metric_label(value: object | None) -> str:if value is None:diff --git a/products/tasks/backend/push_dispatcher.py b/products/tasks/backend/push_dispatcher.pyindex 09fa20210863..2ed015f0d7dd 100644--- a/products/tasks/backend/push_dispatcher.py+++ b/products/tasks/backend/push_dispatcher.py@@ -21,7 +21,8 @@ from __future__ import annotationsfrom typing import TYPE_CHECKING, Literal-from django.db import transaction+from django.conf import settings+from django.db import InterfaceError, OperationalError, close_old_connections, transactionfrom django.utils import timezoneimport structlog@@ -30,6 +31,7 @@ import posthoganalyticsfrom posthog.models.user_push_token import UserPushTokenfrom posthog.tasks.push_notifications import send_user_push+from products.tasks.backend.metrics import PUSH_DISPATCHER_FAILURES_TOTALfrom products.tasks.backend.models import TaskPresencefrom products.tasks.backend.redis import get_tasks_cache@@ -89,7 +91,8 @@ def _enqueue(task_run: TaskRun, *, kind: PushKind, body: str) -> None:"""try:_enqueue_inner(task_run, kind=kind, body=body)- except Exception:+ except Exception as exc:+ PUSH_DISPATCHER_FAILURES_TOTAL.labels(kind=kind, reason=_failure_reason(exc)).inc()logger.warning("push_dispatcher.enqueue_failed",run_id=str(task_run.id),@@ -99,7 +102,14 @@ def _enqueue(task_run: TaskRun, *, kind: PushKind, body: str) -> None:)+def _failure_reason(exc: BaseException) -> str:+ return "db_connection" if isinstance(exc, OperationalError | InterfaceError) else "other"++def _enqueue_inner(task_run: TaskRun, *, kind: PushKind, body: str) -> None:+ if not settings.TEST:+ close_old_connections()+user = task_run.task.created_byif user is None:returndiff --git a/products/tasks/backend/tests/test_push_dispatcher.py b/products/tasks/backend/tests/test_push_dispatcher.pyindex 805ce70b1953..36d78bb17b29 100644--- a/products/tasks/backend/tests/test_push_dispatcher.py+++ b/products/tasks/backend/tests/test_push_dispatcher.py@@ -1,9 +1,11 @@from unittest.mock import patchfrom django.core.cache import cache+from django.db import InterfaceError, OperationalErrorfrom django.test import TransactionTestCasefrom parameterized import parameterized+from prometheus_client import REGISTRYfrom posthog.models import Organization, OrganizationMembership, Team, User@@ -130,6 +132,25 @@ class TestPushDispatcher(TransactionTestCase):# doesn't, this test raises and fails — which is the regression signal.notify_task_run_completed(self.task_run)+ @parameterized.expand(+ [+ (+ "db_connection_operational",+ "db_connection",+ OperationalError("server closed the connection unexpectedly"),+ ),+ ("db_connection_interface", "db_connection", InterfaceError("connection already closed")),+ ("other", "other", RuntimeError("redis is down")),+ ]+ )+ def test_swallowed_failure_increments_metric(self, _name, expected_reason, exc):+ labels = {"kind": "completed", "reason": expected_reason}+ before = REGISTRY.get_sample_value("posthog_tasks_push_dispatcher_failures_total", labels) or 0.0+ with patch("products.tasks.backend.push_dispatcher._enqueue_inner", side_effect=exc):+ notify_task_run_completed(self.task_run)+ after = REGISTRY.get_sample_value("posthog_tasks_push_dispatcher_failures_total", labels) or 0.0+ self.assertEqual(after, before + 1)+@patch("products.tasks.backend.push_dispatcher.notify_task_run_completed")def test_mark_completed_triggers_push(self, mock_notify):self.task_run.mark_completed()