: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(signals): notify reviewers manually added to an inbox report (#71139)
Andrew Maguire91fb8125f7c2
diff --git a/products/signals/backend/slack_inbox_notifications.py b/products/signals/backend/slack_inbox_notifications.pyindex 9e955027aaad..c278417c0511 100644--- a/products/signals/backend/slack_inbox_notifications.py+++ b/products/signals/backend/slack_inbox_notifications.py@@ -16,6 +16,7 @@ from __future__ import annotationsimport reimport jsonimport logging+from collections.abc import Iterablefrom django.conf import settings@@ -635,6 +636,47 @@ def _build_reviewer_routes(return list(routes.values())+def _deliver_route_notification(+ report: SignalReport,+ route: _ChannelRoute,+ *,+ priority: str | None,+ source_products: list[str],+ repository: str | None,+ signals: list[dict] | None = None,+) -> bool:+ """Post one report notification to a route's channel (with optional evidence thread).++ Shared by the report-ready and reviewer-added dispatchers. Returns True if the top-level+ message was sent. Best-effort: Slack errors are logged, not raised.+ """+ channel_id = _channel_id_from_target(route.channel)+ log_context = {+ "report_id": str(report.id),+ "team_id": report.team_id,+ "channel": _channel_display_name(route.channel),+ "destination": "team" if route.is_team_channel else "user",+ }+ try:+ slack = SlackIntegration(route.integration)+ mentions = _resolve_reviewer_mentions(slack, route.users)+ blocks, text = _build_message_blocks(+ report,+ priority=priority,+ source_products=source_products,+ reviewer_mentions=mentions,+ repository=repository,+ )+ response = slack.client.chat_postMessage(channel=channel_id, blocks=blocks, text=text)+ thread_ts = response.get("ts") if hasattr(response, "get") else None+ if signals and thread_ts:+ _post_signal_evidence_thread(slack, channel_id, str(thread_ts), signals)+ return True+ except Exception:+ logger.exception("Failed to deliver signals inbox-item Slack notification", extra=log_context)+ return False++def dispatch_inbox_item_notifications(report_id: str,team_id: int,@@ -701,32 +743,118 @@ def dispatch_inbox_item_notifications(sent = 0for route in routes:- channel_id = _channel_id_from_target(route.channel)- log_context = {- "report_id": report_id,- "team_id": team_id,- "channel": _channel_display_name(route.channel),- "destination": "team" if route.is_team_channel else "user",- }- try:- slack = SlackIntegration(route.integration)- mentions = _resolve_reviewer_mentions(slack, route.users)- blocks, text = _build_message_blocks(- report,- priority=priority,- source_products=sources,- reviewer_mentions=mentions,- repository=repository,- )- response = slack.client.chat_postMessage(channel=channel_id, blocks=blocks, text=text)+ if _deliver_route_notification(+ report,+ route,+ priority=priority,+ source_products=sources,+ repository=repository,+ signals=signals,+ ):sent += 1- thread_ts = response.get("ts") if hasattr(response, "get") else None- if signals and thread_ts:- _post_signal_evidence_thread(slack, channel_id, str(thread_ts), signals)- except Exception:- logger.exception("Failed to deliver signals inbox-item Slack notification", extra=log_context)logger.info("dispatch_inbox_item_notifications: complete",extra={"report_id": report_id, "team_id": team_id, "messages_sent": sent, "routes": len(routes)},)return sent+++def dispatch_reviewer_added_notifications(+ report_id: str,+ team_id: int,+ added_github_logins: Iterable[str],+ source_products: list[str] | None = None,+ exclude_user_id: int | None = None,+) -> int:+ """Notify reviewers a human just added to an already-actionable report.++ Unlike `dispatch_inbox_item_notifications` — fired once, from the report-generation+ pipeline, when a report first becomes READY — this fires when someone manually adds+ reviewers afterwards, so a reviewer who wasn't on the report at generation time still+ hears about it. It targets only the given logins and only their own configured Slack+ channel: a manual add is a personal ping, so there's no team-default fallback (that+ would ping the whole team for a one-person add) and a reviewer with no personal channel+ set up (or whose min-priority filters the report out) gets nothing.++ Gated on the same READY + actionable condition as the initial notification, so it only+ fires for reports that would themselves have notified. `exclude_user_id` drops the actor+ so someone adding themselves isn't pinged. Best-effort; returns messages sent.+ """+ added_logins = {s.strip().lower() for s in added_github_logins if s and s.strip()}+ if not added_logins:+ return 0++ try:+ report = SignalReport.objects.get(id=report_id, team_id=team_id)+ except SignalReport.DoesNotExist:+ logger.warning(+ "dispatch_reviewer_added_notifications: report not found",+ extra={"report_id": report_id, "team_id": team_id},+ )+ return 0++ # Mirror the initial notification's gate: only reports actually surfaced in the inbox+ # (READY and actionable) notify. Status is checked here because — unlike the generation+ # pipeline — this path has no upstream READY guarantee.+ if report.status != SignalReport.Status.READY or _latest_actionability(report) not in _ACTIONABLE_VALUES:+ return 0++ login_to_user = resolve_org_github_login_to_users(team_id, added_logins)+ user_ids = {user.id for user in login_to_user.values() if user.id != exclude_user_id}+ # Org membership alone isn't enough: on a private project an org member without project+ # access must not receive the report's contents, so intersect with the project's access set.+ if user_ids:+ user_ids &= set(report.team.all_users_with_access().filter(id__in=user_ids).values_list("id", flat=True))+ if not user_ids:+ return 0++ priority = _latest_priority(report)++ # Personal channels only — a manual add never falls back to the team channel.+ own_configs = _own_channel_configs_by_user(team_id, user_ids)+ users_by_id = {user.id: user for user in User.objects.filter(id__in=user_ids)}++ routes: dict[tuple[int, str], _ChannelRoute] = {}+ for user_id in sorted(user_ids):+ user = users_by_id.get(user_id)+ config = own_configs.get(user_id)+ if user is None or config is None:+ continue+ # An unprioritized report still pings a reviewer with no min-priority threshold: the+ # initial path would have delivered it via the team channel, but this path has no+ # fallback, so `_meets_min_priority`'s no-priority-never-notifies rule would lose it.+ min_priority = config.slack_notification_min_priority+ if (priority is not None or min_priority is not None) and not _meets_min_priority(priority, min_priority):+ continue+ integration = config.slack_notification_integration+ channel = config.slack_notification_channel+ if integration is None or not channel:+ continue+ key = (integration.id, _channel_id_from_target(channel))+ route = routes.get(key)+ if route is None:+ route = _ChannelRoute(integration, channel, is_team_channel=False)+ routes[key] = route+ route.users.append(user)++ if not routes:+ return 0++ sources = source_products or []+ repository = _report_repository(report)++ sent = 0+ for route in routes.values():+ if _deliver_route_notification(+ report,+ route,+ priority=priority,+ source_products=sources,+ repository=repository,+ ):+ sent += 1+ logger.info(+ "dispatch_reviewer_added_notifications: complete",+ extra={"report_id": report_id, "team_id": team_id, "messages_sent": sent, "routes": len(routes)},+ )+ return sentdiff --git a/products/signals/backend/tasks.py b/products/signals/backend/tasks.pyindex e713e14eaecc..81a097c2279b 100644--- a/products/signals/backend/tasks.py+++ b/products/signals/backend/tasks.py@@ -9,6 +9,7 @@ from celery import shared_taskfrom posthog.cloud_utils import get_cached_instance_licensefrom posthog.event_usage import groupsfrom posthog.exceptions_capture import capture_exception+from posthog.models import Teamfrom posthog.models.scoping import with_team_scopefrom posthog.ph_client import ph_scoped_capturefrom posthog.scoping_audit import skip_team_scope_audit@@ -16,6 +17,7 @@ from posthog.scoping_audit import skip_team_scope_auditfrom products.signals.backend.billing import current_billing_period_boundsfrom products.signals.backend.implementation_pr import PrCloseReason, close_implementation_pr_for_reportfrom products.signals.backend.models import SignalReportRefund+from products.signals.backend.slack_inbox_notifications import dispatch_reviewer_added_notificationslogger = structlog.get_logger(__name__)@@ -52,6 +54,48 @@ def close_dismissed_report_pr(report_id: str, team_id: int, reason: PrCloseReasoclose_implementation_pr_for_report(team_id, report_id, reason=reason)+@shared_task(+ name="products.signals.backend.tasks.send_reviewer_added_slack_notifications",+ ignore_result=True,+ max_retries=0,+)+@with_team_scope()+def send_reviewer_added_slack_notifications(+ report_id: str, team_id: int, added_github_logins: list[str], exclude_user_id: int | None = None+) -> None:+ """Slack-ping reviewers a human just added to a report.++ Runs on a worker because delivery makes several network calls (source-product metadata,+ Slack user lookups, chat.postMessage) that must not hold up the reviewer-edit request.+ Best-effort end to end — the dispatcher logs per-destination failures itself.+ """+ # Imported here rather than at module level: signal_metadata drags posthog.schema and+ # posthog.hogql.query onto the django.setup() path (tasks are autodiscovered by celery),+ # which the startup import budget forbids.+ from products.signals.backend.signal_metadata import fetch_source_products_for_reports # noqa: PLC0415++ team = Team.objects.get(id=team_id)+ # Source products are cosmetic (one metadata line in the message), so a failure fetching+ # them must not suppress the ping itself.+ source_products: list[str] | None = None+ try:+ meta = fetch_source_products_for_reports(team, [report_id]).get(report_id)+ source_products = meta.source_products if meta else None+ except Exception:+ logger.exception(+ "failed to fetch source products for reviewer-added notification",+ report_id=report_id,+ team_id=team_id,+ )+ dispatch_reviewer_added_notifications(+ report_id=report_id,+ team_id=team_id,+ added_github_logins=added_github_logins,+ source_products=source_products,+ exclude_user_id=exclude_user_id,+ )++def _capture_refund_sync_event(refund: SignalReportRefund, event: str, extra: dict[str, object]) -> None:organization = refund.team.organizationwith ph_scoped_capture() as capture:diff --git a/products/signals/backend/test/test_signal_report_artefact_api.py b/products/signals/backend/test/test_signal_report_artefact_api.pyindex 3d667d1acfae..0a510c636a5d 100644--- a/products/signals/backend/test/test_signal_report_artefact_api.py+++ b/products/signals/backend/test/test_signal_report_artefact_api.py@@ -243,6 +243,55 @@ class TestSignalReportArtefactViewSet(APIBaseTest):assert mock_autostart.call_args.kwargs["report_id"] == str(report.id)assert mock_autostart.call_args.kwargs["team_id"] == self.team.id+ def test_put_adding_reviewer_notifies_added_reviewer_on_commit(self):+ # Manually adding a reviewer enqueues a Slack ping (after commit) for only the newly-added+ # login, attributed so the actor is excluded — the point of this feature.+ report = self._create_report()+ artefact = self._create_artefact(report, content=[{"github_login": "alice"}])++ with (+ patch("products.signals.backend.views.send_reviewer_added_slack_notifications") as mock_task,+ patch(+ "products.signals.backend.auto_start.maybe_autostart_from_report_artefacts",+ new_callable=AsyncMock,+ ),+ ):+ with self.captureOnCommitCallbacks(execute=True):+ response = self.client.put(+ self._detail_url(str(report.id), str(artefact.id)),+ data=json.dumps({"content": [{"github_login": "alice"}, {"github_login": "bob"}]}),+ content_type="application/json",+ )++ assert response.status_code == status.HTTP_200_OK+ mock_task.delay.assert_called_once()+ kwargs = mock_task.delay.call_args.kwargs+ assert kwargs["added_github_logins"] == ["bob"]+ assert kwargs["team_id"] == self.team.id+ assert kwargs["exclude_user_id"] == self.user.id++ def test_put_removing_reviewer_does_not_notify(self):+ # Removing a reviewer is not an add, so nobody is pinged.+ report = self._create_report()+ artefact = self._create_artefact(report, content=[{"github_login": "alice"}, {"github_login": "bob"}])++ with (+ patch("products.signals.backend.views.send_reviewer_added_slack_notifications") as mock_task,+ patch(+ "products.signals.backend.auto_start.maybe_autostart_from_report_artefacts",+ new_callable=AsyncMock,+ ),+ ):+ with self.captureOnCommitCallbacks(execute=True):+ response = self.client.put(+ self._detail_url(str(report.id), str(artefact.id)),+ data=json.dumps({"content": [{"github_login": "alice"}]}),+ content_type="application/json",+ )++ assert response.status_code == status.HTTP_200_OK+ mock_task.delay.assert_not_called()+def test_put_reviewers_autostart_delegates_when_report_complete(self):# With actionability + repo + priority + reviewers all present, the reconstruction reaches# the actual autostart decision (delegated to maybe_autostart_implementation_task).diff --git a/products/signals/backend/test/test_slack_inbox_notifications.py b/products/signals/backend/test/test_slack_inbox_notifications.pyindex 3587c0780e2f..53fbf9395d7e 100644--- a/products/signals/backend/test/test_slack_inbox_notifications.py+++ b/products/signals/backend/test/test_slack_inbox_notifications.py@@ -7,6 +7,7 @@ from django.conf import settingsfrom social_django.models import UserSocialAuth+from posthog.constants import AvailableFeaturefrom posthog.models import Organization, Team, Userfrom posthog.models.integration import Integrationfrom posthog.models.organization import OrganizationMembership@@ -28,7 +29,11 @@ from products.signals.backend.slack_inbox_notifications import (_signal_source_line,_summary_excerpt,dispatch_inbox_item_notifications,+ dispatch_reviewer_added_notifications,)+from products.signals.backend.tasks import send_reviewer_added_slack_notifications++from ee.models.rbac.access_control import AccessControl@pytest.mark.parametrize(@@ -1012,3 +1017,176 @@ def test_dispatch_caps_thread_signals_and_posts_overflow_note(org_and_team):assert fake_client.chat_postMessage.call_count == 1 + _MAX_THREAD_SIGNALS + 1overflow_call = fake_client.chat_postMessage.call_args_list[-1]assert f"+{extra_count} more signals in PostHog" in overflow_call.kwargs["text"]+++def test_reviewer_added_notifies_added_reviewer_on_own_channel(org_and_team):+ # Someone manually added to a READY, actionable report is pinged on their own channel,+ # even though they weren't a suggested reviewer when the report first went ready.+ org, team = org_and_team+ user = _make_reviewer_user(org, "[email protected]", "added-bot")+ integration = _make_slack_integration(team, user)+ SignalUserAutonomyConfig.objects.create(+ user=user,+ slack_notification_integration=integration,+ slack_notification_channel="C123|#inbox",+ )+ report = _make_ready_report(team, priority=AutonomyPriority.P1)++ fake_client = MagicMock()+ with (+ patch("products.signals.backend.slack_inbox_notifications.SlackIntegration") as slack_cls,+ patch(+ "products.signals.backend.slack_inbox_notifications.lookup_slack_user_id_by_email",+ return_value="U_ADDED",+ ),+ ):+ slack_cls.return_value.client = fake_client+ sent = dispatch_reviewer_added_notifications(str(report.id), team.id, ["added-bot"])++ assert sent == 1+ assert fake_client.chat_postMessage.call_args.kwargs["channel"] == "C123"+++def test_reviewer_added_skips_org_member_without_project_access(org_and_team):+ # Org membership alone must not leak a private project's report into Slack: a member+ # locked out of the project (project marked private, no explicit access) gets no ping.+ org, team = org_and_team+ org.available_product_features = [{"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL}]+ org.save()+ AccessControl.objects.create(team=team, resource="project", resource_id=str(team.id), access_level="none")++ user = _make_reviewer_user(org, "[email protected]", "no-access-bot")+ integration = _make_slack_integration(team, user)+ SignalUserAutonomyConfig.objects.create(+ user=user,+ slack_notification_integration=integration,+ slack_notification_channel="C123|#inbox",+ )+ report = _make_ready_report(team, priority=AutonomyPriority.P1)++ with patch("products.signals.backend.slack_inbox_notifications.SlackIntegration") as slack_cls:+ sent = dispatch_reviewer_added_notifications(str(report.id), team.id, ["no-access-bot"])++ assert sent == 0+ assert slack_cls.call_count == 0+++ ("min_priority", "expected_sent"),+ [+ # No threshold: an unprioritized report still pings — the initial path would have+ # delivered it via the team channel, and this personal path has no fallback.+ (None, 1),+ # An explicit threshold keeps filtering unprioritized reports out.+ (AutonomyPriority.P1, 0),+ ],+)+def test_reviewer_added_unprioritized_report(org_and_team, min_priority, expected_sent):+ org, team = org_and_team+ user = _make_reviewer_user(org, "[email protected]", "added-noprio-bot")+ integration = _make_slack_integration(team, user)+ SignalUserAutonomyConfig.objects.create(+ user=user,+ slack_notification_integration=integration,+ slack_notification_channel="C555|#inbox",+ slack_notification_min_priority=min_priority,+ )+ report = _make_ready_report(team, priority=None)++ fake_client = MagicMock()+ with (+ patch("products.signals.backend.slack_inbox_notifications.SlackIntegration") as slack_cls,+ patch(+ "products.signals.backend.slack_inbox_notifications.lookup_slack_user_id_by_email",+ return_value="U_ADDED",+ ),+ ):+ slack_cls.return_value.client = fake_client+ sent = dispatch_reviewer_added_notifications(str(report.id), team.id, ["added-noprio-bot"])++ assert sent == expected_sent+++def test_reviewer_added_skips_when_report_not_ready(org_and_team):+ # The add-time ping mirrors the initial notification's gate: a report that isn't READY+ # (still being generated) must not notify.+ org, team = org_and_team+ user = _make_reviewer_user(org, "[email protected]", "added-bot2")+ integration = _make_slack_integration(team, user)+ SignalUserAutonomyConfig.objects.create(+ user=user,+ slack_notification_integration=integration,+ slack_notification_channel="C1|#c",+ )+ report = _make_ready_report(team, priority=AutonomyPriority.P1)+ SignalReport.objects.filter(id=report.id).update(status=SignalReport.Status.IN_PROGRESS)++ with patch("products.signals.backend.slack_inbox_notifications.SlackIntegration") as slack_cls:+ sent = dispatch_reviewer_added_notifications(str(report.id), team.id, ["added-bot2"])++ assert sent == 0+ assert slack_cls.call_count == 0+++def test_reviewer_added_does_not_fall_back_to_team_channel(org_and_team):+ # A manual add is a personal ping — a reviewer with no own channel gets nothing, rather+ # than broadcasting to the whole team's default channel for a one-person add.+ org, team = org_and_team+ user = _make_reviewer_user(org, "[email protected]", "added-bot3")+ _make_slack_integration(team, user)+ _set_team_channel(team, "CTEAM|#signals")+ SignalUserAutonomyConfig.objects.create(user=user) # no personal slack config+ report = _make_ready_report(team, priority=AutonomyPriority.P2)++ with patch("products.signals.backend.slack_inbox_notifications.SlackIntegration") as slack_cls:+ sent = dispatch_reviewer_added_notifications(str(report.id), team.id, ["added-bot3"])++ assert sent == 0+ assert slack_cls.call_count == 0+++def test_reviewer_added_excludes_actor(org_and_team):+ # Adding yourself shouldn't ping you.+ org, team = org_and_team+ user = _make_reviewer_user(org, "[email protected]", "self-bot")+ integration = _make_slack_integration(team, user)+ SignalUserAutonomyConfig.objects.create(+ user=user,+ slack_notification_integration=integration,+ slack_notification_channel="C9|#c",+ )+ report = _make_ready_report(team, priority=AutonomyPriority.P1)++ with patch("products.signals.backend.slack_inbox_notifications.SlackIntegration") as slack_cls:+ sent = dispatch_reviewer_added_notifications(str(report.id), team.id, ["self-bot"], exclude_user_id=user.id)++ assert sent == 0+ assert slack_cls.call_count == 0+++def test_reviewer_added_task_still_dispatches_when_source_product_lookup_fails(org_and_team):+ # Source products are cosmetic; a failure fetching them must not suppress the ping.+ org, team = org_and_team+ with (+ # The task imports this lazily from signal_metadata, so patch it at its source module.+ patch(+ "products.signals.backend.signal_metadata.fetch_source_products_for_reports",+ side_effect=Exception("clickhouse unavailable"),+ ),+ patch("products.signals.backend.tasks.dispatch_reviewer_added_notifications") as mock_dispatch,+ ):+ send_reviewer_added_slack_notifications(+ report_id="019f0000-0000-7000-8000-000000000000",+ team_id=team.id,+ added_github_logins=["someone"],+ )++ mock_dispatch.assert_called_once()+ assert mock_dispatch.call_args.kwargs["source_products"] is Nonediff --git a/products/signals/backend/views.py b/products/signals/backend/views.pyindex 3f506cf1616b..3016e3c35399 100644--- a/products/signals/backend/views.py+++ b/products/signals/backend/views.py@@ -1,5 +1,6 @@import jsonimport uuid+from collections.abc import Sequencefrom datetime import UTC, timedeltafrom typing import cast@@ -123,7 +124,7 @@ from products.signals.backend.task_attribution import (resolve_request_attribution,resolve_task_id_from_header,)-from products.signals.backend.tasks import sync_signals_refund_credit+from products.signals.backend.tasks import send_reviewer_added_slack_notifications, sync_signals_refund_creditfrom products.signals.backend.temporal.backfill_error_tracking import (BackfillErrorTrackingInput,BackfillErrorTrackingWorkflow,@@ -2314,6 +2315,18 @@ class SignalReportArtefactViewSet(),)+ # A human added reviewers: ping the newly-added ones on their own Slack channel so+ # someone added after generation still hears about an actionable report, mirroring+ # the notification sent when it first went ready. Removals aren't notified.+ prior_login_set = set(prior_logins)+ added_logins = [login for login in new_logins if login not in prior_login_set]+ if added_logins:+ self._schedule_reviewer_added_slack_notifications(+ report_id=str(artefact.report_id),+ added_logins=added_logins,+ actor_user_id=attribution.user_id,+ )+# Return the read-shape (enriched) so the client sees the canonical result.login_map = resolve_org_github_login_to_users(self.team.id, list(seen)) if seen else {}read_serializer = SignalReportArtefactSerializer(@@ -2325,6 +2338,27 @@ class SignalReportArtefactViewSet()return Response(read_serializer.data)+ def _schedule_reviewer_added_slack_notifications(+ self, *, report_id: str, added_logins: Sequence[str], actor_user_id: int | None+ ) -> None:+ """After commit, Slack-notify reviewers a human just added to this report.++ Enqueued on commit so nothing is sent if the write rolls back, and so delivery's+ network calls (metadata lookups, Slack) run on a worker instead of holding up the+ request. Best-effort — a Slack failure must never break the reviewer edit.+ """+ team_id = self.team.id+ # robust=True: a broker outage while enqueuing must not 500 an edit that already committed.+ transaction.on_commit(+ lambda: send_reviewer_added_slack_notifications.delay(+ report_id=report_id,+ team_id=team_id,+ added_github_logins=list(added_logins),+ exclude_user_id=actor_user_id,+ ),+ robust=True,+ )+@staticmethoddef _write_response_data(artefact: SignalReportArtefact) -> dict:"""Build the create/update response payload, parsing stored JSON content for the echo."""