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.

fix(review_hog): backend follow-ups after repository enablement (#114851)

Julian Bezd234a7added5
diff --git a/products/review_hog/backend/api/repositories.py b/products/review_hog/backend/api/repositories.py
index e76d1cd9082c..565a96d5b57e 100644
--- a/products/review_hog/backend/api/repositories.py
+++ b/products/review_hog/backend/api/repositories.py
@@ -23,7 +23,7 @@ from posthog.models.organization import OrganizationMembership
from posthog.models.scoping.manager import resolve_effective_team_id
from posthog.models.team import Team
from posthog.models.user import User
-from posthog.permissions import PostHogFeatureFlagPermission
+from posthog.permissions import PostHogFeatureFlagPermission, get_authenticator_scoped_team_ids
from products.review_hog.backend.activity_logging import installation_account_name
from products.review_hog.backend.automatic_review_rules import (
@@ -374,6 +374,11 @@ class EffectiveTeamStrictManagementPermission(BasePermission):
def has_permission(self, request: Request, view: Any) -> bool:
if not isinstance(view, ReviewHogProjectViewSetMixin):
return False
+ # The API scope check covers only the URL project, so a key scoped to an environment must not
+ # reach its parent project.
+ scoped_teams = get_authenticator_scoped_team_ids(request.successful_authenticator)
+ if scoped_teams is not None and view.effective_team_id not in scoped_teams:
+ return False
if request.method in SAFE_METHODS:
return view.user_permissions.team(view.effective_team).effective_membership_level is not None
return view.is_effective_team_admin()
diff --git a/products/review_hog/backend/api/reviews.py b/products/review_hog/backend/api/reviews.py
index 3b41a2dd70dc..6d05015dc166 100644
--- a/products/review_hog/backend/api/reviews.py
+++ b/products/review_hog/backend/api/reviews.py
@@ -11,6 +11,7 @@ from drf_spectacular.utils import OpenApiResponse, extend_schema
from rest_framework import serializers, status, viewsets
from rest_framework.decorators import action
from rest_framework.exceptions import NotFound
+from rest_framework.permissions import BasePermission
from rest_framework.request import Request
from rest_framework.response import Response
@@ -19,7 +20,7 @@ from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.egress.github.transport import GitHubRateLimitError
from posthog.models.scoping.manager import resolve_effective_team_id
from posthog.models.user import User
-from posthog.permissions import PostHogFeatureFlagPermission
+from posthog.permissions import PostHogFeatureFlagPermission, get_authenticator_scoped_team_ids
from products.review_hog.backend.models import ReviewReport, ReviewReportArtefact
from products.review_hog.backend.requested_reviews import (
@@ -53,6 +54,7 @@ from products.review_hog.backend.reviewer.progress import (
snapshot_stats,
turn_stats,
)
+from products.review_hog.backend.reviewer.review_state import completed_turn_review_mode
from products.review_hog.backend.reviewer.tools.github_meta import PRParser
logger = logging.getLogger(__name__)
@@ -63,6 +65,7 @@ MAX_REVIEWS_LIMIT = 100
# Effectiveness stats aggregate deeper than the list — enough history for survival rates to mean something.
PERSPECTIVE_STATS_REPORT_LIMIT = 50
+OWN_DEEP_STATS_REVIEW_LIMIT = 10
_PRIORITY_CHOICES = [priority.value for priority in IssuePriority]
# Display order for the detail view: most urgent first.
@@ -89,13 +92,21 @@ class ReviewsListParamsSerializer(serializers.Serializer):
)
+class PerspectiveStatsScope(models.TextChoices):
+ MINE = SCOPE_MINE, "Mine"
+ EVERYONE = SCOPE_EVERYONE, "Everyone"
+ OWN_DEEP = "own_deep", "Own Deep reviews"
+
+
class PerspectiveStatsParamsSerializer(serializers.Serializer):
scope = serializers.ChoiceField(
- choices=[SCOPE_MINE, SCOPE_EVERYONE],
- default=SCOPE_MINE,
+ choices=PerspectiveStatsScope.choices,
+ default=PerspectiveStatsScope.MINE,
help_text="Whose reviews to aggregate: `mine` (the default) for reviews the requesting user ran "
"plus reviews of pull requests they authored (matched via their linked GitHub login), "
- "`everyone` for every review on this project.",
+ "`everyone` for every review on this project, `own_deep` for the last "
+ f"{OWN_DEEP_STATS_REVIEW_LIMIT} Deep reviews the requesting user started. The review skills "
+ "in the settings use `own_deep`, because only the person who starts a Deep review picks its skills.",
)
@@ -529,6 +540,19 @@ def _review_payload(
}
+class EffectiveTeamScopedKeyPermission(BasePermission):
+ """Reviews live on the root project, and the API scope check covers only the URL project.
+
+ So a key scoped to an environment must not reach its parent project through an environment URL.
+ """
+
+ message = "This key is not scoped to the project that holds the reviews."
+
+ def has_permission(self, request: Request, view: Any) -> bool:
+ scoped_teams = get_authenticator_scoped_team_ids(request.successful_authenticator)
+ return scoped_teams is None or resolve_effective_team_id(view.team_id) in scoped_teams
+
+
class ReviewRecentReviewsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
"""Recent ReviewHog reviews on this project.
@@ -547,7 +571,7 @@ class ReviewRecentReviewsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet
# reachable with a personal API key or OAuth token, which is how MCP tools authenticate. Session
# UI access is unchanged; this only adds token access, gated by review_hog:read / review_hog:write.
scope_object = "review_hog"
- permission_classes = [PostHogFeatureFlagPermission]
+ permission_classes = [PostHogFeatureFlagPermission, EffectiveTeamScopedKeyPermission]
posthog_feature_flag = "review-hog"
# Unscoped only to satisfy the router/introspection; every real query goes through `for_team`.
queryset = ReviewReport.objects.unscoped()
@@ -671,20 +695,40 @@ class ReviewRecentReviewsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet
summary="Perspective effectiveness stats",
description="How many findings each review skill (perspective or blind-spot sweep) raised across the "
"recent completed reviews in scope — the requesting user's by default, every review on this project "
- "with `scope=everyone` — and how many of those the validator kept vs dismissed.",
+ "with `scope=everyone`, the user's own last Deep reviews with `scope=own_deep` — and how many of those "
+ "the validator kept vs dismissed.",
)
@action(methods=["GET"], detail=False, required_scopes=["review_hog:read"])
def perspective_stats(self, request: Request, **kwargs) -> Response:
params = PerspectiveStatsParamsSerializer(data=request.query_params)
params.is_valid(raise_exception=True)
- team_id, queryset = self._reports(request, scope=params.validated_data["scope"])
+ scope = params.validated_data["scope"]
+ queryset: QuerySet[ReviewReport]
+ if scope == PerspectiveStatsScope.OWN_DEEP:
+ team_id = resolve_effective_team_id(self.team_id)
+ # Filter before the report limit, so newer Standard reports cannot push Deep ones out of the window.
+ # Rows from before the per-mode watermark predate Standard reviews.
+ queryset = ReviewReport.objects.for_team(team_id, canonical=True).filter(
+ Q(published_heads_by_mode__has_key=REVIEW_MODE_FULL) | Q(published_heads_by_mode__isnull=True),
+ acting_user_id=request.user.id,
+ )
+ else:
+ team_id, queryset = self._reports(request, scope=scope)
reports = list(
queryset.filter(last_run_at__isnull=False).order_by("-last_run_at")[:PERSPECTIVE_STATS_REPORT_LIMIT]
)
- stats: dict[str, dict[str, int]] = {}
bundle = load_findings_bundle(team_id=team_id, report_ids=[str(report.id) for report in reports])
- for report in reports:
- pairs = bundle.turn(str(report.id), report.run_count)
+ turns = [bundle.turn(str(report.id), report.run_count) for report in reports]
+ if scope == PerspectiveStatsScope.OWN_DEEP:
+ # Standard turns read none of the user's skills, so they would dilute the kept counts.
+ turns = [
+ pairs
+ for report, pairs in zip(reports, turns)
+ if completed_turn_review_mode(report, pairs) == REVIEW_MODE_FULL
+ ]
+ turns = turns[:OWN_DEEP_STATS_REVIEW_LIMIT]
+ stats: dict[str, dict[str, int]] = {}
+ for pairs in turns:
for finding, verdict in pairs:
entry = stats.setdefault(
finding.source_perspective or "unknown", {"raised": 0, "kept": 0, "dismissed": 0}
@@ -694,7 +738,7 @@ class ReviewRecentReviewsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet
entry["kept" if verdict.is_valid else "dismissed"] += 1
items: list[dict[str, Any]] = [{"skill_name": skill_name, **counts} for skill_name, counts in stats.items()]
items.sort(key=lambda item: (-item["kept"], -item["raised"], item["skill_name"]))
- payload = {"report_count": len(reports), "perspectives": items}
+ payload = {"report_count": len(turns), "perspectives": items}
return Response(ReviewPerspectiveStatsSerializer(payload).data)
@extend_schema(
diff --git a/products/review_hog/backend/label_reviews.py b/products/review_hog/backend/label_reviews.py
index e6c4d8b7b025..3bfad5a5cec7 100644
--- a/products/review_hog/backend/label_reviews.py
+++ b/products/review_hog/backend/label_reviews.py
@@ -26,7 +26,12 @@ from products.review_hog.backend.ownership import RepositoryOwnership, Repositor
from products.review_hog.backend.pr_owner import PullRequestOwnerResolver
from products.review_hog.backend.pull_request_events import REVIEWHOG_LABEL
from products.review_hog.backend.reviewer.persistence import lift_review_tier_for_joined_trigger
-from products.review_hog.backend.reviewer.tools.github_client import GitHubAPIError, github_api_request
+from products.review_hog.backend.reviewer.tools.github_client import (
+ GitHubAPIError,
+ github_api_get_paginated,
+ github_api_request,
+ is_app_bot_author,
+)
logger = logging.getLogger(__name__)
_otel = OtelInstrumentFactory("review_hog")
@@ -87,6 +92,17 @@ class LabelReview:
def _github(self, integration: Integration) -> GitHubIntegration:
return GitHubIntegration(integration, source="review_hog", priority=Priority.NORMAL)
+ def _bot_label_comment_posted(self, token: str) -> bool:
+ return any(
+ comment.get("body") == BOT_LABEL_COMMENT and is_app_bot_author(comment.get("user"))
+ for comment in github_api_get_paginated(
+ f"/repos/{self.repository}/issues/{self.pr_number}/comments",
+ token=token,
+ installation_id=self.installation_id,
+ endpoint="/repos/{owner}/{repo}/issues/{issue_number}/comments",
+ )
+ )
+
def _refuse_bot_label(self, integration: Integration) -> None:
# The label goes first: a failed call retries the task, and the comment must post only once.
token = self._github(integration).get_access_token()
@@ -101,6 +117,9 @@ class LabelReview:
except GitHubAPIError as error:
if error.status != 404:
raise
+ # A POST can succeed on GitHub and still fail here, so a retry checks for the earlier comment.
+ if self._bot_label_comment_posted(token):
+ return
github_api_request(
"POST",
f"/repos/{self.repository}/issues/{self.pr_number}/comments",
diff --git a/products/review_hog/backend/reviewer/review_state.py b/products/review_hog/backend/reviewer/review_state.py
index 2280af1919a9..edb027bb23e2 100644
--- a/products/review_hog/backend/reviewer/review_state.py
+++ b/products/review_hog/backend/reviewer/review_state.py
@@ -1,12 +1,14 @@
import json
+from collections.abc import Iterable
from products.review_hog.backend.models import ReviewReport
+from products.review_hog.backend.reviewer.artefact_content import ReviewIssueFinding, ValidationVerdict
from products.review_hog.backend.reviewer.constants import REVIEW_MODE_FLASH, REVIEW_MODE_FULL
from products.review_hog.backend.reviewer.persistence import load_turn_findings
-def review_mode_for_run(report: ReviewReport, run_index: int) -> str:
- for finding, _ in load_turn_findings(team_id=report.team_id, report_id=str(report.id), run_index=run_index):
+def _findings_review_mode(pairs: Iterable[tuple[ReviewIssueFinding, ValidationVerdict | None]]) -> str | None:
+ for finding, _ in pairs:
if finding.validation_context:
try:
context = json.loads(finding.validation_context)
@@ -16,7 +18,16 @@ def review_mode_for_run(report: ReviewReport, run_index: int) -> str:
mode = context.get("review_mode")
if isinstance(mode, str) and mode in (REVIEW_MODE_FULL, REVIEW_MODE_FLASH):
return mode
- return REVIEW_MODE_FULL
+ return None
+
+
+def turn_review_mode(pairs: Iterable[tuple[ReviewIssueFinding, ValidationVerdict | None]]) -> str:
+ """The mode a turn ran in, read from its findings. A turn without findings reads as a Deep (full) turn."""
+ return _findings_review_mode(pairs) or REVIEW_MODE_FULL
+
+
+def review_mode_for_run(report: ReviewReport, run_index: int) -> str:
+ return turn_review_mode(load_turn_findings(team_id=report.team_id, report_id=str(report.id), run_index=run_index))
def published_heads_by_mode(report: ReviewReport) -> dict[str, str]:
@@ -29,5 +40,20 @@ def published_heads_by_mode(report: ReviewReport) -> dict[str, str]:
return {review_mode_for_run(report, run_index): report.published_head_sha}
+def completed_turn_review_mode(
+ report: ReviewReport, pairs: Iterable[tuple[ReviewIssueFinding, ValidationVerdict | None]]
+) -> str:
+ """The mode of a report's completed turn. A turn without findings falls back to the publish watermarks."""
+ mode = _findings_review_mode(pairs)
+ if mode is not None:
+ return mode
+ head = report.completed_head_sha or report.head_sha
+ # Legacy rows kept the mode on findings only, and the findings already said nothing.
+ heads = report.published_heads_by_mode or {}
+ if head and heads.get(REVIEW_MODE_FLASH) == head and heads.get(REVIEW_MODE_FULL) != head:
+ return REVIEW_MODE_FLASH
+ return REVIEW_MODE_FULL
+
+
def review_already_published(report: ReviewReport, head_sha: str, review_mode: str) -> bool:
return bool(head_sha) and published_heads_by_mode(report).get(review_mode) == head_sha
diff --git a/products/review_hog/backend/temporal/activities.py b/products/review_hog/backend/temporal/activities.py
index fe7fb75457a4..6afb098ba300 100644
--- a/products/review_hog/backend/temporal/activities.py
+++ b/products/review_hog/backend/temporal/activities.py
@@ -283,6 +283,8 @@ class ResolveActingUserInput:
# The PR's head branch, which links a self-driving PR to its Inbox report. The fetch refuses forks,
# so the branch is in the base repository. None in older payloads: such a PR then has no owner.
head_branch: str | None = None
+ # Full in older payloads, which keeps them off the Flash-after-Full check below.
+ review_mode: str = REVIEW_MODE_FULL
@dataclass(frozen=False)
@@ -854,6 +856,13 @@ def _automatic_review_allowed(input: ResolveActingUserInput, acting_user_id: int
)
+def _flash_after_full(input: ResolveActingUserInput) -> bool:
+ """Whether a queued Flash request now follows a Full review published while it waited."""
+ if input.review_mode != REVIEW_MODE_FLASH or input.report_id is None:
+ return False
+ return full_review_published(ReviewReport.objects.for_team(input.team_id).filter(id=input.report_id).first())
+
+
def _resolve_acting_user(input: ResolveActingUserInput) -> ResolveActingUserResult:
# Resolved even on override runs: the owner decides resolution and the clean-review media,
# whoever asked for the review.
@@ -873,7 +882,7 @@ def _resolve_acting_user(input: ResolveActingUserInput) -> ResolveActingUserResu
if acting_user_id is None and input.trigger_source == TRIGGER_LABEL:
acting_user_id, resolved_from = input.default_user_id, "default"
automatic_allowed = input.trigger_source == TRIGGER_AUTOMATIC and _automatic_review_allowed(input, acting_user_id)
- if input.trigger_source == TRIGGER_AUTOMATIC and not automatic_allowed:
+ if (input.trigger_source == TRIGGER_AUTOMATIC and not automatic_allowed) or _flash_after_full(input):
if input.report_id is not None:
ReviewReport.objects.for_team(input.team_id).filter(id=input.report_id).update(
status=ReviewReport.Status.IDLE
diff --git a/products/review_hog/backend/temporal/workflow.py b/products/review_hog/backend/temporal/workflow.py
index 4a42f91e588a..8d7fd1a7b0b5 100644
--- a/products/review_hog/backend/temporal/workflow.py
+++ b/products/review_hog/backend/temporal/workflow.py
@@ -531,6 +531,7 @@ class ReviewPRWorkflow:
installation_id=inputs.installation_id,
github_repo_id=inputs.github_repo_id,
head_branch=branch,
+ review_mode=inputs.review_mode,
),
start_to_close_timeout=_QUICK_TIMEOUT,
retry_policy=_RETRY,
diff --git a/products/review_hog/backend/tests/test_acting_user.py b/products/review_hog/backend/tests/test_acting_user.py
index 12425d03f880..cf0a2dbf5f32 100644
--- a/products/review_hog/backend/tests/test_acting_user.py
+++ b/products/review_hog/backend/tests/test_acting_user.py
@@ -142,6 +142,39 @@ class TestResolveActingUser(BaseTest):
report.refresh_from_db()
assert report.status == (ReviewReport.Status.ACTIVE if eligible else ReviewReport.Status.IDLE)
+ @parameterized.expand(
+ [
+ ("flash_after_full", "flash", True, False),
+ ("flash_without_full", "flash", False, True),
+ ("full_after_full", "full", True, True),
+ ]
+ )
+ def test_queued_request_rechecks_flash_after_full(
+ self, _name: str, review_mode: str, full_published: bool, runs: bool
+ ) -> None:
+ report = ReviewReport.objects.for_team(self.team.id).create(
+ team_id=self.team.id,
+ repository="PostHog/posthog",
+ pr_number=7,
+ pr_url="https://github.com/PostHog/posthog/pull/7",
+ head_branch="feat",
+ base_branch="main",
+ published_heads_by_mode={"full": "a" * 40} if full_published else None,
+ )
+ result = _resolve_acting_user(
+ ResolveActingUserInput(
+ team_id=self.team.id,
+ author_login="octocat",
+ override_user_id=None,
+ trigger_source=TRIGGER_MANUAL,
+ report_id=str(report.id),
+ review_mode=review_mode,
+ )
+ )
+ assert result.acting_user_id == (self.user.id if runs else None)
+ report.refresh_from_db()
+ assert report.status == (ReviewReport.Status.ACTIVE if runs else ReviewReport.Status.IDLE)
+
def test_settings_row_flows_into_the_result(self) -> None:
# The user's saved preferences must reach the workflow — if resolve stops loading any of them,
# the gates and publish silently revert to defaults. Each value is the OPPOSITE of its
diff --git a/products/review_hog/backend/tests/test_automatic_reviews.py b/products/review_hog/backend/tests/test_automatic_reviews.py
index bdc4243b76a3..073881ddddc9 100644
--- a/products/review_hog/backend/tests/test_automatic_reviews.py
+++ b/products/review_hog/backend/tests/test_automatic_reviews.py
@@ -24,6 +24,7 @@ from posthog.models.organization import OrganizationMembership
from posthog.models.team import Team
from posthog.models.user import User
+from products.review_hog.backend.label_reviews import BOT_LABEL_COMMENT
from products.review_hog.backend.models import (
ReviewInstallationClaim,
ReviewProjectSettings,
@@ -43,6 +44,7 @@ _LABEL_QUEUE = "products.review_hog.backend.tasks.process_label_event.delay"
_START = "products.review_hog.backend.temporal.client.start_review_pr_workflow"
_BUSY = "products.review_hog.backend.temporal.client.workflow_running"
_GITHUB = "products.review_hog.backend.label_reviews.github_api_request"
+_GITHUB_LIST = "products.review_hog.backend.label_reviews.github_api_get_paginated"
_SECRET = "test-review-hog-webhook-secret"
_HEAD_SHA = "a" * 40
_DISPATCH_METRIC = "posthog_review_hog_authored_pr_review_total"
@@ -460,6 +462,7 @@ class TestLabelReviewTask(BaseTest):
self.enterContext(patch(_BUSY, return_value=False))
self.start = self.enterContext(patch(_START))
self.github = self.enterContext(patch(_GITHUB))
+ self.github_comments = self.enterContext(patch(_GITHUB_LIST, return_value=[]))
self.enterContext(patch("products.review_hog.backend.label_reviews.GitHubIntegration.get_access_token"))
def _queued_event(self, payload: dict[str, object]) -> Mapping[str, object]:
@@ -501,14 +504,19 @@ class TestLabelReviewTask(BaseTest):
def test_a_retried_bot_label_refusal_comments_once(self) -> None:
queued = self._queued_event(_label_payload(sender="renovate[bot]", sender_type="Bot"))
- self.github.side_effect = [GitHubAPIError("boom", status=502), GitHubAPIError("gone", status=404), None]
-
- with self.assertRaises(GitHubAPIError):
- process_label_event.run(**queued)
+ gone = GitHubAPIError("gone", status=404)
+ # The second POST fails after GitHub stored the comment, so the third run finds it and skips.
+ self.github.side_effect = [GitHubAPIError("boom", status=502), gone, GitHubAPIError("boom", status=502), gone]
+ posted = {"body": BOT_LABEL_COMMENT, "user": {"login": "posthog[bot]", "type": "Bot"}}
+ self.github_comments.side_effect = [[], [posted]]
+
+ for _ in range(2):
+ with self.assertRaises(GitHubAPIError):
+ process_label_event.run(**queued)
process_label_event.run(**queued)
calls = [call.args[0] for call in self.github.call_args_list]
- assert calls == ["DELETE", "DELETE", "POST"]
+ assert calls == ["DELETE", "DELETE", "POST", "DELETE"]
self.start.assert_not_called()
@parameterized.expand(
diff --git a/products/review_hog/backend/tests/test_repositories_api.py b/products/review_hog/backend/tests/test_repositories_api.py
index a6bc00a189b1..f96ed2adaa70 100644
--- a/products/review_hog/backend/tests/test_repositories_api.py
+++ b/products/review_hog/backend/tests/test_repositories_api.py
@@ -8,6 +8,8 @@ from posthog.models import Organization, Team, User
from posthog.models.activity_logging.activity_log import ActivityLog
from posthog.models.integration import Integration
from posthog.models.organization import OrganizationMembership
+from posthog.models.personal_api_key import PersonalAPIKey
+from posthog.models.utils import generate_random_token_personal, hash_key_value
from products.access_control.backend.models.access_control import AccessControl
from products.review_hog.backend.models import (
@@ -99,6 +101,33 @@ class TestReviewRepositorySettingsAPI(APIBaseTest):
assert res.status_code == 403, res.json()
assert self.client.get(self._url(path, environment)).status_code == 200
+ @parameterized.expand(
+ [
+ ("environment_only", False, (403, 403, 403)),
+ ("environment_and_parent", True, (200, 200, 200)),
+ ]
+ )
+ def test_a_project_scoped_key_needs_the_parent_project(
+ self, _name: str, include_parent: bool, expected: tuple[int, int, int]
+ ) -> None:
+ environment = Team.objects.create(organization=self.organization, parent_team=self.team, name="Staging")
+ value = generate_random_token_personal()
+ PersonalAPIKey.objects.create(
+ label="Scoped",
+ user=self.user,
+ secure_value=hash_key_value(value),
+ scopes=["*"],
+ scoped_teams=[environment.id, self.team.id] if include_parent else [environment.id],
+ )
+ self.client.logout()
+ self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {value}")
+
+ read = self.client.get(self._url("repositories/", environment))
+ write = self.client.post(self._url("repositories/", environment), {**WEB, "selected": True})
+ reviews = self.client.get(self._url("reviews/", environment))
+
+ assert (read.status_code, write.status_code, reviews.status_code) == expected
+
def test_project_rule_stores_only_what_differs_and_is_logged(self) -> None:
res = self.client.patch(
self._url("project_settings/"),
diff --git a/products/review_hog/backend/tests/test_reviews_api.py b/products/review_hog/backend/tests/test_reviews_api.py
index 9d06d313c6e0..6131252f7129 100644
--- a/products/review_hog/backend/tests/test_reviews_api.py
+++ b/products/review_hog/backend/tests/test_reviews_api.py
@@ -1,3 +1,4 @@
+import json
from datetime import UTC, datetime, timedelta
import time_machine
@@ -120,6 +121,7 @@ class TestRecentReviewsAPI(APIBaseTest):
adjusted: IssuePriority | None = None,
judged: bool = True,
perspective: str | None = None,
+ review_mode: str | None = None,
) -> None:
ReviewReportArtefact.append_finding(
team_id=self.team.id,
@@ -134,6 +136,7 @@ class TestRecentReviewsAPI(APIBaseTest):
suggestion="s",
priority=priority,
source_perspective=perspective,
+ validation_context=json.dumps({"review_mode": review_mode}) if review_mode else None,
),
attribution=ArtefactAttribution.system(),
)
@@ -875,6 +878,33 @@ class TestRecentReviewsAPI(APIBaseTest):
]
assert self.client.get(f"{self.url}perspective_stats/?scope=everything").status_code == 400
+ # The settings read own_deep: a Standard turn reads none of the user's skills, and a teammate's
+ # Deep review uses the teammate's skills, so neither may count.
+ standard = self._report(pr_number=4, acting_user=self.user)
+ self._finding(standard, "1-s", priority=IssuePriority.MUST_FIX, perspective=logic, review_mode="flash")
+ ReviewReport.objects.for_team(self.team.id).filter(id=standard.id).update(
+ last_run_at=datetime(2026, 6, 1, tzinfo=UTC)
+ )
+ # A clean Standard turn has no findings to carry its mode, so only the publish watermark tells.
+ # It is the newest report, and it must not take a slot from the Deep reviews under the report limit.
+ clean_standard = self._report(
+ pr_number=5, acting_user=self.user, head_sha="c1ea2", published_heads_by_mode={"flash": "c1ea2"}
+ )
+ ReviewReport.objects.for_team(self.team.id).filter(id=clean_standard.id).update(
+ last_run_at=datetime(2026, 8, 1, tzinfo=UTC)
+ )
+
+ with patch("products.review_hog.backend.api.reviews.PERSPECTIVE_STATS_REPORT_LIMIT", 2):
+ res = self.client.get(f"{self.url}perspective_stats/?scope=own_deep")
+
+ assert res.status_code == 200
+ data = res.json()
+ assert data["report_count"] == 2
+ assert data["perspectives"] == [
+ {"skill_name": logic, "raised": 2, "kept": 1, "dismissed": 1},
+ {"skill_name": blind, "raised": 1, "kept": 1, "dismissed": 0},
+ ]
+
def test_retrieve_is_project_wide_but_never_cross_team(self) -> None:
# Opening a teammate's review from the everyone-scope list must work, but another team's
# report id must still 404 (tenant isolation), and garbage ids must not 500.
diff --git a/products/review_hog/frontend/generated/api.schemas.ts b/products/review_hog/frontend/generated/api.schemas.ts
index 1171bc52845f..4e6ef0ccae1a 100644
--- a/products/review_hog/frontend/generated/api.schemas.ts
+++ b/products/review_hog/frontend/generated/api.schemas.ts
@@ -1306,10 +1306,11 @@ export const ReviewHogReviewsListScope = {
export type ReviewHogReviewsPerspectiveStatsRetrieveParams = {
/**
- * Whose reviews to aggregate: `mine` (the default) for reviews the requesting user ran plus reviews of pull requests they authored (matched via their linked GitHub login), `everyone` for every review on this project.
+ * Whose reviews to aggregate: `mine` (the default) for reviews the requesting user ran plus reviews of pull requests they authored (matched via their linked GitHub login), `everyone` for every review on this project, `own_deep` for the last 10 Deep reviews the requesting user started. The review skills in the settings use `own_deep`, because only the person who starts a Deep review picks its skills.
*
- * * `mine` - mine
- * * `everyone` - everyone
+ * * `mine` - Mine
+ * * `everyone` - Everyone
+ * * `own_deep` - Own Deep reviews
* @minLength 1
*/
scope?: ReviewHogReviewsPerspectiveStatsRetrieveScope
@@ -1321,4 +1322,5 @@ export type ReviewHogReviewsPerspectiveStatsRetrieveScope =
export const ReviewHogReviewsPerspectiveStatsRetrieveScope = {
Mine: 'mine',
Everyone: 'everyone',
+ OwnDeep: 'own_deep',
} as const
diff --git a/products/review_hog/frontend/generated/api.ts b/products/review_hog/frontend/generated/api.ts
index 5e011190cf70..1cb9dd643122 100644
--- a/products/review_hog/frontend/generated/api.ts
+++ b/products/review_hog/frontend/generated/api.ts
@@ -607,7 +607,7 @@ export const getReviewHogReviewsPerspectiveStatsRetrieveUrl = (
}
/**
- * How many findings each review skill (perspective or blind-spot sweep) raised across the recent completed reviews in scope — the requesting user's by default, every review on this project with `scope=everyone` — and how many of those the validator kept vs dismissed.
+ * How many findings each review skill (perspective or blind-spot sweep) raised across the recent completed reviews in scope — the requesting user's by default, every review on this project with `scope=everyone`, the user's own last Deep reviews with `scope=own_deep` — and how many of those the validator kept vs dismissed.
* @summary Perspective effectiveness stats
*/
export const reviewHogReviewsPerspectiveStatsRetrieve = async (
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index c7c3368025bd..36e9246f8dce 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -126257,10 +126257,11 @@ export namespace Schemas {
export type ReviewHogReviewsPerspectiveStatsRetrieveParams = {
/**
- * Whose reviews to aggregate: `mine` (the default) for reviews the requesting user ran plus reviews of pull requests they authored (matched via their linked GitHub login), `everyone` for every review on this project.
+ * Whose reviews to aggregate: `mine` (the default) for reviews the requesting user ran plus reviews of pull requests they authored (matched via their linked GitHub login), `everyone` for every review on this project, `own_deep` for the last 10 Deep reviews the requesting user started. The review skills in the settings use `own_deep`, because only the person who starts a Deep review picks its skills.
*
- * * `mine` - mine
- * * `everyone` - everyone
+ * * `mine` - Mine
+ * * `everyone` - Everyone
+ * * `own_deep` - Own Deep reviews
* @minLength 1
*/
scope?: ReviewHogReviewsPerspectiveStatsRetrieveScope;
@@ -126272,6 +126273,7 @@ export namespace Schemas {
export const ReviewHogReviewsPerspectiveStatsRetrieveScope = {
Mine: 'mine',
Everyone: 'everyone',
+ OwnDeep: 'own_deep',
} as const;
export type SandboxCustomImagesListParams = {