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): cut the review body to a severity tally (#81739)

Alex Lebedev76bdef36b71f
diff --git a/products/review_hog/ARCHITECTURE.md b/products/review_hog/ARCHITECTURE.md
index 1109c1da1b54..fd8418c616b1 100644
--- a/products/review_hog/ARCHITECTURE.md
+++ b/products/review_hog/ARCHITECTURE.md
@@ -197,10 +197,12 @@ pr_metadata.head_branch` is threaded (as explicit kwargs, alongside `team_id` /
re-researches only the pending ones. The keep/drop **criteria are pulled, not baked**: the prompt instructs the
agent to `skill-get` the team's `review-hog-validation-criteria` skill (version pinned by
`load_validation_skill_for_run`), so the bar for "this issue matters" is team-owned, like the perspectives.
-9. **Build report + finalize** — `build_review_body(chunks, issues, validations, pr_files)` renders the public body
- in-process (verdicts sourced from the DB via `load_run_validations`, the same rows publish reads); chunks with
- no validated finding are skipped, and valid `MUST_FIX`/`SHOULD_FIX` findings whose line isn't on the diff are
- appended as an **"Other findings (outside the changed lines)"** section so they aren't silently dropped at publish.
+9. **Build report + finalize** — `build_review_body(issues, validations, pr_files)` renders the public body
+ in-process (verdicts sourced from the DB via `load_run_validations`, the same rows publish reads). The body is
+ **one line: how many findings this turn publishes, by severity** ("Found **2 must fix**, **1 consider**.") —
+ no chunk walk, no file inventory, no summary of the diff, because nobody reads one. Valid `MUST_FIX`/`SHOULD_FIX`
+ findings whose line isn't on the diff are still appended as an **"Other findings (outside the changed lines)"**
+ section so they aren't silently dropped at publish.
`finalize_review_report` stores it as `ReviewReport.report_markdown` and bumps the run watermark.
10. **Publish** — `publish_review` (GitHub REST via the gated egress transport, **DB-driven**) reads the body from
`ReviewReport.report_markdown` and the inline comments from the valid finding/verdict rows (`load_valid_findings`),
@@ -346,17 +348,16 @@ All Pydantic. `models/__init__.py` is the authoritative registry that generates
`schema.json` files from `Model.model_json_schema()` — **`schema.json` files are generated artifacts; edit
the model and regenerate, never hand-edit.**
-| Model | File | Schema-backed? | Role |
-| ---------------------------------------------------------------------------- | --------------------------------------- | --------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
-| `ChunksList` / `Chunk` / `FileInfo` | `models/split_pr_into_chunks.py` | ✅ chunking | PR → reviewable chunks (`chunk_type`, `key_changes`) |
-| `Issue` / `IssuesReview` / `LineRange` / `IssuePriority` / `PerspectiveType` | `models/issues_review.py` | ✅ issues_review (`IssuesReview`) | **`Issue` is the shared currency** of the dedup → validate → publish stages; `Issue.source_perspective` records which perspective found it |
-| `IssueDeduplication` / `DuplicateIssue` | `models/issue_deduplicator.py` | ✅ issue_deduplicator | ids of issues to drop |
-| `IssueValidation` | `models/issue_validation.py` | ✅ issue_validation | `is_valid` + `category` (+ optional `adjusted_priority`) per issue |
-| `ValidationMarkdownReport*` | `models/prepare_validation_markdown.py` | — internal | report tree (Chunk × Issue) |
-| `PRMetadata` / `PRComment` / `PRFile` / `PRFileUpdate` | `models/github_meta.py` | — internal | raw GitHub ingestion |
+| Model | File | Schema-backed? | Role |
+| ---------------------------------------------------------------------------- | -------------------------------- | --------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
+| `ChunksList` / `Chunk` / `FileInfo` | `models/split_pr_into_chunks.py` | ✅ chunking | PR → reviewable chunks (`chunk_type`, `key_changes`) |
+| `Issue` / `IssuesReview` / `LineRange` / `IssuePriority` / `PerspectiveType` | `models/issues_review.py` | ✅ issues_review (`IssuesReview`) | **`Issue` is the shared currency** of the dedup → validate → publish stages; `Issue.source_perspective` records which perspective found it |
+| `IssueDeduplication` / `DuplicateIssue` | `models/issue_deduplicator.py` | ✅ issue_deduplicator | ids of issues to drop |
+| `IssueValidation` | `models/issue_validation.py` | ✅ issue_validation | `is_valid` + `category` (+ optional `adjusted_priority`) per issue |
+| `PRMetadata` / `PRComment` / `PRFile` / `PRFileUpdate` | `models/github_meta.py` | — internal | raw GitHub ingestion |
`Issue.id` encodes provenance as `"{pass_number}-{chunk_id}-{issue_number}"` and is parsed back throughout
-the pipeline to route validations and group the report. `IssuePriority` is `MUST_FIX` / `SHOULD_FIX` /
+the pipeline to route validations. `IssuePriority` is `MUST_FIX` / `SHOULD_FIX` /
`CONSIDER`. The validator may override a finding's priority via `adjusted_priority` (validator-wins, resolved at
read time by `effective_priority`); see [DECISIONS.md](./DECISIONS.md).
diff --git a/products/review_hog/DECISIONS.md b/products/review_hog/DECISIONS.md
index 3c782f5c4ab3..5649f3141daa 100644
--- a/products/review_hog/DECISIONS.md
+++ b/products/review_hog/DECISIONS.md
@@ -198,6 +198,33 @@ 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-08-12 — review body cut to a severity tally (the chunk summary is gone)
+
+The published body opened with a walk of the chunk tree: a `## <chunk type>` heading per chunk, an `Issues: N`
+line, a collapsed file list, and a collapsed "What were the main changes" block built from the chunker's
+`key_changes`. It was the longest part of a review and the least read — a machine-written summary of a diff the
+author had just written, in front of the findings they actually came for. Sentiment across the company on
+LLM-written PR prose is blunt: people skip it. Decisions:
+
+- **The body is one line: `Found **2 must fix**, **1 consider**.`** Only severities with a non-zero count
+ appear, most urgent first (`PRIORITIES_BY_URGENCY`), and the tally counts exactly what publishes — valid
+ findings at or above the acting user's threshold, bucketed by **effective** (validator-wins) priority. An
+ empty tally renders "No issues to report." (defensive: publish self-skips with nothing publishable, but the
+ body is also stored and shown in the UI for store-only runs).
+- **Labels are shared, not duplicated.** `PRIORITY_LABELS` + `PRIORITIES_BY_URGENCY` moved to `constants.py`,
+ so the body and the status comment's found-counts line can't drift into two vocabularies.
+- **What deliberately stayed:** the `# ReviewHog Report` title (the report's identity in the UI and in the
+ publish test's marker assertions) and the "Other findings (outside the changed lines)" section — that one
+ isn't a summary, it's the only place off-diff findings surface at all.
+- **The chunk tree left the renderer entirely.** `_assemble_report` and
+ `models/prepare_validation_markdown.py` (`ValidationMarkdownReport*`) are deleted, and `build_review_body`
+ no longer takes `chunks_data` — so `_build_and_finalize` drops its `load_chunk_set` call. The chunker's
+ `chunk_type` / `key_changes` are untouched: perspective selection still reads them, and the pipeline-trace UI
+ still shows the chunks. Only the PR-facing prose was the problem.
+- Rejected: keeping the summary behind a `<details>` (still the first thing in the review, still written for
+ nobody), and shortening it with another LLM call (paying per review to generate text we just established
+ people skip).
+
### ✅ BUILT 2026-07-27 — reviews surface exposed as MCP tools (grantable `review_hog` scope)
Agents needed to drive ReviewHog over MCP — kick off a review, poll progress, pull the finished findings
diff --git a/products/review_hog/backend/management/commands/publish_review.py b/products/review_hog/backend/management/commands/publish_review.py
index e4b3e216c353..4f3c69a766b3 100644
--- a/products/review_hog/backend/management/commands/publish_review.py
+++ b/products/review_hog/backend/management/commands/publish_review.py
@@ -8,6 +8,7 @@ from posthog.models.integration import GitHubIntegration
from products.review_hog.backend.models import ReviewReport
from products.review_hog.backend.reviewer.constants import DEFAULT_URGENCY_THRESHOLD
+from products.review_hog.backend.reviewer.models.issues_review import IssuePriority
from products.review_hog.backend.reviewer.tools.github_client import GitHubAPIError, github_api_request
from products.review_hog.backend.reviewer.tools.github_meta import PRParser
from products.review_hog.backend.reviewer.tools.publish_review import publish_persisted_review
@@ -38,6 +39,14 @@ def _stale_head_warning(
)
+def _run_threshold(stamped: str | None) -> IssuePriority:
+ """The threshold the run was finalized under; the default for pre-column or unrecognized values."""
+ try:
+ return IssuePriority(stamped)
+ except ValueError:
+ return DEFAULT_URGENCY_THRESHOLD
+
+
class Command(BaseCommand):
help = "Publish an already-computed ReviewHog review to its PR (no re-review, no sandbox cost)."
@@ -88,9 +97,10 @@ class Command(BaseCommand):
f"ReviewHog ▶ publishing {repository}#{pr_number} · report {report.id} · head {head_sha[:12]}"
)
)
- # A local-only ops command: always the default threshold (consider), not a per-user one —
- # keeps the frozen body and the freshly built inline comments consistent without needing to
- # track which threshold the run itself used.
+ # Republish under the threshold the run itself used (stamped at finalize): the stored body's
+ # severity tally was rendered against it, so the freshly built inline comments have to be gated
+ # by the same set or the tally and the posted comments disagree. Rows from before the column
+ # existed, or an unrecognized value, fall back to the default.
outcome = publish_persisted_review(
team_id=team_id,
report_id=str(report.id),
@@ -100,7 +110,7 @@ class Command(BaseCommand):
repo=repo,
pr_number=pr_number,
token=token,
- urgency_threshold=DEFAULT_URGENCY_THRESHOLD,
+ urgency_threshold=_run_threshold(report.run_urgency_threshold),
installation_id=installation_id,
)
if outcome.posted:
diff --git a/products/review_hog/backend/reviewer/constants.py b/products/review_hog/backend/reviewer/constants.py
index 3df529ea23da..475dec81ec70 100644
--- a/products/review_hog/backend/reviewer/constants.py
+++ b/products/review_hog/backend/reviewer/constants.py
@@ -158,6 +158,17 @@ _PRIORITY_RANK = {IssuePriority.CONSIDER: 0, IssuePriority.SHOULD_FIX: 1, IssueP
# The threshold applied when no per-user setting is available (matches `ReviewUserSettings`' default).
DEFAULT_URGENCY_THRESHOLD = IssuePriority.CONSIDER
+# Severities most urgent first — the order every count breakdown is read in.
+PRIORITIES_BY_URGENCY = (IssuePriority.MUST_FIX, IssuePriority.SHOULD_FIX, IssuePriority.CONSIDER)
+
+# Human-readable severity labels, shared by the PR-facing renderers (the review body and the status
+# comment) so their count lines read the same.
+PRIORITY_LABELS = {
+ IssuePriority.MUST_FIX: "must fix",
+ IssuePriority.SHOULD_FIX: "should fix",
+ IssuePriority.CONSIDER: "consider",
+}
+
def published_priorities_for(threshold: IssuePriority) -> set[IssuePriority]:
"""Priorities at or above the acting user's urgency threshold — the set that gates publishing.
diff --git a/products/review_hog/backend/reviewer/models/prepare_validation_markdown.py b/products/review_hog/backend/reviewer/models/prepare_validation_markdown.py
deleted file mode 100755
index e894b14c7f32..000000000000
--- a/products/review_hog/backend/reviewer/models/prepare_validation_markdown.py
+++ /dev/null
@@ -1,20 +0,0 @@
-from pydantic import BaseModel, Field
-
-from products.review_hog.backend.reviewer.models.issues_review import Issue, IssuePriority
-from products.review_hog.backend.reviewer.models.split_pr_into_chunks import Chunk
-
-
-class ValidationMarkdownReportIssue(BaseModel):
- issue: Issue = Field(description="The issue that was validated")
- effective_priority: IssuePriority = Field(
- description="The issue's priority after the validator's override (validator-wins), used for the chunk count"
- )
-
-
-class ValidationMarkdownReportChunk(BaseModel):
- chunk: Chunk = Field(description="The chunk containing the issue")
- validated_issues: list[ValidationMarkdownReportIssue] = Field(description="The issues that were validated")
-
-
-class ValidationMarkdownReport(BaseModel):
- chunks: list[ValidationMarkdownReportChunk] = Field(description="The chunks that were validated")
diff --git a/products/review_hog/backend/reviewer/status_comment.py b/products/review_hog/backend/reviewer/status_comment.py
index 09e57c9b6b0a..3b8578a3e4e9 100644
--- a/products/review_hog/backend/reviewer/status_comment.py
+++ b/products/review_hog/backend/reviewer/status_comment.py
@@ -23,7 +23,12 @@ from django.utils import timezone
from posthog.models.integration import GitHubIntegration
from products.review_hog.backend.models import ReviewReport
-from products.review_hog.backend.reviewer.constants import effective_priority, published_priorities_for
+from products.review_hog.backend.reviewer.constants import (
+ PRIORITIES_BY_URGENCY,
+ PRIORITY_LABELS,
+ effective_priority,
+ published_priorities_for,
+)
from products.review_hog.backend.reviewer.models.issues_review import IssuePriority
from products.review_hog.backend.reviewer.persistence import load_findings_bundle, load_valid_findings
from products.review_hog.backend.reviewer.progress import (
@@ -78,12 +83,6 @@ _THRESHOLD_ATTRIBUTIONS = {
# Only personal thresholds live in someone's ReviewHog settings; the default variant has no page to point at.
_PERSONAL_THRESHOLD_SOURCES = frozenset({"author", "override"})
-_PRIORITY_LABELS = {
- IssuePriority.MUST_FIX: "must fix",
- IssuePriority.SHOULD_FIX: "should fix",
- IssuePriority.CONSIDER: "consider",
-}
-
# A clean review deserves a reward, not a bare "nothing here". We still post the comment (so "no
# comment" can never be mistaken for "the run broke"), but swap the flat sign-off for calming media.
# Assets are optimized and self-hosted on pr-assets (SHA-pinned, permanent) rather than hotlinked.
@@ -168,8 +167,7 @@ def render_final_body(
"""
found_total = sum(counts.values())
found_line = "Found " + ", ".join(
- f"**{counts[priority]} {_PRIORITY_LABELS[priority]}**"
- for priority in (IssuePriority.MUST_FIX, IssuePriority.SHOULD_FIX, IssuePriority.CONSIDER)
+ f"**{counts[priority]} {PRIORITY_LABELS[priority]}**" for priority in PRIORITIES_BY_URGENCY
)
lines = ["### \U0001f994 ReviewHog reviewed this pull request", ""]
if found_total == 0:
diff --git a/products/review_hog/backend/reviewer/tests/test_prepare_validation_markdown.py b/products/review_hog/backend/reviewer/tests/test_prepare_validation_markdown.py
index f77a1093359b..f315e9083564 100644
--- a/products/review_hog/backend/reviewer/tests/test_prepare_validation_markdown.py
+++ b/products/review_hog/backend/reviewer/tests/test_prepare_validation_markdown.py
@@ -4,7 +4,6 @@ from products.review_hog.backend.reviewer.constants import published_priorities_
from products.review_hog.backend.reviewer.models.github_meta import PRFile, PRFileUpdate
from products.review_hog.backend.reviewer.models.issue_validation import IssueValidation
from products.review_hog.backend.reviewer.models.issues_review import Issue, IssuePriority, LineRange
-from products.review_hog.backend.reviewer.models.split_pr_into_chunks import Chunk, ChunksList, FileInfo
from products.review_hog.backend.reviewer.tools.prepare_validation_markdown import build_review_body
# The should_fix threshold: publishes should_fix and must_fix, drops consider. These tests use it to
@@ -24,10 +23,6 @@ def _issue(issue_id: str, priority: IssuePriority = IssuePriority.MUST_FIX) -> I
)
-def _chunk(chunk_id: int, chunk_type: str) -> Chunk:
- return Chunk(chunk_id=chunk_id, files=[FileInfo(filename="src/auth.py")], chunk_type=chunk_type, key_changes=[])
-
-
def _pr_files() -> list[PRFile]:
# The reviewed diff touches lines 1-2 of src/auth.py, so a finding there is on-diff (inline-able).
return [
@@ -41,46 +36,51 @@ def _pr_files() -> list[PRFile]:
]
-def test_only_validated_issues_count_and_chunk_appears() -> None:
- # One valid + one invalid issue on the same chunk: the body shows the chunk (with a humanized
- # header) and counts only the valid one.
- chunks_data = ChunksList(chunks=[_chunk(1, "business_logic")])
- issues = [_issue("1-1-1"), _issue("1-1-2")]
+ "findings,expected_line",
+ [
+ # Only findings the validator ruled valid are tallied.
+ (
+ [(IssuePriority.MUST_FIX, None, True), (IssuePriority.MUST_FIX, None, False)],
+ "Found **1 must fix**.",
+ ),
+ # Severities read most urgent first, and consider sits below the threshold so it never counts.
+ (
+ [
+ (IssuePriority.CONSIDER, None, True),
+ (IssuePriority.SHOULD_FIX, None, True),
+ (IssuePriority.MUST_FIX, None, True),
+ ],
+ "Found **1 must fix**, **1 should fix**.",
+ ),
+ # Validator-wins: an upgrade joins the tally under its new severity.
+ ([(IssuePriority.CONSIDER, IssuePriority.SHOULD_FIX, True)], "Found **1 should fix**."),
+ # And a downgrade below the threshold leaves nothing to publish.
+ ([(IssuePriority.SHOULD_FIX, IssuePriority.CONSIDER, True)], "No issues to report."),
+ ],
+)
+def test_body_tallies_publishable_findings_by_severity(
+ findings: list[tuple[IssuePriority, IssuePriority | None, bool]], expected_line: str
+) -> None:
+ # The body is a severity tally, so its one line has to count exactly what gets published: valid
+ # findings at or above the acting user's threshold, bucketed by EFFECTIVE (validator-wins) severity.
+ # A miscount here is the whole message being wrong. Asserting the WHOLE body (on-diff lines keep the
+ # off-diff section out) also guards the point of the tally: no chunk headers, file lists, or diff
+ # narrative creeping back in.
+ issues = [_issue(f"1-1-{index}", priority=priority) for index, (priority, _, _) in enumerate(findings)]
validations = {
- "1-1-1": IssueValidation(is_valid=True, argumentation="real bug", category="bug"),
- "1-1-2": IssueValidation(is_valid=False, argumentation="not a bug", category="code_quality"),
+ issue.id: IssueValidation(is_valid=is_valid, argumentation="reason", category="bug", adjusted_priority=adjusted)
+ for issue, (_, adjusted, is_valid) in zip(issues, findings)
}
body = build_review_body(
- chunks_data=chunks_data,
- issues=issues,
- validations=validations,
- pr_files=_pr_files(),
- published_priorities=_SHOULD_FIX_PUBLISHED,
- )
-
- assert "# ReviewHog Report" in body
- assert "## Business logic" in body # chunk_type humanized into the header
- assert "**Issues:** 1 issue" in body # only the valid issue counts
-
-
-def test_chunk_with_no_valid_issue_is_skipped() -> None:
- # chunk 2 has no validated issue, so it must not clutter the body (which summarizes findings, not
- # coverage); chunk 1 has a valid finding and appears.
- chunks_data = ChunksList(chunks=[_chunk(1, "bugfix"), _chunk(2, "frontend")])
- issues = [_issue("1-1-1")]
- validations = {"1-1-1": IssueValidation(is_valid=True, argumentation="real", category="bug")}
-
- body = build_review_body(
- chunks_data=chunks_data,
issues=issues,
validations=validations,
pr_files=_pr_files(),
published_priorities=_SHOULD_FIX_PUBLISHED,
)
- assert "## Bugfix" in body
- assert "## Frontend" not in body
+ assert body == f"# ReviewHog Report\n\n{expected_line}\n"
@pytest.mark.parametrize(
@@ -106,8 +106,7 @@ def test_other_findings_section_membership(
# (validator-wins) is must/should-fix and which have no inline anchor (off-diff) — so an off-diff
# valid finding isn't silently dropped at publish, while consider / invalid / on-diff findings don't
# leak in, and a validator upgrade/downgrade moves the finding in or out. The title renders only in
- # this section (the per-chunk summary lists no titles), so its presence is the membership signal.
- chunks_data = ChunksList(chunks=[_chunk(1, "bugfix")])
+ # this section (the tally lists no titles), so its presence is the membership signal.
issue = Issue(
id="1-1-1",
title="Membership marker finding",
@@ -124,7 +123,6 @@ def test_other_findings_section_membership(
}
body = build_review_body(
- chunks_data=chunks_data,
issues=[issue],
validations=validations,
pr_files=_pr_files(),
@@ -139,7 +137,6 @@ def test_off_diff_finding_sections_lead_with_validation() -> None:
# the inline comment (verdict first, then description, then fix). The two renderers are separate
# templates, so the inline-comment order test can't catch _render_off_diff_section flipping back
# to description-first.
- chunks_data = ChunksList(chunks=[_chunk(1, "bugfix")])
issue = Issue(
id="1-1-1",
title="Off-diff finding",
@@ -152,7 +149,6 @@ def test_off_diff_finding_sections_lead_with_validation() -> None:
validations = {"1-1-1": IssueValidation(is_valid=True, argumentation="verified", category="bug")}
body = build_review_body(
- chunks_data=chunks_data,
issues=[issue],
validations=validations,
pr_files=_pr_files(),
@@ -164,36 +160,3 @@ def test_off_diff_finding_sections_lead_with_validation() -> None:
for label in ("Why we think it's a valid issue", "Issue description", "Suggested fix")
]
assert positions == sorted(positions)
-
-
- "base,adjusted,expected_count_line",
- [
- (IssuePriority.CONSIDER, IssuePriority.SHOULD_FIX, "**Issues:** 1 issue"), # upgrade joins the count
- (IssuePriority.SHOULD_FIX, IssuePriority.CONSIDER, None), # downgrade drops out of the count
- ],
-)
-def test_chunk_count_reflects_effective_priority(
- base: IssuePriority, adjusted: IssuePriority, expected_count_line: str | None
-) -> None:
- # The per-chunk "Issues: N" count must reflect the validator's override, not the reviewer's frozen
- # priority — a finding downgraded to consider stops counting, an upgraded one starts. Uses an
- # on-diff line so the off-diff section never interferes with the count signal.
- chunks_data = ChunksList(chunks=[_chunk(1, "bugfix")])
- issue = _issue("1-1-1", priority=base)
- validations = {
- "1-1-1": IssueValidation(is_valid=True, argumentation="reason", category="bug", adjusted_priority=adjusted)
- }
-
- body = build_review_body(
- chunks_data=chunks_data,
- issues=[issue],
- validations=validations,
- pr_files=_pr_files(),
- published_priorities=_SHOULD_FIX_PUBLISHED,
- )
-
- if expected_count_line is None:
- assert "**Issues:**" not in body
- else:
- assert expected_count_line in body
diff --git a/products/review_hog/backend/reviewer/tests/test_split_pr_into_chunks.py b/products/review_hog/backend/reviewer/tests/test_split_pr_into_chunks.py
index 184880e8f05d..8b05bb409e76 100644
--- a/products/review_hog/backend/reviewer/tests/test_split_pr_into_chunks.py
+++ b/products/review_hog/backend/reviewer/tests/test_split_pr_into_chunks.py
@@ -147,7 +147,7 @@ class TestPlanDeterministicChunks:
def test_single_chunk_holds_all_files_with_neutral_metadata(self) -> None:
# The deterministic chunk gathers every reviewable file under chunk_id 1 with no LLM-derived
- # type/key_changes, so the downstream body renderer falls back to its generic heading.
+ # type/key_changes, so perspective selection reads it from the file list alone.
planned = plan_deterministic_chunks([_file("a.py", 10), _file("b.py", 20)])
assert planned is not None
diff --git a/products/review_hog/backend/reviewer/tools/prepare_validation_markdown.py b/products/review_hog/backend/reviewer/tools/prepare_validation_markdown.py
index 9c4e11fbe187..a626a32976ac 100644
--- a/products/review_hog/backend/reviewer/tools/prepare_validation_markdown.py
+++ b/products/review_hog/backend/reviewer/tools/prepare_validation_markdown.py
@@ -1,14 +1,14 @@
"""Render the PR-facing review body (stored as `ReviewReport.report_markdown` and posted to GitHub).
-Assembles the per-chunk report tree from in-process pipeline objects (chunks, the canonical issues
-and their validations), keeping only validated issues, then renders the high-level summary body. The
-detailed per-issue findings are published as inline comments by `publish_review` (read from the
-durable finding/verdict rows), so the body stays a summary.
+The body opens with a one-line severity tally of the findings this turn publishes. The findings
+themselves go out as inline comments from `publish_review` (read from the durable finding/verdict
+rows), so the tally is all the body says about them — nobody reads a summary of the diff they just
+wrote. The one exception is a finding GitHub can't take an inline comment on: those are written out
+in full in the "Other findings" section below the tally, because the body is the only place they can
+appear at all.
"""
-import logging
-
-from products.review_hog.backend.reviewer.constants import effective_priority
+from products.review_hog.backend.reviewer.constants import PRIORITIES_BY_URGENCY, PRIORITY_LABELS, effective_priority
from products.review_hog.backend.reviewer.diff_position import (
build_diff_line_map,
find_diff_position,
@@ -17,19 +17,10 @@ from products.review_hog.backend.reviewer.diff_position import (
from products.review_hog.backend.reviewer.models.github_meta import PRFile
from products.review_hog.backend.reviewer.models.issue_validation import IssueValidation
from products.review_hog.backend.reviewer.models.issues_review import Issue, IssuePriority
-from products.review_hog.backend.reviewer.models.prepare_validation_markdown import (
- ValidationMarkdownReport,
- ValidationMarkdownReportChunk,
- ValidationMarkdownReportIssue,
-)
-from products.review_hog.backend.reviewer.models.split_pr_into_chunks import ChunksList
-
-logger = logging.getLogger(__name__)
def build_review_body(
*,
- chunks_data: ChunksList,
issues: list[Issue],
validations: dict[str, IssueValidation],
pr_files: list[PRFile],
@@ -38,51 +29,32 @@ def build_review_body(
"""Render the PR-facing review body from this turn's in-process pipeline objects.
`validations` is keyed by the live issue id (`{pass}-{chunk}-{issue}`); only issues the
- validator ruled valid appear in the report. `pr_files` (this turn's reviewed diff) decides which
+ validator ruled valid are counted. `pr_files` (this turn's reviewed diff) decides which
valid findings can't be anchored to an inline comment — those are surfaced in an "Other findings"
section instead of being silently dropped at publish. `published_priorities` is the acting user's
- urgency-threshold set (`published_priorities_for`), shared with the publisher so counts and
- comments agree.
+ urgency-threshold set (`published_priorities_for`), shared with the publisher so the tally and the
+ posted comments agree.
"""
- report = _assemble_report(chunks_data, issues, validations)
+ counts = _published_counts(issues, validations, published_priorities)
off_diff = _off_diff_publishable_findings(issues, validations, pr_files, published_priorities)
- return _render_review_body(report, off_diff, published_priorities)
+ return _render_review_body(counts, off_diff)
-def _assemble_report(
- chunks_data: ChunksList,
+def _published_counts(
issues: list[Issue],
validations: dict[str, IssueValidation],
-) -> ValidationMarkdownReport:
- """Group validated issues under their chunk (keyed via the issue id `{pass}-{chunk}-{issue}`)."""
- issues_by_chunk: dict[int, list[Issue]] = {}
+ published_priorities: set[IssuePriority],
+) -> dict[IssuePriority, int]:
+ """Validated, publishable findings tallied by effective (validator-wins) severity."""
+ counts = dict.fromkeys(IssuePriority, 0)
for issue in issues:
- parts = issue.id.split("-")
- if len(parts) != 3:
- logger.warning(f"Invalid issue ID format: {issue.id}")
- continue
- try:
- chunk_id = int(parts[1])
- except ValueError:
- logger.warning(f"Invalid issue ID format: {issue.id}")
- continue
- issues_by_chunk.setdefault(chunk_id, []).append(issue)
-
- report_chunks: list[ValidationMarkdownReportChunk] = []
- for chunk in chunks_data.chunks:
- validated_issues = [
- ValidationMarkdownReportIssue(
- issue=issue, effective_priority=effective_priority(issue.priority, v.adjusted_priority)
- )
- for issue in issues_by_chunk.get(chunk.chunk_id, [])
- if (v := validations.get(issue.id)) is not None and v.is_valid
- ]
- # A chunk with no validated finding has nothing to show — skip it so the body stays a list of
- # findings and doesn't balloon on a large multi-chunk PR.
- if not validated_issues:
+ validation = validations.get(issue.id)
+ if validation is None or not validation.is_valid:
continue
- report_chunks.append(ValidationMarkdownReportChunk(chunk=chunk, validated_issues=validated_issues))
- return ValidationMarkdownReport(chunks=report_chunks)
+ priority = effective_priority(issue.priority, validation.adjusted_priority)
+ if priority in published_priorities:
+ counts[priority] += 1
+ return counts
def _off_diff_publishable_findings(
@@ -111,38 +83,19 @@ def _off_diff_publishable_findings(
def _render_review_body(
- report: ValidationMarkdownReport,
+ counts: dict[IssuePriority, int],
off_diff_findings: list[tuple[Issue, IssueValidation]],
- published_priorities: set[IssuePriority],
) -> str:
- """Render the top-level review body: the per-chunk overview plus any off-diff findings section."""
+ """Render the review body: the severity tally plus any off-diff findings section."""
lines = [
"# ReviewHog Report",
"",
]
- for chunk_report in report.chunks:
- chunk = chunk_report.chunk
- issue_count = sum(1 for vi in chunk_report.validated_issues if vi.effective_priority in published_priorities)
-
- chunk_type = chunk.chunk_type.replace("_", " ").capitalize() if chunk.chunk_type else "Changes"
- lines.extend([f"## {chunk_type}", ""])
-
- if issue_count > 0:
- issues_label = "issue" if issue_count == 1 else "issues"
- lines.extend([f"**Issues:** {issue_count} {issues_label}", ""])
-
- if chunk.files:
- lines.extend(["<details>", f"<summary>Files ({len(chunk.files)})</summary>", "<br>", ""])
- for f in chunk.files:
- lines.append(f"- `{f.filename}`")
- lines.extend(["", "</details>", ""])
-
- if chunk.key_changes:
- lines.extend(["<details>", "<summary>What were the main changes</summary>", "<br>", ""])
- for change in chunk.key_changes:
- lines.append(f"- {change}")
- lines.extend(["", "</details>", ""])
+ breakdown = ", ".join(
+ f"**{counts[priority]} {PRIORITY_LABELS[priority]}**" for priority in PRIORITIES_BY_URGENCY if counts[priority]
+ )
+ lines.extend([f"Found {breakdown}." if breakdown else "No issues to report.", ""])
lines.extend(_render_off_diff_section(off_diff_findings))
return "\n".join(lines)
diff --git a/products/review_hog/backend/temporal/activities.py b/products/review_hog/backend/temporal/activities.py
index dc091f2644d5..81afe5440e97 100644
--- a/products/review_hog/backend/temporal/activities.py
+++ b/products/review_hog/backend/temporal/activities.py
@@ -1182,13 +1182,11 @@ def _build_and_finalize(
# Verdicts come from the DB (the same rows publish reads), so a partially-failed chunk shows the
# same findings in the body and the posted comments.
validations = load_run_validations(team_id=team_id, report_id=report_id, run_index=run_index, issues=issues)
- chunks_data = load_chunk_set(team_id=team_id, report_id=report_id, head_sha=head_sha) or ChunksList(chunks=[])
# The reviewed diff decides which valid findings can't be anchored inline — the body surfaces those
# in an "Other findings" section (the same snapshot publish positions inline comments against).
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 []
body = build_review_body(
- chunks_data=chunks_data,
issues=issues,
validations=validations,
pr_files=pr_files,
diff --git a/products/review_hog/backend/tests/test_publish_review_command.py b/products/review_hog/backend/tests/test_publish_review_command.py
index 2d6254df31bc..b6bb7609e55f 100644
--- a/products/review_hog/backend/tests/test_publish_review_command.py
+++ b/products/review_hog/backend/tests/test_publish_review_command.py
@@ -5,8 +5,12 @@ from unittest.mock import MagicMock, patch
from django.core.management import call_command
from django.core.management.base import CommandError
+from parameterized import parameterized
+
from products.review_hog.backend.models import ReviewReport
+from products.review_hog.backend.reviewer.constants import DEFAULT_URGENCY_THRESHOLD
from products.review_hog.backend.reviewer.models.github_meta import PRMetadata
+from products.review_hog.backend.reviewer.models.issues_review import IssuePriority
from products.review_hog.backend.reviewer.persistence import upsert_review_report
from products.review_hog.backend.reviewer.tools.publish_review import PublishOutcome
@@ -38,12 +42,22 @@ def _meta() -> PRMetadata:
class TestPublishReviewCommand(BaseTest):
- def _report(self, *, run_count: int, head_sha: str = "sha7", markdown: str = "# body") -> str:
+ def _report(
+ self,
+ *,
+ run_count: int,
+ head_sha: str = "sha7",
+ markdown: str = "# body",
+ run_urgency_threshold: str | None = None,
+ ) -> str:
report_id = upsert_review_report(
team_id=self.team.id, repository="PostHog/posthog", pr_url=_URL, pr_metadata=_meta()
)
ReviewReport.objects.for_team(self.team.id).filter(id=report_id).update(
- run_count=run_count, head_sha=head_sha, report_markdown=markdown
+ run_count=run_count,
+ head_sha=head_sha,
+ report_markdown=markdown,
+ run_urgency_threshold=run_urgency_threshold,
)
return report_id
@@ -77,3 +91,32 @@ class TestPublishReviewCommand(BaseTest):
assert kwargs["head_sha"] == "sha7"
# The installation id rides along so the publish calls are metered against the right budget.
assert kwargs["installation_id"] == "9876543"
+
+ @parameterized.expand(
+ [
+ ("stamped", "must_fix", IssuePriority.MUST_FIX),
+ ("unstamped", None, DEFAULT_URGENCY_THRESHOLD),
+ ]
+ )
+ @patch(_STALE, return_value=None)
+ @patch(_PUBLISH, return_value=PublishOutcome(posted=True))
+ def test_republishes_under_the_threshold_the_run_used(
+ self,
+ _name: str,
+ stamped: str | None,
+ expected: IssuePriority,
+ mock_publish: MagicMock,
+ _stale: MagicMock,
+ ) -> None:
+ # The stored body's tally was rendered under the run's threshold, so republishing has to gate the
+ # inline comments by that same threshold — publishing at the broader default would post findings
+ # the frozen tally doesn't count. A row from before the column existed falls back to the default.
+ self._report(run_count=1, run_urgency_threshold=stamped)
+ integration = MagicMock()
+ integration.get_access_token.return_value = "tok"
+ integration.github_installation_id = "9876543"
+
+ with patch(_INTEGRATION, return_value=integration):
+ call_command("publish_review", pr_url=_URL, team_id=self.team.id)
+
+ assert mock_publish.call_args.kwargs["urgency_threshold"] == expected