Skip to content

: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.

feat(signals): send mobile report and pull request notifications (#118573)

Chris Volzere752dbf3969a
diff --git a/docs/internal/mobilehog-release-checks.md b/docs/internal/mobilehog-release-checks.md
index 4cd70bce286b..ffe60665e704 100644
--- a/docs/internal/mobilehog-release-checks.md
+++ b/docs/internal/mobilehog-release-checks.md
@@ -54,6 +54,8 @@ Task completion from Desktop or mobile uses the same server-side owner notificat
The app registers after sign-in and retries when it becomes active. Notification permissions stay in iOS settings. Expo push delivery can be tested on a supported iOS simulator or a physical device; it needs a push-enabled native build.
To check cross-device delivery, start a cloud task from Desktop, put the mobile app in the background, and confirm that the completion alert arrives and opens that task. Server delivery metrics count Expo acceptance, not confirmed device delivery.
+Self-driving pushes use the same `posthog-code-mobile-push` flag as task pushes. A report first appearing sends "New report for you" to its suggested reviewers. A PR becoming open sends "PR ready to review" to the linked reports' active claimant and suggested reviewers, with one push per person when reports share the PR. Recipients must still have project access, and tapping either alert opens the report. Importing historical legacy assignments, including `backfill_report_pull_requests`, sends no PR-ready push.
+
## Self-driving and task conversations
Self-driving lists reports needing attention and PRs ready for review where the signed-in user is a suggested reviewer.
diff --git a/posthog/test/repo_invariants/setup_receivers_baseline.txt b/posthog/test/repo_invariants/setup_receivers_baseline.txt
index 8bdae774b496..d0fd4cedd677 100644
--- a/posthog/test/repo_invariants/setup_receivers_baseline.txt
+++ b/posthog/test/repo_invariants/setup_receivers_baseline.txt
@@ -237,6 +237,7 @@ post_save:products.signals.backend.receivers.capture_status_change_analytics
post_save:products.signals.backend.receivers.close_pr_when_report_dismissed
post_save:products.signals.backend.receivers.emit_report_embedding_on_document_change
post_save:products.signals.backend.receivers.mark_scout_suggestions_stale_on_fleet_change
+post_save:products.signals.backend.receivers.push_report_to_reviewers_when_first_visible
post_save:products.signals.backend.receivers.reconcile_report_embedding_on_verdict_saved
post_save:products.signals.backend.receivers.requeue_report_checks_on_scout_resume
post_save:products.signals.backend.receivers.roll_up_plan_parents_when_report_closes
diff --git a/products/signals/backend/inbox_push_notifications.py b/products/signals/backend/inbox_push_notifications.py
new file mode 100644
index 000000000000..39d74dc7c39d
--- /dev/null
+++ b/products/signals/backend/inbox_push_notifications.py
@@ -0,0 +1,201 @@
+"""Mobile push notifications for inbox reports.
+
+Two events reach the PostHog mobile app: a report first surfaces with the person as a suggested
+reviewer, and a report's pull request becomes ready for review. Both use the Expo sender and the
+feature flag of the task-run pushes in `products.tasks.backend.push_dispatcher`, so one flag turns
+all mobile pushes on or off for a person.
+
+Recipients resolve on a worker after the triggering write commits, because a report born visible
+gets its reviewers later in the same transaction, and the queries must not hold up a summary
+activity or a pull request webhook. Best effort throughout: a push failure never fails the report
+transition or the pull request sync that triggered it.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Collection
+
+from django.db import transaction
+
+import structlog
+import posthoganalytics
+
+from posthog.models.user import User
+from posthog.tasks.push_notifications import send_user_push
+
+from products.signals.backend.models import SignalReport, SignalReportArtefact, SignalReportPullRequest
+from products.signals.backend.report_claims import get_active_claims, responsible_user
+from products.signals.backend.slack_inbox_notifications import resolve_org_suggested_reviewer_user_ids
+
+logger = structlog.get_logger(__name__)
+
+FEATURE_FLAG_KEY = "posthog-code-mobile-push"
+REPORT_VISIBLE_TITLE = "New report for you"
+PULL_REQUEST_READY_TITLE = "PR ready to review"
+
+# A push for one of these would open a report the inbox no longer lists.
+_HIDDEN_STATUSES = (SignalReport.Status.DELETED, SignalReport.Status.SUPPRESSED)
+
+
+def schedule_report_visible_push(*, team_id: int, report_id: str) -> None:
+ """Queue the "new report" push for after the current transaction commits.
+
+ `robust=True` keeps a broker outage from failing the transition that already committed.
+ """
+ # Function-local because `tasks` imports this module for the task bodies.
+ from products.signals.backend.tasks import send_report_visible_push # noqa: PLC0415
+
+ transaction.on_commit(
+ lambda: send_report_visible_push.delay(team_id=team_id, report_id=report_id),
+ robust=True,
+ )
+
+
+def schedule_pull_request_ready_push(pull_request: SignalReportPullRequest, *, previous_state: str) -> None:
+ """Queue the "PR ready" push when this write moved the pull request into `open`.
+
+ `previous_state` is the state the caller read under its row lock. Only the write that moves the
+ pull request into `open` queues the push, because every later writer reads `open` there.
+ """
+ if previous_state == SignalReportPullRequest.State.OPEN or pull_request.state != SignalReportPullRequest.State.OPEN:
+ return
+
+ from products.signals.backend.tasks import send_pull_request_ready_push # noqa: PLC0415
+
+ team_id = pull_request.team_id
+ pull_request_id = str(pull_request.id)
+ transaction.on_commit(
+ lambda: send_pull_request_ready_push.delay(team_id=team_id, pull_request_id=pull_request_id),
+ robust=True,
+ )
+
+
+def notify_report_visible(*, team_id: int, report_id: str) -> list[int]:
+ """Push the new report to its suggested reviewers. Returns the user ids a push was queued for.
+
+ A report with no reviewer that resolves to a project member pushes to nobody, rather than to
+ the whole team.
+ """
+ report = (
+ SignalReport.objects.filter(team_id=team_id, id=report_id)
+ .exclude(status__in=_HIDDEN_STATUSES)
+ .select_related("team")
+ .first()
+ )
+ if report is None:
+ return []
+ reviewer_ids = resolve_org_suggested_reviewer_user_ids(team_id=team_id, report_ids=[str(report.id)]).get(
+ str(report.id), set()
+ )
+ if not reviewer_ids:
+ return []
+ return _push_report(
+ report,
+ list(report.team.all_users_with_access().filter(id__in=reviewer_ids).order_by("id")),
+ kind="report_visible",
+ title=REPORT_VISIBLE_TITLE,
+ body=report.title or "Untitled report",
+ )
+
+
+def notify_pull_request_ready(*, team_id: int, pull_request_id: str) -> list[int]:
+ """Push a ready pull request to each linked report's claimant and suggested reviewers.
+
+ The claimant is the person who answers for the active claim of any kind, so a report handed to
+ the agent pushes the person who started the agent's task.
+
+ A person linked to several reports that share the pull request gets one push, for the oldest
+ report. Returns the user ids a push was queued for.
+ """
+ pull_request = SignalReportPullRequest.objects.for_team(team_id).filter(id=pull_request_id).first()
+ # Re-read on the worker, because the pull request can return to draft or get approved between
+ # the transition and this task.
+ if (
+ pull_request is None
+ or pull_request.state != SignalReportPullRequest.State.OPEN
+ or pull_request.review_decision == SignalReportPullRequest.ReviewDecision.APPROVED
+ ):
+ return []
+
+ linked_report_ids = SignalReportArtefact.objects.filter(team_id=team_id, pull_request_id=pull_request.id).values(
+ "report_id"
+ )
+ reports = list(
+ SignalReport.objects.filter(team_id=team_id, id__in=linked_report_ids)
+ .exclude(status__in=_HIDDEN_STATUSES)
+ .select_related("team")
+ .order_by("created_at", "id")
+ )
+ if not reports:
+ return []
+ report_ids = [str(report.id) for report in reports]
+ recipients_by_report = resolve_org_suggested_reviewer_user_ids(team_id=team_id, report_ids=report_ids)
+ claims = get_active_claims(team_id=team_id, report_ids=report_ids)
+ for report in reports:
+ recipient_ids = recipients_by_report.setdefault(str(report.id), set())
+ claim = claims.get(str(report.id))
+ claimant = responsible_user(claim) if claim is not None else None
+ if claimant is not None:
+ recipient_ids.add(claimant.id)
+ all_recipient_ids = set().union(*recipients_by_report.values())
+ if not all_recipient_ids:
+ return []
+ # Calculate access once for the batch, including claimants who may have lost project access.
+ users_by_id = {user.id: user for user in reports[0].team.all_users_with_access().filter(id__in=all_recipient_ids)}
+ pushed: list[int] = []
+ for report in reports:
+ recipient_ids = recipients_by_report[str(report.id)] - set(pushed)
+ pushed.extend(
+ _push_report(
+ report,
+ [users_by_id[user_id] for user_id in sorted(recipient_ids) if user_id in users_by_id],
+ kind="pull_request_ready",
+ title=PULL_REQUEST_READY_TITLE,
+ body=report.title or f"{pull_request.repository}#{pull_request.number}",
+ )
+ )
+ return pushed
+
+
+def _push_report(report: SignalReport, users: Collection[User], *, kind: str, title: str, body: str) -> list[int]:
+ if not users:
+ return []
+ data = {
+ "type": "report",
+ "report_id": str(report.id),
+ "project_id": report.team_id,
+ "notificationKind": kind,
+ "url": f"posthog://inbox/{report.id}",
+ }
+ pushed: list[int] = []
+ for user in users:
+ try:
+ if not _push_enabled(user):
+ continue
+ send_user_push.delay(user.id, title, body, data)
+ pushed.append(user.id)
+ except Exception:
+ logger.warning(
+ "signals.inbox_push.enqueue_failed",
+ team_id=report.team_id,
+ report_id=str(report.id),
+ user_id=user.id,
+ kind=kind,
+ exc_info=True,
+ )
+ return pushed
+
+
+def _push_enabled(user: User) -> bool:
+ try:
+ return bool(
+ posthoganalytics.feature_enabled(
+ FEATURE_FLAG_KEY,
+ user.distinct_id or f"user_{user.id}",
+ send_feature_flag_events=False,
+ )
+ )
+ except Exception:
+ # Fail closed, so a flag service outage cannot turn pushes on for every user.
+ logger.warning("signals.inbox_push.flag_check_failed", user_id=user.id, exc_info=True)
+ return False
diff --git a/products/signals/backend/pull_requests.py b/products/signals/backend/pull_requests.py
index 514178aa66d4..9a8cab8ed1a1 100644
--- a/products/signals/backend/pull_requests.py
+++ b/products/signals/backend/pull_requests.py
@@ -110,12 +110,17 @@ def link_pull_request(
if pr.state != SignalReportPullRequest.State.MERGED and details.state != SignalReportPullRequest.State.UNKNOWN:
# Imported/task snapshots must not overwrite a state already verified with GitHub.
if state_source == PullRequestStateSource.GITHUB or pr.checked_at is None:
+ previous_state = pr.state
pr.state = details.state
if state_source == PullRequestStateSource.GITHUB:
pr.checked_at = timezone.now()
pr.save(update_fields=["state", "checked_at", "updated_at"])
# Wait for the complete PR batch and release its locks before locking shared reports.
transaction.on_commit(partial(reconcile_reports_for_pull_request, team_id=report.team_id, pr_id=str(pr.id)))
+ if state_source != PullRequestStateSource.LEGACY_ASSIGNMENT:
+ from products.signals.backend.inbox_push_notifications import schedule_pull_request_ready_push
+
+ schedule_pull_request_ready_push(pr, previous_state=previous_state)
links = SignalReportArtefact.objects.filter(
team_id=report.team_id,
report_id=report.id,
@@ -282,6 +287,7 @@ def update_pull_request_state(
)
if pr is None:
return 0
+ previous_state = pr.state
if pr.state != SignalReportPullRequest.State.MERGED:
pr.state = state
update_fields = ["state", "checked_at", "updated_at"]
@@ -291,6 +297,9 @@ def update_pull_request_state(
pr.checked_at = timezone.now()
pr.save(update_fields=update_fields)
schedule_participant_refresh(pr)
+ from products.signals.backend.inbox_push_notifications import schedule_pull_request_ready_push
+
+ schedule_pull_request_ready_push(pr, previous_state=previous_state)
for report in reports:
apply_report_completion(report)
return len(reports)
diff --git a/products/signals/backend/receivers.py b/products/signals/backend/receivers.py
index 1e55a2bb1388..eb4032b5e373 100644
--- a/products/signals/backend/receivers.py
+++ b/products/signals/backend/receivers.py
@@ -109,6 +109,30 @@ def schedule_handover_for_report_change(sender: type, instance: SignalReport, **
transaction.on_commit(lambda: schedule_report_replacements(team_id, report_id), robust=True)
+@receiver(post_save, sender=SignalReport)
+def push_report_to_reviewers_when_first_visible(
+ sender: type[SignalReport],
+ instance: SignalReport,
+ created: bool,
+ update_fields: set[str] | None = None,
+ **kwargs: Any,
+) -> None:
+ """Send the "new report" mobile push once, on the save that stamps `first_visible_at`.
+
+ A pipeline report gets the stamp from `transition_to`, which always names it in `update_fields`.
+ A report born visible (scout, custom agent, plan layer) carries it from creation.
+ """
+ if instance.first_visible_at is None:
+ return
+ if not created and (update_fields is None or "first_visible_at" not in update_fields):
+ return
+ # Function-local to keep the push module's imports (Slack notifications, the Celery sender) off
+ # the django.setup() path.
+ from products.signals.backend.inbox_push_notifications import schedule_report_visible_push # noqa: PLC0415
+
+ schedule_report_visible_push(team_id=instance.team_id, report_id=str(instance.id))
+
+
def sync_task_run_pr_to_assignments(sender: type, instance: Any, created: bool, **kwargs: Any) -> None:
"""Copy a PR reported by a PR-bearing task run onto its signal report assignments."""
try:
diff --git a/products/signals/backend/slack_inbox_notifications.py b/products/signals/backend/slack_inbox_notifications.py
index f01b5a63d07e..b4307aca05dd 100644
--- a/products/signals/backend/slack_inbox_notifications.py
+++ b/products/signals/backend/slack_inbox_notifications.py
@@ -17,7 +17,7 @@ from __future__ import annotations
import json
import logging
-from collections.abc import Callable, Iterable
+from collections.abc import Callable, Collection, Iterable
from django.conf import settings
@@ -172,45 +172,40 @@ def _latest_actionability(report: SignalReport) -> str | None:
return value if isinstance(value, str) else None
-def _resolve_suggested_reviewer_user_ids(report: SignalReport) -> set[int]:
- """Resolve the report's suggested reviewers to PostHog user IDs.
+def resolve_org_suggested_reviewer_user_ids(*, team_id: int, report_ids: Collection[str]) -> dict[str, set[int]]:
+ """Resolve each report's latest reviewers within the team's organization.
- Uses the same enrichment path the API uses, so a reviewer stored by user uuid resolves whether
- or not they have GitHub linked, and one stored by login is still picked up after they connect
- their GitHub account.
+ Callers must intersect these candidate IDs with project access before delivering content.
"""
artefacts = list(
- report.artefacts.filter(
+ SignalReportArtefact.objects.filter(
+ team_id=team_id,
+ report__team_id=team_id,
+ report_id__in=report_ids,
type=SignalReportArtefact.ArtefactType.SUGGESTED_REVIEWERS,
- ).order_by("-created_at")[:1]
+ )
+ .order_by("report_id", "-created_at")
+ .distinct("report_id")
)
if not artefacts:
- return set()
+ return {}
logins = normalized_github_logins_from_suggested_reviewer_artefacts(artefacts)
user_uuids = normalized_user_uuids_from_suggested_reviewer_artefacts(artefacts)
- if not logins and not user_uuids:
- return set()
- login_map = resolve_org_github_login_to_users(report.team_id, logins) if logins else {}
- uuid_map = resolve_org_users_by_uuid(report.team_id, user_uuids) if user_uuids else {}
- unmapped_count = len(logins - login_map.keys())
- if unmapped_count:
- # These reviewers can't get a personal-channel notification; when the whole list is
- # unmapped the report falls back to the team channel despite being "assigned".
- # Counts only: GitHub logins are member PII and must not reach logs.
- logger.info(
- "slack routing for report %s (team %d): %d of %d suggested reviewer login(s) map to no PostHog user",
- report.id,
- report.team_id,
- unmapped_count,
- len(logins),
- )
- if not login_map and not uuid_map:
- return set()
-
- # Enrich each artefact's payload to drop reviewers that didn't resolve to a user.
- resolved_user_ids: set[int] = set()
+ login_map = resolve_org_github_login_to_users(team_id, logins) if logins else {}
+ uuid_map = resolve_org_users_by_uuid(team_id, user_uuids) if user_uuids else {}
+ result: dict[str, set[int]] = {}
for art in artefacts:
+ report_logins = normalized_github_logins_from_suggested_reviewer_artefacts([art])
+ unmapped_count = len(report_logins - login_map.keys())
+ if unmapped_count:
+ logger.info(
+ "slack routing for report %s (team %d): %d of %d suggested reviewer login(s) map to no PostHog user",
+ art.report_id,
+ team_id,
+ unmapped_count,
+ len(report_logins),
+ )
try:
parsed = json.loads(art.content)
except (json.JSONDecodeError, TypeError, ValueError):
@@ -218,13 +213,30 @@ def _resolve_suggested_reviewer_user_ids(report: SignalReport) -> set[int]:
if not isinstance(parsed, list):
continue
enriched = enrich_reviewer_dicts_with_org_members(
- report.team_id, parsed, login_to_user=login_map, uuid_to_user=uuid_map
+ team_id, parsed, login_to_user=login_map, uuid_to_user=uuid_map, scout_display_names={}
)
+ user_ids: set[int] = set()
for entry in enriched:
user = entry.get("user") if isinstance(entry, dict) else None
if isinstance(user, dict) and user.get("id"):
- resolved_user_ids.add(int(user["id"]))
- return set(report.team.all_users_with_access().filter(id__in=resolved_user_ids).values_list("id", flat=True))
+ user_ids.add(int(user["id"]))
+ result[str(art.report_id)] = user_ids
+ return result
+
+
+def resolve_suggested_reviewer_user_ids(report: SignalReport) -> set[int]:
+ """Resolve the report's suggested reviewers to users with project access.
+
+ Uses the same enrichment path the API uses, so a reviewer stored by user uuid resolves whether
+ or not they have GitHub linked, and one stored by login is still picked up after they connect
+ their GitHub account.
+ """
+ user_ids = resolve_org_suggested_reviewer_user_ids(team_id=report.team_id, report_ids=[str(report.id)]).get(
+ str(report.id), set()
+ )
+ if not user_ids:
+ return set()
+ return set(report.team.all_users_with_access().filter(id__in=user_ids).values_list("id", flat=True))
def _own_target_configs_by_user(team_id: int, user_ids: set[int]) -> dict[int, SignalUserAutonomyConfig]:
@@ -626,7 +638,7 @@ def _build_reviewer_routes(
team-default channel (if configured) with no mentions, so a team is notified even when none of
its members are linked to a resolvable GitHub identity.
"""
- reviewer_user_ids = _resolve_suggested_reviewer_user_ids(report)
+ reviewer_user_ids = resolve_suggested_reviewer_user_ids(report)
reviewer_users = {user.id: user for user in User.objects.filter(id__in=reviewer_user_ids)}
own_configs = _own_target_configs_by_user(report.team_id, reviewer_user_ids)
diff --git a/products/signals/backend/tasks.py b/products/signals/backend/tasks.py
index 5ff82578c31a..5ff77a8d88fb 100644
--- a/products/signals/backend/tasks.py
+++ b/products/signals/backend/tasks.py
@@ -33,6 +33,7 @@ from products.signals.backend.implementation_dispatch_tasks import (
sweep_implementation_dispatches as sweep_implementation_dispatches,
)
from products.signals.backend.implementation_pr import PrCloseReason, close_implementation_pr_for_report
+from products.signals.backend.inbox_push_notifications import notify_pull_request_ready, notify_report_visible
from products.signals.backend.inbox_summary import sync_pull_request_participants
from products.signals.backend.models import (
SignalReport,
@@ -768,6 +769,32 @@ def open_implementation_pr_for_review(team_id: int, report_id: str, pr_url: str)
open_pull_request_ready_for_review(team_id=team_id, report_id=report_id, pr_url=pr_url)
+@shared_task(
+ name="products.signals.backend.tasks.send_report_visible_push",
+ ignore_result=True,
+ max_retries=0,
+)
+@with_team_scope()
+def send_report_visible_push(team_id: int, report_id: str) -> None:
+ """Push a newly visible report to its suggested reviewers' mobile devices.
+
+ Never retried, because a retry after a partial fan-out would push twice to the reviewers it
+ already reached. The same holds for the pull request push below.
+ """
+ notify_report_visible(team_id=team_id, report_id=report_id)
+
+
+@shared_task(
+ name="products.signals.backend.tasks.send_pull_request_ready_push",
+ ignore_result=True,
+ max_retries=0,
+)
+@with_team_scope()
+def send_pull_request_ready_push(team_id: int, pull_request_id: str) -> None:
+ """Push a pull request that became ready for review to its reports' claimants and reviewers."""
+ notify_pull_request_ready(team_id=team_id, pull_request_id=pull_request_id)
+
+
@shared_task(
name="products.signals.backend.tasks.move_merged_report_signals",
ignore_result=True,
diff --git a/products/signals/backend/test/test_backfill_report_pull_requests.py b/products/signals/backend/test/test_backfill_report_pull_requests.py
index 5a2e4714359f..b7504586e342 100644
--- a/products/signals/backend/test/test_backfill_report_pull_requests.py
+++ b/products/signals/backend/test/test_backfill_report_pull_requests.py
@@ -82,10 +82,14 @@ class TestBackfillReportPullRequests(BaseTest):
}
)
SignalReportTask.objects.create(team=self.team, report=task_report, task=task, relationship="implementation")
- with patch("products.signals.backend.tasks.assign_reviewers_on_implementation_pr.delay") as reviewers:
+ with (
+ patch("products.signals.backend.tasks.assign_reviewers_on_implementation_pr.delay") as reviewers,
+ patch("products.signals.backend.tasks.send_pull_request_ready_push.delay") as ready_push,
+ ):
with self.captureOnCommitCallbacks(execute=True):
call_command("backfill_report_pull_requests", team_id=self.team.id, batch_size=1, stdout=StringIO())
reviewers.assert_not_called()
+ ready_push.assert_not_called()
assignment.refresh_from_db()
claim_id = SignalReportArtefact.objects.get(report=active, type="work_claim").id
assert claim_id is not None
diff --git a/products/signals/backend/test/test_inbox_push_notifications.py b/products/signals/backend/test/test_inbox_push_notifications.py
new file mode 100644
index 000000000000..4f44e7bacdc5
--- /dev/null
+++ b/products/signals/backend/test/test_inbox_push_notifications.py
@@ -0,0 +1,238 @@
+import json
+from datetime import UTC, datetime, timedelta
+
+from posthog.test.base import BaseTest
+from unittest.mock import call, patch
+
+from django.db import connection
+from django.test.utils import CaptureQueriesContext
+
+from parameterized import parameterized
+from social_django.models import UserSocialAuth
+
+from posthog.constants import AvailableFeature
+from posthog.models import Team, User
+
+from products.access_control.backend.models.access_control import AccessControl
+from products.signals.backend.artefact_attribution import ArtefactAttribution
+from products.signals.backend.inbox_push_notifications import notify_pull_request_ready
+from products.signals.backend.models import SignalReport, SignalReportArtefact, SignalReportPullRequest
+from products.signals.backend.pull_requests import (
+ PullRequestStateSource,
+ link_pull_request,
+ update_pull_request_review_decision,
+ update_pull_request_state,
+)
+from products.signals.backend.report_assignments import PullRequestDetails, create_claim
+
+# Task ORM model needed for a task-claim fixture; the tasks facade exposes DTOs only.
+from products.tasks.backend.models import Task
+
+PR_URL = "https://github.com/posthog/posthog/pull/123"
+VISIBLE_AT = datetime(2026, 1, 1, tzinfo=UTC)
+
+
+class TestInboxPushNotifications(BaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.reviewer = User.objects.create_and_join(self.organization, "[email protected]", None)
+ send_patch = patch("products.signals.backend.inbox_push_notifications.send_user_push.delay")
+ flag_patch = patch(
+ "products.signals.backend.inbox_push_notifications.posthoganalytics.feature_enabled", return_value=True
+ )
+ self.send_push = send_patch.start()
+ self.flag = flag_patch.start()
+ self.addCleanup(send_patch.stop)
+ self.addCleanup(flag_patch.stop)
+
+ def _report(self, status: SignalReport.Status, **fields: object) -> SignalReport:
+ return SignalReport.objects.create(
+ team=self.team, status=status, title="Checkout fails", summary="Summary", **fields
+ )
+
+ def _add_reviewers(self, report: SignalReport, *users: User) -> None:
+ SignalReportArtefact.objects.create(
+ team=self.team,
+ report=report,
+ type=SignalReportArtefact.ArtefactType.SUGGESTED_REVIEWERS,
+ content=json.dumps([{"user_uuid": str(user.uuid)} for user in users]),
+ )
+
+ def _make_visible(self, report: SignalReport) -> None:
+ report.save(update_fields=report.transition_to(SignalReport.Status.READY, title="Checkout fails", summary="S"))
+
+ @parameterized.expand([("transition_to_ready",), ("born_visible",)])
+ def test_first_visibility_pushes_to_suggested_reviewers(self, path: str) -> None:
+ if path == "transition_to_ready":
+ report = self._report(SignalReport.Status.IN_PROGRESS)
+ self._add_reviewers(report, self.reviewer)
+ with self.captureOnCommitCallbacks(execute=True):
+ self._make_visible(report)
+ else:
+ # The scout path writes reviewers after the report row, inside the same transaction.
+ with self.captureOnCommitCallbacks(execute=True):
+ report = self._report(SignalReport.Status.READY, first_visible_at=VISIBLE_AT)
+ self._add_reviewers(report, self.reviewer)
+
+ assert self.send_push.call_args_list == [
+ call(
+ self.reviewer.id,
+ "New report for you",
+ "Checkout fails",
+ {
+ "type": "report",
+ "report_id": str(report.id),
+ "project_id": self.team.id,
+ "notificationKind": "report_visible",
+ "url": f"posthog://inbox/{report.id}",
+ },
+ )
+ ]
+
+ @parameterized.expand(
+ [
+ ("no_reviewers", False, True, False),
+ ("flag_off", True, False, False),
+ ("visible_before", True, True, True),
+ ]
+ )
+ def test_report_visibility_pushes_nothing(
+ self, _name: str, has_reviewers: bool, flag_enabled: bool, visible_before: bool
+ ) -> None:
+ self.flag.return_value = flag_enabled
+ report = self._report(SignalReport.Status.IN_PROGRESS, first_visible_at=VISIBLE_AT if visible_before else None)
+ if has_reviewers:
+ self._add_reviewers(report, self.reviewer)
+
+ with self.captureOnCommitCallbacks(execute=True):
+ self._make_visible(report)
+
+ self.send_push.assert_not_called()
+
+ @parameterized.expand(
+ [
+ ("user_claim_by_a_reviewer", "user", SignalReportPullRequest.State.DRAFT, None, True),
+ ("task_claim", "task", SignalReportPullRequest.State.DRAFT, None, True),
+ ("already_open", "user", SignalReportPullRequest.State.OPEN, None, False),
+ (
+ "approved",
+ "user",
+ SignalReportPullRequest.State.DRAFT,
+ SignalReportPullRequest.ReviewDecision.APPROVED,
+ False,
+ ),
+ ]
+ )
+ def test_pull_request_ready_pushes_claimant_and_reviewers_once(
+ self, _name: str, claim_kind: str, initial_state: str, review_decision: str | None, expect_push: bool
+ ) -> None:
+ report = self._report(SignalReport.Status.READY)
+ if claim_kind == "user":
+ self._add_reviewers(report, self.user, self.reviewer)
+ create_claim(report, ArtefactAttribution.from_user(self.user.id))
+ else:
+ self._add_reviewers(report, self.reviewer)
+ task = Task.objects.create(
+ team=self.team,
+ title="Fix checkout",
+ description="d",
+ origin_product=Task.OriginProduct.USER_CREATED,
+ created_by=self.user,
+ )
+ create_claim(report, ArtefactAttribution.from_task(str(task.id)))
+ link_pull_request(
+ report=report,
+ details=PullRequestDetails(
+ url=PR_URL, repository="posthog/posthog", number=123, state=initial_state, merged=False
+ ),
+ actor=ArtefactAttribution.from_user(self.user.id),
+ claim_id=None,
+ state_source=PullRequestStateSource.GITHUB,
+ notify_reviewers=False,
+ )
+ update_pull_request_review_decision(
+ team_id=self.team.id, repository="posthog/posthog", number=123, review_decision=review_decision
+ )
+
+ with self.captureOnCommitCallbacks(execute=True):
+ update_pull_request_state(team_id=self.team.id, repository="posthog/posthog", number=123, state="open")
+
+ pushed = sorted((args[0], args[1]) for args, _ in self.send_push.call_args_list)
+ expected = sorted([(self.user.id, "PR ready to review"), (self.reviewer.id, "PR ready to review")])
+ assert pushed == (expected if expect_push else [])
+ for push in self.send_push.call_args_list:
+ assert push.args[3]["url"] == f"posthog://inbox/{report.id}"
+
+ @parameterized.expand([("project_access", True), ("no_project_access", False)])
+ def test_pull_request_ready_batches_reviewer_queries(self, _name: str, has_project_access: bool) -> None:
+ if not has_project_access:
+ self.organization.available_product_features = [
+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL}
+ ]
+ self.organization.save()
+ AccessControl.objects.create(
+ team=self.team, resource="project", resource_id=str(self.team.id), access_level="none"
+ )
+ login_reviewer = User.objects.create_and_join(self.organization, "[email protected]", None)
+ old_reviewer = User.objects.create_and_join(self.organization, "[email protected]", None)
+ UserSocialAuth.objects.create(
+ user=login_reviewer, provider="github", uid="login-reviewer", extra_data={"login": "login-reviewer"}
+ )
+ pull_request = SignalReportPullRequest.objects.for_team(self.team.id).create(
+ team=self.team, repository="posthog/posthog", number=123, url=PR_URL, state="open"
+ )
+
+ def add_linked_report(index: int = 0) -> SignalReport:
+ report = self._report(SignalReport.Status.READY)
+ SignalReport.objects.filter(team_id=self.team.id, id=report.id).update(
+ created_at=VISIBLE_AT + timedelta(days=index)
+ )
+ self._add_reviewers(report, old_reviewer)
+ report.artefacts.filter(type=SignalReportArtefact.ArtefactType.SUGGESTED_REVIEWERS).update(
+ created_at=VISIBLE_AT
+ )
+ reviewers = SignalReportArtefact.objects.create(
+ team=self.team,
+ report=report,
+ type=SignalReportArtefact.ArtefactType.SUGGESTED_REVIEWERS,
+ content=json.dumps([{"user_uuid": str(self.reviewer.uuid)}, {"github_login": "login-reviewer"}]),
+ )
+ SignalReportArtefact.objects.filter(team_id=self.team.id, id=reviewers.id).update(
+ created_at=VISIBLE_AT + timedelta(hours=1)
+ )
+ create_claim(report, ArtefactAttribution.from_user(self.user.id))
+ SignalReportArtefact.objects.create(
+ team=self.team,
+ report=report,
+ type=SignalReportArtefact.ArtefactType.PULL_REQUEST,
+ pull_request=pull_request,
+ content=json.dumps({"url": PR_URL}),
+ )
+ return report
+
+ oldest_report = add_linked_report()
+ with CaptureQueriesContext(connection) as one_report_queries:
+ first_pushed = notify_pull_request_ready(team_id=self.team.id, pull_request_id=str(pull_request.id))
+ expected_users = sorted([self.user.id, self.reviewer.id, login_reviewer.id]) if has_project_access else []
+ assert first_pushed == expected_users
+ self.send_push.reset_mock()
+
+ for index in range(1, 5):
+ add_linked_report(index)
+ other_team = Team.objects.create(organization=self.organization)
+ cross_team_reviewers = SignalReportArtefact.objects.create(
+ team=other_team,
+ report=oldest_report,
+ type=SignalReportArtefact.ArtefactType.SUGGESTED_REVIEWERS,
+ content=json.dumps([{"user_uuid": str(old_reviewer.uuid)}]),
+ )
+ SignalReportArtefact.objects.filter(team_id=other_team.id, id=cross_team_reviewers.id).update(
+ created_at=VISIBLE_AT + timedelta(hours=2)
+ )
+ with CaptureQueriesContext(connection) as many_report_queries:
+ pushed = notify_pull_request_ready(team_id=self.team.id, pull_request_id=str(pull_request.id))
+
+ assert pushed == expected_users
+ assert [push.args[0] for push in self.send_push.call_args_list] == expected_users
+ assert all(push.args[3]["report_id"] == str(oldest_report.id) for push in self.send_push.call_args_list)
+ assert len(many_report_queries) == len(one_report_queries)
diff --git a/products/signals/backend/test/test_slack_inbox_notifications.py b/products/signals/backend/test/test_slack_inbox_notifications.py
index dcd731551688..162635995292 100644
--- a/products/signals/backend/test/test_slack_inbox_notifications.py
+++ b/products/signals/backend/test/test_slack_inbox_notifications.py
@@ -32,11 +32,11 @@ from products.signals.backend.slack_inbox_notifications import (
_build_signal_thread_blocks,
_meets_min_priority,
_resolve_reviewer_mentions,
- _resolve_suggested_reviewer_user_ids,
_signal_source_line,
_summary_excerpt,
dispatch_inbox_item_notifications,
dispatch_reviewer_added_notifications,
+ resolve_suggested_reviewer_user_ids,
)
from products.signals.backend.slack_report_threads import report_id_for_slack_thread
from products.signals.backend.tasks import send_reviewer_added_slack_notifications
@@ -552,7 +552,7 @@ def test_reviewer_resolution_uses_only_the_latest_reviewer_row(
content=json.dumps([{"user_uuid": str(current_reviewer.uuid)}]),
)
- assert _resolve_suggested_reviewer_user_ids(report) == ({current_reviewer.id} if has_project_access else set())
+ assert resolve_suggested_reviewer_user_ids(report) == ({current_reviewer.id} if has_project_access else set())
@pytest.mark.django_db