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): list what other reviewers already raised in full reviews (#114426)

Julian Bez5496dd017556
diff --git a/products/review_hog/ARCHITECTURE.md b/products/review_hog/ARCHITECTURE.md
index f9925db4425a..9735e5b27d6f 100644
--- a/products/review_hog/ARCHITECTURE.md
+++ b/products/review_hog/ARCHITECTURE.md
@@ -301,20 +301,18 @@ heads' PR snapshots are compared by line content per file, so lines a base merge
findings, files whose patch GitHub left out, a first review, and a re-run at the reviewed head skip the check. Step 7 then runs as two dedup calls in parallel (`dedupe_flash_findings`,
`tools/single_agent_review.py`), both one-shot OpenAI calls on `FLASH_DEDUP_MODEL` (`gpt-6-luna` @ medium,
`run_oneshot_openai_review`): the main findings against earlier turns, and the lens findings against the same plus
-the main findings as anchors, so a lens finding can lose to a main finding but never the reverse. PR comments from
-people and other bots join the dedup only when the trigger asks for additional findings
-(`dedupe_against_pr_comments`, off by default), so a review posts what it finds whatever other comments say. In that
-mode the status comment counts the findings skipped because a PR comment already raises them.
+the main findings as anchors, so a lens finding can lose to a main finding but never the reverse. Flash never reads
+PR comments, so it posts what it finds whatever people or other bots already said.
Both calls send every finding to the LLM; the pipeline's positional pre-filter does not apply to Flash.
-The Flash dedup output (`FlashIssueDeduplication`) names what each duplicate repeats (`duplicate_of`: the finding kept
-in its place, an earlier turn's finding by its issue key, or a PR comment id). A finding that survives takes the
+The dedup output (`IssueDeduplication`, shared with the pipeline) names what each duplicate repeats (`duplicate_of`:
+the finding kept in its place, an earlier turn's finding by its issue key, or a PR comment id). A finding that survives takes the
priority of the most severe duplicate removed in its favor, so a lens P1 that repeats a main P3 posts as must-fix.
A removal holds only when what it names survives (`_resolve_duplicates`): a finding that names itself or an id its call
was not shown stays, findings that name each other in a loop keep the first one in the compose order (priority, P level,
main before lens, session order), and a removal whose target also drops records the survivor at the end of the chain.
A Flash dedup call that fails non-retryably (the gateway rejects the model), or fails on the activity's last attempt,
-falls back to the positional pre-filter alone: a finding on the lines of an earlier turn's finding or a PR comment
-drops as its repeat, and findings of this turn never drop each other. The turn logs it, marks those drops
+falls back to the positional pre-filter alone: a finding on the lines of an earlier turn's finding drops as its
+repeat, and findings of this turn never drop each other. The turn logs it, marks those drops
`dedup_fallback`, and reports `flash_dedup_fallback`, so a dedup failure never fails a turn whose sessions succeeded.
`compose_flash_findings` then ranks the findings highest priority first, a reported P0 before a P1 of the same stored
priority, and the main session first on ties, before anything persists. Every must-fix (P0/P1) finding is kept outside the cap, up to `FLASH_MUST_FIX_CAP_MULTIPLIER` (2)
@@ -398,6 +396,11 @@ pr_metadata.head_branch` is threaded (as explicit kwargs, alongside `team_id` /
`DEDUP_*` constants — which also drops findings any prior inline
comment already raised — every reviewer (bot
or human, ReviewHog's own included) treated uniformly, the author handle passed through for context.
+ Only a Full turn reads PR comments here, and it reads them again at dedup time (`_current_pr_comments`),
+ because other review bots often post while it runs; comments GitHub no longer places on a line (outdated)
+ do not count. Each duplicate names what it repeats, and the final status comment lists the findings
+ another reviewer's comment already raises (`already_raised`, ReviewHog's own comments excluded) with a link
+ to that comment, so the agreement shows instead of disappearing. A pipeline Flash turn reads no comments.
Returns the canonical post-dedup `list[Issue]`; `persist_findings` mirrors them to
`issue_finding` rows.
8. **Validate** — the `ValidateIssuesWorkflow` child groups the survivors by chunk and fans out **one warm
diff --git a/products/review_hog/DECISIONS.md b/products/review_hog/DECISIONS.md
index 51c6a0f80e8b..97b974e552c7 100644
--- a/products/review_hog/DECISIONS.md
+++ b/products/review_hog/DECISIONS.md
@@ -198,6 +198,21 @@ read `FINAL_REPORT.md` there first (config glossary + coverage matrix + ranking)
rate drops materially (toward ≤50%) on frozen-PR evals with the valid-finding set intact (item 5's
coverage matrix as the guard); kill if valid findings drop with the noise.
+### ✅ BUILT 2026-10-09 — Full lists what other reviewers already raised; Flash never reads PR comments (`reviewhog-full-1-3`)
+
+- **What.** A Full turn reads the PR's inline comments again at dedup time, skips outdated ones, and still keeps a
+ finding another comment already raises off the PR. The final status comment now lists those findings with the
+ comment they repeat ("Also found in comments already on this pull request"), and a turn with nothing new says
+ "Nothing new to raise." instead of celebrating. Flash, in both designs, never reads PR comments. The
+ `dedupe_against_pr_comments` switch from the entry below is gone: no trigger ever set it, and a flag that changed
+ Flash but not Full would have meant two things.
+- **Why.** How people run Full (Sep 25 to Oct 9, human-authored PRs): 85% of runs are a label the author adds about
+ 6 minutes after opening the PR, and another review bot is active on 85% of PRs, so Full almost always has company.
+ Posting duplicates would cost authors double replies; dropping them silently hid that ReviewHog agreed. Listing
+ them keeps one thread per issue and shows the agreement. When Full is the only reviewer, nothing changes.
+- **Next.** Full's review prompt still shows every PR comment, so its reviewers can still lean on what others said.
+ Showing only the PR author's own comments is the follow-up, measured under its own version.
+
### ✅ BUILT 2026-10-09 — Flash reviews independently of other PR comments (`reviewhog-flash-2-2`)
- **What.** Flash dedup no longer reads the PR's comments, from people or other bots. It still drops repeats of
diff --git a/products/review_hog/backend/reviewer/constants.py b/products/review_hog/backend/reviewer/constants.py
index b7789539f74b..abc9334cecb4 100644
--- a/products/review_hog/backend/reviewer/constants.py
+++ b/products/review_hog/backend/reviewer/constants.py
@@ -112,8 +112,8 @@ def select_review_design(review_mode: str, *, kill_switch_on: bool) -> ReviewDes
# Bump a (major, minor) with a pipeline or design change. Prompt, skill, and model pin edits
# change the turn fingerprint (`reviewer/fingerprint.py`) instead.
REVIEWHOG_VERSIONS: dict[tuple[str, str], tuple[int, int]] = {
- (REVIEW_MODE_FULL, REVIEW_DESIGN_PIPELINE): (1, 2),
- (REVIEW_MODE_FLASH, REVIEW_DESIGN_PIPELINE): (1, 2),
+ (REVIEW_MODE_FULL, REVIEW_DESIGN_PIPELINE): (1, 3),
+ (REVIEW_MODE_FLASH, REVIEW_DESIGN_PIPELINE): (1, 3),
(REVIEW_MODE_FLASH, REVIEW_DESIGN_SINGLE_AGENT): (2, 2),
}
@@ -150,6 +150,16 @@ SINGLE_AGENT_PASS_NUMBER = 2000
SINGLE_AGENT_CHUNK_ID = 1
SINGLE_AGENT_SOURCE = "flash-single-agent"
+# Hidden marker stamped on every ReviewHog inline finding comment (publish_review._format_issue_comment)
+# so the resolution stage can recognize its own threads by content. Installation bot logins vary per
+# deployment, so there is no stable login to match on; this marker is the reliable signal. Same
+# HTML-comment style as the review-body / promo / status markers, invisible in rendered markdown.
+REVIEW_HOG_FINDING_MARKER = "<!-- reviewhog:finding -->"
+
+# A long list would bury the turn's own outcome, so the status comment shows this many of the findings other
+# reviewers already raised, and counts the rest.
+ALREADY_RAISED_SHOWN = 10
+
# The main and lens findings merge into one list by priority, cut so a turn's comments stay few. A larger
# PR gets a few more, because each extra lens part covers more code: 4, 6, 8, 10 for 1-4 parts.
FLASH_MAX_FINDINGS_BASE = 4
diff --git a/products/review_hog/backend/reviewer/fingerprint.py b/products/review_hog/backend/reviewer/fingerprint.py
index a96cb9a73b87..fa8fe4cd62ad 100644
--- a/products/review_hog/backend/reviewer/fingerprint.py
+++ b/products/review_hog/backend/reviewer/fingerprint.py
@@ -48,7 +48,6 @@ from products.review_hog.backend.reviewer.constants import (
validation_arm_for_mode,
)
from products.review_hog.backend.reviewer.models import PROMPTS_DIR
-from products.review_hog.backend.reviewer.models.issue_deduplicator import FlashIssueDeduplication
from products.review_hog.backend.reviewer.review_design import REVIEW_DESIGN_PIPELINE, REVIEW_DESIGN_SINGLE_AGENT
from products.review_hog.backend.reviewer.sandbox.executor import JSON_RETRY_PROMPT
from products.review_hog.backend.reviewer.skill_loader import (
@@ -176,8 +175,6 @@ class TurnFingerprint:
(SINGLE_AGENT_PROMPT_PATH / prompt_file).read_text()
)
hashes["issue_deduplicator/system"] = _text_hash(DEDUP_SYSTEM_PROMPT)
- # The Flash dedup renders its output schema from the model, not from `schema.json`.
- hashes["issue_deduplicator/flash_schema"] = _text_hash(json.dumps(FlashIssueDeduplication.model_json_schema()))
hashes["sandbox/json_retry"] = _text_hash(JSON_RETRY_PROMPT)
return hashes
diff --git a/products/review_hog/backend/reviewer/models/issue_deduplicator.py b/products/review_hog/backend/reviewer/models/issue_deduplicator.py
index 1d588bda9315..b3a1512b3ede 100644
--- a/products/review_hog/backend/reviewer/models/issue_deduplicator.py
+++ b/products/review_hog/backend/reviewer/models/issue_deduplicator.py
@@ -2,18 +2,6 @@ from pydantic import BaseModel, Field
class DuplicateIssue(BaseModel):
- """A finding flagged as a duplicate, to be removed."""
-
- id: str = Field(description="Id of the finding to remove")
-
-
-class IssueDeduplication(BaseModel):
- """Result of deduplication analysis for findings."""
-
- duplicates: list[DuplicateIssue] = Field(description="Ids of the findings to remove as duplicates")
-
-
-class FlashDuplicateIssue(BaseModel):
"""A finding flagged as a duplicate, with what it repeats."""
id: str = Field(description="Id of the finding to remove")
@@ -25,7 +13,7 @@ class FlashDuplicateIssue(BaseModel):
)
-class FlashIssueDeduplication(BaseModel):
- """Result of a Flash deduplication: every duplicate names what it repeats."""
+class IssueDeduplication(BaseModel):
+ """Result of a deduplication: every duplicate names what it repeats."""
- duplicates: list[FlashDuplicateIssue] = Field(description="The findings to remove as duplicates")
+ duplicates: list[DuplicateIssue] = Field(description="The findings to remove as duplicates")
diff --git a/products/review_hog/backend/reviewer/models/issues_review.py b/products/review_hog/backend/reviewer/models/issues_review.py
index 587304c53cdb..8bd9edff18d3 100644
--- a/products/review_hog/backend/reviewer/models/issues_review.py
+++ b/products/review_hog/backend/reviewer/models/issues_review.py
@@ -77,10 +77,10 @@ class Issue(BaseModel):
)
-# Why a single-agent turn drops a finding. A `dedup_*` drop repeats an earlier turn's finding, a PR
-# comment, a main finding (anchor), or a finding of its own session or lens (sibling). `cap` is the cut
-# in `compose_flash_findings`. `old_code` is a follow-up turn's P2 or P3 finding on code that did not
-# change since the last reviewed head.
+# 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`.
+# `old_code` is a follow-up turn's P2 or P3 finding on code that did not change since the last reviewed head.
DropDisposition = Literal[
"old_code",
"dedup_prior",
diff --git a/products/review_hog/backend/reviewer/prompts/issue_deduplicator/prompt.jinja b/products/review_hog/backend/reviewer/prompts/issue_deduplicator/prompt.jinja
index d001b5b86bb1..72b15a7acdbe 100644
--- a/products/review_hog/backend/reviewer/prompts/issue_deduplicator/prompt.jinja
+++ b/products/review_hog/backend/reviewer/prompts/issue_deduplicator/prompt.jinja
@@ -75,7 +75,7 @@ Generate your deduplication analysis as a JSON object that conforms to the provi
IMPORTANT:
- Include all required fields as specified in the schema
-{% if NAMES_DUPLICATE_OF %}- Each "duplicates" entry gives the `id` of a finding to remove and, in `duplicate_of`, the id of what already raises the same problem: the finding you keep in its place (never a finding you also remove), a prior finding, or a prior comment{% else %}- The "duplicates" list must contain only the ids of the findings to remove{% endif %}
+- Each "duplicates" entry gives the `id` of a finding to remove and, in `duplicate_of`, the id of what already raises the same problem: the finding you keep in its place (never a finding you also remove), a prior finding, or a prior comment
- Return ONLY the final JSON output (without any additional text or markdown formatting)
JSON Schema:
diff --git a/products/review_hog/backend/reviewer/prompts/issue_deduplicator/schema.json b/products/review_hog/backend/reviewer/prompts/issue_deduplicator/schema.json
index ca720fd65ee8..e93ab2b7f21c 100644
--- a/products/review_hog/backend/reviewer/prompts/issue_deduplicator/schema.json
+++ b/products/review_hog/backend/reviewer/prompts/issue_deduplicator/schema.json
@@ -1,25 +1,31 @@
{
"$defs": {
"DuplicateIssue": {
- "description": "A finding flagged as a duplicate, to be removed.",
+ "description": "A finding flagged as a duplicate, with what it repeats.",
"properties": {
"id": {
"description": "Id of the finding to remove",
"title": "Id",
"type": "string"
+ },
+ "duplicate_of": {
+ "description": "Id of what already raises the same problem: the finding kept in its place, a prior finding, or a prior comment",
+ "title": "Duplicate Of",
+ "type": "string"
}
},
"required": [
- "id"
+ "id",
+ "duplicate_of"
],
"title": "DuplicateIssue",
"type": "object"
}
},
- "description": "Result of deduplication analysis for findings.",
+ "description": "Result of a deduplication: every duplicate names what it repeats.",
"properties": {
"duplicates": {
- "description": "Ids of the findings to remove as duplicates",
+ "description": "The findings to remove as duplicates",
"items": {
"$ref": "#/$defs/DuplicateIssue"
},
diff --git a/products/review_hog/backend/reviewer/status_comment.py b/products/review_hog/backend/reviewer/status_comment.py
index 74d510852d89..369148294fee 100644
--- a/products/review_hog/backend/reviewer/status_comment.py
+++ b/products/review_hog/backend/reviewer/status_comment.py
@@ -17,6 +17,8 @@ retry a review, so all exceptions are swallowed after logging.
import random
import logging
+from collections.abc import Sequence
+from dataclasses import field
from datetime import timedelta
from typing import Any
@@ -29,11 +31,13 @@ from posthog.models.integration import GitHubIntegration, Integration
from products.review_hog.backend.models import ReviewReport
from products.review_hog.backend.reviewer.constants import (
+ ALREADY_RAISED_SHOWN,
PRIORITIES_BY_URGENCY,
PRIORITY_LABELS,
REVIEW_MODE_FLASH,
REVIEW_MODE_FULL,
effective_priority,
+ finding_heading,
published_priorities_for,
)
from products.review_hog.backend.reviewer.fingerprint import ReviewHogMarker
@@ -54,6 +58,8 @@ from products.review_hog.backend.reviewer.tools.github_client import (
github_api_request,
is_app_bot_author,
)
+from products.review_hog.backend.reviewer.tools.issue_deduplicator import AlreadyRaised
+from products.review_hog.backend.reviewer.tools.redaction import redact_secrets
logger = logging.getLogger(__name__)
@@ -229,7 +235,9 @@ def render_final_body(
celebrate_clean_reviews: bool = True,
marker: ReviewHogMarker | None = None,
capped_lens_parts: int | None = None,
- already_raised: int = 0,
+ raised_elsewhere: Sequence[AlreadyRaised] = (),
+ raised_elsewhere_count: int = 0,
+ pr_url: str | None = None,
) -> str:
"""The completed-state body: the full found counts, and how many the threshold held back.
@@ -239,16 +247,19 @@ def render_final_body(
and links to the report in PostHog (`report_url`, auth-gated) — the PR is otherwise the only
place the author hears about held-back findings, so the comment must not dead-end.
`capped_lens_parts` is set when a single-agent turn reviewed a PR past the lens part cap. The
- note goes here and not in the review body, because a clean turn posts no review. `already_raised`
- counts the findings a review asked for additional findings skipped because a PR comment raises them.
+ note goes here and not in the review body, because a clean turn posts no review. `raised_elsewhere`
+ lists the findings a Full turn did not post because another reviewer's PR comment raises them, each
+ linked to that comment under `pr_url`; `raised_elsewhere_count` counts all of them.
"""
found_total = sum(counts.values())
found_line = "Found " + ", ".join(
f"**{counts[priority]} {PRIORITY_LABELS[priority]}**" for priority in PRIORITIES_BY_URGENCY
)
lines = [f"### \U0001f994 {_product_name(review_mode)} reviewed this pull request", ""]
+ if found_total == 0 and raised_elsewhere:
+ lines.append("Nothing new to raise.")
# A flash turn is the quick pass, so a clean one gets a plain line instead of the celebration.
- if found_total == 0 and review_mode == REVIEW_MODE_FLASH:
+ elif found_total == 0 and review_mode == REVIEW_MODE_FLASH:
lines.append("Nothing worth raising.")
elif found_total == 0 and celebrate_clean_reviews:
media_url, media_alt = random.choice(_NO_ISSUES_MEDIA)
@@ -287,13 +298,15 @@ def render_final_body(
f"This pull request is large, so the review ran in {capped_lens_parts} parts with less depth than usual.",
]
)
- if already_raised > 0:
- lines.extend(
- [
- "",
- f"Skipped {_plural(already_raised, 'finding')} that other comments on this pull request already raise.",
- ]
- )
+ if raised_elsewhere:
+ shown = raised_elsewhere[:ALREADY_RAISED_SHOWN]
+ lines.extend(["", "Also found in comments already on this pull request, so not posted again:"])
+ for raised in shown:
+ link = f" ([comment]({pr_url}#discussion_r{raised.comment_id}))" if pr_url else ""
+ lines.append(f"- {finding_heading(raised.title, raised.level)}, raised by `{raised.commenter}`{link}")
+ hidden = max(raised_elsewhere_count, len(raised_elsewhere)) - len(shown)
+ if hidden > 0:
+ lines.append(f"- and {hidden} more")
lines.extend(["", status_marker(report_id)])
if marker is not None:
lines.append(marker.hidden_comment())
@@ -592,7 +605,8 @@ class FinalizeStatusCommentInput:
celebrate_clean_reviews: bool = True
marker: ReviewHogMarker | None = None
capped_lens_parts: int | None = None
- already_raised: int = 0
+ raised_elsewhere: list[AlreadyRaised] = field(default_factory=list)
+ raised_elsewhere_count: int = 0
def finalize_status_comment(input: FinalizeStatusCommentInput) -> None:
@@ -610,7 +624,7 @@ def finalize_status_comment(input: FinalizeStatusCommentInput) -> None:
published = published_priorities_for(threshold)
published_count = sum(count for priority, count in counts.items() if priority in published)
held_back_count = sum(count for priority, count in counts.items() if priority not in published)
- body = render_final_body(
+ rendered = render_final_body(
input.report_id,
counts=counts,
published_count=published_count,
@@ -623,8 +637,14 @@ def finalize_status_comment(input: FinalizeStatusCommentInput) -> None:
celebrate_clean_reviews=input.celebrate_clean_reviews,
marker=input.marker,
capped_lens_parts=input.capped_lens_parts,
- already_raised=input.already_raised,
+ raised_elsewhere=input.raised_elsewhere,
+ raised_elsewhere_count=input.raised_elsewhere_count,
+ pr_url=report.pr_url or None,
)
+ # The list of findings other reviewers raised carries model-written titles, which may quote sandbox output.
+ body, redacted = redact_secrets(rendered)
+ if redacted:
+ logger.warning("Redacted %s credential-shaped string(s) from the status comment", redacted)
_edit_and_stamp(input.team_id, report, body)
except Exception:
logger.exception("Could not finalize the ReviewHog status comment; the review is unaffected")
diff --git a/products/review_hog/backend/reviewer/tests/test_direct_llm.py b/products/review_hog/backend/reviewer/tests/test_direct_llm.py
index a46eb8693be6..2776cd8fd8ed 100644
--- a/products/review_hog/backend/reviewer/tests/test_direct_llm.py
+++ b/products/review_hog/backend/reviewer/tests/test_direct_llm.py
@@ -194,7 +194,7 @@ async def _openai_call() -> IssueDeduplication:
@pytest.mark.parametrize(
"content,finish_reason,non_retryable",
[
- ('{"duplicates": [{"id": "1-1-1"}]}', "stop", None),
+ ('{"duplicates": [{"id": "1-1-1", "duplicate_of": "1-1-2"}]}', "stop", None),
('{"duplicates": [', "stop", False),
('{"duplicates": [', "length", True),
(None, None, False),
diff --git a/products/review_hog/backend/reviewer/tests/test_issue_deduplicator.py b/products/review_hog/backend/reviewer/tests/test_issue_deduplicator.py
index 32a421ac8c24..c89b12015d5b 100644
--- a/products/review_hog/backend/reviewer/tests/test_issue_deduplicator.py
+++ b/products/review_hog/backend/reviewer/tests/test_issue_deduplicator.py
@@ -13,20 +13,19 @@ from products.review_hog.backend.reviewer.constants import (
DEDUP_RUNTIME_ADAPTER,
FLASH_DEDUP_MODEL,
FLASH_DEDUP_REASONING_EFFORT,
+ REVIEW_HOG_FINDING_MARKER,
)
from products.review_hog.backend.reviewer.models.github_meta import PRComment, PRMetadata
-from products.review_hog.backend.reviewer.models.issue_deduplicator import (
- DuplicateIssue,
- FlashDuplicateIssue,
- FlashIssueDeduplication,
- IssueDeduplication,
-)
+from products.review_hog.backend.reviewer.models.issue_deduplicator import DuplicateIssue, IssueDeduplication
from products.review_hog.backend.reviewer.models.issues_review import Issue, IssuePriority, LineRange
from products.review_hog.backend.reviewer.tests.conftest import create_mock_run_sandbox_review
from products.review_hog.backend.reviewer.tools.issue_deduplicator import (
+ AlreadyRaised,
DedupOutcome,
+ Duplicate,
_comment_range,
_select_dedup_candidates,
+ already_raised,
deduplicate_issues,
)
@@ -68,6 +67,7 @@ def _prior_comment(path: str, line: int, user: str) -> PRComment:
# A prior inline comment. The dedup never branches on the author — it's passed to the LLM as
# context only.
return PRComment(
+ id=77,
path=path,
line=line,
body="x",
@@ -193,7 +193,7 @@ async def test_deduplicate_no_positional_collision_reaches_only_the_flash_llm_ca
_issue("1-2", "src/b.py", 30, 40),
_issue("1-3", "src/c.py", 50, 60),
]
- flash_drops_one = FlashIssueDeduplication(duplicates=[FlashDuplicateIssue(id="1-2", duplicate_of="1-1")])
+ flash_drops_one = IssueDeduplication(duplicates=[DuplicateIssue(id="1-2", duplicate_of="1-1")])
with (
patch(f"{_MODULE}.run_oneshot_review") as mock_oneshot,
@@ -226,7 +226,7 @@ async def test_deduplicate_drops_llm_flagged_duplicate_keeps_isolated(pr_metadat
_issue("2-1", "src/auth.py", 45, 50),
_issue("1-2", "src/other.py", 10, 12),
]
- dedup = IssueDeduplication(duplicates=[DuplicateIssue(id="2-1")])
+ dedup = IssueDeduplication(duplicates=[DuplicateIssue(id="2-1", duplicate_of="1-1")])
with patch(f"{_MODULE}.run_oneshot_review", create_mock_run_sandbox_review(dedup)):
result = await deduplicate_issues(
@@ -251,7 +251,7 @@ async def test_deduplicate_prior_comment_makes_issue_a_candidate(pr_metadata: PR
# one hardcoded bot), and nothing in our code branches on who wrote the comment.
issues = [_issue("1-1", "src/auth.py", 45, 50)]
comments = [_prior_comment("src/auth.py", 47, user="some-reviewer[bot]")]
- dedup = IssueDeduplication(duplicates=[DuplicateIssue(id="1-1")])
+ dedup = IssueDeduplication(duplicates=[DuplicateIssue(id="1-1", duplicate_of=str(comments[0].id))])
with patch(f"{_MODULE}.run_oneshot_review", create_mock_run_sandbox_review(dedup)):
result = await deduplicate_issues(
@@ -266,6 +266,8 @@ async def test_deduplicate_prior_comment_makes_issue_a_candidate(pr_metadata: PR
)
assert result.kept == []
+ # Full lists what a PR comment already raises, so the removal must keep which comment it repeats.
+ assert [duplicate.duplicate_of for duplicate in result.duplicates] == [str(comments[0].id)]
@pytest.mark.asyncio
@@ -274,7 +276,7 @@ async def test_deduplicate_prior_turn_finding_makes_issue_a_candidate(pr_metadat
# even with no other issue or comment nearby — otherwise it re-enters validation every turn.
issues = [_issue("1-1", "src/auth.py", 45, 50)]
prior = [_prior_finding("src/auth.py", 46, 48, dismissed=True)]
- dedup = IssueDeduplication(duplicates=[DuplicateIssue(id="1-1")])
+ dedup = IssueDeduplication(duplicates=[DuplicateIssue(id="1-1", duplicate_of=prior[0][0].issue_key)])
with patch(f"{_MODULE}.run_oneshot_review", create_mock_run_sandbox_review(dedup)):
result = await deduplicate_issues(
@@ -309,12 +311,11 @@ async def test_dedup_llm_call_routes_by_oneshot_gate(
# A Flash dedup skips the gate: it always runs on its own OpenAI pins, never on Anthropic ones.
issues = [_issue(f"1-{i}", "src/auth.py", 45, 50) for i in range(issue_count)]
keep_all = IssueDeduplication(duplicates=[])
- flash_keep_all = FlashIssueDeduplication(duplicates=[])
with (
patch(f"{_MODULE}.run_oneshot_review", new=AsyncMock(return_value=keep_all)) as mock_oneshot,
patch(f"{_MODULE}.run_sandbox_review", new=AsyncMock(return_value=keep_all)) as mock_sandbox,
- patch(f"{_MODULE}.run_oneshot_openai_review", new=AsyncMock(return_value=flash_keep_all)) as mock_openai,
+ patch(f"{_MODULE}.run_oneshot_openai_review", new=AsyncMock(return_value=keep_all)) as mock_openai,
):
result = await deduplicate_issues(
team_id=1,
@@ -331,8 +332,9 @@ async def test_dedup_llm_call_routes_by_oneshot_gate(
assert len(result.kept) == issue_count
routes = {"oneshot": mock_oneshot, "sandbox": mock_sandbox, "openai": mock_openai}
assert [name for name, mock in routes.items() if mock.called] == [expected_route]
+ # Every route asks what each duplicate repeats, because Full lists the comments its findings repeat.
instructions = routes[expected_route].call_args.kwargs["prompt"].split("JSON Schema:")[0]
- assert ("`duplicate_of`" in instructions) == for_flash
+ assert "`duplicate_of`" in instructions
if expected_route == "sandbox":
# The pin kwargs default to None, so dropping them at this call site would silently fall
# back to the sandbox default model — same contract as the chunking and review pin tests.
@@ -430,3 +432,33 @@ async def test_flash_dedup_transient_failure_retries_before_the_last_attempt(pr_
# dedup; falling back at once would trade it for the coarser positional one.
with pytest.raises(ApplicationError):
await _dedupe_with_a_failing_flash_call(pr_metadata, non_retryable=False, final_attempt=False)
+
+
+def test_already_raised_lists_each_other_reviewers_comment_once() -> None:
+ # The status comment says another reviewer already raised these. ReviewHog's own comments and earlier
+ # findings must not appear, a human who pastes ReviewHog's public marker must not leave the list, and
+ # several perspectives repeating one comment must not fill the list with copies of it.
+ def comment(comment_id: int, user: str, body: str = "Retries can double charge") -> PRComment:
+ return PRComment(id=comment_id, path="a.py", line=5, body=body, diff_hunk="", user=user, created_at="c")
+
+ own_body = f"**P2 · Old**\n\nx\n\n{REVIEW_HOG_FINDING_MARKER}"
+ comments = [
+ comment(1, "greptile-apps[bot]"),
+ comment(2, "posthog[bot]", own_body),
+ comment(3, "someone", own_body),
+ ]
+ must_fix = _issue("1-4", "a.py", 5, 6).model_copy(update={"priority": IssuePriority.MUST_FIX})
+ duplicates = [
+ Duplicate(issue=_issue("1-1", "a.py", 5, 6), duplicate_of="1"),
+ Duplicate(issue=must_fix, duplicate_of="1"),
+ Duplicate(issue=_issue("1-2", "a.py", 9, 9), duplicate_of="2"),
+ Duplicate(issue=_issue("1-3", "a.py", 20, 21), duplicate_of="r1:a.py:20"),
+ Duplicate(issue=_issue("1-5", "a.py", 5, 5), duplicate_of="3"),
+ ]
+
+ raised = already_raised(duplicates, comments)
+
+ assert raised == [
+ AlreadyRaised(title="Issue 1-4", level="P1", comment_id=1, commenter="greptile-apps[bot]"),
+ AlreadyRaised(title="Issue 1-5", level="P2", comment_id=3, commenter="someone"),
+ ]
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 6744d7fd9c08..22171b65eda2 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
@@ -10,8 +10,8 @@ from products.review_hog.backend.reviewer.constants import (
SINGLE_AGENT_SOURCE,
flash_max_findings,
)
-from products.review_hog.backend.reviewer.models.github_meta import PRComment, PRFile, PRFileUpdate, PRMetadata
-from products.review_hog.backend.reviewer.models.issue_deduplicator import FlashDuplicateIssue, FlashIssueDeduplication
+from products.review_hog.backend.reviewer.models.github_meta import PRFile, PRFileUpdate, PRMetadata
+from products.review_hog.backend.reviewer.models.issue_deduplicator import DuplicateIssue, IssueDeduplication
from products.review_hog.backend.reviewer.models.issues_review import (
DroppedIssue,
Issue,
@@ -228,8 +228,8 @@ class TestComposeFlashFindings:
def _flash_dedup(*duplicates: tuple[str, str]) -> AsyncMock:
return AsyncMock(
- return_value=FlashIssueDeduplication(
- duplicates=[FlashDuplicateIssue(id=issue_id, duplicate_of=target) for issue_id, target in duplicates]
+ return_value=IssueDeduplication(
+ duplicates=[DuplicateIssue(id=issue_id, duplicate_of=target) for issue_id, target in duplicates]
)
)
@@ -245,9 +245,7 @@ class TestDedupeFlashFindings:
mock_llm: AsyncMock,
*,
prior_findings: list[ReviewIssueFinding] | None = None,
- pr_comments: list[PRComment] | None = None,
changed_since: ChangedSinceReview | None = None,
- against_pr_comments: bool = False,
) -> FlashSelection:
with patch(f"{_DEDUP_MODULE}.run_oneshot_openai_review", mock_llm):
return await dedupe_flash_findings(
@@ -255,13 +253,11 @@ class TestDedupeFlashFindings:
user_id=1,
issues=issues,
pr_metadata=pr_metadata,
- pr_comments=pr_comments or [],
prior_findings=[(finding, None) for finding in prior_findings or []],
branch="feat",
repository="o/r",
lens_part_count=1,
changed_since=changed_since,
- against_pr_comments=against_pr_comments,
)
@pytest.mark.asyncio
@@ -369,7 +365,6 @@ class TestDedupeFlashFindings:
pytest.param("2000-1-1", "dedup_anchor", "2000-1-1", id="main_finding"),
pytest.param("2002-1-2", "dedup_sibling", "2002-1-2", id="lens_sibling"),
pytest.param(_PRIOR_KEY, "dedup_prior", _PRIOR_KEY, id="earlier_turn"),
- pytest.param("77", "dedup_comment", "comment:77", id="pr_comment"),
],
)
async def test_a_dedup_drop_records_what_it_repeats(
@@ -392,12 +387,9 @@ class TestDedupeFlashFindings:
suggestion="",
priority=IssuePriority.SHOULD_FIX,
)
- comment = PRComment(id=77, path="a.py", line=10, body="x", diff_hunk="", user="reviewer", created_at="c")
mock_llm = _flash_dedup(("2002-1-1", named))
- selection = await self._dedupe(
- pr_metadata, issues, mock_llm, prior_findings=[prior], pr_comments=[comment], against_pr_comments=True
- )
+ selection = await self._dedupe(pr_metadata, issues, mock_llm, prior_findings=[prior])
[drop] = selection.dropped
recorded = drop.duplicate_of.id if isinstance(drop.duplicate_of, Issue) else drop.duplicate_of
@@ -405,33 +397,6 @@ class TestDedupeFlashFindings:
# The dedup can only name an earlier finding it was shown with its key.
assert all(_PRIOR_KEY in call.kwargs["prompt"] for call in mock_llm.call_args_list)
- @pytest.mark.asyncio
- @pytest.mark.parametrize(
- "against_pr_comments,posts",
- [
- pytest.param(False, True, id="independent_review_posts_what_a_comment_already_says"),
- pytest.param(True, False, id="additional_review_skips_it"),
- ],
- )
- async def test_pr_comments_count_as_earlier_findings_only_when_asked(
- self, pr_metadata: PRMetadata, against_pr_comments: bool, posts: bool
- ) -> None:
- # By default a review reports what it finds, so a finding another reviewer already posted must still
- # post. Only a review asked for additional findings skips what a PR comment already raises.
- comment = PRComment(id=77, path="a.py", line=10, body="x", diff_hunk="", user="other-bot", created_at="c")
- mock_llm = _flash_dedup(("2000-1-1", "77"))
-
- selection = await self._dedupe(
- pr_metadata,
- [_issue("2000-1-1", IssuePriority.SHOULD_FIX)],
- mock_llm,
- pr_comments=[comment],
- against_pr_comments=against_pr_comments,
- )
-
- assert [issue.id for issue in selection.kept] == (["2000-1-1"] if posts else [])
- assert all(("77" in call.kwargs["prompt"]) is against_pr_comments for call in mock_llm.call_args_list)
-
@pytest.mark.asyncio
@pytest.mark.parametrize(
"llm_duplicates,expected_kept,expected_drops",
diff --git a/products/review_hog/backend/reviewer/tools/github_meta.py b/products/review_hog/backend/reviewer/tools/github_meta.py
index 7ca6b4adc9c6..4647ff4914b3 100644
--- a/products/review_hog/backend/reviewer/tools/github_meta.py
+++ b/products/review_hog/backend/reviewer/tools/github_meta.py
@@ -426,8 +426,22 @@ class PRFetcher:
changed_files=pr["changed_files"],
)
- def fetch_pr_comments(self, pr_filter: PRFilter) -> list[PRComment]:
- """Fetch the PR's review comments (filtered files / test files dropped)."""
+ def fetch_head_sha(self) -> str:
+ """The commit the PR's head branch points at now."""
+ pr = github_api_request(
+ "GET",
+ f"/repos/{self.owner}/{self.repo}/pulls/{self.pr_number}",
+ token=self._token,
+ installation_id=self._installation_id,
+ endpoint="/repos/{owner}/{repo}/pulls/{pull_number}",
+ ).json()
+ return pr["head"]["sha"]
+
+ def fetch_pr_comments(self, pr_filter: PRFilter, *, raise_errors: bool = False) -> list[PRComment]:
+ """Fetch the PR's review comments (filtered files / test files dropped).
+
+ A GitHub error returns what was read so far, unless `raise_errors` asks for the error instead.
+ """
pr_comments: list[PRComment] = []
try:
for comment in github_api_get_paginated(
@@ -451,6 +465,8 @@ class PRFetcher:
)
)
except (GitHubAPIError, GitHubRateLimitError) as e:
+ if raise_errors:
+ raise
logger.warning(f"Could not fetch review comments: {e}")
return pr_comments
diff --git a/products/review_hog/backend/reviewer/tools/github_threads.py b/products/review_hog/backend/reviewer/tools/github_threads.py
index 11331b575f42..bddec09ee2f7 100644
--- a/products/review_hog/backend/reviewer/tools/github_threads.py
+++ b/products/review_hog/backend/reviewer/tools/github_threads.py
@@ -20,6 +20,7 @@ from posthog.egress.github.transport import GitHubRateLimitError, github_request
from posthog.egress.limiter.policies import Priority
from products.review_hog.backend.reviewer.artefact_content import ThreadVerdictArtefact
+from products.review_hog.backend.reviewer.constants import REVIEW_HOG_FINDING_MARKER
from products.review_hog.backend.reviewer.tools.github_client import (
GITHUB_API_BASE,
GitHubAPIError,
@@ -48,12 +49,6 @@ _RANK_HUMAN = 0
_RANK_REVIEW_HOG = 1
_RANK_OTHER_BOT = 2
-# Hidden marker stamped on every ReviewHog inline finding comment (publish_review._format_issue_comment)
-# so the resolution stage can recognize its own threads by content. Installation bot logins vary per
-# deployment, so there is no stable login to match on; this marker is the reliable signal. Same
-# HTML-comment style as the review-body / promo / status markers, invisible in rendered markdown.
-REVIEW_HOG_FINDING_MARKER = "<!-- reviewhog:finding -->"
-
class ThreadComment(BaseModel):
"""One comment inside a review thread, as the resolution stage consumes it."""
diff --git a/products/review_hog/backend/reviewer/tools/issue_deduplicator.py b/products/review_hog/backend/reviewer/tools/issue_deduplicator.py
index ea384a35baee..51ed3ffe78c4 100644
--- a/products/review_hog/backend/reviewer/tools/issue_deduplicator.py
+++ b/products/review_hog/backend/reviewer/tools/issue_deduplicator.py
@@ -2,6 +2,8 @@ import json
import logging
from collections.abc import Sequence
+from django.conf import settings
+
from temporalio.exceptions import ApplicationError
from posthog.dataclasses import frozen
@@ -14,10 +16,12 @@ from products.review_hog.backend.reviewer.constants import (
DEDUP_RUNTIME_ADAPTER,
FLASH_DEDUP_MODEL,
FLASH_DEDUP_REASONING_EFFORT,
+ REVIEW_HOG_FINDING_MARKER,
+ display_level,
)
from products.review_hog.backend.reviewer.models.github_meta import PRComment, PRMetadata
-from products.review_hog.backend.reviewer.models.issue_deduplicator import FlashIssueDeduplication, IssueDeduplication
-from products.review_hog.backend.reviewer.models.issues_review import Issue, LineRange
+from products.review_hog.backend.reviewer.models.issue_deduplicator import IssueDeduplication
+from products.review_hog.backend.reviewer.models.issues_review import Issue, LineRange, ReportedPriority
from products.review_hog.backend.reviewer.sandbox.direct_llm import run_oneshot_openai_review, run_oneshot_review
from products.review_hog.backend.reviewer.sandbox.executor import run_sandbox_review
from products.review_hog.backend.reviewer.tools.prompt_helpers import load_template_and_schema
@@ -31,10 +35,57 @@ class Duplicate:
issue: Issue
# The id of what it repeats: a finding of this call, an anchor, an earlier turn's issue key, or a PR
- # comment id. Only the Flash dedup names it.
+ # comment id.
duplicate_of: str | None
+@frozen
+class AlreadyRaised:
+ """A finding a turn did not post because another reviewer's PR comment already raises it."""
+
+ title: str
+ level: ReportedPriority
+ comment_id: int
+ commenter: str
+
+
+def _is_review_hog_finding(comment: PRComment) -> bool:
+ """ReviewHog's own finding comment. The marker is public, so it only counts on a bot's comment, and on
+ ReviewHog's own app when its login is configured; otherwise anyone could paste it to leave the list."""
+ expected = settings.REVIEWHOG_GITHUB_BOT_LOGIN
+ by_review_hog = comment.user == expected if expected else comment.user.endswith("[bot]")
+ return by_review_hog and REVIEW_HOG_FINDING_MARKER in comment.body
+
+
+def already_raised(duplicates: Sequence[Duplicate], pr_comments: Sequence[PRComment]) -> list[AlreadyRaised]:
+ """The other reviewers' PR comments that a turn's findings repeat.
+
+ One entry per comment, at the most severe level any of its repeating findings gave it, because several
+ perspectives often find the same problem.
+ """
+ others = {
+ str(comment.id): comment
+ for comment in pr_comments
+ if comment.id is not None and not _is_review_hog_finding(comment)
+ }
+ by_comment: dict[int, AlreadyRaised] = {}
+ for duplicate in duplicates:
+ comment = others.get(duplicate.duplicate_of or "")
+ if comment is None or comment.id is None:
+ continue
+ raised = AlreadyRaised(
+ title=duplicate.issue.title,
+ level=display_level(duplicate.issue.priority, duplicate.issue.reported_priority),
+ comment_id=comment.id,
+ commenter=comment.user,
+ )
+ current = by_comment.get(comment.id)
+ # "P0" sorts before "P3", so the smaller level is the more severe one.
+ if current is None or raised.level < current.level:
+ by_comment[comment.id] = raised
+ return list(by_comment.values())
+
+
@frozen
class DedupOutcome:
kept: list[Issue]
@@ -120,16 +171,13 @@ def _positional_duplicates(
return named
-def _prior_finding_payload(finding: ReviewIssueFinding, verdict: ValidationVerdict | None, *, with_id: bool) -> dict:
- """One prior finding as prompt data: its content plus how the earlier turn's validator ruled.
-
- `with_id` adds the issue key as the finding's id, for a dedup that names what each duplicate repeats.
- """
+def _prior_finding_payload(finding: ReviewIssueFinding, verdict: ValidationVerdict | None) -> dict:
+ """One prior finding as prompt data: its content, its issue key as the id a duplicate names, and how
+ the earlier turn's validator ruled."""
payload = finding.model_dump(
mode="json", include={"title", "file", "lines", "body", "suggestion", "priority", "source_perspective"}
)
- if with_id:
- payload["id"] = finding.issue_key
+ payload["id"] = finding.issue_key
if verdict is None:
payload["prior_ruling"] = "not validated (the earlier turn did not finish judging it)"
elif verdict.is_valid:
@@ -233,8 +281,8 @@ async def deduplicate_issues(
`anchors` are findings this turn keeps whatever the LLM answers. They count as prior coverage, so
an issue that restates one is dropped, and they are never dropped or returned themselves.
- `for_flash` runs the LLM call on the Flash dedup pins instead of the pipeline's, and asks it to name
- what each duplicate repeats (`Duplicate.duplicate_of`). A Flash call that fails non-retryably, or
+ Every call names what each duplicate repeats (`Duplicate.duplicate_of`). `for_flash` runs the LLM call
+ on the Flash dedup pins instead of the pipeline's. A Flash call that fails non-retryably, or
fails at all when `fall_back_on_any_error` says no retry follows, falls back to the positional
pre-filter alone (`_positional_duplicates`), because the review sessions already ran and a dedup
failure must not cost the turn.
@@ -269,15 +317,11 @@ async def deduplicate_issues(
PR_CONTEXT=json.dumps(pr_metadata.model_dump(mode="json"), indent=2),
PRIOR_COMMENTS_JSON=json.dumps([c.model_dump(mode="json") for c in pr_comments], indent=2),
PRIOR_FINDINGS_JSON=json.dumps(
- [_prior_finding_payload(f, v, with_id=for_flash) for f, v in prior_findings]
- + [_anchor_payload(a) for a in anchors],
+ [_prior_finding_payload(f, v) for f, v in prior_findings] + [_anchor_payload(a) for a in anchors],
indent=2,
),
ISSUES_JSON=json.dumps([issue.model_dump(mode="json") for issue in candidates], indent=2),
- DEDUPLICATION_SCHEMA=(
- json.dumps(FlashIssueDeduplication.model_json_schema(), indent=2) if for_flash else schema.strip()
- ),
- NAMES_DUPLICATE_OF=for_flash,
+ DEDUPLICATION_SCHEMA=schema.strip(),
)
# Each removed id, mapped to what it repeats when the dedup names it.
@@ -290,7 +334,7 @@ async def deduplicate_issues(
user_id=user_id,
prompt=prompt,
system_prompt=DEDUP_SYSTEM_PROMPT,
- model_to_validate=FlashIssueDeduplication,
+ model_to_validate=IssueDeduplication,
step_name="dedup",
model=FLASH_DEDUP_MODEL,
reasoning_effort=FLASH_DEDUP_REASONING_EFFORT,
@@ -314,7 +358,7 @@ async def deduplicate_issues(
repository=repository,
workflow_id_prefix=workflow_id_prefix,
)
- named_duplicates = {dup.id: None for dup in deduplication_result.duplicates}
+ named_duplicates = {dup.id: dup.duplicate_of for dup in deduplication_result.duplicates}
# `unique` issues always survive; only positional candidates can be dropped by the LLM.
deduplicated_issues = unique + [issue for issue in candidates if issue.id not in named_duplicates]
logger.info(
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 865dee66f87f..0af15ade64eb 100644
--- a/products/review_hog/backend/reviewer/tools/single_agent_review.py
+++ b/products/review_hog/backend/reviewer/tools/single_agent_review.py
@@ -33,7 +33,7 @@ from products.review_hog.backend.reviewer.constants import (
priority_rank,
)
from products.review_hog.backend.reviewer.models import PROMPTS_DIR
-from products.review_hog.backend.reviewer.models.github_meta import PRComment, PRFile, PRMetadata
+from products.review_hog.backend.reviewer.models.github_meta import PRFile, PRMetadata
from products.review_hog.backend.reviewer.models.issues_review import (
DropDisposition,
DroppedIssue,
@@ -351,9 +351,8 @@ def _dropped_duplicate(
*,
dedup_fallback: bool,
turn_issues: dict[str, Issue],
- prior_keys: set[str],
) -> DroppedIssue:
- """Record a dedup drop with the survivor it repeats: a finding of this turn, an earlier turn's finding, or a comment."""
+ """Record a dedup drop with the survivor it repeats: a finding of this turn or an earlier turn's finding."""
named = duplicate.duplicate_of
target = turn_issues.get(named) if named is not None else None
disposition: DropDisposition
@@ -365,11 +364,8 @@ def _dropped_duplicate(
)
disposition = "dedup_anchor" if repeats_anchor else "dedup_sibling"
duplicate_of = target
- elif named in prior_keys:
- disposition = "dedup_prior"
else:
- disposition = "dedup_comment"
- duplicate_of = f"comment:{named}"
+ disposition = "dedup_prior"
return DroppedIssue(
issue=duplicate.issue, disposition=disposition, duplicate_of=duplicate_of, dedup_fallback=dedup_fallback
)
@@ -597,7 +593,6 @@ async def dedupe_flash_findings(
user_id: int,
issues: list[Issue],
pr_metadata: PRMetadata,
- pr_comments: list[PRComment],
prior_findings: list[tuple[ReviewIssueFinding, ValidationVerdict | None]],
branch: str,
repository: str,
@@ -605,21 +600,18 @@ async def dedupe_flash_findings(
workflow_id_prefix: str | None = None,
fall_back_on_any_error: bool = False,
changed_since: ChangedSinceReview | None = None,
- against_pr_comments: bool = False,
) -> FlashSelection:
"""Deduplicate a single-agent turn's main and lens findings, then keep the few it posts.
- Two dedup calls run in parallel. The main findings dedup against earlier turns, and against PR comments
- only with `against_pr_comments`: by default a review posts what it finds whatever other comments say.
- The lens findings dedup against those too and against the main findings as anchors, so a lens
+ Two dedup calls run in parallel. The main findings dedup against earlier turns only: Flash posts what it
+ finds whatever other comments on the PR say. The lens findings dedup against those too and against the
+ main findings as anchors, so a lens
finding can lose to a main finding but never the other way around. A removal holds only when what
it repeats survives (`_resolve_duplicates`). A finding that survives takes the priority of the most
severe duplicate removed in its favor. `fall_back_on_any_error` lets a dedup
call fall back to the positional pre-filter on any failure, for the activity's last attempt.
On a follow-up turn, `changed_since` drops the P2 and P3 findings on unchanged code before dedup.
"""
- if not against_pr_comments:
- pr_comments = []
old_code = _old_code_findings(issues, changed_since)
old_code_ids = {issue.id for issue in old_code}
reviewed = [issue for issue in issues if issue.id not in old_code_ids]
@@ -631,7 +623,7 @@ async def dedupe_flash_findings(
user_id=user_id,
issues=main,
pr_metadata=pr_metadata,
- pr_comments=pr_comments,
+ pr_comments=[],
prior_findings=prior_findings,
branch=branch,
repository=repository,
@@ -644,7 +636,7 @@ async def dedupe_flash_findings(
user_id=user_id,
issues=lens,
pr_metadata=pr_metadata,
- pr_comments=pr_comments,
+ pr_comments=[],
prior_findings=prior_findings,
branch=branch,
repository=repository,
@@ -655,8 +647,7 @@ async def dedupe_flash_findings(
),
)
prior_keys = {finding.issue_key for finding, _ in prior_findings}
- comment_ids = {str(comment.id) for comment in pr_comments if comment.id is not None}
- held = _resolve_duplicates(main, lens, main_outcome, lens_outcome, earlier_ids=prior_keys | comment_ids)
+ held = _resolve_duplicates(main, lens, main_outcome, lens_outcome, earlier_ids=prior_keys)
removed_ids = {removal.duplicate.issue.id for removal in held}
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]
@@ -664,9 +655,7 @@ async def dedupe_flash_findings(
composed = compose_flash_findings(kept_main, kept_lens, lens_part_count=lens_part_count, group_levels=group_levels)
turn_issues = {issue.id: issue for issue in issues}
dedup_drops = [
- _dropped_duplicate(
- removal.duplicate, dedup_fallback=removal.fell_back, turn_issues=turn_issues, prior_keys=prior_keys
- )
+ _dropped_duplicate(removal.duplicate, dedup_fallback=removal.fell_back, turn_issues=turn_issues)
for removal in held
]
logger.info(
diff --git a/products/review_hog/backend/temporal/activities.py b/products/review_hog/backend/temporal/activities.py
index 8612f86d11ea..ac3b1f9f36f1 100644
--- a/products/review_hog/backend/temporal/activities.py
+++ b/products/review_hog/backend/temporal/activities.py
@@ -36,6 +36,7 @@ from posthog.temporal.common.utils import close_db_connections
from products.review_hog.backend.automatic_reviews import authored_reviews_enabled
from products.review_hog.backend.models import ReviewReport, ReviewUserSettings
from products.review_hog.backend.reviewer.constants import (
+ ALREADY_RAISED_SHOWN,
CHUNKING_MODEL,
CHUNKING_ONESHOT_MAX_ADDITIONS,
CHUNKING_REASONING_EFFORT,
@@ -67,7 +68,7 @@ from products.review_hog.backend.reviewer.lazy_seed import (
sync_canonical_validation,
)
from products.review_hog.backend.reviewer.models import generate_all_schemas
-from products.review_hog.backend.reviewer.models.github_meta import PRFile, PRMetadata
+from products.review_hog.backend.reviewer.models.github_meta import PRComment, PRFile, PRMetadata
from products.review_hog.backend.reviewer.models.issue_validation import IssueValidation
from products.review_hog.backend.reviewer.models.issues_review import Issue, IssuePriority, IssuesReview
from products.review_hog.backend.reviewer.models.perspective_selection import PerspectiveSelection
@@ -124,12 +125,17 @@ from products.review_hog.backend.reviewer.telemetry import review_event_uuid, re
from products.review_hog.backend.reviewer.tools.github_client import GitHubAPIError, github_api_request
from products.review_hog.backend.reviewer.tools.github_meta import (
PRFetcher,
+ PRFilter,
fetch_branch_compare,
find_open_pr_for_branch,
)
from products.review_hog.backend.reviewer.tools.issue_cleaner import clean_issues
from products.review_hog.backend.reviewer.tools.issue_combination import combine_issues
-from products.review_hog.backend.reviewer.tools.issue_deduplicator import deduplicate_issues
+from products.review_hog.backend.reviewer.tools.issue_deduplicator import (
+ AlreadyRaised,
+ already_raised,
+ deduplicate_issues,
+)
from products.review_hog.backend.reviewer.tools.issue_validation import (
VALIDATION_SYSTEM_PROMPT,
build_validation_followup_prompt,
@@ -339,7 +345,6 @@ 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)
- dedupe_against_pr_comments: bool = field(default=False, kw_only=True)
@dataclass
@@ -414,6 +419,10 @@ class DedupResult:
issue_ids: list[str]
# A single-agent turn's finding counts, which the workflow hands to the completed event.
flash_stats: FlashTurnStats | None = None
+ # A Full turn's findings that another reviewer's PR comment already raises, for the status comment: the
+ # ones it shows, and how many there are in all, so the payload stays small.
+ raised_elsewhere: list[AlreadyRaised] = field(default_factory=list)
+ raised_elsewhere_count: int = 0
@dataclass(frozen=False)
@@ -1430,6 +1439,33 @@ def _changed_since_last_review(
return ChangedSinceReview.between(reviewed.pr_files, current_files)
+def _current_pr_comments(input: SandboxStageInput, snapshot: "PRSnapshotArtefact") -> list[PRComment]:
+ """The PR's inline comments as they stand now, without outdated ones.
+
+ The fetch stage read them when the turn started, and other review bots often post while a Full turn
+ runs, so dedup reads them again. It keeps the first read when the PR moved to a new commit meanwhile,
+ because GitHub then places the comments on code the turn did not review. A comment GitHub no longer
+ places on a line is outdated: the code it was about changed.
+ """
+ comments = snapshot.pr_comments
+ pr_number = snapshot.pr_metadata.number
+ if pr_number is not None:
+ try:
+ token, installation_id = _installation_auth(input.team_id, input.repository)
+ owner, repo = input.repository.split("/", 1)
+ fetcher = PRFetcher(
+ owner=owner, repo=repo, pr_number=pr_number, token=token, installation_id=installation_id
+ )
+ if fetcher.fetch_head_sha() == input.head_sha:
+ # A complete read replaces the first one, so a comment deleted during the turn is gone.
+ comments = fetcher.fetch_pr_comments(PRFilter(), raise_errors=True)
+ except Exception:
+ logger.warning(
+ "Could not read the PR's comments again; deduplicating against the first read", exc_info=True
+ )
+ return [comment for comment in comments if comment.line is not None or comment.start_line is not None]
+
+
@activity.defn
@scoped_temporal()
@close_db_connections
@@ -1466,6 +1502,7 @@ async def dedup_activity(input: SandboxStageInput) -> DedupResult:
prior_findings = await database_sync_to_async(load_prior_findings_with_verdicts, thread_sensitive=False)(
team_id=input.team_id, report_id=input.report_id, before_run_index=input.run_index
)
+ raised_elsewhere: list[AlreadyRaised] = []
flash_selection: FlashSelection | None = None
flash_stats: FlashTurnStats | None = None
async with ReviewActivityHeartbeater(team_id=input.team_id, report_id=input.report_id, head_sha=input.head_sha):
@@ -1479,7 +1516,6 @@ async def dedup_activity(input: SandboxStageInput) -> DedupResult:
user_id=input.user_id,
issues=issues,
pr_metadata=snapshot.pr_metadata,
- pr_comments=snapshot.pr_comments,
prior_findings=prior_findings,
branch=input.branch,
repository=input.repository,
@@ -1487,23 +1523,29 @@ 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,
- against_pr_comments=input.dedupe_against_pr_comments,
)
survivors = flash_selection.kept
flash_stats = flash_turn_stats(issues, flash_selection, reviewable_lines=lens_plan.reviewable_lines)
else:
+ # Flash posts what it finds whatever other comments say; only Full checks the PR's comments.
+ pr_comments = (
+ await database_sync_to_async(_current_pr_comments, thread_sensitive=False)(input, snapshot)
+ if input.review_mode == REVIEW_MODE_FULL
+ else []
+ )
outcome = await deduplicate_issues(
team_id=input.team_id,
user_id=input.user_id,
issues=issues,
pr_metadata=snapshot.pr_metadata,
- pr_comments=snapshot.pr_comments,
+ pr_comments=pr_comments,
prior_findings=prior_findings,
branch=input.branch,
repository=input.repository,
workflow_id_prefix=_sandbox_workflow_id_prefix("dedup"),
)
survivors = outcome.kept
+ raised_elsewhere = already_raised(outcome.duplicates, pr_comments)
issue_ids = await database_sync_to_async(replace_deduplicated_findings, thread_sensitive=False)(
team_id=input.team_id,
report_id=input.report_id,
@@ -1540,7 +1582,12 @@ async def dedup_activity(input: SandboxStageInput) -> DedupResult:
run_index=input.run_index,
)
await _refresh_status_comment(input.team_id, input.report_id, input.review_mode, input.review_design)
- return DedupResult(issue_ids=issue_ids, flash_stats=flash_stats)
+ return DedupResult(
+ issue_ids=issue_ids,
+ flash_stats=flash_stats,
+ raised_elsewhere=raised_elsewhere[:ALREADY_RAISED_SHOWN],
+ raised_elsewhere_count=len(raised_elsewhere),
+ )
# --- Validate (per-chunk warm-session fan-out) -----------------------------------------------------
diff --git a/products/review_hog/backend/temporal/scheduling.py b/products/review_hog/backend/temporal/scheduling.py
index 3142bd0b3431..095e85376c70 100644
--- a/products/review_hog/backend/temporal/scheduling.py
+++ b/products/review_hog/backend/temporal/scheduling.py
@@ -38,7 +38,6 @@ class ReviewRequestQueue:
and request.publish == self.active.publish
and request.acting_user_id == self.active.acting_user_id
and request.resolve_comments == self.active.resolve_comments
- and request.dedupe_against_pr_comments == self.active.dedupe_against_pr_comments
and (request.trigger_source == TRIGGER_AUTOMATIC) == (self.active.trigger_source == TRIGGER_AUTOMATIC)
):
return
diff --git a/products/review_hog/backend/temporal/types.py b/products/review_hog/backend/temporal/types.py
index 9d3ccfb1d0ca..1706485065dd 100644
--- a/products/review_hog/backend/temporal/types.py
+++ b/products/review_hog/backend/temporal/types.py
@@ -75,9 +75,6 @@ class ReviewPRWorkflowInputs:
# payloads from before the field still deserialize as full reviews.
review_mode: str = REVIEW_MODE_FULL
requested_head_sha: str | None = None
- # Off by default, so a review posts what it finds whatever other comments on the PR say. A trigger that
- # asks for only the findings not on the PR yet turns it on.
- dedupe_against_pr_comments: bool = False
@property
def repository(self) -> str:
diff --git a/products/review_hog/backend/temporal/workflow.py b/products/review_hog/backend/temporal/workflow.py
index 2722d4cc10b4..dc7e3e13f01b 100644
--- a/products/review_hog/backend/temporal/workflow.py
+++ b/products/review_hog/backend/temporal/workflow.py
@@ -686,7 +686,6 @@ class ReviewPRWorkflow:
review_mode=inputs.review_mode,
flash_reasoning_effort=acting.flash_reasoning_effort,
review_design=review_design,
- dedupe_against_pr_comments=inputs.dedupe_against_pr_comments,
)
if review_design == REVIEW_DESIGN_SINGLE_AGENT:
@@ -861,11 +860,8 @@ class ReviewPRWorkflow:
celebrate_clean_reviews=acting.celebrate_clean_reviews,
marker=marker,
capped_lens_parts=meta.lens_chunk_count if meta.lens_chunks_capped else None,
- already_raised=(
- dedup.flash_stats.dropped.get("dedup_comment", 0)
- if dedup is not None and dedup.flash_stats is not None
- else 0
- ),
+ raised_elsewhere=dedup.raised_elsewhere if dedup is not None else [],
+ raised_elsewhere_count=dedup.raised_elsewhere_count if dedup is not None else 0,
),
start_to_close_timeout=_QUICK_TIMEOUT,
retry_policy=_RETRY,
diff --git a/products/review_hog/backend/tests/test_constants.py b/products/review_hog/backend/tests/test_constants.py
index f34286f62e7f..3cef42cd065e 100644
--- a/products/review_hog/backend/tests/test_constants.py
+++ b/products/review_hog/backend/tests/test_constants.py
@@ -72,8 +72,8 @@ class TestSelectReviewDesign:
[
# Dashboards split Flash by version, so a v2 turn must never report the v1 id or the reverse.
("flash_single_agent", REVIEW_MODE_FLASH, REVIEW_DESIGN_SINGLE_AGENT, "reviewhog-flash-2-2"),
- ("flash_pipeline", REVIEW_MODE_FLASH, REVIEW_DESIGN_PIPELINE, "reviewhog-flash-1-2"),
- ("full_pipeline", REVIEW_MODE_FULL, REVIEW_DESIGN_PIPELINE, "reviewhog-full-1-2"),
+ ("flash_pipeline", REVIEW_MODE_FLASH, REVIEW_DESIGN_PIPELINE, "reviewhog-flash-1-3"),
+ ("full_pipeline", REVIEW_MODE_FULL, REVIEW_DESIGN_PIPELINE, "reviewhog-full-1-3"),
]
)
def test_version_id_depends_on_mode_and_design(
diff --git a/products/review_hog/backend/tests/test_review_activity.py b/products/review_hog/backend/tests/test_review_activity.py
index 069445f4037a..c849f1c73842 100644
--- a/products/review_hog/backend/tests/test_review_activity.py
+++ b/products/review_hog/backend/tests/test_review_activity.py
@@ -21,7 +21,7 @@ from products.review_hog.backend.reviewer.constants import (
ReviewArm,
review_arm_for_mode,
)
-from products.review_hog.backend.reviewer.models.github_meta import PRFile, PRMetadata
+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 (
ChunkPerspectiveSelection,
@@ -37,6 +37,7 @@ from products.review_hog.backend.temporal.activities import (
ReviewChunkInput,
SandboxStageInput,
SelectPerspectivesInput,
+ _current_pr_comments,
lens_review_activity,
review_chunk_activity,
select_perspectives_activity,
@@ -591,3 +592,39 @@ async def test_single_agent_session_persists_mapped_findings_under_the_arm_dedup
(IssuePriority.SHOULD_FIX, "P2", [LineRange(start=12)], None, expected_source),
(IssuePriority.CONSIDER, "P3", [LineRange(start=9)], None, expected_source),
]
+
+
+def _comment(comment_id: int, line: int | None) -> PRComment:
+ return PRComment(id=comment_id, path="a.py", line=line, body="x", diff_hunk="", user="other-bot", created_at="c")
+
+
+ "fetch_fails,current_head,expected_ids",
+ [
+ pytest.param(False, "sha1", [2, 1], id="the_new_read_adds_new_comments_and_drops_deleted_ones"),
+ pytest.param(True, "sha1", [1, 4], id="keeps_the_first_read_when_github_fails"),
+ pytest.param(False, "sha2", [1, 4], id="keeps_the_first_read_after_a_push_during_the_turn"),
+ ],
+)
+def test_full_dedup_reads_current_comments_without_outdated_ones(
+ fetch_fails: bool, current_head: str, expected_ids: list[int]
+) -> None:
+ # Other bots often post while a Full turn runs, so a start-of-turn read misses what they raise, and a comment
+ # deleted meanwhile must not keep a finding off the PR. A comment GitHub no longer places on a line is about
+ # code that changed, so it must not suppress a finding either. After a push during the turn, GitHub places
+ # comments on code the turn did not review, so the first read stays.
+ snapshot = _snapshot().model_copy(update={"pr_comments": [_comment(1, 10), _comment(3, None), _comment(4, 30)]})
+ fetcher = MagicMock()
+ fetcher.return_value.fetch_pr_comments.return_value = [_comment(2, 20), _comment(1, 10)]
+ fetcher.return_value.fetch_head_sha.return_value = current_head
+ with (
+ patch(
+ f"{_MODULE}._installation_auth",
+ side_effect=RuntimeError("no installation") if fetch_fails else None,
+ return_value=("tok", None),
+ ),
+ patch(f"{_MODULE}.PRFetcher", fetcher),
+ ):
+ comments = _current_pr_comments(SandboxStageInput(**_single_agent_stage()), snapshot)
+
+ assert [comment.id for comment in comments] == expected_ids
diff --git a/products/review_hog/backend/tests/test_review_scheduling.py b/products/review_hog/backend/tests/test_review_scheduling.py
index f7b3944af22b..9cf3a27c6d69 100644
--- a/products/review_hog/backend/tests/test_review_scheduling.py
+++ b/products/review_hog/backend/tests/test_review_scheduling.py
@@ -141,12 +141,9 @@ async def test_automatic_review_waits_for_resolution_before_starting() -> None:
assert probes == 2
- "resolve_comments,dedupe_against_pr_comments,expect_pending",
- [(False, False, False), (None, False, True), (False, True, True)],
-)
-def test_a_repeated_request_waits_when_it_changes_what_the_review_does(
- resolve_comments: bool | None, dedupe_against_pr_comments: bool, expect_pending: bool
[email protected]("resolve_comments,expect_pending", [(False, False), (None, True)])
+def test_a_repeated_full_request_waits_when_it_changes_comment_resolution(
+ resolve_comments: bool | None, expect_pending: bool
) -> None:
active = ReviewPRWorkflowInputs(
team_id=1,
@@ -161,7 +158,7 @@ def test_a_repeated_request_waits_when_it_changes_what_the_review_does(
acting_user_id=1,
resolve_comments=False,
)
- request = replace(active, resolve_comments=resolve_comments, dedupe_against_pr_comments=dedupe_against_pr_comments)
+ request = replace(active, resolve_comments=resolve_comments)
queue = ReviewRequestQueue(active=active)
queue.add(request)
diff --git a/products/review_hog/backend/tests/test_status_comment.py b/products/review_hog/backend/tests/test_status_comment.py
index 82fa15c4ae96..3585aec53d3d 100644
--- a/products/review_hog/backend/tests/test_status_comment.py
+++ b/products/review_hog/backend/tests/test_status_comment.py
@@ -32,6 +32,7 @@ from products.review_hog.backend.reviewer.status_comment import (
status_marker,
update_resolution_status_comment,
)
+from products.review_hog.backend.reviewer.tools.issue_deduplicator import AlreadyRaised
from products.review_hog.backend.temporal.activities import _fail_run
_MODULE = "products.review_hog.backend.reviewer.status_comment"
@@ -241,21 +242,14 @@ class TestRenderFinalBody:
@parameterized.expand(
[
- # A clean turn posts no review, so the status comment is the only place a note can appear.
- ("clean_large_pr", 0, 4, 0, True, False),
- ("large_pr_with_findings", 2, 4, 0, True, False),
- ("normal_pr", 2, None, 0, False, False),
- ("clean_additional_review", 0, None, 2, False, True),
+ # A clean turn posts no review, so the status comment is the only place the note can appear.
+ ("clean_large_pr", 0, 4, True),
+ ("large_pr_with_findings", 2, 4, True),
+ ("normal_pr", 2, None, False),
]
)
- def test_turn_notes_show_whether_or_not_a_review_posts(
- self,
- _name: str,
- must_fix: int,
- capped_lens_parts: int | None,
- already_raised: int,
- expect_large_note: bool,
- expect_skipped_note: bool,
+ def test_large_pr_note_shows_whether_or_not_a_review_posts(
+ self, _name: str, must_fix: int, capped_lens_parts: int | None, expect_note: bool
) -> None:
body = render_final_body(
"rid",
@@ -266,12 +260,39 @@ class TestRenderFinalBody:
review_url=None,
review_mode=REVIEW_MODE_FLASH,
capped_lens_parts=capped_lens_parts,
- already_raised=already_raised,
)
- large_note = "This pull request is large, so the review ran in 4 parts with less depth than usual."
- skipped_note = "Skipped 2 findings that other comments on this pull request already raise."
- assert ((large_note in body), (skipped_note in body)) == (expect_large_note, expect_skipped_note)
+ note = "This pull request is large, so the review ran in 4 parts with less depth than usual."
+ assert (note in body) is expect_note
+
+ @parameterized.expand([("clean_turn", 0, "Nothing new to raise."), ("turn_with_findings", 1, "Found ")])
+ def test_full_lists_what_other_comments_already_raise(self, _name: str, must_fix: int, opening: str) -> None:
+ raised = [
+ AlreadyRaised(title=f"Problem {n}", level="P2", comment_id=100 + n, commenter="greptile-apps[bot]")
+ for n in range(12)
+ ]
+
+ body = render_final_body(
+ "rid",
+ counts={IssuePriority.MUST_FIX: must_fix, IssuePriority.SHOULD_FIX: 0, IssuePriority.CONSIDER: 0},
+ published_count=must_fix,
+ held_back_count=0,
+ threshold=IssuePriority.SHOULD_FIX,
+ review_url=None,
+ raised_elsewhere=raised[:10],
+ raised_elsewhere_count=len(raised),
+ pr_url="https://github.com/o/r/pull/7",
+ )
+
+ # A Full turn that only repeated other reviewers must say so instead of celebrating a clean PR.
+ assert opening in body
+ assert "Enjoy the moment" not in body
+ assert (
+ "- **P2 · Problem 0**, raised by `greptile-apps[bot]` ([comment](https://github.com/o/r/pull/7#discussion_r100))"
+ in body
+ )
+ assert "Problem 10" not in body
+ assert "- and 2 more" in body
def _pr_metadata(pr_number: int = 123) -> PRMetadata:
@@ -454,6 +475,7 @@ class TestFinalizeStatusComment(BaseTest):
for issue, validation in verdicts:
persist_verdict(team_id=self.team.id, report_id=report_id, issue=issue, validation=validation, run_index=1)
+ leaked = "ghs_" + "a" * 36
finalize_status_comment(
FinalizeStatusCommentInput(
team_id=self.team.id,
@@ -461,12 +483,19 @@ class TestFinalizeStatusComment(BaseTest):
run_index=1,
urgency_threshold=IssuePriority.SHOULD_FIX.value,
review_url="https://g/review",
+ raised_elsewhere=[
+ AlreadyRaised(title=f"Token {leaked} leaks", level="P1", comment_id=9, commenter="other[bot]")
+ ],
+ raised_elsewhere_count=1,
)
)
assert _patches(mock_request) == ["/repos/o/r/issues/comments/555"]
body = mock_request.call_args.kwargs["json"]["body"]
assert "Found **1 must fix**, **0 should fix**, **2 consider**" in body
+ # Titles in the already-raised list are model text, so a token quoted from sandbox output must not post.
+ assert leaked not in body
+ assert "**P1 · Token [redacted] leaks**" in body
assert "Published 1 finding ([view the review](https://g/review))" in body
assert '2 findings stayed below the author\'s "Should fix" urgency threshold' in body
# The held-back link into the app. `?review=<report id>` is a permanent public contract