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): cap the findings standard reviews post per pull request (#116921)

Julian Bez4bd9143443e2
diff --git a/products/review_hog/ARCHITECTURE.md b/products/review_hog/ARCHITECTURE.md
index a4f301d84cf2..2a1c32f7fab3 100644
--- a/products/review_hog/ARCHITECTURE.md
+++ b/products/review_hog/ARCHITECTURE.md
@@ -346,13 +346,27 @@ Standard turn posts a short review with it next to the 👍. That review has its
marker, so a pull request gets it once and re-reviews do not repeat it. It does not set the published watermark, so a
later turn on the head still publishes its findings.
+The finding budget (`reviewer/finding_budget.py`) caps what automatic Standard reviews post on one pull request in
+total. It counts every valid finding that published turns let through their urgency threshold, from every mode and
+trigger. Once the pull request has `FINDING_BUDGET` (20) posted findings, `compose_flash_findings` keeps only the
+must-fix findings of an automatic turn: they count toward the budget but always post. Automatic reviews run on every
+pull request as a safeguard, so past the budget they only raise what must be fixed. A review someone asks for (a
+comment, the label, the UI) is not limited, and `SandboxStageInput.trigger_source` tells the dedup stage which kind ran.
+A finding that fits under the turn's cap but not under the budget drops as `budget`. A review that still posts ends
+with one line that says how many it left out and, where comment commands run, offers `@posthog review --deep`: the head
+already has its Standard review, so only a Deep review runs on it again. A turn that keeps nothing stays silent. Fixing or resolving a finding gives no budget back, because a coding agent that fixes and resolves
+everything would otherwise refill it. Pull requests split into two arms by a hash of the repository and number
+(`budget_arm`). Only the `budget` arm applies the budget, and `finding_budget_arm` on `reviewhog_review_completed` and
+`reviewhog_finding_outcome` splits the measurement.
+
Every finding the turn drops after scope cleaning persists as a `dropped_finding` artefact (`DroppedFindingArtefact`,
written by `replace_dropped_findings` beside `replace_deduplicated_findings` in the dedup activity): the full finding
with its `reported_priority`, the session's pass and part, the `disposition` (`old_code`, `dedup_prior`, `dedup_comment`,
-`dedup_anchor`, `dedup_sibling`, or `cap`), `duplicate_of` (an issue key, or `comment:<id>`), the
+`dedup_anchor`, `dedup_sibling`, `cap`, or `budget`), `duplicate_of` (an issue key, or `comment:<id>`), the
rank in the composed order for a cut finding, the cap, and the lens part count. A retried turn replaces its rows by
-`run_index`. Only analysis reads them: publishing, the status comment, outcome classification, `load_prior_findings`,
-and the reviews API read `issue_finding` rows, so a dropped finding can neither post nor suppress a later finding.
+`run_index`. Only analysis reads them, and publishing counts the `budget` drops for its note: the status comment, outcome
+classification, `load_prior_findings`, and the reviews API read `issue_finding` rows, so a dropped finding can neither post
+nor suppress a later finding.
A Flash turn of any size runs the single-agent design. The **pipeline design** (`reviewhog-flash-1-1`), the steps
below, runs a Flash turn only when the `reviewhog-flash-pipeline-kill-switch` feature flag is on (organization-keyed,
@@ -501,7 +515,7 @@ pr_metadata.head_branch` is threaded (as explicit kwargs, alongside `team_id` /
A single-agent turn's completed event also carries its finding funnel and session health: `flash_cap`,
`flash_lens_parts`, `flash_reviewable_lines`, per session (`main` or a lens name) `flash_candidates`,
`flash_must_fix` (P0/P1 as the session reported them) and `flash_must_fix_share`, then `flash_after_dedup`,
- `flash_dropped` per disposition, `flash_kept`, `flash_lens_failures`, `flash_lens_timeouts`, and
+ `flash_dropped` per disposition, `flash_kept`, `flash_budget_left` (null outside the finding budget), `flash_lens_failures`, `flash_lens_timeouts`, and
`flash_slowest_session_seconds`. The dedup activity returns the counts on `DedupResult.flash_stats`, and the
workflow measures the sessions in workflow time. Cost stays on `$ai_generation`, per `ai_stage`.
Flash finding outcomes use the mode and model configurations saved in the finding's `validation_context`,
diff --git a/products/review_hog/backend/presentation/views/reviews.py b/products/review_hog/backend/presentation/views/reviews.py
index 1095490f7bc0..9939a9245ab9 100644
--- a/products/review_hog/backend/presentation/views/reviews.py
+++ b/products/review_hog/backend/presentation/views/reviews.py
@@ -629,6 +629,7 @@ class ReviewDropDisposition(models.TextChoices):
DEDUP_ANCHOR = "dedup_anchor", "Same spot as another finding"
DEDUP_SIBLING = "dedup_sibling", "Repeat of a finding"
CAP = "cap", "Over the limit"
+ BUDGET = "budget", "Over the pull request limit"
class ReviewDroppedFindingPriority(models.TextChoices):
diff --git a/products/review_hog/backend/reviewer/finding_budget.py b/products/review_hog/backend/reviewer/finding_budget.py
new file mode 100644
index 000000000000..e9c9809cb4a3
--- /dev/null
+++ b/products/review_hog/backend/reviewer/finding_budget.py
@@ -0,0 +1,97 @@
+"""The finding budget: how many findings automatic Standard reviews post on one pull request in total.
+
+Each Standard turn already keeps only a few findings (`compose_flash_findings`). On a busy pull request
+those add up turn after turn, and the late ones are rarely acted on. The budget counts every finding
+ever posted on the pull request, by any review mode and trigger. Once the count reaches `FINDING_BUDGET`,
+an automatic turn posts only its must-fix findings, and the others drop with the `budget` disposition.
+Automatic reviews run on every pull request as a safeguard, so past the budget they only raise what must
+be fixed. A review someone asks for (a comment, the label, the UI) is not limited.
+
+The count never goes down. Fixing or resolving a finding gives no budget back, because a coding agent
+that fixes and resolves everything would otherwise refill it forever. A dropped finding is not queued
+for a later turn, and the next turn that finds it again drops it again.
+
+Pull requests split into two arms by a hash of the repository and number, so the effect can be measured
+against pull requests that keep posting. The cap comes from a replay of 30 days of closed pull requests
+in `review-eval/experiments/2026-10-14-review-throttle`.
+"""
+
+import hashlib
+from collections.abc import Sequence
+from typing import Literal
+
+from posthog.dataclasses import frozen
+from posthog.utils import pluralize
+
+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 effective_priority, published_priorities_for
+from products.review_hog.backend.reviewer.models.issues_review import IssuePriority
+
+FINDING_BUDGET = 20
+
+BudgetArm = Literal["budget", "control"]
+
+
+def budget_arm(repository: str, pr_number: int | None) -> BudgetArm:
+ """The arm of a pull request, stable for its whole life. A run without a pull request posts nothing."""
+ if pr_number is None:
+ return "control"
+ digest = hashlib.sha256(f"{repository.lower()}#{pr_number}".encode()).digest()
+ return "budget" if digest[0] % 2 == 0 else "control"
+
+
+def budget_note(dropped: int, comment_commands_on: bool) -> str:
+ """The line a review ends with when the budget kept some of its findings off the pull request.
+
+ It offers a Deep review, because this head already has its Standard review and a second one would not run.
+ """
+ note = (
+ f"This pull request reached its limit of {FINDING_BUDGET} automatic review findings, so this review left "
+ f"out {pluralize(dropped, 'lower-priority finding')}. Must-fix findings still post."
+ )
+ if comment_commands_on:
+ note = f"{note} Comment `@posthog review --deep` for a review without the limit."
+ return note
+
+
+@frozen
+class FindingBudget:
+ arm: BudgetArm
+ # Findings the pull request showed before this turn.
+ posted_before: int
+
+ @classmethod
+ def for_turn(
+ cls, report: ReviewReport, prior_findings: Sequence[tuple[ReviewIssueFinding, ValidationVerdict | None]]
+ ) -> "FindingBudget":
+ """`prior_findings` are the findings of the turns before this one, with their verdicts."""
+ return cls(
+ arm=budget_arm(report.repository, report.pr_number), posted_before=_posted_count(report, prior_findings)
+ )
+
+ @property
+ def left(self) -> int | None:
+ """How many more findings the pull request may post, None for a pull request outside the budget."""
+ if self.arm == "control":
+ return None
+ return max(FINDING_BUDGET - self.posted_before, 0)
+
+
+def _posted_count(report: ReviewReport, findings: Sequence[tuple[ReviewIssueFinding, ValidationVerdict | None]]) -> int:
+ """The valid findings that published turns let through their urgency threshold.
+
+ Only turns with a stored threshold count. Turns published before the threshold was stored are older
+ than the budget and stay out of it.
+ """
+ thresholds = report.published_urgency_thresholds or {}
+ count = 0
+ for finding, verdict in findings:
+ threshold = thresholds.get(str(finding.run_index))
+ if verdict is None or not verdict.is_valid or threshold is None:
+ continue
+ if effective_priority(finding.priority, verdict.adjusted_priority) in published_priorities_for(
+ IssuePriority(threshold)
+ ):
+ count += 1
+ return count
diff --git a/products/review_hog/backend/reviewer/models/issues_review.py b/products/review_hog/backend/reviewer/models/issues_review.py
index 5f2790999b12..35442e721a5b 100644
--- a/products/review_hog/backend/reviewer/models/issues_review.py
+++ b/products/review_hog/backend/reviewer/models/issues_review.py
@@ -79,7 +79,8 @@ class Issue(BaseModel):
# Why a single-agent turn drops a finding. A `dedup_*` drop repeats an earlier turn's finding, a main
# finding (anchor), or a finding of its own session or lens (sibling). Only records from before Flash
-# stopped reading PR comments carry `dedup_comment`. `cap` is the cut in `compose_flash_findings`.
+# stopped reading PR comments carry `dedup_comment`. `cap` is the cut in `compose_flash_findings`, and
+# `budget` the cut the pull request's finding budget adds on top (`finding_budget.py`).
# `old_code` is a follow-up turn's P3 finding on code that did not change since the last reviewed head.
DropDisposition = Literal[
"old_code",
@@ -88,6 +89,7 @@ DropDisposition = Literal[
"dedup_anchor",
"dedup_sibling",
"cap",
+ "budget",
]
diff --git a/products/review_hog/backend/reviewer/outcomes/classify.py b/products/review_hog/backend/reviewer/outcomes/classify.py
index 69a04a6857c5..3c937c0b2267 100644
--- a/products/review_hog/backend/reviewer/outcomes/classify.py
+++ b/products/review_hog/backend/reviewer/outcomes/classify.py
@@ -58,6 +58,7 @@ from products.review_hog.backend.reviewer.constants import (
priority_rank,
published_priorities_for,
)
+from products.review_hog.backend.reviewer.finding_budget import budget_arm
from products.review_hog.backend.reviewer.models.issues_review import IssuePriority
from products.review_hog.backend.reviewer.outcomes.comment_signal import engagement_method, find_finding_comment
from products.review_hog.backend.reviewer.outcomes.discovery import unclassified_published_reports
@@ -435,6 +436,7 @@ async def _emit_and_mark(
"is_directly_related_to_changes": oc.finding.is_directly_related_to_changes,
"outcome": oc.outcome,
"classification_method": oc.method,
+ "finding_budget_arm": budget_arm(repository, report.pr_number),
"reviewed_head": oc.reviewed_head,
"final_head": oc.final_head,
**finding_routing_properties(report, oc.finding),
diff --git a/products/review_hog/backend/reviewer/tests/test_finding_budget.py b/products/review_hog/backend/reviewer/tests/test_finding_budget.py
new file mode 100644
index 000000000000..32094c3f6999
--- /dev/null
+++ b/products/review_hog/backend/reviewer/tests/test_finding_budget.py
@@ -0,0 +1,64 @@
+import pytest
+
+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.finding_budget import FINDING_BUDGET, FindingBudget, budget_arm, budget_note
+from products.review_hog.backend.reviewer.models.issues_review import IssuePriority
+
+
+def _pair(
+ run_index: int, priority: IssuePriority, *, valid: bool = True
+) -> tuple[ReviewIssueFinding, ValidationVerdict | None]:
+ key = f"r{run_index}:a.py:1:flash-single-agent:{priority.value}-{valid}"
+ finding = ReviewIssueFinding(
+ issue_key=key, run_index=run_index, title="t", file="a.py", body="b", suggestion="", priority=priority
+ )
+ return finding, ValidationVerdict(issue_key=key, is_valid=valid, argumentation="a")
+
+
+def _report(pr_number: int | None, thresholds: dict[str, str]) -> ReviewReport:
+ return ReviewReport(repository="PostHog/posthog", pr_number=pr_number, published_urgency_thresholds=thresholds)
+
+
+ "repository,pr_number,expected",
+ [
+ ("PostHog/posthog", 114369, "budget"),
+ ("posthog/POSTHOG", 114369, "budget"),
+ ("PostHog/posthog", 116849, "control"),
+ ("PostHog/posthog", None, "control"),
+ ],
+)
+def test_budget_arm_is_stable_for_a_pull_request(repository: str, pr_number: int | None, expected: str) -> None:
+ assert budget_arm(repository, pr_number) == expected
+
+
+def test_budget_counts_only_findings_that_published_turns_posted() -> None:
+ prior = [
+ _pair(1, IssuePriority.SHOULD_FIX),
+ _pair(1, IssuePriority.CONSIDER),
+ _pair(1, IssuePriority.MUST_FIX, valid=False),
+ _pair(2, IssuePriority.CONSIDER),
+ _pair(2, IssuePriority.MUST_FIX),
+ _pair(3, IssuePriority.SHOULD_FIX),
+ ]
+ # Turn 2 gated at must_fix, so its consider finding stayed off the PR; turn 3 never published.
+ budget = FindingBudget.for_turn(_report(114369, {"1": "consider", "2": "must_fix"}), prior)
+
+ assert (budget.posted_before, budget.left) == (3, FINDING_BUDGET - 3)
+
+
+def test_control_arm_has_no_budget() -> None:
+ budget = FindingBudget.for_turn(_report(116849, {"1": "consider"}), [_pair(1, IssuePriority.SHOULD_FIX)])
+
+ assert (budget.arm, budget.left) == ("control", None)
+
+
[email protected]("comment_commands_on,offers_deep", [(True, True), (False, False)])
+def test_budget_note_offers_only_a_review_that_runs_on_this_head(comment_commands_on: bool, offers_deep: bool) -> None:
+ # The head already has its Standard review, so a second Standard request would be refused.
+ note = budget_note(3, comment_commands_on)
+
+ assert note.startswith("This pull request reached its limit of 20 automatic review findings")
+ assert ("`@posthog review --deep`" in note) is offers_deep
+ assert "`@posthog review` " not in note
diff --git a/products/review_hog/backend/reviewer/tests/test_publish_review.py b/products/review_hog/backend/reviewer/tests/test_publish_review.py
index e45a0a6cfd39..83c43bf38e62 100644
--- a/products/review_hog/backend/reviewer/tests/test_publish_review.py
+++ b/products/review_hog/backend/reviewer/tests/test_publish_review.py
@@ -524,6 +524,50 @@ class TestPublishReviewGate:
# The skip check matches a note from any earlier head, so re-reviews do not repeat it.
assert mock_post.call_args.kwargs["marker"] == "<!-- reviewhog:large-pr-note:rep:"
+ @parameterized.expand(
+ [
+ ("keeps_nothing_stays_silent", IssuePriority.CONSIDER, False),
+ ("posts_findings_with_the_note", IssuePriority.SHOULD_FIX, True),
+ ]
+ )
+ @patch(_POST)
+ @patch(_LOAD_FINDINGS)
+ @patch(_REPORT)
+ def test_standard_turn_notes_the_finding_budget_only_when_it_posts(
+ self,
+ _name: str,
+ priority: IssuePriority,
+ expected_posted: bool,
+ mock_report_cls: MagicMock,
+ mock_load: MagicMock,
+ mock_post: MagicMock,
+ ) -> None:
+ # Past the budget an automatic turn only looks for must-fix findings, so a turn that keeps nothing
+ # must not post a review just to say so.
+ self._wire_report(mock_report_cls, "old")
+ mock_load.return_value = [(_finding(priority=priority), _verdict())]
+
+ outcome = publish_review(
+ owner="o",
+ repo="r",
+ pr_number=1,
+ team_id=1,
+ report_id="rep",
+ run_index=1,
+ pr_files=[],
+ token="t",
+ head_sha="sha",
+ published_priorities=_SHOULD_FIX_PUBLISHED,
+ review_mode="flash",
+ budget_note="Budget note.",
+ )
+
+ assert outcome.posted is expected_posted
+ if expected_posted:
+ assert "Budget note." in mock_post.call_args.args[3]
+ else:
+ mock_post.assert_not_called()
+
@parameterized.expand(
[
# The validator wins: an upgraded consider crosses the publish bar; a downgraded should_fix
diff --git a/products/review_hog/backend/reviewer/tests/test_single_agent_review.py b/products/review_hog/backend/reviewer/tests/test_single_agent_review.py
index 980a9f013a29..38c5f3327df3 100644
--- a/products/review_hog/backend/reviewer/tests/test_single_agent_review.py
+++ b/products/review_hog/backend/reviewer/tests/test_single_agent_review.py
@@ -265,6 +265,39 @@ class TestComposeFlashFindings:
]
assert (selection.cap, selection.lens_part_count) == (4, 1)
+ @pytest.mark.parametrize(
+ "budget_left,expected_kept,expected_dropped",
+ [
+ pytest.param(
+ 3,
+ ["m1", "m2", "m3"],
+ [("m4", "budget", 4), ("m5", "cap", 5)],
+ id="must_fix_counts_toward_the_budget",
+ ),
+ pytest.param(
+ 0,
+ ["m1"],
+ [("m2", "budget", 2), ("m3", "budget", 3), ("m4", "budget", 4), ("m5", "cap", 5)],
+ id="must_fix_posts_when_the_budget_is_spent",
+ ),
+ pytest.param(
+ None,
+ ["m1", "m2", "m3", "m4"],
+ [("m5", "cap", 5)],
+ id="no_budget_keeps_the_cap",
+ ),
+ ],
+ )
+ def test_the_finding_budget_cuts_below_the_cap(
+ self, budget_left: int | None, expected_kept: list[str], expected_dropped: list[tuple[str, str, int]]
+ ) -> None:
+ main = [_issue("m1", IssuePriority.MUST_FIX)] + [_issue(f"m{n}", IssuePriority.SHOULD_FIX) for n in range(2, 6)]
+
+ selection = compose_flash_findings(main, [], lens_part_count=1, budget_left=budget_left)
+
+ assert [issue.id for issue in selection.kept] == expected_kept
+ assert [(drop.issue.id, drop.disposition, drop.rank) for drop in selection.dropped] == expected_dropped
+
def _flash_dedup(*duplicates: tuple[str, str]) -> AsyncMock:
return AsyncMock(
diff --git a/products/review_hog/backend/reviewer/tools/publish_review.py b/products/review_hog/backend/reviewer/tools/publish_review.py
index 96e937c963a8..994aab2d1504 100644
--- a/products/review_hog/backend/reviewer/tools/publish_review.py
+++ b/products/review_hog/backend/reviewer/tools/publish_review.py
@@ -21,9 +21,14 @@ from products.review_hog.backend.reviewer.constants import (
published_priorities_for,
)
from products.review_hog.backend.reviewer.diff_position import build_diff_line_map, find_diff_position
+from products.review_hog.backend.reviewer.finding_budget import budget_note
from products.review_hog.backend.reviewer.models.github_meta import PRFile
from products.review_hog.backend.reviewer.models.issues_review import IssuePriority
-from products.review_hog.backend.reviewer.persistence import load_pr_snapshot, load_valid_findings
+from products.review_hog.backend.reviewer.persistence import (
+ load_dropped_findings,
+ load_pr_snapshot,
+ load_valid_findings,
+)
from products.review_hog.backend.reviewer.review_state import published_heads_by_mode, review_already_published
from products.review_hog.backend.reviewer.status_comment import large_pr_note, render_review_summary
from products.review_hog.backend.reviewer.tools.github_client import (
@@ -92,6 +97,7 @@ def publish_persisted_review(
capped_lens_parts: int | None = None,
footer: str = "",
draft_notice: str = "",
+ comment_commands_on: bool = False,
) -> PublishOutcome:
"""Publish an already-computed review for `report_id` at `head_sha`, idempotently.
@@ -107,6 +113,7 @@ def publish_persisted_review(
event loop.
`draft_notice` closes a review with findings when the turn's snapshot shows the PR as a draft.
+ `comment_commands_on` picks the trigger the finding budget note points to.
"""
report = ReviewReport.objects.for_team(team_id).get(id=report_id)
if review_already_published(report, head_sha, review_mode):
@@ -115,6 +122,13 @@ def publish_persisted_review(
return PublishOutcome(posted=False)
snapshot = load_pr_snapshot(team_id=team_id, report_id=report_id, head_sha=head_sha)
pr_files = snapshot.pr_files if snapshot is not None else []
+ over_budget = sum(
+ 1
+ for dropped in load_dropped_findings(
+ team_id=team_id, report_id=report_id, run_index=run_index, head_sha=head_sha
+ )
+ if dropped.disposition == "budget"
+ )
outcome = publish_review(
owner=owner,
repo=repo,
@@ -131,6 +145,7 @@ def publish_persisted_review(
capped_lens_parts=capped_lens_parts,
footer=footer,
findings_footer=draft_notice if snapshot is not None and snapshot.pr_metadata.draft else "",
+ budget_note=budget_note(over_budget, comment_commands_on) if over_budget else "",
)
if outcome.posted:
if report.outcomes_emitted_at is not None:
@@ -224,6 +239,7 @@ def publish_review(
capped_lens_parts: int | None = None,
footer: str = "",
findings_footer: str = "",
+ budget_note: str = "",
) -> PublishOutcome:
"""Publish the review to GitHub: the stored body plus inline comments from the durable rows.
@@ -241,6 +257,9 @@ def publish_review(
review then carries the large pull request note, and a clean Standard turn posts a short review with it.
`findings_footer` follows `footer` only on a review that posts findings, never on the clean-turn note.
+
+ `budget_note` says the finding budget left findings out. A turn that keeps nothing stays silent: once
+ the budget is spent an automatic review only looks for must-fix findings.
"""
logger.info(f"Publishing review for {owner}/{repo}#{pr_number}")
@@ -251,6 +270,7 @@ def publish_review(
# `footer` closes the review whichever body posts, so the inline-only body keeps it too.
footer_block = f"{footer}\n\n" if footer else ""
note_block = f"{large_pr_note(large_pr_parts)}\n\n" if large_pr_parts is not None else ""
+ budget_block = f"{budget_note}\n\n" if budget_note else ""
valid_findings = load_valid_findings(team_id=team_id, report_id=report_id, run_index=run_index)
diff_lines = build_diff_line_map(pr_files)
@@ -291,6 +311,7 @@ def publish_review(
remove_own_pr_reactions(repository, pr_number, "+1", token=token, installation_id=installation_id)
if findings_footer:
footer_block = f"{footer_block}{findings_footer}\n\n"
+ footer_block = f"{budget_block}{footer_block}"
body = f"{report.report_markdown}\n\n{note_block}{footer_block}{marker}"
# When every publishable finding has its own inline comment, the body's tally repeats what the
diff --git a/products/review_hog/backend/reviewer/tools/single_agent_review.py b/products/review_hog/backend/reviewer/tools/single_agent_review.py
index 0735d26ab3d0..a2021b10ff8e 100644
--- a/products/review_hog/backend/reviewer/tools/single_agent_review.py
+++ b/products/review_hog/backend/reviewer/tools/single_agent_review.py
@@ -246,6 +246,8 @@ class FlashSelection:
lens_part_count: int
# A dedup call failed and fell back to the positional pre-filter alone.
dedup_fell_back: bool = False
+ # How many more findings the pull request could post before this turn, None outside the finding budget.
+ budget_left: int | None = None
def _reported_level(issue: Issue) -> int:
@@ -274,7 +276,12 @@ def _flash_order(main: list[Issue], lens: list[Issue], group_levels: Mapping[str
def compose_flash_findings(
- main: list[Issue], lens: list[Issue], *, lens_part_count: int, group_levels: Mapping[str, int] | None = None
+ main: list[Issue],
+ lens: list[Issue],
+ *,
+ lens_part_count: int,
+ group_levels: Mapping[str, int] | None = None,
+ budget_left: int | None = None,
) -> FlashSelection:
"""The findings a Flash turn keeps, highest priority first, P0 before P1, and the main review first on ties.
@@ -282,6 +289,10 @@ def compose_flash_findings(
`FLASH_MUST_FIX_CAP_MULTIPLIER` times the cap. P2 and then P3 findings fill the slots the must-fix
findings leave under the cap. The rest drop with their rank.
+ `budget_left` is how many more findings the pull request may post (`finding_budget.py`), None when no
+ budget applies. Must-fix findings count toward it but always post. A finding that fits under the cap
+ but not under the budget drops as `budget`, the rest as `cap`.
+
The caller persists only the kept findings. A persisted finding that never posts counts as already
raised, so every later turn would keep it off the PR too.
"""
@@ -290,16 +301,20 @@ def compose_flash_findings(
must_fix = [issue for issue in ranked if issue.priority == IssuePriority.MUST_FIX]
must_fix = must_fix[: FLASH_MUST_FIX_CAP_MULTIPLIER * cap]
others = [issue for issue in ranked if issue.priority != IssuePriority.MUST_FIX]
- kept_ids = {issue.id for issue in [*must_fix, *others[: max(cap - len(must_fix), 0)]]}
+ under_cap = others[: max(cap - len(must_fix), 0)]
+ kept = under_cap if budget_left is None else under_cap[: max(budget_left - len(must_fix), 0)]
+ kept_ids = {issue.id for issue in [*must_fix, *kept]}
+ over_budget_ids = {issue.id for issue in under_cap} - kept_ids
return FlashSelection(
kept=[issue for issue in ranked if issue.id in kept_ids],
dropped=[
- DroppedIssue(issue=issue, disposition="cap", rank=rank)
+ DroppedIssue(issue=issue, disposition="budget" if issue.id in over_budget_ids else "cap", rank=rank)
for rank, issue in enumerate(ranked, start=1)
if issue.id not in kept_ids
],
cap=cap,
lens_part_count=lens_part_count,
+ budget_left=budget_left,
)
@@ -326,6 +341,7 @@ class FlashTurnStats:
kept: int
# A dedup call failed and fell back to the positional pre-filter alone.
dedup_fell_back: bool
+ budget_left: int | None = None
def flash_turn_stats(candidates: list[Issue], selection: FlashSelection, *, reviewable_lines: int) -> FlashTurnStats:
@@ -341,7 +357,7 @@ def flash_turn_stats(candidates: list[Issue], selection: FlashSelection, *, revi
per_session[session] = per_session.get(session, 0) + 1
if issue.reported_priority in ("P0", "P1"):
must_fix[session] = must_fix.get(session, 0) + 1
- cut = sum(1 for drop in selection.dropped if drop.disposition == "cap")
+ cut = sum(1 for drop in selection.dropped if drop.disposition in ("cap", "budget"))
return FlashTurnStats(
cap=selection.cap,
lens_part_count=selection.lens_part_count,
@@ -352,6 +368,7 @@ def flash_turn_stats(candidates: list[Issue], selection: FlashSelection, *, revi
dropped=dict(Counter(drop.disposition for drop in selection.dropped)),
kept=len(selection.kept),
dedup_fell_back=selection.dedup_fell_back,
+ budget_left=selection.budget_left,
)
@@ -609,6 +626,7 @@ async def dedupe_flash_findings(
workflow_id_prefix: str | None = None,
fall_back_on_any_error: bool = False,
changed_since: ChangedSinceReview | None = None,
+ budget_left: int | None = None,
) -> FlashSelection:
"""Deduplicate a single-agent turn's main and lens findings, then keep the few it posts.
@@ -661,7 +679,9 @@ async def dedupe_flash_findings(
kept_main = [issue for issue in main if issue.id not in removed_ids]
kept_lens = [issue for issue in lens if issue.id not in removed_ids]
group_levels = _raise_survivors([*kept_main, *kept_lens], [removal.duplicate for removal in held])
- composed = compose_flash_findings(kept_main, kept_lens, lens_part_count=lens_part_count, group_levels=group_levels)
+ composed = compose_flash_findings(
+ kept_main, kept_lens, lens_part_count=lens_part_count, group_levels=group_levels, budget_left=budget_left
+ )
turn_issues = {issue.id: issue for issue in issues}
dedup_drops = [
_dropped_duplicate(removal.duplicate, dedup_fallback=removal.fell_back, turn_issues=turn_issues)
diff --git a/products/review_hog/backend/temporal/activities.py b/products/review_hog/backend/temporal/activities.py
index 60de93d2a484..7749a504348d 100644
--- a/products/review_hog/backend/temporal/activities.py
+++ b/products/review_hog/backend/temporal/activities.py
@@ -45,6 +45,7 @@ from products.review_hog.backend.pr_owner import PullRequestOwnerResolver
from products.review_hog.backend.preferences import ReviewPreferences
from products.review_hog.backend.pull_request_events import REVIEW_LABELS, has_skip_agent_review_label
from products.review_hog.backend.review_request_rules import ResolutionGate, full_review_published
+from products.review_hog.backend.reviewer.artefact_content import ReviewIssueFinding, ValidationVerdict
from products.review_hog.backend.reviewer.constants import (
ALREADY_RAISED_SHOWN,
CHUNKING_MODEL,
@@ -69,6 +70,7 @@ from products.review_hog.backend.reviewer.constants import (
validation_arm_for_mode,
)
from products.review_hog.backend.reviewer.feature_flags import flash_pipeline_kill_switch_on, standard_coordinator_on
+from products.review_hog.backend.reviewer.finding_budget import FindingBudget, budget_arm
from products.review_hog.backend.reviewer.fingerprint import ReviewHogMarker, record_turn_marker
from products.review_hog.backend.reviewer.lazy_seed import (
sync_canonical_authoring,
@@ -403,6 +405,8 @@ class SandboxStageInput:
review_mode: str = field(default=REVIEW_MODE_FULL, kw_only=True)
flash_reasoning_effort: str = field(default=ReasoningEffort.MEDIUM.value, kw_only=True)
review_design: str = field(default=REVIEW_DESIGN_PIPELINE, kw_only=True)
+ # Only an automatic turn is held to the finding budget. None on payloads from before the field.
+ trigger_source: str | None = field(default=None, kw_only=True)
@dataclass
@@ -1675,6 +1679,13 @@ def _combine_and_clean(
return clean_issues(raw_issues, pr_files)
+def _finding_budget(
+ team_id: int, report_id: str, prior_findings: list[tuple[ReviewIssueFinding, ValidationVerdict | None]]
+) -> FindingBudget:
+ report = ReviewReport.objects.for_team(team_id).get(id=report_id)
+ return FindingBudget.for_turn(report, prior_findings)
+
+
def _changed_since_last_review(
team_id: int, report_id: str, head_sha: str, current_files: list[PRFile]
) -> ChangedSinceReview | None:
@@ -1768,6 +1779,12 @@ async def dedup_activity(input: SandboxStageInput) -> DedupResult:
changed_since = await database_sync_to_async(_changed_since_last_review, thread_sensitive=False)(
input.team_id, input.report_id, input.head_sha, snapshot.pr_files
)
+ budget_left = None
+ if input.trigger_source == TRIGGER_AUTOMATIC:
+ budget = await database_sync_to_async(_finding_budget, thread_sensitive=False)(
+ input.team_id, input.report_id, prior_findings
+ )
+ budget_left = budget.left
flash_selection = await dedupe_flash_findings(
team_id=input.team_id,
user_id=input.user_id,
@@ -1780,6 +1797,7 @@ async def dedup_activity(input: SandboxStageInput) -> DedupResult:
workflow_id_prefix=_sandbox_workflow_id_prefix("dedup"),
fall_back_on_any_error=_is_final_attempt(),
changed_since=changed_since,
+ budget_left=budget_left,
)
survivors = flash_selection.kept
flash_stats = flash_turn_stats(issues, flash_selection, reviewable_lines=lens_plan.reviewable_lines)
@@ -2042,10 +2060,12 @@ def _publish(input: PublishInput) -> PublishResult:
if input.trigger_source == TRIGGER_LABEL and comment_commands_enabled(input.team_id):
footer = label_commands_hint(input.review_mode)
# Only an automatic turn can promise the review on ready: a label or UI review runs for authors
- # without automatic reviews too.
+ # without automatic reviews too. Only an automatic turn is held to the finding budget, too.
draft_notice = ""
+ comment_commands_on = False
if input.trigger_source == TRIGGER_AUTOMATIC:
- draft_notice = draft_review_notice(comment_commands_enabled(input.team_id))
+ comment_commands_on = comment_commands_enabled(input.team_id)
+ draft_notice = draft_review_notice(comment_commands_on)
outcome = publish_persisted_review(
team_id=input.team_id,
report_id=input.report_id,
@@ -2061,6 +2081,7 @@ def _publish(input: PublishInput) -> PublishResult:
capped_lens_parts=input.capped_lens_parts,
footer=footer,
draft_notice=draft_notice,
+ comment_commands_on=comment_commands_on,
)
if input.trigger_source == TRIGGER_AUTOMATIC:
ReviewReport.objects.for_team(input.team_id).filter(id=input.report_id).update(
@@ -2186,6 +2207,7 @@ def _flash_event_properties(turn: FlashTurnStats | None, sessions: FlashSessionS
"flash_dropped": turn.dropped,
"flash_kept": turn.kept,
"flash_dedup_fallback": turn.dedup_fell_back,
+ "flash_budget_left": turn.budget_left,
}
)
if sessions is not None:
@@ -2407,6 +2429,8 @@ def _track_review_completed(input: TrackReviewCompletedInput) -> None:
),
**_pr_size_properties(snapshot),
"pr_draft": _pr_draft(snapshot),
+ # Split by this to measure the finding budget against pull requests that keep posting.
+ "finding_budget_arm": budget_arm(report.repository, report.pr_number),
"duration_seconds": duration_seconds,
# No marker means a turn started before the marker shipped, or a failed marker: the version is unknown.
"reviewhog_version": input.marker.version if input.marker is not None else None,
diff --git a/products/review_hog/backend/temporal/workflow.py b/products/review_hog/backend/temporal/workflow.py
index b14e5b99969b..e1aee744d060 100644
--- a/products/review_hog/backend/temporal/workflow.py
+++ b/products/review_hog/backend/temporal/workflow.py
@@ -730,6 +730,7 @@ class ReviewPRWorkflow:
review_mode=inputs.review_mode,
flash_reasoning_effort=acting.flash_reasoning_effort,
review_design=review_design,
+ trigger_source=inputs.trigger_source,
)
# The patch keeps a history from before the coordinator existed on separate sessions when it replays.
diff --git a/products/review_hog/backend/tests/test_publish_idempotency.py b/products/review_hog/backend/tests/test_publish_idempotency.py
index d2a2fde2b4af..43ea3e8a172a 100644
--- a/products/review_hog/backend/tests/test_publish_idempotency.py
+++ b/products/review_hog/backend/tests/test_publish_idempotency.py
@@ -20,7 +20,8 @@ from products.review_hog.backend.models import ReviewReport
from products.review_hog.backend.reviewer.artefact_content import PRSnapshotArtefact
from products.review_hog.backend.reviewer.constants import LEGACY_FLASH_MODE_MESSAGE_PREFIX
from products.review_hog.backend.reviewer.models.github_meta import PRMetadata
-from products.review_hog.backend.reviewer.persistence import upsert_review_report
+from products.review_hog.backend.reviewer.models.issues_review import DroppedIssue, Issue, IssuePriority
+from products.review_hog.backend.reviewer.persistence import replace_dropped_findings, upsert_review_report
from products.review_hog.backend.reviewer.tools.github_client import GitHubAPIError
from products.review_hog.backend.reviewer.tools.publish_review import (
PublishOutcome,
@@ -228,6 +229,36 @@ class TestPublishIdempotency(BaseTest):
# save must restore rest or the row reads as in-progress until the staleness cutoff.
assert report.status == ReviewReport.Status.IDLE
+ @patch(_PUBLISH)
+ @patch(_SNAPSHOT, return_value=None)
+ @patch(_AUTH, return_value=("tok", None))
+ def test_a_review_says_when_the_finding_budget_left_findings_out(self, _auth, _snapshot, mock_publish) -> None:
+ mock_publish.return_value = PublishOutcome(posted=True)
+ report_id = self._report()
+ cut = Issue(
+ id="1-1-2", title="Cut", file="a.py", lines=[], issue="i", suggestion="", priority=IssuePriority.CONSIDER
+ )
+ replace_dropped_findings(
+ team_id=self.team.id,
+ report_id=report_id,
+ run_index=1,
+ head_sha="sha1",
+ dropped=[
+ DroppedIssue(issue=cut, disposition="budget", rank=2),
+ DroppedIssue(issue=cut.model_copy(update={"id": "1-1-3"}), disposition="budget", rank=3),
+ DroppedIssue(issue=cut.model_copy(update={"id": "1-1-4"}), disposition="cap", rank=4),
+ ],
+ cap=4,
+ lens_part_count=1,
+ )
+
+ _publish(_publish_input(self.team.id, report_id, "sha1"))
+
+ assert mock_publish.call_args.kwargs["budget_note"] == (
+ "This pull request reached its limit of 20 automatic review findings, so this review left out "
+ "2 lower-priority findings. Must-fix findings still post."
+ )
+
@patch(_PUBLISH)
@patch(_SNAPSHOT, return_value=None)
@patch(_AUTH, return_value=("tok", None))
diff --git a/products/review_hog/backend/tests/test_review_activity.py b/products/review_hog/backend/tests/test_review_activity.py
index 7aa077dcb823..770f3371d225 100644
--- a/products/review_hog/backend/tests/test_review_activity.py
+++ b/products/review_hog/backend/tests/test_review_activity.py
@@ -27,6 +27,7 @@ from products.review_hog.backend.reviewer.constants import (
ReviewArm,
review_arm_for_mode,
)
+from products.review_hog.backend.reviewer.finding_budget import FINDING_BUDGET, FindingBudget
from products.review_hog.backend.reviewer.models.github_meta import PRComment, PRFile, PRMetadata
from products.review_hog.backend.reviewer.models.issues_review import Issue, IssuePriority, IssuesReview, LineRange
from products.review_hog.backend.reviewer.models.perspective_selection import (
@@ -40,6 +41,7 @@ from products.review_hog.backend.reviewer.tools.coordinator_review import Coordi
from products.review_hog.backend.reviewer.tools.issue_deduplicator import AlreadyRaised, DedupOutcome, Duplicate
from products.review_hog.backend.reviewer.tools.publish_review import PublishOutcome
from products.review_hog.backend.reviewer.tools.select_perspectives import PerspectiveSelectionDTO
+from products.review_hog.backend.reviewer.tools.single_agent_review import FlashSelection
from products.review_hog.backend.temporal.activities import (
CoordinatorReviewInput,
LensReviewInput,
@@ -744,6 +746,42 @@ async def test_full_dedup_lists_other_reviewers_comments_when_the_app_login_is_n
assert result.raised_elsewhere == [AlreadyRaised(title="Already said", level="P2", comment_id=2, commenter="alice")]
+ "trigger_source,expected_budget_left",
+ [
+ pytest.param("automatic", 2, id="automatic_turn_is_held_to_the_budget"),
+ pytest.param("comment", None, id="requested_review_is_not"),
+ pytest.param(None, None, id="payload_from_before_the_field"),
+ ],
+)
+async def test_only_an_automatic_standard_turn_is_held_to_the_finding_budget(
+ trigger_source: str | None, expected_budget_left: int | None
+) -> None:
+ # Automatic reviews are the safeguard that stops at must-fix findings once the budget is spent. A review
+ # someone asks for must surface everything the turn keeps.
+ dedupe = AsyncMock(return_value=FlashSelection(kept=[], dropped=[], cap=4, lens_part_count=1))
+ with (
+ patch(f"{_MODULE}.ReviewActivityHeartbeater"),
+ patch(f"{_MODULE}.load_review_arm", return_value=DEFAULT_REVIEW_ARM),
+ patch(f"{_MODULE}._combine_and_clean", return_value=[]),
+ patch(f"{_MODULE}.load_pr_snapshot", return_value=_snapshot()),
+ patch(f"{_MODULE}.load_prior_findings_with_verdicts", return_value=[]),
+ patch(f"{_MODULE}._changed_since_last_review", return_value=None),
+ patch(f"{_MODULE}._finding_budget", return_value=FindingBudget(arm="budget", posted_before=FINDING_BUDGET - 2)),
+ patch(f"{_MODULE}.dedupe_flash_findings", dedupe),
+ patch(f"{_MODULE}.replace_deduplicated_findings", return_value=[]),
+ patch(f"{_MODULE}.replace_dropped_findings"),
+ patch(f"{_MODULE}.persist_verdicts"),
+ patch(f"{_MODULE}._refresh_status_comment", AsyncMock()),
+ ):
+ await ActivityEnvironment().run(
+ dedup_activity, SandboxStageInput(**_single_agent_stage(trigger_source=trigger_source))
+ )
+
+ assert dedupe.call_args.kwargs["budget_left"] == expected_budget_left
+
+
@pytest.mark.parametrize(
"trigger_source,commands_on,expected_hint",
[
diff --git a/products/review_hog/backend/tests/test_review_completed_tracking.py b/products/review_hog/backend/tests/test_review_completed_tracking.py
index 9d4acd65c4d0..2bb47dfa0973 100644
--- a/products/review_hog/backend/tests/test_review_completed_tracking.py
+++ b/products/review_hog/backend/tests/test_review_completed_tracking.py
@@ -19,6 +19,7 @@ from products.review_hog.backend.reviewer.constants import (
VALIDATION_MODEL,
VALIDATION_REASONING_EFFORT,
)
+from products.review_hog.backend.reviewer.finding_budget import budget_arm
from products.review_hog.backend.reviewer.fingerprint import ReviewHogMarker
from products.review_hog.backend.reviewer.models.github_meta import PRFile, PRMetadata
from products.review_hog.backend.reviewer.models.issue_validation import IssueValidation
@@ -204,6 +205,8 @@ class TestTrackReviewCompleted(BaseTest):
assert props["pr_commits"] == 3
assert props["pr_reviewable_additions"] == 80
assert props["pr_draft"] is True
+ # The finding budget's effect is measured by splitting on this, so it must be on every turn.
+ assert props["finding_budget_arm"] == budget_arm("o/r", 7)
assert 90 <= props["duration_seconds"] < 600
assert props["reviewhog_version"] == "reviewhog-full-9-9"
assert props["reviewhog_fingerprint"] == "abc1234"
@@ -223,6 +226,7 @@ class TestTrackReviewCompleted(BaseTest):
dropped={"dedup_anchor": 2, "cap": 1},
kept=4,
dedup_fell_back=True,
+ budget_left=3,
)
sessions = FlashSessionStats(lens_failures=1, lens_timeouts=1, slowest_session_seconds=412.5)
@@ -242,6 +246,7 @@ class TestTrackReviewCompleted(BaseTest):
"flash_dropped": {"dedup_anchor": 2, "cap": 1},
"flash_kept": 4,
"flash_dedup_fallback": True,
+ "flash_budget_left": 3,
"flash_lens_failures": 1,
"flash_lens_timeouts": 1,
"flash_slowest_session_seconds": 412.5,
diff --git a/products/review_hog/frontend/CodeReviewScene.tsx b/products/review_hog/frontend/CodeReviewScene.tsx
index b66d3d740b3d..cc082acd0ac5 100644
--- a/products/review_hog/frontend/CodeReviewScene.tsx
+++ b/products/review_hog/frontend/CodeReviewScene.tsx
@@ -538,6 +538,7 @@ const DROP_REASON_LABEL: Record<ReviewDropDispositionEnumApi, string> = {
dedup_anchor: 'Same spot as another finding',
old_code: 'On unchanged code',
cap: 'Over the limit',
+ budget: 'Over the pull request limit',
}
// Display order of the reasons: the label map's key order.
@@ -548,7 +549,9 @@ function DropReason({ finding }: { finding: ReviewDroppedFindingApi }): JSX.Elem
return (
<>
<LemonTag type="muted" size="small">
- {finding.disposition === 'cap' && finding.rank ? `${label} (#${finding.rank})` : label}
+ {(finding.disposition === 'cap' || finding.disposition === 'budget') && finding.rank
+ ? `${label} (#${finding.rank})`
+ : label}
</LemonTag>
{finding.comment_url && (
<Link to={finding.comment_url} target="_blank" targetBlankIcon className="text-xs">
diff --git a/products/review_hog/frontend/generated/api.schemas.ts b/products/review_hog/frontend/generated/api.schemas.ts
index 713011a2d5f3..87b2a2caaa5a 100644
--- a/products/review_hog/frontend/generated/api.schemas.ts
+++ b/products/review_hog/frontend/generated/api.schemas.ts
@@ -1005,6 +1005,7 @@ export const ReviewDroppedFindingPriorityEnumApi = {
* * `dedup_anchor` - Same spot as another finding
* * `dedup_sibling` - Repeat of a finding
* * `cap` - Over the limit
+ * * `budget` - Over the pull request limit
*/
export type ReviewDropDispositionEnumApi =
(typeof ReviewDropDispositionEnumApi)[keyof typeof ReviewDropDispositionEnumApi]
@@ -1016,6 +1017,7 @@ export const ReviewDropDispositionEnumApi = {
DedupAnchor: 'dedup_anchor',
DedupSibling: 'dedup_sibling',
Cap: 'cap',
+ Budget: 'budget',
} as const
export interface ReviewDroppedFindingApi {
@@ -1047,7 +1049,8 @@ export interface ReviewDroppedFindingApi {
* * `dedup_comment` - Already in a PR comment
* * `dedup_anchor` - Same spot as another finding
* * `dedup_sibling` - Repeat of a finding
- * * `cap` - Over the limit */
+ * * `cap` - Over the limit
+ * * `budget` - Over the pull request limit */
disposition: ReviewDropDispositionEnumApi
/**
* For a dedup drop, what it repeats: an issue key, or `comment:<id>` for a PR comment. Null for other dispositions.
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index f78c004e0e40..77fd023a4e58 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -96624,6 +96624,7 @@ export namespace Schemas {
* * `dedup_anchor` - Same spot as another finding
* * `dedup_sibling` - Repeat of a finding
* * `cap` - Over the limit
+ * * `budget` - Over the pull request limit
*/
export type ReviewDropDispositionEnum = typeof ReviewDropDispositionEnum[keyof typeof ReviewDropDispositionEnum];
@@ -96635,6 +96636,7 @@ export namespace Schemas {
DedupAnchor: 'dedup_anchor',
DedupSibling: 'dedup_sibling',
Cap: 'cap',
+ Budget: 'budget',
} as const;
export interface ReviewDroppedFinding {
@@ -96666,7 +96668,8 @@ export namespace Schemas {
* * `dedup_comment` - Already in a PR comment
* * `dedup_anchor` - Same spot as another finding
* * `dedup_sibling` - Repeat of a finding
- * * `cap` - Over the limit */
+ * * `cap` - Over the limit
+ * * `budget` - Over the pull request limit */
disposition: ReviewDropDispositionEnum;
/**
* For a dedup drop, what it repeats: an issue key, or `comment:<id>` for a PR comment. Null for other dispositions.