: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
feat(tasks): add push notification delivery telemetry (#80396)
Alessandro Pogliaghibfb606c58006
diff --git a/posthog/tasks/push_notifications.py b/posthog/tasks/push_notifications.pyindex 3cdf24b2b598..29d5874128ba 100644--- a/posthog/tasks/push_notifications.py+++ b/posthog/tasks/push_notifications.py@@ -12,6 +12,7 @@ from typing import Anyimport structlogfrom celery import shared_task+from prometheus_client import Counterfrom posthog.models.user import Userfrom posthog.push_notifications import send_push_to_user@@ -19,6 +20,12 @@ from posthog.scoping_audit import skip_team_scope_auditlogger = structlog.get_logger(__name__)+PUSH_DELIVERY_OUTCOMES_TOTAL = Counter(+ "posthog_push_delivery_outcomes_total",+ "Expo push delivery task outcomes. Accepted means Expo returned a successful ticket, not final device delivery.",+ labelnames=["kind", "outcome"],+)+@shared_task(ignore_result=True)@skip_team_scope_audit@@ -40,19 +47,24 @@ def send_user_push(e.g. devices whose presence beacon says they're already watching the taskthat triggered this push."""+ notification_kind = str((data or {}).get("notificationKind", "other"))try:user = User.objects.get(pk=user_id)except User.DoesNotExist:+ PUSH_DELIVERY_OUTCOMES_TOTAL.labels(kind=notification_kind, outcome="user_missing").inc()logger.warning("send_user_push.user_not_found", user_id=user_id)returntry:- send_push_to_user(+ accepted = send_push_to_user(user,title=title,body=body,data=data,suppressed_push_token_ids=suppressed_push_token_ids,)+ outcome = "accepted" if accepted > 0 else "none_accepted"+ PUSH_DELIVERY_OUTCOMES_TOTAL.labels(kind=notification_kind, outcome=outcome).inc()except Exception:+ PUSH_DELIVERY_OUTCOMES_TOTAL.labels(kind=notification_kind, outcome="failed").inc()logger.warning("send_user_push.failed", user_id=user_id, exc_info=True)diff --git a/products/tasks/backend/metrics.py b/products/tasks/backend/metrics.pyindex 3778cc0e1a6b..4af7b2ede3e5 100644--- a/products/tasks/backend/metrics.py+++ b/products/tasks/backend/metrics.py@@ -191,6 +191,12 @@ PUSH_DISPATCHER_FAILURES_TOTAL = Counter(labelnames=["kind", "reason"],)+PUSH_DISPATCHER_OUTCOMES_TOTAL = Counter(+ "posthog_tasks_push_dispatcher_outcomes_total",+ "Push-notification dispatcher decisions before the Celery delivery task",+ labelnames=["kind", "outcome"],+)+# reason is one of: created, deduped, overlap_skipped, rate_capped, disabled, gate_blocked# (LoopFireResult.reason), a fixed, code-defined set, safe as a label.LOOP_FIRE_TOTAL = Counter(diff --git a/products/tasks/backend/push_dispatcher.py b/products/tasks/backend/push_dispatcher.pyindex 18966e3e493f..2c23d0113822 100644--- a/products/tasks/backend/push_dispatcher.py+++ b/products/tasks/backend/push_dispatcher.py@@ -31,7 +31,7 @@ from posthog.models.user import Userfrom posthog.models.user_push_token import UserPushTokenfrom posthog.tasks.push_notifications import send_user_push-from products.tasks.backend.metrics import PUSH_DISPATCHER_FAILURES_TOTAL+from products.tasks.backend.metrics import PUSH_DISPATCHER_FAILURES_TOTAL, PUSH_DISPATCHER_OUTCOMES_TOTALfrom products.tasks.backend.models import Task, TaskPresencefrom products.tasks.backend.redis import get_tasks_cachefrom products.tasks.backend.visibility import task_visibility_q@@ -209,9 +209,11 @@ def _enqueue_inner(task_run: TaskRun, *, kind: PushKind, body: str) -> None:user = task_run.task.created_byif user is None:+ PUSH_DISPATCHER_OUTCOMES_TOTAL.labels(kind=kind, outcome="no_recipient").inc()returnif not user.teams.filter(id=task_run.team_id).exists():+ PUSH_DISPATCHER_OUTCOMES_TOTAL.labels(kind=kind, outcome="access_denied").inc()logger.debug("push_dispatcher.recipient_lost_access",user_id=user.id,@@ -250,20 +252,29 @@ def _enqueue_user(# Failing closed on flag-evaluation errors keeps an outage from# silently flipping pushes on for the whole user base.logger.warning("push_dispatcher.flag_check_failed", user_id=user.id, exc_info=True)+ PUSH_DISPATCHER_OUTCOMES_TOTAL.labels(kind=kind, outcome="flag_check_failed").inc()returnif not flag_enabled:+ PUSH_DISPATCHER_OUTCOMES_TOTAL.labels(kind=kind, outcome="flag_disabled").inc()returncooldown_key = f"push_notification:{cooldown_subject}:{kind}"if not get_tasks_cache().add(cooldown_key, True, timeout=_COOLDOWN_SECONDS[kind]):+ PUSH_DISPATCHER_OUTCOMES_TOTAL.labels(kind=kind, outcome="cooldown_deduped").inc()logger.debug("push_dispatcher.cooldown_hit", subject=cooldown_subject, kind=kind)returnsuppressed = _suppressed_push_token_ids_for_task(user_id=user.id, task_id=task.id)+ data["notificationKind"] = kind# on_commit so we never schedule a push for a write that ends up rolling# back. Outside an atomic block this fires immediately, which is fine.- transaction.on_commit(lambda: send_user_push.delay(user.id, PUSH_TITLE, body, data, suppressed))+ def dispatch() -> None:+ outcome = "presence_suppressed" if suppressed else "enqueued"+ PUSH_DISPATCHER_OUTCOMES_TOTAL.labels(kind=kind, outcome=outcome).inc()+ send_user_push.delay(user.id, PUSH_TITLE, body, data, suppressed)++ transaction.on_commit(dispatch)def _suppressed_push_token_ids_for_task(*, user_id: int, task_id) -> list[str]:diff --git a/products/tasks/backend/tests/test_push_dispatcher.py b/products/tasks/backend/tests/test_push_dispatcher.pyindex ee7c7cb889ea..c3b25819e8e7 100644--- a/products/tasks/backend/tests/test_push_dispatcher.py+++ b/products/tasks/backend/tests/test_push_dispatcher.py@@ -8,6 +8,7 @@ from parameterized import parameterizedfrom prometheus_client import REGISTRYfrom posthog.models import Organization, OrganizationMembership, Team, User+from posthog.tasks.push_notifications import send_user_pushfrom products.tasks.backend.models import Task, TaskRunfrom products.tasks.backend.push_dispatcher import (@@ -62,15 +63,20 @@ class TestPushDispatcher(TestCase):self.assertIn(expected_body_fragment, body)self.assertEqual(data["taskId"], str(self.task.id))self.assertEqual(data["taskRunId"], str(self.task_run.id))+ self.assertEqual(data["notificationKind"], _name)# No presence rows in this test's setUp, so nothing to suppress.self.assertEqual(suppressed, [])@patch("products.tasks.backend.push_dispatcher.posthoganalytics.feature_enabled", return_value=False)@patch("products.tasks.backend.push_dispatcher.send_user_push.delay")def test_feature_flag_off_skips_dispatch(self, mock_delay, _flag):+ labels = {"kind": "completed", "outcome": "flag_disabled"}+ before = REGISTRY.get_sample_value("posthog_tasks_push_dispatcher_outcomes_total", labels) or 0.0with self.captureOnCommitCallbacks(execute=True):notify_task_run_completed(self.task_run)mock_delay.assert_not_called()+ after = REGISTRY.get_sample_value("posthog_tasks_push_dispatcher_outcomes_total", labels) or 0.0+ self.assertEqual(after, before + 1)@patch("products.tasks.backend.push_dispatcher.posthoganalytics.feature_enabled",@@ -85,11 +91,15 @@ class TestPushDispatcher(TestCase):@patch("products.tasks.backend.push_dispatcher.posthoganalytics.feature_enabled", return_value=True)@patch("products.tasks.backend.push_dispatcher.send_user_push.delay")def test_cooldown_collapses_duplicates(self, mock_delay, _flag):+ labels = {"kind": "completed", "outcome": "cooldown_deduped"}+ before = REGISTRY.get_sample_value("posthog_tasks_push_dispatcher_outcomes_total", labels) or 0.0with self.captureOnCommitCallbacks(execute=True):notify_task_run_completed(self.task_run)notify_task_run_completed(self.task_run)notify_task_run_completed(self.task_run)self.assertEqual(mock_delay.call_count, 1)+ after = REGISTRY.get_sample_value("posthog_tasks_push_dispatcher_outcomes_total", labels) or 0.0+ self.assertEqual(after, before + 2)@patch("products.tasks.backend.push_dispatcher.posthoganalytics.feature_enabled", return_value=True)@patch("products.tasks.backend.push_dispatcher.send_user_push.delay")@@ -172,3 +182,19 @@ class TestPushDispatcher(TestCase):def test_mark_failed_triggers_push(self, mock_notify):self.task_run.mark_failed("nope")mock_notify.assert_called_once_with(self.task_run)++ @patch("posthog.tasks.push_notifications.send_push_to_user", return_value=2)+ def test_delivery_task_records_expo_acceptance(self, mock_send):+ labels = {"kind": "completed", "outcome": "accepted"}+ before = REGISTRY.get_sample_value("posthog_push_delivery_outcomes_total", labels) or 0.0++ send_user_push(+ self.user.id,+ "PostHog Desktop",+ "Finished",+ {"notificationKind": "completed"},+ )++ mock_send.assert_called_once()+ after = REGISTRY.get_sample_value("posthog_push_delivery_outcomes_total", labels) or 0.0+ self.assertEqual(after, before + 1)