: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): Send inbox Slack notifications once per channel (#60991)
Michael Matlokaf18b307d6e88
diff --git a/products/signals/backend/slack_inbox_notifications.py b/products/signals/backend/slack_inbox_notifications.pyindex 13a857d1affa..407861ff890b 100644--- a/products/signals/backend/slack_inbox_notifications.py+++ b/products/signals/backend/slack_inbox_notifications.py@@ -2,15 +2,19 @@When a report transitions to READY (a new inbox item lands), we look up thesuggested reviewers from its `suggested_reviewers` artefact, resolve them to-PostHog users, and dispatch a Slack message to each user that has configured a+PostHog users, and dispatch a Slack message for each user that has configured aSlack channel and integration in their `SignalUserAutonomyConfig`.+Reviewers are grouped by their resolved Slack channel so each channel receives a+single message — when several reviewers point at the same channel, that one+message tags all of them rather than posting once per reviewer.+Each user's `slack_notification_min_priority` filters out reports below theconfigured threshold (P0 is highest). When the report has no priorityjudgement, we notify regardless of the user's threshold — the inbox shouldnot silently swallow these.-Messages are framed for public channels: each post names the suggested reviewer+Messages are framed for public channels: each post names the suggested reviewers(Slack @mention when email matches the workspace, otherwise their PostHog name)."""@@ -242,6 +246,13 @@ def _recipient_presentation(return _RecipientPresentation(slack_mention=slack_mention, plain_name=plain_name)+def _recipient_label(recipient: _RecipientPresentation) -> str:+ # Mention pings the user inside mrkdwn; otherwise escape the plain name so it renders literally.+ return recipient.slack_mention or recipient.plain_name.replace("&", "&").replace("<", "<").replace(+ ">", ">"+ )++def _format_source_product_labels(source_products: list[str]) -> str:if not source_products:return ""@@ -267,7 +278,7 @@ def _build_message_blocks(*,priority: str | None,source_products: list[str],- recipient: _RecipientPresentation,+ recipients: list[_RecipientPresentation],implementation_pr_url: str | None = None,) -> tuple[list[dict], str]:title_line = report.title or "New signals inbox item"@@ -275,9 +286,7 @@ def _build_message_blocks(if len(header_text) > _SLACK_HEADER_MAX_LEN:header_text = header_text[: _SLACK_HEADER_MAX_LEN - 3] + "..."- recipient_label = recipient.slack_mention or recipient.plain_name.replace("&", "&").replace(- "<", "<"- ).replace(">", ">")+ recipient_label = ", ".join(_recipient_label(recipient) for recipient in recipients)metadata_parts = [f"Matched to {recipient_label} per code"]if priority:metadata_parts.insert(0, _slack_priority_label(priority))@@ -325,7 +334,8 @@ def _build_message_blocks(blocks.append({"type": "actions", "elements": action_elements})priority_suffix = f" ({priority})" if priority else ""- fallback_text = f"Inbox for {recipient.plain_name}{priority_suffix}: {title_line}"+ recipient_names = ", ".join(recipient.plain_name for recipient in recipients)+ fallback_text = f"Inbox for {recipient_names}{priority_suffix}: {title_line}"return blocks, fallback_text@@ -358,32 +368,43 @@ def dispatch_inbox_item_notifications(implementation_pr_url = fetch_implementation_pr_urls_for_reports([str(report.id)]).get(str(report.id))users_by_id = {user.id: user for user in User.objects.filter(id__in=[config.user_id for config in targets])}- sent = 0+ # Several reviewers can resolve to the same channel — group them so each channel gets a+ # single message that still tags every matched reviewer. Keyed by integration + channel id,+ # since the same channel id under a different integration is a distinct destination.+ channels: dict[tuple[int, str], list[SignalUserAutonomyConfig]] = {}for config in targets:if not _meets_min_priority(priority, config.slack_notification_min_priority):continue-- user = users_by_id.get(config.user_id)- if user is None:+ if config.user_id not in users_by_id:logger.warning("signals_inbox_slack_notification_missing_user",extra={"report_id": report_id, "team_id": team_id, "user_id": config.user_id},)continue-integration = config.slack_notification_integrationchannel = config.slack_notification_channelif integration is None or not channel:continue+ channels.setdefault((integration.id, _channel_id_from_target(channel)), []).append(config)++ sent = 0+ for configs in channels.values():+ # All configs in a group share the same integration and resolved channel id.+ integration = configs[0].slack_notification_integration+ channel = configs[0].slack_notification_channel+ if integration is None or not channel:+ continue # Needed to satisfy mypytry:slack = SlackIntegration(integration)- recipient = _recipient_presentation(user, slack, integration)+ recipients = [+ _recipient_presentation(users_by_id[config.user_id], slack, integration) for config in configs+ ]blocks, text = _build_message_blocks(report,priority=priority,source_products=sources,- recipient=recipient,+ recipients=recipients,implementation_pr_url=implementation_pr_url,)slack.client.chat_postMessage(@@ -398,7 +419,7 @@ def dispatch_inbox_item_notifications(extra={"report_id": report_id,"team_id": team_id,- "user_id": config.user_id,+ "user_ids": [config.user_id for config in configs],"channel": _channel_display_name(channel),},)diff --git a/products/signals/backend/test/test_slack_inbox_notifications.py b/products/signals/backend/test/test_slack_inbox_notifications.pyindex f3018970372f..5694b7ca848b 100644--- a/products/signals/backend/test/test_slack_inbox_notifications.py+++ b/products/signals/backend/test/test_slack_inbox_notifications.py@@ -74,7 +74,7 @@ def test_build_message_blocks_includes_recipient_and_posthog_code_button() -> Noreport,priority="P1",source_products=["error_tracking"],- recipient=recipient,+ recipients=[recipient],)assert blocks[0]["text"]["text"] == "📬 Checkout errors spiked"@@ -95,6 +95,18 @@ def test_build_message_blocks_includes_recipient_and_posthog_code_button() -> Noassert text == "Inbox for Marcus Twix (P1): Checkout errors spiked"+def test_build_message_blocks_tags_all_recipients() -> None:+ report = SignalReport(id="report-uuid", title="Shared channel report")+ recipients = [+ _RecipientPresentation(slack_mention="<@U123>", plain_name="Marcus Twix"),+ _RecipientPresentation(slack_mention=None, plain_name="Dana Snickers"),+ ]+ blocks, text = _build_message_blocks(report, priority="P2", source_products=[], recipients=recipients)++ assert blocks[1]["text"]["text"].startswith("*❗ P2 • Matched to <@U123>, Dana Snickers per code*")+ assert text == "Inbox for Marcus Twix, Dana Snickers (P2): Shared channel report"++def test_build_message_blocks_includes_github_pr_button_when_pr_url_provided() -> None:report = SignalReport(id="report-uuid",@@ -108,7 +120,7 @@ def test_build_message_blocks_includes_github_pr_button_when_pr_url_provided() -report,priority="P1",source_products=["error_tracking"],- recipient=recipient,+ recipients=[recipient],implementation_pr_url=pr_url,)@@ -126,7 +138,7 @@ def test_build_message_blocks_omits_github_pr_button_without_pr_url() -> None:report,priority=None,source_products=[],- recipient=recipient,+ recipients=[recipient],implementation_pr_url=None,)@@ -151,7 +163,7 @@ def test_build_message_blocks_prefixes_priority_with_emoji(priority: str, expectreport,priority=priority,source_products=[],- recipient=recipient,+ recipients=[recipient],)assert blocks[1]["text"]["text"] == f"*{expected_priority_label} • Matched to <@U123> per code*"@@ -424,3 +436,44 @@ def test_dispatch_continues_after_per_user_failure(org_and_team):assert sent == 1assert fake_client.chat_postMessage.call_count == 2+++def test_dispatch_sends_once_per_channel_when_reviewers_share_channel(org_and_team):+ org, team = org_and_team+ user1 = _make_reviewer_user(org, "[email protected]", "shared-login-1")+ user2 = _make_reviewer_user(org, "[email protected]", "shared-login-2")+ integration = _make_slack_integration(team, user1)+ # Both reviewers point at the same channel id — the display alias differs but the id matches.+ SignalUserAutonomyConfig.objects.create(+ user=user1,+ slack_notification_integration=integration,+ slack_notification_channel="C123|#inbox",+ )+ SignalUserAutonomyConfig.objects.create(+ user=user2,+ slack_notification_integration=integration,+ slack_notification_channel="C123|#inbox-alias",+ )+ report = _make_ready_report(team, suggested_logins=["shared-login-1", "shared-login-2"])++ mentions = {"[email protected]": "U_ONE", "[email protected]": "U_TWO"}++ 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",+ side_effect=lambda _slack, email: mentions.get(email),+ ),+ ):+ slack_cls.return_value.client = fake_client+ sent = dispatch_inbox_item_notifications(str(report.id), team.id)++ assert sent == 1+ assert fake_client.chat_postMessage.call_count == 1+ call_kwargs = fake_client.chat_postMessage.call_args.kwargs+ assert call_kwargs["channel"] == "C123"+ # The single message still tags both reviewers that resolved to the channel.+ section_text = call_kwargs["blocks"][1]["text"]["text"]+ assert "Matched to <@U_ONE>, <@U_TWO> per code" in section_text