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): add telemetry for unlinkable suggested reviewers (#83288)

Andrew Maguire0b9f2d3e22d3
diff --git a/products/signals/backend/artefact_schemas.py b/products/signals/backend/artefact_schemas.py
index 27102c78f7b5..fa564bb1c1ba 100644
--- a/products/signals/backend/artefact_schemas.py
+++ b/products/signals/backend/artefact_schemas.py
@@ -209,7 +209,9 @@ class SuggestedReviewerEntry(BaseModel):
def github_login_must_not_be_empty(cls, v: str) -> str:
if not v.strip():
raise ValueError("must not be empty or whitespace-only")
- return v
+ # Strip on the way in: read-time enrichment and autostart look logins up with
+ # `login.lower()` and no strip, so a padded login would persist but never match.
+ return v.strip()
class SuggestedReviewers(RootModel[list[SuggestedReviewerEntry]]):
diff --git a/products/signals/backend/auto_start.py b/products/signals/backend/auto_start.py
index a38760486394..0392110cf2f1 100644
--- a/products/signals/backend/auto_start.py
+++ b/products/signals/backend/auto_start.py
@@ -465,11 +465,21 @@ def _resolve_autostart_assignee(
login = reviewer.get("github_login")
if not login:
continue
- candidate = login_to_user.get(login.lower())
+ # strip + lower matches the resolver's key normalization, so a legacy padded login
+ # (stored before the schema stripped on write) still resolves.
+ candidate = login_to_user.get(str(login).strip().lower())
if isinstance(candidate, User):
candidate_users.append(candidate)
if not candidate_users:
+ attempted_count = len({str(r["github_login"]).lower() for r in identity_candidates if r.get("github_login")})
+ if attempted_count:
+ # Count only: GitHub logins are member PII and must not reach logs.
+ logger.info(
+ "no autostart identity: no suggested reviewer login maps to an org member",
+ team_id=team_id,
+ login_count=attempted_count,
+ )
return None
# Personal autonomy configs are optional: load any that exist to honor a reviewer's own
diff --git a/products/signals/backend/custom_agent/persistence.py b/products/signals/backend/custom_agent/persistence.py
index 1ccf8da9710f..9fc1ae6d4e83 100644
--- a/products/signals/backend/custom_agent/persistence.py
+++ b/products/signals/backend/custom_agent/persistence.py
@@ -8,6 +8,7 @@ from django.db import transaction
from products.signals.backend.artefact_schemas import ArtefactContent, SuggestedReviewers
from products.signals.backend.custom_agent.schemas import CustomAgentFinalReport
from products.signals.backend.models import ArtefactAttribution, SignalReport, SignalReportArtefact
+from products.signals.backend.report_generation.reviewer_telemetry import capture_suggested_reviewers_resolved
from products.signals.backend.report_generation.select_repo import RepoSelectionResult
from products.signals.backend.task_run_artefacts import append_task_run_artefact
@@ -100,4 +101,22 @@ def create_custom_agent_ready_report(
task_id=task_id,
)
+ # After the transaction so a telemetry failure can't roll back the report. Telemetry mirrors
+ # the live reviewer set: suggested_reviewers appends are latest-wins and registered artefacts
+ # are written after the assignees append, so a registered SuggestedReviewers overrides it —
+ # including an empty one, which is a persisted "no reviewers" state and must still emit.
+ reviewer_logins = [assignee.github_login for assignee in final_report.assignees]
+ reviewers_written = bool(final_report.assignees)
+ for artefact_content in registered_artefacts:
+ if isinstance(artefact_content, SuggestedReviewers):
+ reviewers_written = True
+ reviewer_logins = [entry.github_login for entry in artefact_content.root]
+ if reviewers_written:
+ capture_suggested_reviewers_resolved(
+ team_id=team_id,
+ report_id=str(report.id),
+ github_logins=reviewer_logins,
+ source="custom_agent",
+ )
+
return PersistedCustomAgentReport(report_id=str(report.id), task_id=task_id)
diff --git a/products/signals/backend/report_generation/AGENTS.md b/products/signals/backend/report_generation/AGENTS.md
index b4796243d92b..a69103ed7491 100644
--- a/products/signals/backend/report_generation/AGENTS.md
+++ b/products/signals/backend/report_generation/AGENTS.md
@@ -23,6 +23,11 @@ It is exercised locally via management commands, and it is also used by the prod
- very short factual summary
- optional charts (see below), when the team is opted in
The repository used for research is tracked separately via the `repo_selection` artefact.
+- `reviewer_telemetry.py`
+ Emits the `signals_suggested_reviewers_resolved` product-analytics event whenever a report's suggested reviewers are persisted, recording which GitHub logins link to a PostHog user and which don't (unlinkable reviewers can't be routed or run autostart, but still count as "assigned" in reviewer metrics).
+ - Called after the artefact write commits (via `transaction.on_commit` where a transaction is open), never in-transaction: the research activity (`source="pipeline"`), scout report creation and reviewer edits (`"scout"` / `"scout_edit"`), custom-agent persistence (`"custom_agent"`), the app reviewers PUT (`"user_edit"`), and the artefacts POST (`"api"`).
+ - Best-effort: failures are logged and never break report generation.
+ - Delivery is at-least-once (activity retries re-fire an identical payload) and reviewer edits legitimately re-fire with the new list, so consumers read report state as the latest event per `report_id`, never by counting raw events.
- `fixtures/analyze_report_funnel_research_output.json`
Saved previous research output used by local `update` testing.
- `fixtures/insight_scene_logic_mode_property_bug.json`
diff --git a/products/signals/backend/report_generation/resolve_reviewers.py b/products/signals/backend/report_generation/resolve_reviewers.py
index 773869d5c1b0..b71c23b1aa63 100644
--- a/products/signals/backend/report_generation/resolve_reviewers.py
+++ b/products/signals/backend/report_generation/resolve_reviewers.py
@@ -83,7 +83,9 @@ def enrich_reviewer_dicts_with_org_members(
enriched: list[dict] = []
for r in reviewer_dicts:
login = r.get("github_login", "")
- user = resolved_map.get(login.lower()) if login else None
+ # strip + lower matches the resolver's key normalization, so a legacy padded login
+ # (stored before the schema stripped on write) still resolves.
+ user = resolved_map.get(login.strip().lower()) if login else None
enriched.append(
{
**r,
diff --git a/products/signals/backend/report_generation/reviewer_telemetry.py b/products/signals/backend/report_generation/reviewer_telemetry.py
new file mode 100644
index 000000000000..b524732d2c8d
--- /dev/null
+++ b/products/signals/backend/report_generation/reviewer_telemetry.py
@@ -0,0 +1,84 @@
+import logging
+from typing import Literal
+
+import posthoganalytics
+
+from posthog.dataclasses import frozen
+from posthog.event_usage import groups
+from posthog.models import Team
+
+from products.signals.backend.report_generation.resolve_reviewers import resolve_org_github_login_to_users
+
+logger = logging.getLogger(__name__)
+
+# Pipeline suggestions are capped at MAX_SUGGESTED_REVIEWERS, but scout assignee lists are
+# model-proposed and unbounded, so cap what reaches event properties.
+_MAX_LOGINS_PER_EVENT = 10
+
+ReviewerSuggestionSource = Literal["pipeline", "scout", "scout_edit", "custom_agent", "user_edit", "api"]
+
+
+@frozen
+class ReviewerLinkability:
+ linkable_logins: list[str]
+ unlinkable_logins: list[str]
+
+
+def split_reviewer_linkability(team_id: int, github_logins: list[str]) -> ReviewerLinkability:
+ """Split suggested-reviewer GitHub logins by whether they resolve to an org member."""
+ normalized = list(dict.fromkeys(login.strip().lower() for login in github_logins if login and login.strip()))
+ login_to_user = resolve_org_github_login_to_users(team_id, normalized)
+ return ReviewerLinkability(
+ linkable_logins=[login for login in normalized if login in login_to_user],
+ unlinkable_logins=[login for login in normalized if login not in login_to_user],
+ )
+
+
+def capture_suggested_reviewers_resolved(
+ *,
+ team_id: int,
+ report_id: str,
+ github_logins: list[str],
+ source: ReviewerSuggestionSource,
+) -> None:
+ """Emit `signals_suggested_reviewers_resolved` when a report's suggested reviewers are persisted.
+
+ Suggested reviewers are stored as bare GitHub logins; the login -> PostHog user mapping only
+ happens downstream (Slack routing, autostart, API read), where an unmapped login falls through
+ silently. A report whose logins map to nobody cannot be routed to a person, yet still counts as
+ "assigned" in `suggested_reviewers`-based metrics. This event records the linkable/unlinkable
+ split at suggestion time so that bucket is measurable.
+
+ Best-effort: never raises, so analytics can't break report generation.
+ """
+ try:
+ linkability = split_reviewer_linkability(team_id, github_logins)
+ if linkability.unlinkable_logins:
+ # GitHub logins are member PII, so logs carry counts only; the logins themselves go in
+ # the event properties, the same internal-analytics surface the artefact already feeds.
+ logger.info(
+ "suggested reviewers for report %s (team %d): %d of %d login(s) have no PostHog user",
+ report_id,
+ team_id,
+ len(linkability.unlinkable_logins),
+ len(linkability.linkable_logins) + len(linkability.unlinkable_logins),
+ )
+ team = Team.objects.select_related("organization").get(id=team_id)
+ posthoganalytics.capture(
+ event="signals_suggested_reviewers_resolved",
+ distinct_id=str(team.uuid),
+ properties={
+ "team_id": team_id,
+ "report_id": report_id,
+ "source": source,
+ "suggested_count": len(linkability.linkable_logins) + len(linkability.unlinkable_logins),
+ "linkable_count": len(linkability.linkable_logins),
+ "unlinkable_count": len(linkability.unlinkable_logins),
+ "linkable_logins": linkability.linkable_logins[:_MAX_LOGINS_PER_EVENT],
+ "unlinkable_logins": linkability.unlinkable_logins[:_MAX_LOGINS_PER_EVENT],
+ "all_unlinkable": bool(linkability.unlinkable_logins) and not linkability.linkable_logins,
+ },
+ groups=groups(team.organization, team),
+ )
+ except Exception:
+ logger.exception("Failed to capture signals_suggested_reviewers_resolved for report %s", report_id)
diff --git a/products/signals/backend/scout_report/persistence.py b/products/signals/backend/scout_report/persistence.py
index 480a58f2d0cc..21ebe9ea408d 100644
--- a/products/signals/backend/scout_report/persistence.py
+++ b/products/signals/backend/scout_report/persistence.py
@@ -29,6 +29,7 @@ import logging
from collections.abc import Sequence
from dataclasses import dataclass, field
from datetime import datetime
+from functools import partial
from django.db import transaction
from django.utils import timezone
@@ -52,6 +53,7 @@ from products.signals.backend.artefact_schemas import (
)
from products.signals.backend.models import ArtefactAttribution, SignalReport, SignalReportArtefact, SignalScoutRun
from products.signals.backend.report_charts import ReportChart, chart_batch_error
+from products.signals.backend.report_generation.reviewer_telemetry import capture_suggested_reviewers_resolved
from products.signals.backend.report_generation.select_repo import RepoSelectionResult
from products.signals.backend.scout_harness.tools.emit import SCOUT_SIGNAL_WEIGHT, SOURCE_PRODUCT, SOURCE_TYPE
@@ -227,6 +229,17 @@ def create_scout_report(
attribution=attribution,
reevaluate_autostart=False,
)
+ # on_commit, not inline: telemetry must not fire for a rolled-back report, and it must
+ # still fire when the post-commit signal emits below fail (they propagate).
+ transaction.on_commit(
+ partial(
+ capture_suggested_reviewers_resolved,
+ team_id=team_id,
+ report_id=report_id,
+ github_logins=[entry.github_login for entry in suggested_reviewers.root],
+ source="scout",
+ )
+ )
# Committed: now emit the backing signals (unless suppressed-unsafe — see `emit_signals`).
# Sequential (not on_commit) so the call is observable and so a Kafka failure surfaces to the
@@ -520,9 +533,22 @@ def set_scout_report_reviewers(
content=NoteArtefact(note=f"Set suggested reviewers: {', '.join(logins)}", author=author),
attribution=attribution,
)
+ # on_commit, not inline: `_do_edit_report` wraps this call in an outer transaction, so an
+ # inline capture would fire for an edit that later rolls back — and a DB error inside the
+ # capture, though swallowed, would poison that outer transaction. The merged content is the
+ # live reviewer set (latest-wins), so telemetry reflects what routing will actually see.
+ transaction.on_commit(
+ partial(
+ capture_suggested_reviewers_resolved,
+ team_id=team_id,
+ report_id=report_id,
+ github_logins=[entry.github_login for entry in merged.root],
+ source="scout_edit",
+ )
+ )
logger.info(
"signals_scout.edit_report: reviewers set",
- extra={"team_id": team_id, "report_id": report_id, "reviewers": logins},
+ extra={"team_id": team_id, "report_id": report_id, "reviewer_count": len(logins)},
)
return True
diff --git a/products/signals/backend/slack_inbox_notifications.py b/products/signals/backend/slack_inbox_notifications.py
index 7ca7f6c2be0a..80d04edad878 100644
--- a/products/signals/backend/slack_inbox_notifications.py
+++ b/products/signals/backend/slack_inbox_notifications.py
@@ -187,6 +187,18 @@ def _resolve_suggested_reviewer_user_ids(report: SignalReport) -> set[int]:
if not logins:
return set()
login_map = resolve_org_github_login_to_users(report.team_id, logins)
+ 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:
return set()
diff --git a/products/signals/backend/temporal/agentic/report.py b/products/signals/backend/temporal/agentic/report.py
index 61c1f89b0a40..fc19701a7c36 100644
--- a/products/signals/backend/temporal/agentic/report.py
+++ b/products/signals/backend/temporal/agentic/report.py
@@ -32,6 +32,7 @@ from products.signals.backend.report_generation.research import (
run_multi_turn_research,
)
from products.signals.backend.report_generation.resolve_reviewers import resolve_suggested_reviewers
+from products.signals.backend.report_generation.reviewer_telemetry import capture_suggested_reviewers_resolved
from products.signals.backend.report_generation.select_repo import RepoSelectionResult
from products.signals.backend.temporal.agentic import (
SIGNALS_REPORT_RESEARCH_ENV_NAME,
@@ -365,6 +366,18 @@ async def _persist_agentic_report_artefacts(
artefacts=artefacts,
)
+ # Telemetry mirrors persistence: fires when a suggested_reviewers artefact was appended
+ # above, so re-promotions without new findings don't re-fire. Delivery is at-least-once
+ # (a retry of this activity re-captures an identical payload), so consumers read report
+ # state as the latest event per report_id rather than counting raw events.
+ if reviewers_content and has_new_finding:
+ await database_sync_to_async(capture_suggested_reviewers_resolved, thread_sensitive=False)(
+ team_id=team_id,
+ report_id=report_id,
+ github_logins=[reviewer["github_login"] for reviewer in reviewers_content],
+ source="pipeline",
+ )
+
# Backfill the research task's title now that research has produced the report title. At
# task-creation time the report has no title yet (research is what produces it), so the task
# starts with a sandbox-prompt placeholder; relabel it "Research: <report title>".
diff --git a/products/signals/backend/test/test_artefact_schemas.py b/products/signals/backend/test/test_artefact_schemas.py
index 31980f91bdb9..13dc8a926319 100644
--- a/products/signals/backend/test/test_artefact_schemas.py
+++ b/products/signals/backend/test/test_artefact_schemas.py
@@ -11,6 +11,7 @@ from products.signals.backend.artefact_schemas import (
CodeReference,
Commit,
NoteArtefact,
+ SuggestedReviewerEntry,
SummaryChange,
TaskRunArtefact,
TitleChange,
@@ -161,6 +162,11 @@ class TestValidateArtefactContent(SimpleTestCase):
with self.assertRaises(ArtefactContentValidationError):
parse_artefact_content(artefact_type, content)
+ def test_suggested_reviewer_login_is_stripped(self):
+ # Enrichment and autostart look logins up with `login.lower()` and no strip, so a padded
+ # login that survived to storage would count as suggested but never match a user.
+ assert SuggestedReviewerEntry(github_login=" Octocat ").github_login == "Octocat"
+
def test_parsing_normalizes_to_the_schema(self):
# Parsing into the typed model is the boundary: unknown keys are not persisted, and
# omitted optional fields are stored with their defaults.
diff --git a/products/signals/backend/test/test_reviewer_telemetry.py b/products/signals/backend/test/test_reviewer_telemetry.py
new file mode 100644
index 000000000000..8ced7fe3d6c9
--- /dev/null
+++ b/products/signals/backend/test/test_reviewer_telemetry.py
@@ -0,0 +1,67 @@
+import pytest
+from unittest.mock import patch
+
+from social_django.models import UserSocialAuth
+
+from posthog.models import Organization, Team, User
+from posthog.models.organization import OrganizationMembership
+
+from products.signals.backend.report_generation.reviewer_telemetry import capture_suggested_reviewers_resolved
+
+
+def organization():
+ org = Organization.objects.create(name="test-reviewer-telemetry-org")
+ yield org
+ org.delete()
+
+
+def team(organization):
+ return Team.objects.create(organization=organization, name="test-reviewer-telemetry-team")
+
+
+def test_captures_linkable_unlinkable_split(organization, team):
+ user = User.objects.create(email="[email protected]")
+ OrganizationMembership.objects.create(user=user, organization=organization)
+ UserSocialAuth.objects.create(user=user, provider="github", uid="gh-1", extra_data={"login": "octocat"})
+
+ with patch(
+ "products.signals.backend.report_generation.reviewer_telemetry.posthoganalytics.capture"
+ ) as mock_capture:
+ capture_suggested_reviewers_resolved(
+ team_id=team.id,
+ report_id="report-1",
+ github_logins=["OctoCat", "ghost-contrib", " ", "octocat"],
+ source="pipeline",
+ )
+
+ assert mock_capture.call_count == 1
+ kwargs = mock_capture.call_args.kwargs
+ assert kwargs["event"] == "signals_suggested_reviewers_resolved"
+ props = kwargs["properties"]
+ assert props["team_id"] == team.id
+ assert props["report_id"] == "report-1"
+ assert props["source"] == "pipeline"
+ assert props["suggested_count"] == 2
+ assert props["linkable_logins"] == ["octocat"]
+ assert props["unlinkable_logins"] == ["ghost-contrib"]
+ assert props["linkable_count"] == 1
+ assert props["unlinkable_count"] == 1
+ assert props["all_unlinkable"] is False
+
+
+def test_never_raises_on_missing_team():
+ with patch(
+ "products.signals.backend.report_generation.reviewer_telemetry.posthoganalytics.capture"
+ ) as mock_capture:
+ capture_suggested_reviewers_resolved(
+ team_id=-1,
+ report_id="report-1",
+ github_logins=["octocat"],
+ source="scout",
+ )
+
+ mock_capture.assert_not_called()
diff --git a/products/signals/backend/test/test_scout_report_persistence.py b/products/signals/backend/test/test_scout_report_persistence.py
index 6330f469f022..d18b2ef587b3 100644
--- a/products/signals/backend/test/test_scout_report_persistence.py
+++ b/products/signals/backend/test/test_scout_report_persistence.py
@@ -16,6 +16,8 @@ from products.signals.backend.artefact_schemas import (
ActionabilityAssessment,
ActionabilityChoice,
SafetyJudgment,
+ SuggestedReviewerEntry,
+ SuggestedReviewers,
TaskRunArtefact,
)
from products.signals.backend.models import (
@@ -32,6 +34,7 @@ from products.signals.backend.scout_report import (
ScoutReportSignal,
create_scout_report,
set_report_charts,
+ set_scout_report_reviewers,
soft_delete_scout_signal,
update_scout_report,
)
@@ -139,6 +142,52 @@ class TestScoutReportPersistence(BaseTest):
run.refresh_from_db()
assert run.emitted_report_ids == [result.report_id]
+ def test_create_with_reviewers_fires_linkability_telemetry(self) -> None:
+ # Scout-authored reports persist reviewers here, not through the custom-agent path; without
+ # this call the scout bucket silently disappears from the reviewer-linkability metric.
+ with (
+ patch(f"{PERSISTENCE_MODULE}.capture_suggested_reviewers_resolved") as mock_capture,
+ self.captureOnCommitCallbacks(execute=True),
+ ):
+ create_scout_report(
+ team_id=self.team.id,
+ title="Checkout API p99 latency regressed",
+ summary="The checkout endpoint p99 doubled after the 4.2 deploy.",
+ signals=[ScoutReportSignal(description="p99 doubled on /checkout", source_id="obs-1", weight=1.0)],
+ attribution=ArtefactAttribution.system(),
+ suggested_reviewers=SuggestedReviewers(root=[SuggestedReviewerEntry(github_login="octocat")]),
+ )
+
+ assert mock_capture.call_count == 1
+ kwargs = mock_capture.call_args.kwargs
+ assert kwargs["source"] == "scout"
+ assert kwargs["github_logins"] == ["octocat"]
+
+ def test_set_reviewers_fires_linkability_telemetry_with_merged_list(self) -> None:
+ result = create_scout_report(
+ team_id=self.team.id,
+ title="Checkout API p99 latency regressed",
+ summary="The checkout endpoint p99 doubled after the 4.2 deploy.",
+ signals=[ScoutReportSignal(description="p99 doubled on /checkout", source_id="obs-1", weight=1.0)],
+ attribution=ArtefactAttribution.system(),
+ )
+
+ with (
+ patch(f"{PERSISTENCE_MODULE}.capture_suggested_reviewers_resolved") as mock_capture,
+ self.captureOnCommitCallbacks(execute=True),
+ ):
+ set_scout_report_reviewers(
+ team_id=self.team.id,
+ report_id=result.report_id,
+ suggested_reviewers=SuggestedReviewers(root=[SuggestedReviewerEntry(github_login="octocat")]),
+ attribution=ArtefactAttribution.system(),
+ )
+
+ assert mock_capture.call_count == 1
+ kwargs = mock_capture.call_args.kwargs
+ assert kwargs["source"] == "scout_edit"
+ assert kwargs["github_logins"] == ["octocat"]
+
@parameterized.expand(
[
("empty_title", "", "summary", [ScoutReportSignal(description="d", source_id="s")]),
diff --git a/products/signals/backend/test/test_signal_report_artefact_api.py b/products/signals/backend/test/test_signal_report_artefact_api.py
index 3c27aaf7c9d4..cdb281fea191 100644
--- a/products/signals/backend/test/test_signal_report_artefact_api.py
+++ b/products/signals/backend/test/test_signal_report_artefact_api.py
@@ -18,6 +18,8 @@ from products.signals.backend.artefact_schemas import (
NoteArtefact,
Priority,
PriorityAssessment,
+ SuggestedReviewerEntry,
+ SuggestedReviewers,
TaskRunArtefact,
)
from products.signals.backend.models import ArtefactAttribution, SignalReport, SignalReportArtefact
@@ -1195,6 +1197,33 @@ class TestSignalReportArtefactLogWriteViewSet(APIBaseTest):
assert report_response.status_code == status.HTTP_200_OK
assert report_response.json()["priority"] == "P3"
+ def test_delete_latest_reviewers_artefact_re_emits_surviving_state(self):
+ # A deleted reviewers row reverts the canonical set to the previous row; without a fresh
+ # event, latest-per-report telemetry keeps describing the deleted list forever.
+ report = self._create_report()
+ for login in ("first-reviewer", "second-reviewer"):
+ SignalReportArtefact.append_status(
+ team_id=self.team.id,
+ report_id=str(report.id),
+ content=SuggestedReviewers(root=[SuggestedReviewerEntry(github_login=login)]),
+ attribution=ArtefactAttribution.system(),
+ )
+ latest = SignalReportArtefact.objects.filter(
+ report=report, type=SignalReportArtefact.ArtefactType.SUGGESTED_REVIEWERS
+ ).order_by("-created_at")[0]
+
+ with (
+ patch("products.signals.backend.views.capture_suggested_reviewers_resolved") as mock_capture,
+ self.captureOnCommitCallbacks(execute=True),
+ ):
+ response = self.client.delete(self._detail_url(str(report.id), str(latest.id)))
+
+ assert response.status_code == status.HTTP_204_NO_CONTENT
+ assert mock_capture.call_count == 1
+ kwargs = mock_capture.call_args.kwargs
+ assert kwargs["github_logins"] == ["first-reviewer"]
+ assert kwargs["source"] == "api"
+
def test_delete_other_team_returns_404(self):
other_team = Team.objects.create(organization=self.organization, name="Other Team")
other_report = self._create_report(team=other_team)
diff --git a/products/signals/backend/views.py b/products/signals/backend/views.py
index d84deaedde28..b51b4d406a4c 100644
--- a/products/signals/backend/views.py
+++ b/products/signals/backend/views.py
@@ -2,6 +2,7 @@ import json
import uuid
from collections.abc import Callable, Sequence
from datetime import UTC, timedelta
+from functools import partial
from typing import Any, cast
from django.conf import settings
@@ -113,6 +114,7 @@ from products.signals.backend.report_generation.resolve_reviewers import (
normalized_github_logins_from_suggested_reviewer_artefacts,
resolve_org_github_login_to_users,
)
+from products.signals.backend.report_generation.reviewer_telemetry import capture_suggested_reviewers_resolved
from products.signals.backend.serializers import (
CommitDiffResponseSerializer,
PullRequestChecksResponseSerializer,
@@ -3072,6 +3074,16 @@ def append_suggested_reviewers(
content=SuggestedReviewers.model_validate(new_content),
attribution=attribution,
)
+ # on_commit so a rolled-back edit emits nothing, matching every other reviewer write path.
+ transaction.on_commit(
+ partial(
+ capture_suggested_reviewers_resolved,
+ team_id=team.id,
+ report_id=str(report_id),
+ github_logins=[entry["github_login"] for entry in new_content],
+ source="user_edit",
+ )
+ )
# Human reviewer corrections are a routing signal (scouts query them via the
# activity log to learn who owns an area), so log them — but only genuine
@@ -3404,8 +3416,60 @@ class SignalReportArtefactViewSet(
content=parsed_content,
attribution=attribution,
)
+ if isinstance(parsed_content, SuggestedReviewers):
+ # on_commit so a rolled-back write emits nothing, matching every other reviewer write path.
+ transaction.on_commit(
+ partial(
+ capture_suggested_reviewers_resolved,
+ team_id=self.team.id,
+ report_id=report_id,
+ github_logins=[entry.github_login for entry in parsed_content.root],
+ source="api",
+ )
+ )
return Response(self._write_response_data(artefact), status=status.HTTP_201_CREATED)
+ def _capture_canonical_reviewer_state(self, report_id: str) -> None:
+ """Re-emit reviewer telemetry from the latest surviving `suggested_reviewers` row.
+
+ Deleting or editing a reviewers artefact changes the report's canonical reviewer set
+ without going through an append path, so the "latest event per report" read would
+ otherwise keep describing the removed row. An empty login list is a valid state (the
+ deletion removed the only row).
+
+ Fully best-effort: this runs in a non-robust on_commit callback after the mutation
+ committed, so an exception here would turn an already-successful request into a 500."""
+ try:
+ latest = (
+ SignalReportArtefact.objects.filter(
+ team_id=self.team.id,
+ report_id=report_id,
+ type=SignalReportArtefact.ArtefactType.SUGGESTED_REVIEWERS,
+ )
+ .order_by("-created_at")
+ .first()
+ )
+ logins: list[str] = []
+ if latest is not None:
+ try:
+ parsed = json.loads(latest.content)
+ except (json.JSONDecodeError, TypeError, ValueError):
+ parsed = []
+ if isinstance(parsed, list):
+ logins = [
+ str(entry.get("github_login"))
+ for entry in parsed
+ if isinstance(entry, dict) and entry.get("github_login")
+ ]
+ capture_suggested_reviewers_resolved(
+ team_id=self.team.id,
+ report_id=report_id,
+ github_logins=logins,
+ source="api",
+ )
+ except Exception:
+ logger.exception("failed to re-emit canonical reviewer state", report_id=report_id)
+
@validated_request(
request_serializer=SignalReportArtefactLogUpdateSerializer,
responses={
@@ -3439,6 +3503,9 @@ class SignalReportArtefactViewSet(
{"error": f"content does not match the '{artefact.type}' schema: {e}"},
status=status.HTTP_400_BAD_REQUEST,
)
+ if artefact.type == SignalReportArtefact.ArtefactType.SUGGESTED_REVIEWERS:
+ # Editing a reviewers row can change the report's canonical reviewer set in place.
+ transaction.on_commit(partial(self._capture_canonical_reviewer_state, str(artefact.report_id)))
return Response(self._write_response_data(artefact))
@extend_schema(
@@ -3456,7 +3523,13 @@ class SignalReportArtefactViewSet(
)
def destroy(self, request, *args, **kwargs) -> Response:
artefact = cast(SignalReportArtefact, self.get_object())
+ was_reviewers = artefact.type == SignalReportArtefact.ArtefactType.SUGGESTED_REVIEWERS
+ report_id = str(artefact.report_id)
artefact.delete()
+ if was_reviewers:
+ # Deleting the latest reviewers row reverts the canonical set to the previous row (or
+ # none) — re-emit so the latest event per report tracks the surviving state.
+ transaction.on_commit(partial(self._capture_canonical_reviewer_state, report_id))
return Response(status=status.HTTP_204_NO_CONTENT)
@extend_schema(