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): record why a report ended up with no suggested reviewers (#83789)

Andrew Maguire7504eb67146b
diff --git a/products/signals/backend/report_generation/AGENTS.md b/products/signals/backend/report_generation/AGENTS.md
index 900c1ed7e309..ca12c56940a3 100644
--- a/products/signals/backend/report_generation/AGENTS.md
+++ b/products/signals/backend/report_generation/AGENTS.md
@@ -28,6 +28,8 @@ It is exercised locally via management commands, and it is also used by the prod
- 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.
+ - Also emits `signals_suggested_reviewers_unresolved` when a pipeline run resolves no reviewers at all (nothing is persisted for an empty list, so this is the only record of why): the `outcome` (`no_repository`, `no_commit_hashes`, `no_github_integration`, `github_rate_limited`, `no_commit_authors`, `only_bot_authors`, `no_candidates`) plus lookup counters from `ReviewerResolutionDiagnostics` in `resolve_reviewers.py`. Same latest-per-`report_id` read contract, which is why a re-promotion that resolves nobody stays silent when the report's previous reviewers remain its live set.
+ - Two outcomes read narrower than they are: `no_github_integration` also covers an access probe that failed transiently, and `no_repository` never reaches this event (the summary workflow bails to `repo_selection_required` before research runs) — see the comment on `ReviewerResolutionOutcome`.
- `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 b71c23b1aa63..9182adf61c65 100644
--- a/products/signals/backend/report_generation/resolve_reviewers.py
+++ b/products/signals/backend/report_generation/resolve_reviewers.py
@@ -16,6 +16,7 @@ from django.utils import timezone
from social_django.models import UserSocialAuth
+from posthog.dataclasses import frozen
from posthog.egress.github.transport import GitHubRateLimitError
from posthog.models.integration import GitHubIntegration, Integration
from posthog.models.organization import OrganizationMembership
@@ -58,6 +59,52 @@ GitHubLoginFieldLookup = Literal[
"config__connecting_user_github_login",
]
+# Why a resolution ended with no reviewers. `no_repository` / `no_commit_hashes` are set by
+# callers that bail before calling into GitHub; the rest are decided here. Two caveats worth
+# knowing when reading the event:
+# - `no_github_integration` means "no integration whose access probe said yes", which also
+# covers a probe that failed transiently: `installation_can_access_repository` returns False
+# for a GitHub 5xx or a token/transport failure just as it does for a repo the installation
+# genuinely can't see. Distinguishing them needs probe-failure information that
+# `first_for_team_repository` doesn't return today.
+# - `no_repository` is unreachable from the research pipeline (the summary workflow bails to
+# `repo_selection_required` before running research); it exists for the other callers of
+# `resolve_suggested_reviewers`, which discard diagnostics.
+ReviewerResolutionOutcome = Literal[
+ "resolved",
+ "no_repository",
+ "no_commit_hashes",
+ "no_github_integration",
+ "github_rate_limited",
+ "no_commit_authors",
+ "only_bot_authors",
+ "no_candidates",
+]
+
+
+@frozen
+class ReviewerResolutionDiagnostics:
+ """Counters explaining a resolution, so an empty suggestion list is attributable to a cause."""
+
+ outcome: ReviewerResolutionOutcome
+ commit_hash_count: int = 0
+ lookups_attempted: int = 0
+ # A lookup "resolves" when GitHub attributes the commit to an account (bot or human);
+ # "missing" covers non-200 responses, unattributed commits, and lookups lost to a rate limit.
+ lookups_resolved: int = 0
+ lookups_missing: int = 0
+ lookups_rate_limited: int = 0
+ bot_author_count: int = 0
+ blame_login_count: int = 0
+ touched_path_count: int = 0
+ activity_login_count: int = 0
+
+
+@frozen
+class ReviewerResolution:
+ reviewers: list[_ResolvedReviewer]
+ diagnostics: ReviewerResolutionDiagnostics
+
def enrich_reviewer_dicts_with_org_members(
team_id: int,
@@ -140,6 +187,14 @@ def resolve_suggested_reviewers(
repository: str,
commit_hashes_with_reasons: dict[str, str],
) -> list[_ResolvedReviewer]:
+ return resolve_suggested_reviewers_with_diagnostics(team_id, repository, commit_hashes_with_reasons).reviewers
+
+
+def resolve_suggested_reviewers_with_diagnostics(
+ team_id: int,
+ repository: str,
+ commit_hashes_with_reasons: dict[str, str],
+) -> ReviewerResolution:
"""Resolve commit hashes to up to 3 reviewers, preferring recently-active owners.
Blame candidates (commit authors, weighted by finding position) are recency-shaped
@@ -149,22 +204,25 @@ def resolve_suggested_reviewers(
an unrouted report goes unreviewed, so crowded-area contributors are proposed as the
final fallback (``allow_crowd_fallback``).
"""
- if not commit_hashes_with_reasons or not repository:
- return []
+ commit_hash_count = len(commit_hashes_with_reasons)
+ if not repository:
+ return _empty_resolution("no_repository", commit_hash_count=commit_hash_count)
+ if not commit_hashes_with_reasons:
+ return _empty_resolution("no_commit_hashes")
try:
github = GitHubIntegration.first_for_team_repository(team_id, repository)
except GitHubRateLimitError:
# Suggested reviewers are an optional artefact — omit them rather than failing the report.
logger.info("GitHub rate limited while probing %s, skipping reviewer resolution", repository)
- return []
+ return _empty_resolution("github_rate_limited", commit_hash_count=commit_hash_count)
if github is None:
logger.info(
"No GitHub integration for team %d can access %s, cannot resolve reviewers",
team_id,
repository,
)
- return []
+ return _empty_resolution("no_github_integration", commit_hash_count=commit_hash_count)
# Cap lookups — we only need 3 reviewers, so diminishing returns past ~15 commits.
items = list(commit_hashes_with_reasons.items())[:MAX_COMMIT_LOOKUPS]
@@ -172,6 +230,7 @@ def resolve_suggested_reviewers(
# Fetch all commit author info in parallel (IO-bound GitHub API calls)
author_results: dict[int, Any] = {}
+ lookups_rate_limited = 0
with ThreadPoolExecutor(max_workers=min(total, 5)) as pool:
future_to_idx = {
pool.submit(github.get_commit_author_info, repository, sha): i for i, (sha, _reason) in enumerate(items)
@@ -181,32 +240,73 @@ def resolve_suggested_reviewers(
author_results[future_to_idx[future]] = future.result()
except GitHubRateLimitError:
# Best-effort: score reviewers from whatever lookups landed before the limit.
+ lookups_rate_limited += 1
logger.info("GitHub rate limited during commit author lookups for %s", repository)
# Weight earlier commits more heavily (position-based weighting)
login_weights: Counter[str] = Counter()
login_commits: dict[str, list[RelevantCommit]] = {}
login_names: dict[str, str | None] = {}
+ bot_author_count = 0
for i, (sha, reason) in enumerate(items):
author_info = author_results.get(i)
- if author_info and not author_info.is_bot:
- # Lowercased to match the activity map's keys (and the persisted artefact shape).
- login = author_info.login.lower()
- weight = total - i
- login_weights[login] += weight
- login_commits.setdefault(login, []).append(
- RelevantCommit(sha=sha, url=author_info.commit_url, reason=reason)
- )
- if login not in login_names:
- login_names[login] = author_info.name
+ if author_info is None:
+ continue
+ if author_info.is_bot:
+ bot_author_count += 1
+ continue
+ # Lowercased to match the activity map's keys (and the persisted artefact shape).
+ login = author_info.login.lower()
+ weight = total - i
+ login_weights[login] += weight
+ login_commits.setdefault(login, []).append(RelevantCommit(sha=sha, url=author_info.commit_url, reason=reason))
+ if login not in login_names:
+ login_names[login] = author_info.name
touched_paths = [path for info in author_results.values() if info is not None for path in info.file_paths]
activity_by_login = _relevant_area_activity(team_id, repository, touched_paths)
- return _rank_scored_candidates(
+ reviewers = _rank_scored_candidates(
login_weights, activity_by_login, login_commits, login_names, allow_crowd_fallback=True
)
+ lookups_resolved = sum(1 for info in author_results.values() if info is not None)
+ outcome: ReviewerResolutionOutcome
+ if reviewers:
+ outcome = "resolved"
+ elif lookups_rate_limited:
+ # Any throttled lookup could have been the one holding the missing human author, so a
+ # mixed batch is attributed to the rate limit rather than to whatever the lookups that
+ # did land happened to return.
+ outcome = "github_rate_limited"
+ elif lookups_resolved == 0:
+ outcome = "no_commit_authors"
+ elif not login_weights:
+ outcome = "only_bot_authors"
+ else:
+ outcome = "no_candidates"
+ return ReviewerResolution(
+ reviewers=reviewers,
+ diagnostics=ReviewerResolutionDiagnostics(
+ outcome=outcome,
+ commit_hash_count=commit_hash_count,
+ lookups_attempted=total,
+ lookups_resolved=lookups_resolved,
+ lookups_missing=total - lookups_resolved,
+ lookups_rate_limited=lookups_rate_limited,
+ bot_author_count=bot_author_count,
+ blame_login_count=len(login_weights),
+ touched_path_count=len(touched_paths),
+ activity_login_count=len(activity_by_login),
+ ),
+ )
+
+
+def _empty_resolution(outcome: ReviewerResolutionOutcome, *, commit_hash_count: int = 0) -> ReviewerResolution:
+ return ReviewerResolution(
+ reviewers=[],
+ diagnostics=ReviewerResolutionDiagnostics(outcome=outcome, commit_hash_count=commit_hash_count),
+ )
def rank_assignee_candidates(
diff --git a/products/signals/backend/report_generation/reviewer_telemetry.py b/products/signals/backend/report_generation/reviewer_telemetry.py
index b524732d2c8d..2f9382ddbc27 100644
--- a/products/signals/backend/report_generation/reviewer_telemetry.py
+++ b/products/signals/backend/report_generation/reviewer_telemetry.py
@@ -1,4 +1,5 @@
import logging
+import dataclasses
from typing import Literal
import posthoganalytics
@@ -7,7 +8,10 @@ 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
+from products.signals.backend.report_generation.resolve_reviewers import (
+ ReviewerResolutionDiagnostics,
+ resolve_org_github_login_to_users,
+)
logger = logging.getLogger(__name__)
@@ -82,3 +86,48 @@ def capture_suggested_reviewers_resolved(
)
except Exception:
logger.exception("Failed to capture signals_suggested_reviewers_resolved for report %s", report_id)
+
+
+def capture_suggested_reviewers_unresolved(
+ *,
+ team_id: int,
+ report_id: str,
+ diagnostics: ReviewerResolutionDiagnostics,
+ finding_count: int,
+ has_new_finding: bool,
+) -> None:
+ """Emit `signals_suggested_reviewers_unresolved` when a pipeline run yields no reviewers.
+
+ Nothing is persisted for an empty list, so this is the only record of *why* a report ended
+ up with no one to route to: no repository, findings without commits, no reachable GitHub
+ integration, or lookups that came back without an attributable author. Fires per run;
+ read it as the latest event per `report_id`.
+
+ Best-effort: never raises, so analytics can't break report generation.
+ """
+ try:
+ logger.info(
+ "no suggested reviewers for report %s (team %d): %s (%d commit hash(es), %d/%d lookups resolved)",
+ report_id,
+ team_id,
+ diagnostics.outcome,
+ diagnostics.commit_hash_count,
+ diagnostics.lookups_resolved,
+ diagnostics.lookups_attempted,
+ )
+ team = Team.objects.select_related("organization").get(id=team_id)
+ posthoganalytics.capture(
+ event="signals_suggested_reviewers_unresolved",
+ distinct_id=str(team.uuid),
+ properties={
+ "team_id": team_id,
+ "report_id": report_id,
+ "source": "pipeline",
+ "finding_count": finding_count,
+ "has_new_finding": has_new_finding,
+ **dataclasses.asdict(diagnostics),
+ },
+ groups=groups(team.organization, team),
+ )
+ except Exception:
+ logger.exception("Failed to capture signals_suggested_reviewers_unresolved for report %s", report_id)
diff --git a/products/signals/backend/temporal/agentic/report.py b/products/signals/backend/temporal/agentic/report.py
index fc19701a7c36..238b55b015a4 100644
--- a/products/signals/backend/temporal/agentic/report.py
+++ b/products/signals/backend/temporal/agentic/report.py
@@ -9,6 +9,7 @@ import temporalio
import posthoganalytics
from pydantic import BaseModel, ValidationError
+from posthog.dataclasses import frozen
from posthog.models.team.team import Team
from posthog.ph_client import feature_enabled_or_false
from posthog.sync import database_sync_to_async
@@ -31,8 +32,14 @@ from products.signals.backend.report_generation.research import (
SignalFinding,
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.resolve_reviewers import (
+ ReviewerResolutionDiagnostics,
+ resolve_suggested_reviewers_with_diagnostics,
+)
+from products.signals.backend.report_generation.reviewer_telemetry import (
+ capture_suggested_reviewers_resolved,
+ capture_suggested_reviewers_unresolved,
+)
from products.signals.backend.report_generation.select_repo import RepoSelectionResult
from products.signals.backend.temporal.agentic import (
SIGNALS_REPORT_RESEARCH_ENV_NAME,
@@ -210,16 +217,22 @@ class ArtefactDraft:
attribution: ArtefactAttribution
+@frozen
+class _PipelineReviewerResolution:
+ reviewers: list[ReviewerContent]
+ diagnostics: ReviewerResolutionDiagnostics
+
+
def _build_reviewers_content(
team_id: int,
repository: str,
findings: list[SignalFinding],
-) -> list[ReviewerContent]:
+) -> _PipelineReviewerResolution:
"""Collect relevant commit SHAs from research findings and resolve them to GitHub reviewers.
Deduplicates commit hashes across all findings (keeping the first reason seen per SHA),
- then calls resolve_suggested_reviewers to identify the authors/committers of those commits
- and returns them as serializable ReviewerContent dicts.
+ then calls the resolver to identify the authors/committers of those commits and returns
+ them as serializable ReviewerContent dicts, plus the diagnostics explaining an empty list.
The returned list is stored as a ``suggested_reviewers`` artefact keyed only by
github_login — no PostHog user IDs are persisted. This is intentional:
@@ -237,15 +250,10 @@ def _build_reviewers_content(
if sha and sha not in commit_hashes_with_reasons:
commit_hashes_with_reasons[sha] = str(reason) if reason else ""
- if not commit_hashes_with_reasons or not repository:
- return []
-
- resolved = resolve_suggested_reviewers(team_id, repository, commit_hashes_with_reasons)
- if not resolved:
- return []
+ resolution = resolve_suggested_reviewers_with_diagnostics(team_id, repository, commit_hashes_with_reasons)
reviewers_content: list[ReviewerContent] = []
- for reviewer in resolved:
+ for reviewer in resolution.reviewers:
reviewers_content.append(
ReviewerContent(
github_login=reviewer.login.lower(),
@@ -256,7 +264,34 @@ def _build_reviewers_content(
is_skill_owner=False,
)
)
- return reviewers_content
+ return _PipelineReviewerResolution(reviewers=reviewers_content, diagnostics=resolution.diagnostics)
+
+
+def _report_has_live_suggested_reviewers(report_id: str) -> bool:
+ """Whether the report's live (latest) ``suggested_reviewers`` artefact still names anyone.
+
+ Unlike the artefacts this pipeline writes, this one can also come from a user edit or the API,
+ so unparseable content is treated as "someone is still assigned": the caller only uses this to
+ decide whether it may call the report reviewerless, and it must not claim that on a guess.
+ """
+ artefact = (
+ SignalReportArtefact.objects.filter(
+ report_id=report_id, type=SignalReportArtefact.ArtefactType.SUGGESTED_REVIEWERS
+ )
+ .order_by("-created_at")
+ .first()
+ )
+ if artefact is None:
+ return False
+ try:
+ return bool(SuggestedReviewers.model_validate_json(artefact.content).root)
+ except ValidationError:
+ logger.warning(
+ "Could not parse the report's suggested_reviewers artefact",
+ report_id=report_id,
+ artefact_id=str(artefact.id),
+ )
+ return True
def _append_agentic_report_artefacts(*, team_id: int, report_id: str, artefacts: list[ArtefactDraft]) -> None:
@@ -319,11 +354,13 @@ async def _persist_agentic_report_artefacts(
) -> None:
# Resolve suggested reviewers from commit hashes (always, from the effective findings —
# auto-start below needs them even when nothing is persisted this run)
- reviewers_content = await database_sync_to_async(_build_reviewers_content, thread_sensitive=False)(
+ findings = result.effective_findings()
+ reviewer_resolution = await database_sync_to_async(_build_reviewers_content, thread_sensitive=False)(
team_id=team_id,
repository=repo_selection.repository or "",
- findings=result.effective_findings(),
+ findings=findings,
)
+ reviewers_content = reviewer_resolution.reviewers
# Persist only what's new this run; values the agent confirmed unchanged keep their latest
# persisted row. Reviewers are derived purely from findings, so they're only re-persisted
@@ -377,6 +414,29 @@ async def _persist_agentic_report_artefacts(
github_logins=[reviewer["github_login"] for reviewer in reviewers_content],
source="pipeline",
)
+ elif not reviewers_content:
+ # An empty list persists nothing, so without this the report's lack of a reviewer is
+ # indistinguishable from never having been researched. A re-promotion that resolves
+ # nobody leaves the previously-persisted list as the report's live reviewer set, though —
+ # that report isn't reviewerless, so firing here would make the latest-event-per-report
+ # read contradict the artefact.
+ keeps_previous_reviewers = await database_sync_to_async(
+ _report_has_live_suggested_reviewers, thread_sensitive=False
+ )(report_id)
+ if keeps_previous_reviewers:
+ logger.info(
+ "Reviewer resolution came back empty but the report keeps its previous reviewers",
+ report_id=report_id,
+ outcome=reviewer_resolution.diagnostics.outcome,
+ )
+ else:
+ await database_sync_to_async(capture_suggested_reviewers_unresolved, thread_sensitive=False)(
+ team_id=team_id,
+ report_id=report_id,
+ diagnostics=reviewer_resolution.diagnostics,
+ finding_count=len(findings),
+ has_new_finding=has_new_finding,
+ )
# 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
diff --git a/products/signals/backend/test/test_agentic_report_activity.py b/products/signals/backend/test/test_agentic_report_activity.py
index c7530952f268..7503f1a61c25 100644
--- a/products/signals/backend/test/test_agentic_report_activity.py
+++ b/products/signals/backend/test/test_agentic_report_activity.py
@@ -367,7 +367,10 @@ async def test_run_agentic_report_activity_persists_artefacts(monkeypatch, ateam
fake_run_multi_turn_research,
)
- with patch("products.signals.backend.temporal.agentic.report.Heartbeater"):
+ with (
+ patch("products.signals.backend.temporal.agentic.report.Heartbeater"),
+ patch("products.signals.backend.report_generation.reviewer_telemetry.posthoganalytics.capture") as mock_capture,
+ ):
result = await run_agentic_report_activity(
RunAgenticReportInput(
team_id=ateam.id,
@@ -380,6 +383,15 @@ async def test_run_agentic_report_activity_persists_artefacts(monkeypatch, ateam
)
assert result.title == "Onboarding funnel completion tracking may be regressing"
+
+ # The findings cite no commits, so no reviewers artefact is written; the run must say why.
+ assert [call.kwargs["event"] for call in mock_capture.call_args_list] == [
+ "signals_suggested_reviewers_unresolved"
+ ]
+ unresolved_props = mock_capture.call_args.kwargs["properties"]
+ assert unresolved_props["report_id"] == str(report.id)
+ assert unresolved_props["outcome"] == "no_commit_hashes"
+ assert unresolved_props["finding_count"] == 2
assert result.choice == ActionabilityChoice.IMMEDIATELY_ACTIONABLE
assert result.priority == Priority.P1
assert result.already_addressed is False
@@ -421,6 +433,56 @@ async def test_run_agentic_report_activity_persists_artefacts(monkeypatch, ateam
assert [finding["signal_id"] for finding in finding_contents] == ["sig-1", "sig-2"]
+async def test_run_agentic_report_activity_keeps_quiet_when_reviewers_are_retained(monkeypatch, ateam):
+ # A re-promotion that resolves nobody persists no empty list, so the earlier reviewers stay the
+ # report's live set. Firing `unresolved` here would make the latest-event-per-report read call a
+ # report reviewerless while its artefact still names someone.
+ report = await database_sync_to_async(SignalReport.objects.create)(
+ team=ateam,
+ status=SignalReport.Status.IN_PROGRESS,
+ signal_count=2,
+ total_weight=1.3,
+ )
+ await database_sync_to_async(SignalReportArtefact.objects.create)(
+ team=ateam,
+ report=report,
+ type=SignalReportArtefact.ArtefactType.SUGGESTED_REVIEWERS,
+ content=json.dumps([{"github_login": "someone", "github_name": "Someone", "relevant_commits": []}]),
+ )
+
+ monkeypatch.setattr(
+ "products.signals.backend.temporal.agentic.report.resolve_user_id_for_team",
+ lambda team_id: 1,
+ )
+
+ async def fake_run_multi_turn_research(*args, **kwargs):
+ return _build_research_output()
+
+ monkeypatch.setattr(
+ "products.signals.backend.temporal.agentic.report.run_multi_turn_research",
+ fake_run_multi_turn_research,
+ )
+
+ with (
+ patch("products.signals.backend.temporal.agentic.report.Heartbeater"),
+ patch("products.signals.backend.report_generation.reviewer_telemetry.posthoganalytics.capture") as mock_capture,
+ ):
+ await run_agentic_report_activity(
+ RunAgenticReportInput(
+ team_id=ateam.id,
+ report_id=str(report.id),
+ signals=_build_signals(),
+ repo_selection=RepoSelectionResult(
+ repository="posthog/posthog", reason="Single repository connected: posthog/posthog"
+ ),
+ )
+ )
+
+ assert mock_capture.call_args_list == []
+
+
@pytest.mark.asyncio
@pytest.mark.django_db
@pytest.mark.parametrize(
diff --git a/products/signals/backend/test/test_resolve_reviewers.py b/products/signals/backend/test/test_resolve_reviewers.py
index 35a9993319a4..e9fcfed2f96c 100644
--- a/products/signals/backend/test/test_resolve_reviewers.py
+++ b/products/signals/backend/test/test_resolve_reviewers.py
@@ -8,6 +8,7 @@ from django.utils import timezone
from social_django.models import UserSocialAuth
+from posthog.egress.github.transport import GitHubRateLimitError
from posthog.models import Organization, Team, User
from posthog.models.github_integration_base import GitHubCommitAuthor
from posthog.models.integration import Integration
@@ -29,6 +30,7 @@ from products.signals.backend.report_generation.resolve_reviewers import (
rank_assignee_candidates,
resolve_org_github_login_to_users,
resolve_suggested_reviewers,
+ resolve_suggested_reviewers_with_diagnostics,
)
@@ -576,3 +578,107 @@ class TestResolveSuggestedReviewersEndToEnd:
logins = [r.login for r in reviewers]
assert "fresh-owner" in logins
assert logins.index("fresh-owner") < logins.index("aged-author")
+
+
+class TestResolveSuggestedReviewersDiagnostics:
+ @pytest.mark.parametrize(
+ "name,repository,commit_hashes,author,expected_outcome,expected_counts",
+ [
+ ("no_repository", "", {"d" * 7: "bug"}, None, "no_repository", {"commit_hash_count": 1}),
+ ("no_commit_hashes", "acme/app", {}, None, "no_commit_hashes", {"commit_hash_count": 0}),
+ (
+ "unattributed_commits",
+ "acme/app",
+ {"d" * 7: "bug", "e" * 7: "bug"},
+ None,
+ "no_commit_authors",
+ {"lookups_attempted": 2, "lookups_resolved": 0, "lookups_missing": 2},
+ ),
+ (
+ "bot_only_no_activity",
+ "acme/app",
+ {"d" * 7: "bug"},
+ GitHubCommitAuthor(
+ login="dependabot[bot]",
+ name="dependabot",
+ commit_url="https://github.com/acme/app/commit/ddddddd",
+ file_paths=("products/signals/backend/models.py",),
+ is_bot=True,
+ ),
+ "only_bot_authors",
+ {"lookups_resolved": 1, "bot_author_count": 1, "blame_login_count": 0, "touched_path_count": 1},
+ ),
+ ],
+ )
+ def test_empty_result_names_its_cause(
+ self, team, name, repository, commit_hashes, author, expected_outcome, expected_counts
+ ):
+ class FakeGitHub:
+ def get_commit_author_info(self, repository, sha):
+ return author
+
+ with (
+ patch(
+ "products.signals.backend.report_generation.resolve_reviewers.GitHubIntegration.first_for_team_repository",
+ return_value=FakeGitHub(),
+ ),
+ patch(
+ "products.signals.backend.report_generation.resolve_reviewers.get_area_activity",
+ return_value={},
+ ),
+ patch(
+ "products.signals.backend.report_generation.resolve_reviewers.repository_activity_needs_rebuild",
+ return_value=False,
+ ),
+ ):
+ resolution = resolve_suggested_reviewers_with_diagnostics(team.id, repository, commit_hashes)
+
+ assert resolution.reviewers == []
+ assert resolution.diagnostics.outcome == expected_outcome
+ for field, value in expected_counts.items():
+ assert getattr(resolution.diagnostics, field) == value, field
+
+ def test_a_throttled_lookup_outweighs_what_the_others_returned(self, team):
+ # One lookup throttled, the other unattributed. The throttled commit is the one that could
+ # have carried the human author, so the rate limit is the cause worth reporting — reading
+ # this as `no_commit_authors` would send someone hunting a GitHub attribution problem.
+ class FakeGitHub:
+ def get_commit_author_info(self, repository, sha):
+ if sha.startswith("d"):
+ raise GitHubRateLimitError("rate limited")
+ return None
+
+ with (
+ patch(
+ "products.signals.backend.report_generation.resolve_reviewers.GitHubIntegration.first_for_team_repository",
+ return_value=FakeGitHub(),
+ ),
+ patch(
+ "products.signals.backend.report_generation.resolve_reviewers.get_area_activity",
+ return_value={},
+ ),
+ patch(
+ "products.signals.backend.report_generation.resolve_reviewers.repository_activity_needs_rebuild",
+ return_value=False,
+ ),
+ ):
+ resolution = resolve_suggested_reviewers_with_diagnostics(
+ team.id, "acme/app", {"d" * 7: "bug", "e" * 7: "bug"}
+ )
+
+ assert resolution.reviewers == []
+ assert resolution.diagnostics.outcome == "github_rate_limited"
+ assert resolution.diagnostics.lookups_rate_limited == 1
+ assert resolution.diagnostics.lookups_attempted == 2
+
+ def test_no_integration_is_reported_before_any_lookup(self, team):
+ with patch(
+ "products.signals.backend.report_generation.resolve_reviewers.GitHubIntegration.first_for_team_repository",
+ return_value=None,
+ ):
+ resolution = resolve_suggested_reviewers_with_diagnostics(team.id, "acme/app", {"d" * 7: "bug"})
+
+ assert resolution.reviewers == []
+ assert resolution.diagnostics.outcome == "no_github_integration"
+ assert resolution.diagnostics.lookups_attempted == 0