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(review_hog): add a paginated reviews table endpoint (#114914)

Julian Bez8806f4c4f4ec
diff --git a/products/review_hog/backend/api/reviews.py b/products/review_hog/backend/api/reviews.py
index 4db1ab8a2781..0e0b02b03002 100644
--- a/products/review_hog/backend/api/reviews.py
+++ b/products/review_hog/backend/api/reviews.py
@@ -3,7 +3,9 @@ import logging
from typing import Any, cast, get_args
from django.db import models
-from django.db.models import Q, QuerySet
+from django.db.models import F, Func, OuterRef, Q, QuerySet, Subquery, Value
+from django.db.models.fields.json import KeyTextTransform
+from django.db.models.functions import Cast, Coalesce
from django.utils import timezone
from drf_spectacular.openapi import AutoSchema
@@ -22,7 +24,7 @@ from posthog.models.scoping.manager import resolve_effective_team_id
from posthog.models.user import User
from posthog.permissions import PostHogFeatureFlagPermission, get_authenticator_scoped_team_ids
-from products.review_hog.backend.models import ReviewReport
+from products.review_hog.backend.models import ReviewReport, ReviewReportArtefact
from products.review_hog.backend.pr_status import PRStatus, PRStatusLookup, ReviewPRState, ReviewRequestOutcomeStatus
from products.review_hog.backend.preferences import UrgencyThreshold
from products.review_hog.backend.requested_reviews import (
@@ -64,6 +66,7 @@ from products.review_hog.backend.reviewer.progress import (
latest_resolution_summaries,
progress_payload,
resolution_states,
+ running_q,
snapshot_stats,
turn_markers,
turn_stats,
@@ -75,8 +78,11 @@ from products.review_hog.backend.reviewer.tools.github_meta import PRParser
logger = logging.getLogger(__name__)
DEFAULT_REVIEWS_LIMIT = 5
+DEFAULT_REVIEWS_TABLE_LIMIT = 25
# Caps "Show more" growth — enrichment (jsonb stats + findings bundle) is per-row work.
MAX_REVIEWS_LIMIT = 100
+# Far beyond any real history, and well inside PostgreSQL's bigint OFFSET.
+MAX_REVIEWS_TABLE_OFFSET = 1_000_000
# Effectiveness stats aggregate deeper than the list — enough history for survival rates to mean something.
PERSPECTIVE_STATS_REPORT_LIMIT = 50
@@ -90,6 +96,11 @@ SCOPE_MINE = "mine"
SCOPE_EVERYONE = "everyone"
+class ReviewScope(models.TextChoices):
+ MINE = SCOPE_MINE, "Mine"
+ EVERYONE = SCOPE_EVERYONE, "Everyone"
+
+
class ReviewsListParamsSerializer(serializers.Serializer):
scope = serializers.ChoiceField(
choices=[SCOPE_MINE, SCOPE_EVERYONE],
@@ -342,6 +353,64 @@ class ReviewRecentReviewsPageSerializer(serializers.Serializer):
)
+class ReviewTableStatus(models.TextChoices):
+ RUNNING = "running", "Running"
+ COMPLETED = "completed", "Completed"
+
+
+class ReviewsTableParamsSerializer(serializers.Serializer):
+ scope = serializers.ChoiceField(
+ choices=ReviewScope.choices,
+ default=SCOPE_MINE,
+ help_text="Whose reviews to list: `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.",
+ )
+ repository = serializers.CharField(
+ required=False,
+ help_text="Only reviews of this repository, as `owner/repo`. Matched case-insensitively.",
+ )
+ review_mode = serializers.ChoiceField(
+ choices=ReviewTriggerReviewMode.choices,
+ required=False,
+ help_text="Only reviews whose latest completed turn ran this mode: 'full' (Deep) or 'flash' "
+ "(Standard). Turns that did not record their mode match neither value.",
+ )
+ status = serializers.ChoiceField(
+ choices=ReviewTableStatus.choices,
+ required=False,
+ help_text="Only reviews in this state: 'running' for reviews with a run in flight (activity within "
+ "the last 30 minutes), 'completed' for reviews with a completed turn and nothing running now.",
+ )
+ published = serializers.BooleanField(
+ required=False,
+ allow_null=True,
+ default=None,
+ help_text="Only reviews whose latest completed turn was (true) or was not (false) published to GitHub.",
+ )
+ limit = serializers.IntegerField(
+ default=DEFAULT_REVIEWS_TABLE_LIMIT,
+ min_value=1,
+ max_value=MAX_REVIEWS_LIMIT,
+ help_text=f"Rows per page. Defaults to {DEFAULT_REVIEWS_TABLE_LIMIT}, at most {MAX_REVIEWS_LIMIT}.",
+ )
+ offset = serializers.IntegerField(
+ default=0,
+ min_value=0,
+ max_value=MAX_REVIEWS_TABLE_OFFSET,
+ help_text="How many rows to skip, for paging through the table.",
+ )
+
+
+class ReviewReviewsTablePageSerializer(serializers.Serializer):
+ count = serializers.IntegerField(help_text="How many reviews match the scope and every filter, across all pages.")
+ running_count = serializers.IntegerField(
+ help_text="How many reviews have a run in flight under the scope and filters, ignoring `status`. "
+ "Labels the running quick filter without a second request."
+ )
+ results = ReviewRecentReviewSerializer(many=True, help_text="One page of reviews, most recent activity first.")
+
+
_TRIGGER_REFUSAL_STATUS = {
PRReviewRequestStatus.INVALID: status.HTTP_400_BAD_REQUEST,
PRReviewRequestStatus.NOT_ALLOWED: status.HTTP_403_FORBIDDEN,
@@ -692,6 +761,35 @@ class _PageEnvelopeSchema(AutoSchema):
return operation_id
+def _completed_turn_mode(team_id: int) -> Subquery:
+ """The review mode on the completed turn's marker, matching what `turn_markers` puts on the row."""
+ content = Cast("content", models.JSONField())
+ return Subquery(
+ ReviewReportArtefact.objects.for_team(team_id)
+ .filter(report_id=OuterRef("id"), type=ReviewReportArtefact.ArtefactType.TURN_MARKER)
+ .annotate(
+ marker_run_index=Cast(KeyTextTransform("run_index", content), models.IntegerField()),
+ marker_review_mode=KeyTextTransform("review_mode", content),
+ )
+ .filter(marker_run_index=OuterRef("run_count"))
+ .order_by("-created_at", "-id")
+ .values_list("marker_review_mode")[:1]
+ )
+
+
+def _completed_turn_published() -> Func:
+ """Whether `published_head_shas` has the completed turn's run index as a key (the row's `turn_published`)."""
+ return Coalesce(
+ Func(
+ F("published_head_shas"),
+ Cast("run_count", models.CharField()),
+ function="jsonb_exists",
+ output_field=models.BooleanField(),
+ ),
+ Value(False),
+ )
+
+
def _turn_progress(
team_id: int,
reports: list[ReviewReport],
@@ -900,6 +998,38 @@ def _review_payload(
}
+def _review_rows(team_id: int, reports: list[ReviewReport], in_progress_ids: set[str]) -> list[dict[str, Any]]:
+ """List-row payloads for a page of reports, with every per-row read batched across the page."""
+ # Row stats anchor to each report's COMPLETED turn (matching the findings' run_count); the
+ # in-flight progress payload alone reads the live head. Pre-column rows fall back to the live
+ # watermark, which is also correct for never-finalized first turns.
+ snapshots = snapshot_stats(team_id, {str(r.id): r.completed_head_sha or r.head_sha for r in reports})
+ turns = turn_stats(team_id, {str(r.id): r.completed_head_sha or r.head_sha for r in reports})
+ report_ids = [str(report.id) for report in reports]
+ bundle = load_findings_bundle(team_id=team_id, report_ids=report_ids)
+ resolution_map = resolution_states(team_id, reports)
+ progress_map = _turn_progress(team_id, reports, in_progress_ids, resolution_map, bundle)
+ markers = turn_markers(team_id, report_ids)
+ latest_resolutions = latest_resolution_summaries(team_id, reports)
+ items = []
+ for report in reports:
+ report_id = str(report.id)
+ items.append(
+ _review_payload(
+ report,
+ report.run_count,
+ snapshots.get(report_id, SnapshotStats()),
+ turns.get(report_id, TurnStats()),
+ bundle.turn(report_id, report.run_count),
+ markers.get((report_id, report.run_count)),
+ progress_map.get(report_id),
+ resolution_map.get(report_id),
+ latest_resolutions.get(report_id),
+ )
+ )
+ return items
+
+
class EffectiveTeamScopedKeyPermission(BasePermission):
"""Reviews live on the root project, and the API scope check covers only the URL project.
@@ -1008,37 +1138,59 @@ class ReviewRecentReviewsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet
seen.add(str(report.id))
reports.append(report)
has_more = len(reports) > limit
- reports = reports[:limit]
-
- # Row stats anchor to each report's COMPLETED turn (matching the findings' run_count); the
- # in-flight progress payload alone reads the live head. Pre-column rows fall back to the live
- # watermark, which is also correct for never-finalized first turns.
- snapshots = snapshot_stats(team_id, {str(r.id): r.completed_head_sha or r.head_sha for r in reports})
- turns = turn_stats(team_id, {str(r.id): r.completed_head_sha or r.head_sha for r in reports})
- report_ids = [str(report.id) for report in reports]
- bundle = load_findings_bundle(team_id=team_id, report_ids=report_ids)
- resolution_map = resolution_states(team_id, reports)
- progress_map = _turn_progress(team_id, reports, in_progress_ids, resolution_map, bundle)
- markers = turn_markers(team_id, report_ids)
- latest_resolutions = latest_resolution_summaries(team_id, reports)
- items = []
- for report in reports:
- report_id = str(report.id)
- items.append(
- _review_payload(
- report,
- report.run_count,
- snapshots.get(report_id, SnapshotStats()),
- turns.get(report_id, TurnStats()),
- bundle.turn(report_id, report.run_count),
- markers.get((report_id, report.run_count)),
- progress_map.get(report_id),
- resolution_map.get(report_id),
- latest_resolutions.get(report_id),
- )
- )
+ items = _review_rows(team_id, reports[:limit], in_progress_ids)
return Response(ReviewRecentReviewsPageSerializer({"results": items, "has_more": has_more}).data)
+ @extend_schema(
+ parameters=[ReviewsTableParamsSerializer],
+ responses={
+ 200: OpenApiResponse(
+ response=ReviewReviewsTablePageSerializer,
+ description="One page of reviews, most recent activity first, with the total and running counts.",
+ ),
+ },
+ summary="List reviews as a paginated table",
+ description="ReviewHog reviews on this project as a paginated table: reviews with a completed turn "
+ "plus reviews with a run in flight, ordered by last activity, so a review that starts or finishes "
+ "moves to the top. Pages with `limit` and `offset`; `count` is the total across pages. Filters by "
+ "`repository`, `review_mode`, `status`, and `published`. `running_count` counts the running reviews "
+ "under every filter except `status`. By default only the requesting user's reviews; "
+ "`scope=everyone` lists every review on the project.",
+ )
+ @action(methods=["GET"], detail=False, required_scopes=["review_hog:read"])
+ def table(self, request: Request, **kwargs) -> Response:
+ params = ReviewsTableParamsSerializer(data=request.query_params)
+ params.is_valid(raise_exception=True)
+ filters = params.validated_data
+ team_id, queryset = self._reports(request, scope=filters["scope"])
+ running = running_q(team_id)
+ # A first turn that died before completing has nothing to show, so it only appears while it runs.
+ queryset = queryset.filter(Q(last_run_at__isnull=False) | running)
+ if "repository" in filters:
+ queryset = queryset.filter(repository__iexact=filters["repository"])
+ if "review_mode" in filters:
+ queryset = queryset.annotate(completed_turn_mode=_completed_turn_mode(team_id)).filter(
+ completed_turn_mode=filters["review_mode"]
+ )
+ if filters["published"] is not None:
+ queryset = queryset.annotate(completed_turn_published=_completed_turn_published()).filter(
+ completed_turn_published=filters["published"]
+ )
+ running_count = queryset.filter(running).count()
+ if filters.get("status") == ReviewTableStatus.RUNNING:
+ queryset = queryset.filter(running)
+ elif filters.get("status") == ReviewTableStatus.COMPLETED:
+ queryset = queryset.filter(last_run_at__isnull=False).exclude(running)
+
+ offset: int = filters["offset"]
+ reports = list(queryset.order_by("-updated_at", "-id")[offset : offset + filters["limit"]])
+ items = _review_rows(team_id, reports, in_progress_report_ids(team_id, reports))
+ return Response(
+ ReviewReviewsTablePageSerializer(
+ {"count": queryset.count(), "running_count": running_count, "results": items}
+ ).data
+ )
+
@extend_schema(
parameters=[PerspectiveStatsParamsSerializer],
responses={
diff --git a/products/review_hog/backend/reviewer/persistence.py b/products/review_hog/backend/reviewer/persistence.py
index 9c66d37f2325..6fdc3d18f216 100644
--- a/products/review_hog/backend/reviewer/persistence.py
+++ b/products/review_hog/backend/reviewer/persistence.py
@@ -985,10 +985,13 @@ def finalize_review_report(
outcome (`publish_persisted_review`), and the workflow's failure activity covers a publish that
dies past retries.
"""
+ now = timezone.now()
updates: dict[str, object] = {
"report_markdown": body_markdown,
"run_count": run_index,
- "last_run_at": timezone.now(),
+ "last_run_at": now,
+ # `QuerySet.update()` skips `auto_now`; the reviews table sorts by `updated_at`.
+ "updated_at": now,
"completed_head_sha": head_sha,
"run_urgency_threshold": urgency_threshold,
}
diff --git a/products/review_hog/backend/reviewer/progress.py b/products/review_hog/backend/reviewer/progress.py
index d82c826b870f..da53af7367f4 100644
--- a/products/review_hog/backend/reviewer/progress.py
+++ b/products/review_hog/backend/reviewer/progress.py
@@ -14,7 +14,20 @@ from datetime import datetime, timedelta
from functools import reduce
from typing import Any, Final, Literal
-from django.db.models import Case, CharField, Func, IntegerField, JSONField, Max, Q, QuerySet, Value, When
+from django.db.models import (
+ Case,
+ CharField,
+ Exists,
+ Func,
+ IntegerField,
+ JSONField,
+ Max,
+ OuterRef,
+ Q,
+ QuerySet,
+ Value,
+ When,
+)
from django.db.models.fields.json import KeyTextTransform, KeyTransform
from django.db.models.functions import Cast
from django.utils import timezone
@@ -678,6 +691,17 @@ def in_progress_report_ids(team_id: int, reports: list[ReviewReport]) -> set[str
return fresh
+def running_q(team_id: int) -> Q:
+ """The same liveness as `in_progress_report_ids`, as a queryset filter for the paginated table."""
+ cutoff = timezone.now() - IN_PROGRESS_STALE_AFTER
+ fresh_artefact = Exists(
+ _activity_artefacts(
+ ReviewReportArtefact.objects.for_team(team_id).filter(report_id=OuterRef("id"), created_at__gte=cutoff)
+ )
+ )
+ return Q(status=ReviewReport.Status.ACTIVE) & (Q(updated_at__gte=cutoff) | Q(fresh_artefact))
+
+
def _expected_reads(team_id: int, report: ReviewReport, turn: TurnStats) -> int | None:
"""How many (pass, chunk) reviews this turn should produce.
diff --git a/products/review_hog/backend/tests/test_persistence.py b/products/review_hog/backend/tests/test_persistence.py
index 1dda84c989e0..8442697af84e 100644
--- a/products/review_hog/backend/tests/test_persistence.py
+++ b/products/review_hog/backend/tests/test_persistence.py
@@ -136,6 +136,7 @@ class TestUpsertReviewReport(BaseTest):
assert report.report_markdown == "# report"
assert report.status == ReviewReport.Status.IDLE
assert report.completed_head_sha == "sha-2" # what the finished turn reviewed, for read anchoring
+ assert report.updated_at == report.last_run_at # the reviews table sorts finished turns by updated_at
def test_finalize_defers_idle_for_publishing_runs(self) -> None:
# On publishing runs the publish stage owns the idle write: going idle at finalize hands
diff --git a/products/review_hog/backend/tests/test_repositories_api.py b/products/review_hog/backend/tests/test_repositories_api.py
index 26a0c2c618ae..598d6309a669 100644
--- a/products/review_hog/backend/tests/test_repositories_api.py
+++ b/products/review_hog/backend/tests/test_repositories_api.py
@@ -105,13 +105,13 @@ class TestReviewRepositorySettingsAPI(APIBaseTest):
@parameterized.expand(
[
- ("environment_only", False, (403, 403, 403, 403)),
- ("environment_and_parent", True, (200, 200, 200, 200)),
+ ("environment_only", False, (403, 403, 403, 403, 403)),
+ ("environment_and_parent", True, (200, 200, 200, 200, 200)),
]
)
@patch("products.review_hog.backend.pr_status.probe_workflow", return_value=WorkflowProbe.NOT_RUNNING)
def test_a_project_scoped_key_needs_the_parent_project(
- self, _name: str, include_parent: bool, expected: tuple[int, int, int, int], _probe: MagicMock
+ self, _name: str, include_parent: bool, expected: tuple[int, int, int, int, int], _probe: MagicMock
) -> None:
environment = Team.objects.create(organization=self.organization, parent_team=self.team, name="Staging")
value = generate_random_token_personal()
@@ -131,8 +131,15 @@ class TestReviewRepositorySettingsAPI(APIBaseTest):
pr_status = self.client.get(
self._url("reviews/pr_status/", environment), {"pr_url": "https://github.com/PostHog/posthog/pull/5"}
)
-
- assert (read.status_code, write.status_code, reviews.status_code, pr_status.status_code) == expected
+ table = self.client.get(self._url("reviews/table/", environment))
+
+ assert (
+ read.status_code,
+ write.status_code,
+ reviews.status_code,
+ pr_status.status_code,
+ table.status_code,
+ ) == expected
def test_project_rule_stores_only_what_differs_and_is_logged(self) -> None:
res = self.client.patch(
diff --git a/products/review_hog/backend/tests/test_reviews_api.py b/products/review_hog/backend/tests/test_reviews_api.py
index dda1c4d87b1a..216115fe0b57 100644
--- a/products/review_hog/backend/tests/test_reviews_api.py
+++ b/products/review_hog/backend/tests/test_reviews_api.py
@@ -6,6 +6,8 @@ import time_machine
from posthog.test.base import APIBaseTest
from unittest.mock import patch
+from django.db import connection
+from django.test.utils import CaptureQueriesContext
from django.utils import timezone
from parameterized import parameterized
@@ -1176,3 +1178,108 @@ class TestRecentReviewsAPI(APIBaseTest):
assert self.client.get(f"{self.url}{theirs.id}/").status_code == 200
assert self.client.get(f"{self.url}{foreign.id}/").status_code == 404
assert self.client.get(f"{self.url}not-a-uuid/").status_code == 404
+
+ def test_table_pages_by_last_activity_with_counts(self) -> None:
+ # The table orders by activity, not by completion, so a review that starts moves to the top.
+ # A crashed first turn must stay out, a run kept alive only by fresh artefacts must count as
+ # running, and `count` must cover every page while `offset` walks them.
+ now = timezone.now()
+ with time_machine.travel(now - timedelta(hours=4), tick=False):
+ artefact_alive = self._report(pr_number=3, acting_user=self.user, status=ReviewReport.Status.ACTIVE)
+ with time_machine.travel(now - timedelta(hours=3), tick=False):
+ self._report(pr_number=1, acting_user=self.user)
+ with time_machine.travel(now - timedelta(hours=2), tick=False):
+ self._report(pr_number=2, acting_user=self.user)
+ self._report(pr_number=5, acting_user=self.user, completed=False, run_count=0)
+ with time_machine.travel(now - timedelta(minutes=5), tick=False):
+ self._report(pr_number=4, acting_user=self.user, completed=False, run_count=0)
+ other = User.objects.create_and_join(self.organization, "[email protected]", None)
+ with time_machine.travel(now - timedelta(hours=1), tick=False):
+ self._report(pr_number=6, acting_user=other)
+ with time_machine.travel(now, tick=False):
+ ReviewReportArtefact.add_log(
+ team_id=self.team.id,
+ report_id=str(artefact_alive.id),
+ content=NoteArtefact(note="Chunk 2 reviewed", author="review_hog"),
+ attribution=ArtefactAttribution.system(),
+ )
+
+ mine = self.client.get(f"{self.url}table/").json()
+ second_page = self.client.get(f"{self.url}table/", {"limit": 2, "offset": 1}).json()
+ everyone = self.client.get(f"{self.url}table/", {"scope": "everyone"}).json()
+
+ assert [row["pr_number"] for row in mine["results"]] == [4, 2, 1, 3]
+ assert (mine["count"], mine["running_count"]) == (4, 2)
+ assert [row["pr_number"] for row in second_page["results"]] == [2, 1]
+ assert second_page["count"] == 4
+ assert [row["pr_number"] for row in everyone["results"]] == [4, 6, 2, 1, 3]
+ assert self.client.get(f"{self.url}table/", {"limit": 101}).status_code == 400
+
+ @parameterized.expand(
+ [
+ ("no_filter", {}, {1, 2, 3, 4}, 2),
+ ("repository_ignores_case", {"repository": "posthog/OTHER"}, {3, 4}, 1),
+ ("standard_mode", {"review_mode": "flash"}, {1}, 0),
+ ("deep_mode_ignores_the_in_flight_marker", {"review_mode": "full"}, {2}, 1),
+ ("running", {"status": "running"}, {2, 3}, 2),
+ ("completed", {"status": "completed"}, {1, 4}, 2),
+ ("published_turn", {"published": "true"}, {1}, 0),
+ ("unpublished_turn", {"published": "false"}, {2, 3, 4}, 2),
+ ]
+ )
+ def test_table_filters(
+ self, _name: str, params: dict[str, str], expected: set[int], expected_running_count: int
+ ) -> None:
+ standard = self._report(pr_number=1, acting_user=self.user, published_head_shas={"1": "a"})
+ self._turn_marker(standard, run_index=1, review_mode=REVIEW_MODE_FLASH, head_sha="a")
+ # An older turn was published and a new turn is running: neither may stand in for the completed turn.
+ re_review = self._report(
+ pr_number=2,
+ acting_user=self.user,
+ run_count=2,
+ status=ReviewReport.Status.ACTIVE,
+ published_head_shas={"1": "x"},
+ )
+ self._turn_marker(re_review, run_index=2, review_mode=REVIEW_MODE_FULL, head_sha="y")
+ self._turn_marker(re_review, run_index=3, review_mode=REVIEW_MODE_FLASH, head_sha="z")
+ for pr_number, completed in ((3, False), (4, True)):
+ ReviewReport.objects.for_team(self.team.id).create(
+ team_id=self.team.id,
+ repository="PostHog/other",
+ pr_number=pr_number,
+ head_branch="b",
+ base_branch="main",
+ acting_user=self.user,
+ run_count=1 if completed else 0,
+ last_run_at=timezone.now() if completed else None,
+ status=ReviewReport.Status.IDLE if completed else ReviewReport.Status.ACTIVE,
+ )
+
+ res = self.client.get(f"{self.url}table/", params)
+
+ assert res.status_code == 200, res.json()
+ assert {row["pr_number"] for row in res.json()["results"]} == expected
+ assert res.json()["count"] == len(expected)
+ assert res.json()["running_count"] == expected_running_count
+ assert self.client.get(f"{self.url}table/", {"status": "failed"}).status_code == 400
+
+ def test_table_query_count_does_not_grow_with_the_page(self) -> None:
+ for pr_number in range(1, 6):
+ report = self._report(pr_number=pr_number, acting_user=self.user, head_sha=f"h{pr_number}")
+ self._finding(report, f"1-{pr_number}", priority=IssuePriority.MUST_FIX)
+ self._turn_marker(report, run_index=1, review_mode=REVIEW_MODE_FULL, head_sha=f"h{pr_number}")
+ running = self._report(pr_number=9, acting_user=self.user, completed=False, run_count=0)
+ ReviewReport.objects.for_team(self.team.id).filter(id=running.id).update(
+ updated_at=timezone.now() + timedelta(minutes=1)
+ )
+
+ self.client.get(f"{self.url}table/") # warm the per-request auth and team caches
+ query_counts = []
+ for limit in (2, 6):
+ with CaptureQueriesContext(connection) as queries:
+ res = self.client.get(f"{self.url}table/", {"limit": limit})
+ assert len(res.json()["results"]) == limit
+ assert res.json()["results"][0]["in_progress"] is True
+ query_counts.append(len(queries))
+
+ assert query_counts[0] == query_counts[1], query_counts
diff --git a/products/review_hog/frontend/generated/api.schemas.ts b/products/review_hog/frontend/generated/api.schemas.ts
index 024f9d2798e8..4f55a9dfd1a5 100644
--- a/products/review_hog/frontend/generated/api.schemas.ts
+++ b/products/review_hog/frontend/generated/api.schemas.ts
@@ -1347,6 +1347,15 @@ export interface ReviewPRStatusApi {
request_outcome: ReviewPRStatusRequestOutcomeApi | null
}
+export interface ReviewReviewsTablePageApi {
+ /** How many reviews match the scope and every filter, across all pages. */
+ count: number
+ /** How many reviews have a run in flight under the scope and filters, ignoring `status`. Labels the running quick filter without a second request. */
+ running_count: number
+ /** One page of reviews, most recent activity first. */
+ results: ReviewRecentReviewApi[]
+}
+
/**
* * `review` - Review
* * `review_only` - Review only
@@ -1727,3 +1736,76 @@ export const ReviewHogReviewsPrStatusRetrieveRunMode = {
ResolveOnly: 'resolve_only',
Flash: 'flash',
} as const
+
+export type ReviewHogReviewsTableRetrieveParams = {
+ /**
+ * Rows per page. Defaults to 25, at most 100.
+ * @minimum 1
+ * @maximum 100
+ */
+ limit?: number
+ /**
+ * How many rows to skip, for paging through the table.
+ * @minimum 0
+ * @maximum 1000000
+ */
+ offset?: number
+ /**
+ * Only reviews whose latest completed turn was (true) or was not (false) published to GitHub.
+ * @nullable
+ */
+ published?: boolean | null
+ /**
+ * Only reviews of this repository, as `owner/repo`. Matched case-insensitively.
+ * @minLength 1
+ */
+ repository?: string
+ /**
+ * Only reviews whose latest completed turn ran this mode: 'full' (Deep) or 'flash' (Standard). Turns that did not record their mode match neither value.
+ *
+ * * `full` - Deep
+ * * `flash` - Standard
+ * @minLength 1
+ */
+ review_mode?: ReviewHogReviewsTableRetrieveReviewMode
+ /**
+ * Whose reviews to list: `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.
+ *
+ * * `mine` - Mine
+ * * `everyone` - Everyone
+ * @minLength 1
+ */
+ scope?: ReviewHogReviewsTableRetrieveScope
+ /**
+ * Only reviews in this state: 'running' for reviews with a run in flight (activity within the last 30 minutes), 'completed' for reviews with a completed turn and nothing running now.
+ *
+ * * `running` - Running
+ * * `completed` - Completed
+ * @minLength 1
+ */
+ status?: ReviewHogReviewsTableRetrieveStatus
+}
+
+export type ReviewHogReviewsTableRetrieveReviewMode =
+ (typeof ReviewHogReviewsTableRetrieveReviewMode)[keyof typeof ReviewHogReviewsTableRetrieveReviewMode]
+
+export const ReviewHogReviewsTableRetrieveReviewMode = {
+ Full: 'full',
+ Flash: 'flash',
+} as const
+
+export type ReviewHogReviewsTableRetrieveScope =
+ (typeof ReviewHogReviewsTableRetrieveScope)[keyof typeof ReviewHogReviewsTableRetrieveScope]
+
+export const ReviewHogReviewsTableRetrieveScope = {
+ Mine: 'mine',
+ Everyone: 'everyone',
+} as const
+
+export type ReviewHogReviewsTableRetrieveStatus =
+ (typeof ReviewHogReviewsTableRetrieveStatus)[keyof typeof ReviewHogReviewsTableRetrieveStatus]
+
+export const ReviewHogReviewsTableRetrieveStatus = {
+ Running: 'running',
+ Completed: 'completed',
+} as const
diff --git a/products/review_hog/frontend/generated/api.ts b/products/review_hog/frontend/generated/api.ts
index d22e59b3e067..5c5397459db7 100644
--- a/products/review_hog/frontend/generated/api.ts
+++ b/products/review_hog/frontend/generated/api.ts
@@ -23,6 +23,7 @@ import type {
ReviewHogReviewsPerspectiveStatsRetrieveParams,
ReviewHogReviewsPrStatusRetrieveParams,
ReviewHogReviewsRetrieveParams,
+ ReviewHogReviewsTableRetrieveParams,
ReviewInstallationClaimApi,
ReviewInstallationClaimCreateApi,
ReviewPRStatusApi,
@@ -39,6 +40,7 @@ import type {
ReviewRepositoryWriteApi,
ReviewRepositoryWriteResponseApi,
ReviewResolutionConfigApi,
+ ReviewReviewsTablePageApi,
ReviewTriggerRequestApi,
ReviewTriggerResponseApi,
ReviewUserSettingsApi,
@@ -675,6 +677,40 @@ export const reviewHogReviewsPrStatusRetrieve = async (
})
}
+export const getReviewHogReviewsTableRetrieveUrl = (
+ projectId: string,
+ params?: ReviewHogReviewsTableRetrieveParams
+) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/review_hog/reviews/table/?${stringifiedParams}`
+ : `/api/projects/${projectId}/review_hog/reviews/table/`
+}
+
+/**
+ * ReviewHog reviews on this project as a paginated table: reviews with a completed turn plus reviews with a run in flight, ordered by last activity, so a review that starts or finishes moves to the top. Pages with `limit` and `offset`; `count` is the total across pages. Filters by `repository`, `review_mode`, `status`, and `published`. `running_count` counts the running reviews under every filter except `status`. By default only the requesting user's reviews; `scope=everyone` lists every review on the project.
+ * @summary List reviews as a paginated table
+ */
+export const reviewHogReviewsTableRetrieve = async (
+ projectId: string,
+ params?: ReviewHogReviewsTableRetrieveParams,
+ options?: RequestInit
+): Promise<ReviewReviewsTablePageApi> => {
+ return apiMutator<ReviewReviewsTablePageApi>(getReviewHogReviewsTableRetrieveUrl(projectId, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
export const getReviewHogReviewsTriggerCreateUrl = (projectId: string) => {
return `/api/projects/${projectId}/review_hog/reviews/trigger/`
}
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 27b7e3572f33..413b030f96e7 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -96293,6 +96293,15 @@ export namespace Schemas {
body: string;
}
+ export interface ReviewReviewsTablePage {
+ /** How many reviews match the scope and every filter, across all pages. */
+ count: number;
+ /** How many reviews have a run in flight under the scope and filters, ignoring `status`. Labels the running quick filter without a second request. */
+ running_count: number;
+ /** One page of reviews, most recent activity first. */
+ results: ReviewRecentReview[];
+ }
+
export interface ReviewStateCounts {
needs_review: number;
clean: number;
@@ -126843,6 +126852,79 @@ export namespace Schemas {
Flash: 'flash',
} as const;
+ export type ReviewHogReviewsTableRetrieveParams = {
+ /**
+ * Rows per page. Defaults to 25, at most 100.
+ * @minimum 1
+ * @maximum 100
+ */
+ limit?: number;
+ /**
+ * How many rows to skip, for paging through the table.
+ * @minimum 0
+ * @maximum 1000000
+ */
+ offset?: number;
+ /**
+ * Only reviews whose latest completed turn was (true) or was not (false) published to GitHub.
+ * @nullable
+ */
+ published?: boolean | null;
+ /**
+ * Only reviews of this repository, as `owner/repo`. Matched case-insensitively.
+ * @minLength 1
+ */
+ repository?: string;
+ /**
+ * Only reviews whose latest completed turn ran this mode: 'full' (Deep) or 'flash' (Standard). Turns that did not record their mode match neither value.
+ *
+ * * `full` - Deep
+ * * `flash` - Standard
+ * @minLength 1
+ */
+ review_mode?: ReviewHogReviewsTableRetrieveReviewMode;
+ /**
+ * Whose reviews to list: `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.
+ *
+ * * `mine` - Mine
+ * * `everyone` - Everyone
+ * @minLength 1
+ */
+ scope?: ReviewHogReviewsTableRetrieveScope;
+ /**
+ * Only reviews in this state: 'running' for reviews with a run in flight (activity within the last 30 minutes), 'completed' for reviews with a completed turn and nothing running now.
+ *
+ * * `running` - Running
+ * * `completed` - Completed
+ * @minLength 1
+ */
+ status?: ReviewHogReviewsTableRetrieveStatus;
+ };
+
+ export type ReviewHogReviewsTableRetrieveReviewMode = typeof ReviewHogReviewsTableRetrieveReviewMode[keyof typeof ReviewHogReviewsTableRetrieveReviewMode];
+
+
+ export const ReviewHogReviewsTableRetrieveReviewMode = {
+ Full: 'full',
+ Flash: 'flash',
+ } as const;
+
+ export type ReviewHogReviewsTableRetrieveScope = typeof ReviewHogReviewsTableRetrieveScope[keyof typeof ReviewHogReviewsTableRetrieveScope];
+
+
+ export const ReviewHogReviewsTableRetrieveScope = {
+ Mine: 'mine',
+ Everyone: 'everyone',
+ } as const;
+
+ export type ReviewHogReviewsTableRetrieveStatus = typeof ReviewHogReviewsTableRetrieveStatus[keyof typeof ReviewHogReviewsTableRetrieveStatus];
+
+
+ export const ReviewHogReviewsTableRetrieveStatus = {
+ Running: 'running',
+ Completed: 'completed',
+ } as const;
+
export type SandboxCustomImagesListParams = {
/**
* Number of results to return per page.