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(reviewhog): add flash reviews with luna medium (#102657)

Alex Lebedev594dc97f1231
diff --git a/docs/internal/sandboxes-setup-guide.md b/docs/internal/sandboxes-setup-guide.md
index 77a42b3ce01d..ad2599951fb6 100644
--- a/docs/internal/sandboxes-setup-guide.md
+++ b/docs/internal/sandboxes-setup-guide.md
@@ -196,6 +196,37 @@ When a run lands on the Python gateway unexpectedly, check those two variables f
Their absence means no token was minted, so the agent falls back to deriving the
product from the task run it fetches at boot, which is the path that fails quietly.
+ReviewHog Flash uses `gpt-5.6-luna` at `medium` reasoning effort for review, blind-spot checks, and validation.
+The shared `FLASH_ARM` in `products/review_hog/backend/reviewer/constants.py` pins the Codex runtime and `full-access` permission mode.
+Flash uses the existing `review_hog` model allowance.
+Both review modes instruct the agent to fetch pinned review and validation skills through the PostHog MCP with `skill-get`.
+The agent can fetch referenced bundled files with `skill-file-get`.
+Choose **Review in Flash mode** from the Code review page's review menu to run it for one turn without changing the PR's full-review configuration.
+Flash requests preserve an existing report's review tier, including when they join a running review.
+Flash labels its GitHub messages with `FLASH MODE` and never starts comment resolution.
+To run Flash locally, use `run_review --review-mode flash` from the repository root:
+
+```bash
+.codex/with-flox python manage.py run_review \
+ --pr-url https://github.com/PostHog/posthog/pull/PR_NUMBER \
+ --team-id 1 --user-id 1 --review-mode flash
+```
+
+Replace `PR_NUMBER` and use the team and user IDs from your local instance.
+The command defaults to Full mode and only requests GitHub publishing when you add `--publish`.
+For isolated tests, use a fresh local report with no active review on the same PR and an original branch that still points at the reviewed commit.
+An existing workflow keeps its original inputs, and an existing report's status comment can still receive progress updates.
+If a review fails, the next attempt keeps cached reviewer results for the same commit and model.
+Deduplication retires superseded findings from the unfinished turn and reuses a verdict only when its finding, commit, review mode, and model configurations are unchanged.
+Completed turns remain in the report history.
+Review-started, completed, and failed event IDs distinguish Full and Flash retries while preserving the legacy Full IDs.
+When calculating completion rates, match report, turn, and mode, treating an absent mode as Full for legacy events.
+Flash finding-outcome events use the model configuration saved with the finding, even if the Flash defaults change before classification.
+Full findings retain report-level model attribution, and findings without readable saved context have an unknown review mode.
+When recovering a failed Flash publish with `python manage.py publish_review`, pass `--review-mode flash` to preserve the Flash labels.
+The recovery command defaults to Full and does not infer the mode from the stored report.
+Recovery uses the completed turn's commit when recorded, even if a newer unfinished turn has fetched another commit.
+
### Agent run telemetry (optional)
To ship agent-server run metadata to PostHog Logs, set both of the first two; the third additionally produces one APM trace per run (root `task_run` span, a `turn` span per prompt, a `tool_call:<kind>` span per tool call) with trace/span ids stamped on the log records:
diff --git a/products/review_hog/ARCHITECTURE.md b/products/review_hog/ARCHITECTURE.md
index e7590725b14c..b92979d6e491 100644
--- a/products/review_hog/ARCHITECTURE.md
+++ b/products/review_hog/ARCHITECTURE.md
@@ -343,15 +343,25 @@ pr_metadata.head_branch` is threaded (as explicit kwargs, alongside `team_id` /
whose threshold it was (the author's / the requester's / the default, from `resolved_from`) plus a
"View them in PostHog" deep link to the exact report (`/project/<team>/code-review?review=<report id>`,
a **permanent public contract** — the frontend URL sync and `report_deep_link` must keep agreeing on it).
+ Every message a **flash** turn writes — the status comment in each of its states, the promo comment, the
+ review body, and each inline comment — opens with `FLASH MODE` + newline (`message_prefix_for_mode`), applied
+ in `_post_github_review` and the status-comment renderers before redaction.
The workflow captures one **`reviewhog_review_started`** product-analytics event per turn that passed every
gate (`track_review_started_activity`) and, after the publish stage, one **`reviewhog_review_completed`** per
finalized turn (published or stored), carrying repository / PR / trigger / finding-count / PR-size properties
(`track_review_completed_activity`); a dead turn gets `reviewhog_review_failed` instead. All three, and the
- per-finding `reviewhog_finding_outcome`, carry `review_routing_properties` (`reviewer/telemetry.py`): the tier,
- the reviewer arm as resolved for that report, and the validator / resolver pins, so every event says which
- model and effort the review spent. Started carries the arm as the turn began; completed the arm at the end,
+ per-finding `reviewhog_finding_outcome`, carry routing properties from `reviewer/telemetry.py`: the tier,
+ reviewer configuration, validator and resolver pins, and review mode when known.
+ Flash turn events name the Flash arm in both seats.
+ Flash finding outcomes use the mode and model configurations saved in the finding's `validation_context`,
+ so later changes to the Flash defaults do not relabel an earlier finding.
+ Full finding outcomes retain the report's arm at classification time; tier and resolver labels remain report-level and module-level values.
+ Findings with no readable context retain the legacy report-level labels and `review_mode: null`.
+ Started carries the arm as the turn began; completed the arm at the end,
which differs when a person's trigger lifted the tier mid-turn or, rarely, when the registry dropped the
arm's model mid-turn (`review_arm_fallback`). Best-effort: telemetry can never fail a review.
+ Turn event IDs distinguish Full and Flash while preserving the legacy Full IDs across deployments.
+ Completion-rate calculations match failures and completions by report, turn, and mode; an absent mode means Full for legacy events.
---
@@ -416,7 +426,14 @@ cheaper arms are rolled out per team through the `REVIEWHOG_TEAM_IDS` dogfood ga
but run the default arm. `load_review_arm` → `resolve_review_arm` honors a persisted arm only while it stays a
registry-supported combo — anything else falls back to the default (full-strength) pins and stamps
`review_arm_fallback` on the run's analytics events. Chunking, dedup, and the validator stay on Claude at fixed
-pins; the resolution stage runs the validator's model (`claude-opus-5` @ xhigh). See [DECISIONS.md](./DECISIONS.md)
+pins; the resolution stage runs the validator's model (`claude-opus-5` @ xhigh). One per-turn override sits on top
+of all of this: **Flash mode** (`review_mode` on the workflow input, `REVIEW_MODE_FLASH`; the UI trigger's
+`run_mode=flash`) runs both sandbox seats — the perspective wave with its blind-spot sweep, and the validator — on
+one cheap arm, `FLASH_ARM` (`gpt-5.6-luna` @ medium, Codex with `full-access`), for that turn only. The report's tier and arm are
+untouched, so the PR's next normal trigger reviews normally; `review_arm_for_mode` / `validation_arm_for_mode`
+are the two helpers the activities and the analytics events both read, so a flash turn's events name the flash
+arm in both seats. A flash turn never chains the resolution stage. Both modes instruct the agent to fetch pinned
+review and validation skills over MCP (see [Prompts](#prompts)). See [DECISIONS.md](./DECISIONS.md)
for the Sonnet-vs-Sol production A/B that picked Sol (and the `full-access` permission-mode gotcha headless Codex
needs) and for the tier decision, and [Selecting the sandbox model & reasoning
effort](#selecting-the-sandbox-model--reasoning-effort) below for the path that applies these knobs.
@@ -536,9 +553,10 @@ content". Most begin with `{{ CLAUDE_CODE_CONTEXT | safe }}` (the `@path#L…` r
- `chunking/prompt.jinja` — group changed files into logical, independently reviewable chunks by cohesion /
imports / layer boundaries; order by review priority. → `ChunksList`.
- `issues_review/prompt.jinja` — the core review prompt, run once per perspective per chunk; 10-step process
- with mandatory codebase investigation. The per-perspective focus is **no longer spliced in** — the
- `<your_review_perspective>` block instructs the agent to `skill-get(PERSPECTIVE_SKILL_NAME, version=N)` over
- MCP and apply that perspective's focus (pull delivery). → `IssuesReview`. The perspective focuses themselves
+ with mandatory codebase investigation. In both full and Flash mode, the `<your_review_perspective>` block
+ instructs the agent to `skill-get(PERSPECTIVE_SKILL_NAME, version=N)` over MCP and apply that perspective's focus.
+ Validation uses the same delivery path for its pinned criteria.
+ → `IssuesReview`. The perspective focuses themselves
live as **DB-synced LLMA skills** at
`products/review_hog/skills/review-hog-perspective-{logic-correctness,contracts-security,performance-reliability}/SKILL.md`.
- `issue_deduplicator/prompt.jinja` — mark duplicates (same file + overlapping lines + similar root cause)
@@ -573,8 +591,10 @@ Per-run state by kind:
(re-fetchable from GitHub). The reviewed unified `diff` rides back as a string and becomes the per-turn
**`commit`** artefact (the durable point-in-time snapshot).
- **Working state** (the resume substrate, head_sha-scoped): `chunk_set`, `perspective_result`, and the
- `pr_snapshot` artefacts. The raw/cleaned/combined issue sets are in-process values down the
- combine→clean→dedup chain.
+ `pr_snapshot` artefacts. A `perspective_result` is stamped with the reviewer model that wrote it and is only
+ reused by a turn running that model: a flash turn and a full turn can share a commit, and a full turn must never
+ resume Luna's results in place of running Sol (rows from before the stamp are never reused). The
+ raw/cleaned/combined issue sets are in-process values down the combine→clean→dedup chain.
- **Outputs:** `issue_finding` + `validation_verdict` artefacts (the canonical findings/verdicts) and
`ReviewReport.report_markdown` (the rendered review body) + the `head_sha` / `last_seen_comment_id`
watermark.
@@ -614,12 +634,17 @@ See [DECISIONS.md](./DECISIONS.md) for the "reuse the leaf, own the model" bound
- **Run a review:** `python manage.py run_review --pr-url <github_pr_url> --team-id <id> --user-id <id>`
(`backend/management/commands/run_review.py`, blocking `execute_review_pr_workflow`, default no-publish, with an
optional `--publish`). All three args are required.
+ Add `--review-mode flash` for Luna medium review and validation, or use the default `--review-mode full`.
+ The startup banner shows the selected review mode and whether publishing was requested.
- **Default local-testing PR:** an **origin-branch** PR — its head branch must live on `PostHog/posthog`,
because the sandbox clones the **base** repo and checks out the head branch **by name**
(`get_sandbox_for_repository`, owned by `products/tasks`), so a **fork** PR fails at the checkout step. Until
the sandbox learns to fetch `refs/pull/N/head`, test against origin-branch PRs.
-- **Publish a computed review without recomputing:** `python manage.py publish_review --pr-url <url> --team-id <id>`
- publishes the latest completed turn at its reviewed `head_sha` (DB-driven; no Temporal, no sandbox).
+- **Publish a computed review without recomputing:** `python manage.py publish_review --pr-url <url> --team-id <id>`.
+ This publishes the latest completed turn at the head that turn reviewed (`completed_head_sha`, falling back to
+ `head_sha` for pre-column rows), so a later failed turn's commit cannot be published instead (DB-driven; no
+ Temporal, no sandbox).
+ Add `--review-mode flash` when the stored review came from Flash; the command defaults to Full.
- **Reset local state:** `DEBUG=1 python manage.py reset_review_hog [--dry-run] [--yes]` wipes all ReviewHog rows
across every team (DEBUG-only; GitHub comments untouched).
- **Turn a per-user toggle on or off in bulk:** `python manage.py {enable,disable}_inbox_reviews --team-id <id>
@@ -652,7 +677,9 @@ See [DECISIONS.md](./DECISIONS.md) for the "reuse the leaf, own the model" bound
**Triggers.** Five entry points drive the same `ReviewPRWorkflow`: the `run_review` CLI (manual / eval), the
`reviewhog` **label** on a `PostHog/posthog` PR (a thin GitHub Action → `POST /api/review_hog/trigger`), a **UI**
-"Review this PR" field in the Code review scene (any installation-accessible PR), an **inbox** trigger (a
+"Review this PR" field in the Code review scene (any installation-accessible PR; its split button's `run_mode`
+also carries the review-without-resolving, resolve-only, and **flash** variants — flash is the only trigger of
+the cheap mode, and it pins resolution off), an **inbox** trigger (a
`TaskRun` receiver auto-reviews self-driving Signals implementations once their PR exists — a pushed branch without
a PR is not reviewed, and the PR must sit in the task's own repository because `output.pr_url` is written by
whoever controls the run, the sandbox agent included), and **MCP tools**
diff --git a/products/review_hog/CONTEXT.md b/products/review_hog/CONTEXT.md
index 8d0471950f9f..b2f639d3318f 100644
--- a/products/review_hog/CONTEXT.md
+++ b/products/review_hog/CONTEXT.md
@@ -32,7 +32,7 @@ Vocabulary settled while working on the product. Pure vocabulary — no spec, no
- **Review cycle** — one review turn plus its chained resolution, taken as a unit: the span from review start until the resolution stage finishes settling that review's comments. Two Temporal workflows implement it (see ADR 0001), but users reason about the cycle — "the PR is being worked on" — not the stages.
- **Busy-guard** — the explicit cross-stage check that refuses to start a new review while the PR's `resolve-pr` workflow is running, and refuses to start a standalone resolution while its `review-pr` workflow is running (the chained hand-off is exempt: it fires only after publish). Needed because Temporal's same-id joining cannot see across the two workflows.
- **Resolution etiquette** — triage and fixing logic is identical for every thread regardless of author; only the _resolve_ action is author-gated. Human-authored threads: reply as the bot with the outcome (fix + commit link, or the decline/escalate reasoning), **never resolve** — the human keeps the final word on their own thread. Bot-authored threads: reply and resolve on terminal outcomes. ESCALATE never resolves, for any author. (Autonomous adaptation of the triage skill's "bot threads: reply + resolve; human threads: hand back" invariant — the bot now speaks as itself, but resolution of human threads still belongs to humans.)
-- **Entry points** — the durable interface is a trigger-style endpoint (mirroring `ReviewHogTriggerViewSet`: shared-secret bearer, server-side team/user resolution, unscoped mount), callable by API clients (other products, e.g. self-driving) and by a thin label-driven GitHub Action. Chained mode — `ReviewPRWorkflow` dispatching the stage after publish — is an internal dispatch, not an HTTP hop, and it is the **default**: reviewing includes resolving, gated by the acting user's `resolve_comments` setting (on unless they opt out; snapshotted at acting-user resolution like the other gates), with the workflow input as a per-run override only the Code review scene uses (its split Review button offers "review without resolving" and "resolve only"). A `run_resolution` management command mirrors `run_review` for dev/test. Deterministic skip gates run before any sandbox: closed/merged PR, fork (hard refuse — this stage writes), empty work-list after the pre-filter. One run per PR at a time via a deterministic workflow ID.
+- **Entry points** — the durable interface is a trigger-style endpoint (mirroring `ReviewHogTriggerViewSet`: shared-secret bearer, server-side team/user resolution, unscoped mount), callable by API clients (other products, e.g. self-driving) and by a thin label-driven GitHub Action. Chained mode — `ReviewPRWorkflow` dispatching the stage after publish — is an internal dispatch, not an HTTP hop, and it is the **default**: reviewing includes resolving, gated by the acting user's `resolve_comments` setting (on unless they opt out; snapshotted at acting-user resolution like the other gates), with the workflow input as a per-run override only the Code review scene uses (its split Review button offers "review without resolving", "resolve only", and "flash" — the Luna medium review that never resolves). A `run_resolution` management command mirrors `run_review` for dev/test. Deterministic skip gates run before any sandbox: closed/merged PR, fork (hard refuse — this stage writes), empty work-list after the pre-filter. One run per PR at a time via a deterministic workflow ID.
- **Writing mechanics** — one signed commit per FIXED thread (a signed commit is inherently remote — the harness creates commits via the GitHub API, so commit cadence _is_ push cadence), with that thread's reply/resolve posted right after its commit is visible. On a mid-run race (author pushed; signed commit refuses because the remote advanced): sync onto the new head once, re-verify, retry; if the branch moves again, yield gracefully — done threads keep their outcomes, the rest wait for the next run.
- **CI boundary** — the resolution stage handles review threads only; it never waits on, chases, or fixes PR checks. CI babysitting already exists (the Tasks CI follow-up loop). Known seam to close on the Tasks side: `_should_run_ci_follow_up` also fires on new unresolved threads and `DEFAULT_CI_MESSAGE` mandates comment-addressing — narrow that to checks-only (or skip its thread trigger) where the resolution stage is active, so two bots never fix the same comment.
- **Run budget** — a run resolves at most **20** threads, priority-ordered; the binding constraint is the warm session's context window (every turn accumulates, and fix quality degrades as it fills), not just sandbox cost. Overflow is always named in the run summary ("handled 20, N remain") and the next run continues — never silent truncation. Session/turn timeouts are inherited from the Tasks runner. Fix _size_ is deliberately not a numeric cap — proportionality in the criteria skill is the guard. Model/effort pinned by `RESOLUTION_*` constants (validator's Claude default to start).
diff --git a/products/review_hog/DECISIONS.md b/products/review_hog/DECISIONS.md
index d1e51d66788a..6b22c5feeae4 100644
--- a/products/review_hog/DECISIONS.md
+++ b/products/review_hog/DECISIONS.md
@@ -236,6 +236,28 @@ read `FINAL_REPORT.md` there first (config glossary + coverage matrix + ranking)
400). Watch the next dogfood resolution run for drift after a long in-sandbox investigation, which the one-shot
cannot reproduce.
+### ✅ BUILT 2026-09-17: Flash mode uses Luna medium for review and validation
+
+- **What.** The Code review page's **Review in Flash mode** action sends `run_mode=flash` for one review turn.
+ `FLASH_ARM` uses `gpt-5.6-luna` at `medium` reasoning effort with the Codex runtime and `full-access` permission mode.
+ The perspective reviews, blind-spot sweep, and validator share that arm.
+ Chunking, selection, and deduplication keep their Sonnet one-shots.
+ Flash prompts instruct the agent to fetch pinned review and validation skills over MCP with `skill-get`, as full reviews do.
+- **Why.** The [Flash experiment](https://github.com/PostHog/posthog/blob/1f09ba3e98adb9d23c8c63cff6d9978ed6a9ba17/products/review_hog/eval/experiments/2026-09-flash-mode/FINAL_REPORT.md) compared five configurations, with two runs each on one frozen PR.
+ Those benchmark runs used inlined skill bodies.
+ Luna medium posted three distinct serious issues per run for $0.59, compared with 1.5 for $0.30 at low.
+ Its false-comment share was 53%, so it remains a budget choice with permissive validation.
+ Xhigh improved coverage but cost $3.32 per run.
+- **Turn isolation.** Flash leaves the report's stored tier and arm unchanged so later full reviews use their normal configuration.
+ The mode travels in the workflow payload to each stage, and telemetry reads the same arm-selection helpers as execution.
+ Cached perspective results carry the reviewer model, preventing a full Sol review from reusing Luna findings.
+ The existing join-on-running and already-reviewed rules still allow only one review per commit.
+- **Publishing.** Flash prefixes status, promotion, review-body, and inline comments with `FLASH MODE` followed by a newline.
+ It never chains comment resolution.
+ The UI and generated MCP trigger accept the mode; the CLI exposes it through `run_review --review-mode flash`.
+- **Gateway access.** Luna already belongs to the `review_hog` model allowance.
+ Flash requires no additional gateway permissions.
+
### ✅ BUILT 2026-09-03 — comment layout back to description-first (reverses the 2026-07-17 validation-first order)
User call: the issue description reads first, the validator's verdict second.
diff --git a/products/review_hog/backend/api/reviews.py b/products/review_hog/backend/api/reviews.py
index 1732364b8ea5..230220e5a3ef 100644
--- a/products/review_hog/backend/api/reviews.py
+++ b/products/review_hog/backend/api/reviews.py
@@ -27,7 +27,7 @@ from products.review_hog.backend.reviewer.artefact_content import (
ReviewIssueFinding,
ValidationVerdict,
)
-from products.review_hog.backend.reviewer.constants import effective_priority
+from products.review_hog.backend.reviewer.constants import REVIEW_MODE_FLASH, REVIEW_MODE_FULL, effective_priority
from products.review_hog.backend.reviewer.models.issues_review import IssuePriority
from products.review_hog.backend.reviewer.models.split_pr_into_chunks import ChunksList
from products.review_hog.backend.reviewer.persistence import (
@@ -246,10 +246,12 @@ class ReviewRecentReviewsPageSerializer(serializers.Serializer):
# What the trigger runs. The default 'review' includes the resolution stage when the requesting
-# user's `resolve_comments` setting is on; the other two are the split button's explicit variants.
+# user's `resolve_comments` setting is on; the others are the split button's explicit variants.
+# Flash never resolves comments because it must not write code.
RUN_MODE_REVIEW = "review"
RUN_MODE_REVIEW_ONLY = "review_only"
RUN_MODE_RESOLVE_ONLY = "resolve_only"
+RUN_MODE_FLASH = "flash"
class ReviewTriggerRequestSerializer(serializers.Serializer):
@@ -260,12 +262,13 @@ class ReviewTriggerRequestSerializer(serializers.Serializer):
run_mode = serializers.ChoiceField(
required=False,
default=RUN_MODE_REVIEW,
- choices=[RUN_MODE_REVIEW, RUN_MODE_REVIEW_ONLY, RUN_MODE_RESOLVE_ONLY],
+ choices=[RUN_MODE_REVIEW, RUN_MODE_REVIEW_ONLY, RUN_MODE_RESOLVE_ONLY, RUN_MODE_FLASH],
help_text="What to run on the pull request. 'review' (default) reviews it and, when the "
"requesting user's resolve_comments setting is on, chains the resolution stage; "
"'review_only' reviews without resolving regardless of that setting; 'resolve_only' skips "
"the review and only runs the resolution stage on the PR's existing unresolved review "
- "threads.",
+ "threads; 'flash' uses a lower-cost model for the review passes and validation, and never "
+ "resolves comments.",
)
@@ -276,8 +279,9 @@ class ReviewTriggerResponseSerializer(serializers.Serializer):
status = serializers.CharField(
help_text="Run lifecycle marker: 'started' when the review was queued, 'already_reviewed' when the "
"pull request's current commit already has a published review (no new run starts), "
- "'joined_running_review' when a review was already in flight (no new run starts; a report in a "
- "cheaper tier is lifted to human strength for the rest of that review and every later one)."
+ "'joined_running_review' when a review was already in flight (no new run starts and its mode "
+ "stays unchanged; requests for Full mode lift a cheaper stored tier for later Full reviews, "
+ "while Flash requests leave the tier unchanged)."
)
@@ -715,7 +719,8 @@ class ReviewRecentReviewsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet
"enabled perspectives, blind-spot check, validator, urgency threshold, and resolution criteria "
"drive the run, and it appears under their recent reviews. `run_mode` picks the variant: a review "
"(which chains the resolution stage per the user's resolve_comments setting), a review without "
- "resolving, or resolution only. Nonexistent, closed, and fork PRs are rejected synchronously; "
+ "resolving, resolution only, or a lower-cost Flash review that never resolves comments. "
+ "Nonexistent, closed, and fork PRs are rejected synchronously; "
"a PR whose current commit already has a published review returns 'already_reviewed' without "
"starting a run (resolve_only skips that check — settling threads on a reviewed head is its whole "
"point), and triggering a PR whose run is currently in flight joins that run. "
@@ -852,11 +857,16 @@ class ReviewRecentReviewsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet
publish=True,
acting_user_id=requester_id,
trigger_source=TRIGGER_UI,
- # None = the requester's resolve_comments setting decides; review_only pins it off.
- resolve_comments=False if run_mode == RUN_MODE_REVIEW_ONLY else None,
+ # None = the requester's resolve_comments setting decides; review_only and flash pin it off.
+ resolve_comments=False if run_mode in (RUN_MODE_REVIEW_ONLY, RUN_MODE_FLASH) else None,
+ review_mode=REVIEW_MODE_FLASH if run_mode == RUN_MODE_FLASH else REVIEW_MODE_FULL,
)
if joins_running_review:
- lifted = lift_review_tier_for_joined_trigger(team_id=team_id, repository=repository, pr_number=pr_number)
+ # Flash is excluded for the same reason the fetch upsert excludes it: the lift rewrites
+ # the persisted arm, so the cheapest request must not raise what later turns cost.
+ lifted = run_mode != RUN_MODE_FLASH and lift_review_tier_for_joined_trigger(
+ team_id=team_id, repository=repository, pr_number=pr_number
+ )
logger.info(
f"ReviewHog UI trigger joined running workflow {workflow_id} for {pr_url} (tier lifted={lifted})"
)
diff --git a/products/review_hog/backend/management/commands/publish_review.py b/products/review_hog/backend/management/commands/publish_review.py
index d1ed96846f16..66f4d064c285 100644
--- a/products/review_hog/backend/management/commands/publish_review.py
+++ b/products/review_hog/backend/management/commands/publish_review.py
@@ -7,7 +7,11 @@ from posthog.egress.github.transport import GitHubRateLimitError
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.constants import (
+ DEFAULT_URGENCY_THRESHOLD,
+ REVIEW_MODE_FLASH,
+ REVIEW_MODE_FULL,
+)
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
@@ -53,6 +57,12 @@ class Command(BaseCommand):
def add_arguments(self, parser: CommandParser) -> None:
parser.add_argument("--pr-url", required=True, help="GitHub PR URL the review was computed for")
parser.add_argument("--team-id", type=int, required=True, help="Team the review is persisted under")
+ parser.add_argument(
+ "--review-mode",
+ choices=(REVIEW_MODE_FULL, REVIEW_MODE_FLASH),
+ default=REVIEW_MODE_FULL,
+ help="Mode that produced the stored review; use flash to preserve its Flash labels",
+ )
def handle(self, *args: Any, **options: Any) -> None:
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s")
@@ -68,7 +78,12 @@ class Command(BaseCommand):
raise CommandError(f"No review found for {repository}#{pr_number} on team {team_id}. Run run_review first.")
if report.run_count == 0 or not report.report_markdown:
raise CommandError(f"Review for {repository}#{pr_number} hasn't completed a run yet; nothing to publish.")
- head_sha = report.head_sha
+ # The head the latest COMPLETED turn reviewed. `head_sha` advances at turn START, so a turn
+ # that fetched a new commit and then failed leaves it pointing past the findings published
+ # here — positioning them against that diff anchors comments on shifted lines and burns the
+ # published-head watermark on a commit the turn never reviewed. Pre-column rows fall back,
+ # like every other latest-turn reader.
+ head_sha = report.completed_head_sha or report.head_sha
if not head_sha:
raise CommandError(f"Review for {repository}#{pr_number} has no reviewed head_sha; nothing to publish.")
@@ -114,6 +129,7 @@ class Command(BaseCommand):
token=token,
urgency_threshold=_run_threshold(report.run_urgency_threshold),
installation_id=installation_id,
+ review_mode=options["review_mode"],
)
if outcome.posted:
self.stdout.write(self.style.SUCCESS(f"ReviewHog ✓ published {repository}#{pr_number}"))
diff --git a/products/review_hog/backend/management/commands/run_review.py b/products/review_hog/backend/management/commands/run_review.py
index 8a6ba7bcbefd..b9c66704bfea 100644
--- a/products/review_hog/backend/management/commands/run_review.py
+++ b/products/review_hog/backend/management/commands/run_review.py
@@ -3,6 +3,7 @@ from typing import Any
from django.core.management.base import BaseCommand, CommandParser
+from products.review_hog.backend.reviewer.constants import REVIEW_MODE_FLASH, REVIEW_MODE_FULL
from products.review_hog.backend.temporal.client import execute_review_pr_workflow
@@ -31,6 +32,12 @@ class Command(BaseCommand):
"applies this user's enabled perspectives regardless of the PR author (deterministic eval)."
),
)
+ parser.add_argument(
+ "--review-mode",
+ choices=[REVIEW_MODE_FULL, REVIEW_MODE_FLASH],
+ default=REVIEW_MODE_FULL,
+ help="Review mode for this run (default: full)",
+ )
parser.add_argument(
"--publish",
action="store_true",
@@ -44,10 +51,18 @@ class Command(BaseCommand):
pr_url = options["pr_url"]
team_id = options["team_id"]
user_id = options["user_id"]
+ review_mode = options["review_mode"]
publish = options["publish"]
mode = "publish" if publish else "no-publish"
- self.stdout.write(self.style.MIGRATE_HEADING(f"ReviewHog ▶ starting · {pr_url} · team {team_id} · {mode}"))
+ self.stdout.write(
+ self.style.MIGRATE_HEADING(f"ReviewHog ▶ starting · {pr_url} · team {team_id} · {review_mode} · {mode}")
+ )
report_id = execute_review_pr_workflow(
- pr_url=pr_url, team_id=team_id, user_id=user_id, publish=publish, acting_user_id=user_id
+ pr_url=pr_url,
+ team_id=team_id,
+ user_id=user_id,
+ publish=publish,
+ acting_user_id=user_id,
+ review_mode=review_mode,
)
self.stdout.write(self.style.SUCCESS(f"ReviewHog ✓ finished · report {report_id}"))
diff --git a/products/review_hog/backend/models.py b/products/review_hog/backend/models.py
index 40dbd4ab8d20..87b3b7ffb208 100644
--- a/products/review_hog/backend/models.py
+++ b/products/review_hog/backend/models.py
@@ -164,11 +164,12 @@ def review_report_artefact_type_choices() -> list[tuple[str, str | Promise]]:
class ReviewReportArtefact(UUIDModel, TeamScopedRootMixin):
- """Append-only work log for a `ReviewReport`.
+ """Work log for a `ReviewReport`, with append-only completed turns.
Mirrors Signals' `SignalReportArtefact` funnel — the row's type is derived from the content
model's class and attribution maps to `created_by` / `task` columns — but owns its own types
and has no auto-start side effects.
+ Deduplication can retire superseded findings and verdicts from an unfinished turn.
"""
class ArtefactType(models.TextChoices):
diff --git a/products/review_hog/backend/reviewer/artefact_content.py b/products/review_hog/backend/reviewer/artefact_content.py
index 1b57051e296e..40a5121c8812 100644
--- a/products/review_hog/backend/reviewer/artefact_content.py
+++ b/products/review_hog/backend/reviewer/artefact_content.py
@@ -55,6 +55,10 @@ class ReviewIssueFinding(BaseModel):
run_index: int = Field(
description="The review turn (1-based) that produced this finding; scopes publishing to one turn."
)
+ validation_context: str | None = Field(
+ default=None,
+ description="The reviewed head, mode, and model configurations for verdict reuse and Flash outcome attribution.",
+ )
title: str = Field(description="Issue title.")
file: str = Field(description="Repository-relative path to the file containing the issue.")
lines: list[LineRange] = Field(default_factory=list, description="Affected line ranges.")
@@ -245,12 +249,18 @@ class PerspectiveSelectionArtefact(BaseModel):
class PerspectiveResultArtefact(BaseModel):
- """Content for a `perspective_result` artefact: one (perspective, chunk) review for one turn."""
+ """Content for a `perspective_result` artefact: one (perspective, chunk) review for one turn.
+
+ `review_model` keys the resume: the cache is per commit, and a flash turn and a full turn can run at
+ the same commit, so a result is only reused by a turn running the model that wrote it. Rows from
+ before the field carry None and are never reused.
+ """
head_sha: str = Field(description="PR head commit this review was computed for.")
pass_number: int = Field(description="The review perspective (1=Logic, 2=Contracts, 3=Performance).")
chunk_id: int = Field(description="The chunk this perspective reviewed.")
review: IssuesReview = Field(description="The issues this perspective found in this chunk.")
+ review_model: str | None = Field(default=None, description="The reviewer model that produced this result.")
class PRSnapshotArtefact(BaseModel):
diff --git a/products/review_hog/backend/reviewer/constants.py b/products/review_hog/backend/reviewer/constants.py
index ec4e23b63a80..47a9b199bc14 100644
--- a/products/review_hog/backend/reviewer/constants.py
+++ b/products/review_hog/backend/reviewer/constants.py
@@ -58,6 +58,35 @@ DEFAULT_REVIEW_ARM = ReviewArm(
)
+# REVIEW MODE
+# What a single turn runs on, chosen per trigger and carried in the workflow input, never persisted on
+# the report: a flash turn must not change what the PR's next normal review runs on. Plain strings so
+# Temporal payloads stay forward/backward-compatible across deploys, like the trigger sources.
+REVIEW_MODE_FULL = "full"
+REVIEW_MODE_FLASH = "flash"
+
+# Share the arm so Flash's reviewer and validator use the same cost and reasoning budget.
+FLASH_ARM = ReviewArm(
+ runtime_adapter=RuntimeAdapter.CODEX,
+ model="gpt-5.6-luna",
+ reasoning_effort=ReasoningEffort.MEDIUM,
+ initial_permission_mode="full-access",
+)
+
+# Every GitHub message a flash turn writes (status comment, promo, review body, inline comments)
+# starts with this, so a reader can tell a flash review from a full one at a glance.
+FLASH_MODE_MESSAGE_PREFIX = "FLASH MODE\n"
+
+
+def message_prefix_for_mode(review_mode: str) -> str:
+ return FLASH_MODE_MESSAGE_PREFIX if review_mode == REVIEW_MODE_FLASH else ""
+
+
+def review_arm_for_mode(review_mode: str, persisted: ReviewArm) -> ReviewArm:
+ """The arm a turn's review units run on: the flash arm for a flash turn, else the report's own."""
+ return FLASH_ARM if review_mode == REVIEW_MODE_FLASH else persisted
+
+
class ReviewTier(StrEnum):
"""The routing bucket a report's reviewer arm is chosen from; persisted as `ReviewReport.review_tier`.
@@ -183,13 +212,26 @@ def resolve_review_arm(
# VALIDATION MODEL
-# Pins for the per-chunk warm validation sessions. All-None = the agent server's default model at its
-# default effort (the behavior before this knob existed); set all three to pin, like the review pins.
-VALIDATION_RUNTIME_ADAPTER: RuntimeAdapter | None = RuntimeAdapter.CLAUDE
-VALIDATION_MODEL: str | None = "claude-opus-5"
-VALIDATION_REASONING_EFFORT: ReasoningEffort | None = ReasoningEffort.XHIGH
+# Pins for the per-chunk warm validation sessions, bundled like the review arm so a mode can swap
+# the whole seat at once.
+VALIDATION_RUNTIME_ADAPTER = RuntimeAdapter.CLAUDE
+VALIDATION_MODEL = "claude-opus-5"
+VALIDATION_REASONING_EFFORT = ReasoningEffort.XHIGH
VALIDATION_INITIAL_PERMISSION_MODE: str | None = None
+DEFAULT_VALIDATION_ARM = ReviewArm(
+ runtime_adapter=VALIDATION_RUNTIME_ADAPTER,
+ model=VALIDATION_MODEL,
+ reasoning_effort=VALIDATION_REASONING_EFFORT,
+ initial_permission_mode=VALIDATION_INITIAL_PERMISSION_MODE,
+)
+
+
+def validation_arm_for_mode(review_mode: str) -> ReviewArm:
+ """The arm a turn's validation sessions run on: the flash arm for a flash turn, else the pins."""
+ return FLASH_ARM if review_mode == REVIEW_MODE_FLASH else DEFAULT_VALIDATION_ARM
+
+
# RESOLUTION MODEL
# Pins for the resolution stage's warm per-PR session (assess + implement, one thread per turn).
# The validator's model and effort: resolution is judgment plus careful editing, the validator's job.
diff --git a/products/review_hog/backend/reviewer/outcomes/classify.py b/products/review_hog/backend/reviewer/outcomes/classify.py
index b8ba924a48d7..6cddf1c7d308 100644
--- a/products/review_hog/backend/reviewer/outcomes/classify.py
+++ b/products/review_hog/backend/reviewer/outcomes/classify.py
@@ -62,7 +62,7 @@ from products.review_hog.backend.reviewer.outcomes.github_fetch import fetch_com
from products.review_hog.backend.reviewer.outcomes.judge import judge_finding
from products.review_hog.backend.reviewer.outcomes.line_proximity import parse_compare_files, touched_near
from products.review_hog.backend.reviewer.persistence import load_findings_bundle
-from products.review_hog.backend.reviewer.telemetry import review_routing_properties
+from products.review_hog.backend.reviewer.telemetry import finding_routing_properties
from products.review_hog.backend.reviewer.tools.github_client import GitHubAPIError
from products.signals.backend.artefact_attribution import ArtefactAttribution
@@ -402,7 +402,7 @@ async def _emit_and_mark(
"classification_method": oc.method,
"reviewed_head": oc.reviewed_head,
"final_head": oc.final_head,
- **review_routing_properties(report),
+ **finding_routing_properties(report, oc.finding),
},
)
if flush is not None:
diff --git a/products/review_hog/backend/reviewer/persistence.py b/products/review_hog/backend/reviewer/persistence.py
index 885f20ecc5c6..41e8c0eaf5cc 100644
--- a/products/review_hog/backend/reviewer/persistence.py
+++ b/products/review_hog/backend/reviewer/persistence.py
@@ -6,6 +6,7 @@ within one run and persists them as rows; the DB-driven resume reads those rows
on-disk store. Resume is head_sha-scoped and covers the turn-stable sandbox stages — chunk_set /
perspective_result; dedup recomputes on a re-run because its post-dedup issue set (and thus the
per-issue ids) isn't stable across runs, while validation resumes per issue off its persisted verdicts.
+Dedup replaces only an unfinished turn's superseded findings and verdicts; completed turns remain intact.
Durable rows this layer writes:
@@ -23,9 +24,10 @@ per-thread rulings + delivery watermarks, via the helpers below) plus `task_run`
work-log entries for its session, fix commits, and run summaries.
"""
+import json
import logging
from collections.abc import Sequence
-from dataclasses import dataclass, field
+from dataclasses import asdict, dataclass, field
from django.conf import settings
from django.db import IntegrityError, transaction
@@ -388,9 +390,14 @@ def load_perspective_selection(*, team_id: int, report_id: str, head_sha: str) -
def persist_perspective_results(
- *, team_id: int, report_id: str, head_sha: str, results: dict[tuple[int, int], IssuesReview]
+ *,
+ team_id: int,
+ report_id: str,
+ head_sha: str,
+ results: dict[tuple[int, int], IssuesReview],
+ review_model: str,
) -> None:
- """Append one `perspective_result` artefact per (pass, chunk) reviewed this turn."""
+ """Append one `perspective_result` artefact per (pass, chunk) reviewed this turn, stamped with its model."""
if not results:
return
with transaction.atomic():
@@ -399,19 +406,34 @@ def persist_perspective_results(
team_id=team_id,
report_id=report_id,
content=PerspectiveResultArtefact(
- head_sha=head_sha, pass_number=pass_number, chunk_id=chunk_id, review=review
+ head_sha=head_sha,
+ pass_number=pass_number,
+ chunk_id=chunk_id,
+ review=review,
+ review_model=review_model,
),
attribution=ArtefactAttribution.system(),
)
-def load_perspective_results(*, team_id: int, report_id: str, head_sha: str) -> dict[tuple[int, int], IssuesReview]:
- """The (pass, chunk) perspective reviews already computed for this turn (latest wins per key)."""
+def load_perspective_results(
+ *, team_id: int, report_id: str, head_sha: str, review_model: str
+) -> dict[ # nosemgrep: tuple-return-prefer-dataclass -- Shared (pass, chunk) cache keys.
+ tuple[int, int], IssuesReview
+]:
+ """The (pass, chunk) reviews already computed for this turn by `review_model` (latest wins per key).
+
+ The cache is per commit, so results another model wrote at the same commit (a flash turn before a
+ full one, or the reverse) are skipped: reusing them would hand this turn findings its own reviewer
+ never produced.
+ """
out: dict[tuple[int, int], IssuesReview] = {}
for content in _load_working_state(
team_id, report_id, ReviewReportArtefact.ArtefactType.PERSPECTIVE_RESULT, head_sha
):
assert isinstance(content, PerspectiveResultArtefact)
+ if content.review_model != review_model:
+ continue
out[(content.pass_number, content.chunk_id)] = content.review
return out
@@ -493,6 +515,73 @@ def persist_findings(*, team_id: int, report_id: str, issues: list[Issue], run_i
return [issue.id for issue, _finding in pairs]
+def replace_deduplicated_findings(
+ *,
+ team_id: int,
+ report_id: str,
+ issues: list[Issue],
+ run_index: int,
+ head_sha: str,
+ review_mode: str,
+ review_arm: ReviewArm,
+ validation_arm: ReviewArm,
+) -> list[str]:
+ """Replace an unfinished turn's dedup snapshot, retaining only compatible cached verdicts.
+
+ A failed turn keeps its index, so its next attempt can produce different findings or use different
+ models. Only unpublished working rows retire: completed history and per-commit reviewer results
+ stay intact. Identical findings at the same head, mode, and arm configurations keep their verdicts.
+ """
+ context = json.dumps(
+ {
+ "head_sha": head_sha,
+ "review_mode": review_mode,
+ "review_arm": asdict(review_arm),
+ "validation_arm": asdict(validation_arm),
+ },
+ sort_keys=True,
+ )
+ pairs = _persistable_findings(issues, run_index, validation_context=context)
+ with transaction.atomic():
+ report = ReviewReport.objects.for_team(team_id).select_for_update().only("run_count").get(id=report_id)
+ if run_index <= report.run_count:
+ raise ValueError("Cannot replace findings from a completed review turn")
+
+ previous: dict[str, ReviewIssueFinding] = {}
+ row_keys: dict[str, str] = {}
+ rows = (
+ ReviewReportArtefact.objects.for_team(team_id)
+ .filter(
+ report_id=report_id,
+ type__in=[
+ ReviewReportArtefact.ArtefactType.ISSUE_FINDING,
+ ReviewReportArtefact.ArtefactType.VALIDATION_VERDICT,
+ ],
+ )
+ .order_by("created_at", "id")
+ )
+ for row in rows:
+ try:
+ content = parse_artefact_content(row.type, row.content)
+ except ArtefactContentValidationError:
+ continue
+ if isinstance(content, ReviewIssueFinding) and content.run_index == run_index:
+ previous[content.issue_key] = content
+ row_keys[str(row.id)] = content.issue_key
+ elif isinstance(content, ValidationVerdict) and content.issue_key.startswith(f"r{run_index}:"):
+ row_keys[str(row.id)] = content.issue_key
+
+ preserved = {finding.issue_key for _, finding in pairs if previous.get(finding.issue_key) == finding}
+ obsolete_ids = [row_id for row_id, key in row_keys.items() if key not in preserved]
+ if obsolete_ids:
+ ReviewReportArtefact.objects.for_team(team_id).filter(report_id=report_id, id__in=obsolete_ids).delete()
+ for _, finding in pairs:
+ ReviewReportArtefact.append_finding(
+ team_id=team_id, report_id=report_id, content=finding, attribution=ArtefactAttribution.system()
+ )
+ return [issue.id for issue, _ in pairs]
+
+
def persist_verdicts(
*, team_id: int, report_id: str, issues: list[Issue], validations: dict[str, IssueValidation], run_index: int
) -> int:
@@ -816,7 +905,9 @@ def _issue_key(issue: Issue, run_index: int) -> str:
return f"r{run_index}:{issue.file}:{start}:{perspective}:{issue.id}"
-def _persistable_findings(issues: list[Issue], run_index: int) -> list[tuple[Issue, ReviewIssueFinding]]:
+def _persistable_findings(
+ issues: list[Issue], run_index: int, *, validation_context: str | None = None
+) -> list[tuple[Issue, ReviewIssueFinding]]:
"""Pair each canonical issue with its durable finding, dropping any that fail durable validation.
Shared by both persist passes so a verdict is only ever written for an issue that produced a
@@ -825,17 +916,18 @@ def _persistable_findings(issues: list[Issue], run_index: int) -> list[tuple[Iss
pairs: list[tuple[Issue, ReviewIssueFinding]] = []
for issue in issues:
try:
- pairs.append((issue, _to_finding(issue, run_index)))
+ pairs.append((issue, _to_finding(issue, run_index, validation_context=validation_context)))
except ValidationError as e:
logger.warning("Skipping finding %s that failed durable validation: %s", issue.id, e)
return pairs
-def _to_finding(issue: Issue, run_index: int) -> ReviewIssueFinding:
+def _to_finding(issue: Issue, run_index: int, *, validation_context: str | None = None) -> ReviewIssueFinding:
"""Map a live pipeline `Issue` onto the durable `ReviewIssueFinding` content schema."""
return ReviewIssueFinding(
issue_key=_issue_key(issue, run_index),
run_index=run_index,
+ validation_context=validation_context,
title=issue.title,
file=issue.file,
lines=issue.lines,
diff --git a/products/review_hog/backend/reviewer/prompts/issue_validation/prompt.jinja b/products/review_hog/backend/reviewer/prompts/issue_validation/prompt.jinja
index 7614449f7249..e13fa6033b9a 100644
--- a/products/review_hog/backend/reviewer/prompts/issue_validation/prompt.jinja
+++ b/products/review_hog/backend/reviewer/prompts/issue_validation/prompt.jinja
@@ -30,7 +30,6 @@ Return your assessment as a JSON object that conforms to the provided schema.
<your_validation_criteria>
## Your validation criteria
-
The bar for what counts as a valid, worth-keeping issue lives in a skill you MUST read before judging. As your first step, call this over the PostHog MCP:
skill-get(skill_name="{{ VALIDATION_SKILL_NAME }}", version={{ VALIDATION_SKILL_VERSION }})
@@ -59,4 +58,4 @@ After completing your analysis:
```json
{{VALIDATION_SCHEMA | safe}}
```
-</output_schema>
\ No newline at end of file
+</output_schema>
diff --git a/products/review_hog/backend/reviewer/prompts/issues_review/prompt.jinja b/products/review_hog/backend/reviewer/prompts/issues_review/prompt.jinja
index feb3579e178c..28214eb2d3f6 100644
--- a/products/review_hog/backend/reviewer/prompts/issues_review/prompt.jinja
+++ b/products/review_hog/backend/reviewer/prompts/issues_review/prompt.jinja
@@ -277,4 +277,4 @@ After completing your analysis:
```json
{{ OUTPUT_SCHEMA | safe }}
```
-</output_schema>
\ No newline at end of file
+</output_schema>
diff --git a/products/review_hog/backend/reviewer/skill_loader.py b/products/review_hog/backend/reviewer/skill_loader.py
index 16e25bd5de04..ce5bae400950 100644
--- a/products/review_hog/backend/reviewer/skill_loader.py
+++ b/products/review_hog/backend/reviewer/skill_loader.py
@@ -3,9 +3,8 @@
ReviewHog's review **perspectives**, its **validation criteria**, and its **blind-spot check** are
stored and synced the way Signals' scouts store theirs: canonical `SKILL.md` on disk
(`products/review_hog/skills/`) mirrored into per-team `LLMSkill` rows by `lazy_seed.sync_canonical_*`.
-Delivery is **pull** — the review / validation prompts instruct the sandbox agent to `skill-get` the
-skill body over the PostHog MCP — so these loaders only need to pin the current version per skill
-(not the body).
+Each run pins the current version per skill. Both full and Flash prompts instruct the agent to pull
+bodies and bundled files over the PostHog MCP.
"""
from __future__ import annotations
diff --git a/products/review_hog/backend/reviewer/status_comment.py b/products/review_hog/backend/reviewer/status_comment.py
index 111cf76ada8c..f9c6002e1ee0 100644
--- a/products/review_hog/backend/reviewer/status_comment.py
+++ b/products/review_hog/backend/reviewer/status_comment.py
@@ -31,7 +31,9 @@ from products.review_hog.backend.models import ReviewReport
from products.review_hog.backend.reviewer.constants import (
PRIORITIES_BY_URGENCY,
PRIORITY_LABELS,
+ REVIEW_MODE_FULL,
effective_priority,
+ message_prefix_for_mode,
published_priorities_for,
)
from products.review_hog.backend.reviewer.models.issues_review import IssuePriority
@@ -147,13 +149,15 @@ def _plural(count: int, noun: str) -> str:
return f"{count} {noun}" if count == 1 else f"{count} {noun}s"
-def render_in_progress_body(report_id: str, progress: dict[str, Any] | None) -> str:
+def render_in_progress_body(
+ report_id: str, progress: dict[str, Any] | None, *, review_mode: str = REVIEW_MODE_FULL
+) -> str:
"""The running-state body: the current step (mirroring the UI), plus a one-line explainer."""
label = _STAGE_LABELS.get(progress["review_stage"], "Review in progress") if progress else _STAGE_LABELS["fetching"]
done = progress.get("done") if progress else None
total = progress.get("total") if progress else None
counter = f" · {done}/{total}" if done is not None and total else ""
- return "\n".join(
+ return message_prefix_for_mode(review_mode) + "\n".join(
[
"### \U0001f994 PostHog Review is reviewing this pull request",
"",
@@ -179,6 +183,7 @@ def render_final_body(
review_url: str | None,
resolved_from: str = "author",
report_url: str | None = None,
+ review_mode: str = REVIEW_MODE_FULL,
) -> str:
"""The completed-state body: the full found counts, and how many the threshold held back.
@@ -224,7 +229,7 @@ def render_final_body(
sentence += f" [View them in PostHog]({report_url})."
lines.append(sentence)
lines.extend(["", status_marker(report_id)])
- return "\n".join(lines)
+ return message_prefix_for_mode(review_mode) + "\n".join(lines)
def render_resolution_progress_section(*, done: int, total: int, fixed: int, left_for_you: int) -> str:
@@ -279,8 +284,8 @@ def _splice_resolution_section(body: str, section: str) -> str:
return f"{body.rstrip()}\n\n{block}" if body.strip() else block
-def render_failed_body(report_id: str) -> str:
- return "\n".join(
+def render_failed_body(report_id: str, *, review_mode: str = REVIEW_MODE_FULL) -> str:
+ return message_prefix_for_mode(review_mode) + "\n".join(
[
"### \U0001f994 PostHog Review couldn't finish this review",
"",
@@ -380,7 +385,7 @@ def _split_repository(repository: str) -> tuple[str, str]:
return owner, repo
-def ensure_status_comment(team_id: int, report_id: str) -> None:
+def ensure_status_comment(team_id: int, report_id: str, *, review_mode: str = REVIEW_MODE_FULL) -> None:
"""Post (or reset) the report's status comment at run kickoff and remember its id.
Reuses the previous turn's comment when one exists — by the stored id, falling back to a marker
@@ -397,7 +402,7 @@ def ensure_status_comment(team_id: int, report_id: str) -> None:
token, installation_id = auth
owner, repo = _split_repository(report.repository)
marker = status_marker(report_id)
- body = render_in_progress_body(report_id, None)
+ body = render_in_progress_body(report_id, None, review_mode=review_mode)
comment_id = report.status_comment_id
if comment_id is None:
@@ -422,7 +427,7 @@ def ensure_status_comment(team_id: int, report_id: str) -> None:
logger.exception("Could not post the ReviewHog status comment; the review continues without it")
-def maybe_refresh_status_comment(team_id: int, report_id: str) -> None:
+def maybe_refresh_status_comment(team_id: int, report_id: str, *, review_mode: str = REVIEW_MODE_FULL) -> None:
"""Refresh the status comment with the turn's current stage, at most once per interval.
Called after pipeline activities persist progress artefacts. The debounce is an atomic claim on
@@ -462,7 +467,7 @@ def maybe_refresh_status_comment(team_id: int, report_id: str) -> None:
owner,
repo,
report.status_comment_id,
- render_in_progress_body(report_id, progress),
+ render_in_progress_body(report_id, progress, review_mode=review_mode),
token=token,
installation_id=installation_id,
)
@@ -481,6 +486,7 @@ class FinalizeStatusCommentInput:
# Whose threshold gated the run ("author" / "override" / "default", from the resolve snapshot) —
# the held-back sentence must blame the right settings. Defaulted so pre-field payloads deserialize.
resolved_from: str = "author"
+ review_mode: str = REVIEW_MODE_FULL
def finalize_status_comment(input: FinalizeStatusCommentInput) -> None:
@@ -507,19 +513,20 @@ def finalize_status_comment(input: FinalizeStatusCommentInput) -> None:
review_url=input.review_url,
resolved_from=input.resolved_from,
report_url=report_deep_link(input.team_id, input.report_id),
+ review_mode=input.review_mode,
)
_edit_and_stamp(input.team_id, report, body)
except Exception:
logger.exception("Could not finalize the ReviewHog status comment; the review is unaffected")
-def fail_status_comment(team_id: int, report_id: str) -> None:
+def fail_status_comment(team_id: int, report_id: str, *, review_mode: str = REVIEW_MODE_FULL) -> None:
"""Rewrite the status comment as failed, so a dead run never reads as forever in progress."""
try:
report = ReviewReport.objects.for_team(team_id).filter(id=report_id).first()
if report is None or report.status_comment_id is None or report.pr_number is None:
return
- _edit_and_stamp(team_id, report, render_failed_body(report_id))
+ _edit_and_stamp(team_id, report, render_failed_body(report_id, review_mode=review_mode))
except Exception:
logger.exception("Could not mark the ReviewHog status comment as failed")
diff --git a/products/review_hog/backend/reviewer/telemetry.py b/products/review_hog/backend/reviewer/telemetry.py
index 36035602efc2..e297a92d3235 100644
--- a/products/review_hog/backend/reviewer/telemetry.py
+++ b/products/review_hog/backend/reviewer/telemetry.py
@@ -1,26 +1,55 @@
"""The model and effort labels every ReviewHog analytics event carries."""
-from products.review_hog.backend.models import ReviewReport
+from __future__ import annotations
+
+from typing import TYPE_CHECKING, Literal
+from uuid import NAMESPACE_URL, uuid5
+
+from pydantic import BaseModel, ValidationError
+
from products.review_hog.backend.reviewer.constants import (
RESOLUTION_MODEL,
RESOLUTION_REASONING_EFFORT,
- VALIDATION_MODEL,
- VALIDATION_REASONING_EFFORT,
+ REVIEW_MODE_FLASH,
+ REVIEW_MODE_FULL,
+ ReviewArm,
resolve_review_arm,
+ review_arm_for_mode,
+ validation_arm_for_mode,
)
+if TYPE_CHECKING:
+ from products.review_hog.backend.models import ReviewReport
+ from products.review_hog.backend.reviewer.artefact_content import ReviewIssueFinding
+
+
+class _FindingModelContext(BaseModel):
+ review_mode: Literal["full", "flash"]
+ review_arm: ReviewArm
+ validation_arm: ReviewArm
+
+
+def review_event_uuid(event_name: str, *, report_id: str, run_index: int, review_mode: str) -> str:
+ """Preserve legacy Full event IDs while separating retry histories by review mode."""
+ identity = f"{event_name}:{report_id}:{run_index}"
+ if review_mode != REVIEW_MODE_FULL:
+ identity = f"{identity}:{review_mode}"
+ return str(uuid5(NAMESPACE_URL, identity))
-def review_routing_properties(report: ReviewReport) -> dict[str, str | bool | None]:
- """The tier, the reviewer arm, and the fixed validator and resolver pins of a report's reviews.
+
+def review_routing_properties(report: ReviewReport, *, review_mode: str | None = None) -> dict[str, str | bool | None]:
+ """The tier, the reviewer arm, and the validator and resolver pins of a report's reviews.
Every review event (started, completed, failed, finding outcome) spreads this in, so a dashboard
can split any of them by what actually ran. The reviewer arm is resolved, not raw: pre-arm rows
carry NULLs but their reviews run on the default pins, and the event must say what ran. The tier
and priority are raw: they are the decision as recorded, and NULL means the row predates tiers.
The values are the row's as of the call: a per-turn event reads them at that point of the turn,
- and the finding-outcome event reads the report's arm when the outcome is classified, not the
- arm of the turn that produced the finding. The validator and resolver are module pins, not per
- report; they are included so one event names every model a turn spent on.
+ and Full finding outcomes read the report's arm when the outcome is classified. `review_mode`
+ is the turn's, and the per-turn events pass it so a flash turn names the flash arm in both seats.
+ Flash finding outcomes override these pins with their saved configuration in
+ `finding_routing_properties`. The resolver is a module pin, not per report; it is included so
+ one event names every model a turn spent on.
"""
persisted = (
report.review_runtime_adapter,
@@ -28,9 +57,18 @@ def review_routing_properties(report: ReviewReport) -> dict[str, str | bool | No
report.review_reasoning_effort,
report.review_initial_permission_mode,
)
- arm = resolve_review_arm(*persisted)
- resolved = (arm.runtime_adapter.value, arm.model, arm.reasoning_effort.value, arm.initial_permission_mode)
+ stored_arm = resolve_review_arm(*persisted)
+ resolved = (
+ stored_arm.runtime_adapter.value,
+ stored_arm.model,
+ stored_arm.reasoning_effort.value,
+ stored_arm.initial_permission_mode,
+ )
+ mode = review_mode if review_mode is not None else REVIEW_MODE_FULL
+ arm = review_arm_for_mode(mode, stored_arm)
+ validator = validation_arm_for_mode(mode)
return {
+ "review_mode": review_mode,
"review_tier": report.review_tier,
"signal_priority": report.review_signal_priority,
"signal_report_id": str(report.signal_report_id) if report.signal_report_id else None,
@@ -41,9 +79,33 @@ def review_routing_properties(report: ReviewReport) -> dict[str, str | bool | No
# instead of its tier's arm; per-tier dashboards must exclude these contaminated turns.
# The whole bundle is compared because a failed assignment can share the default arm's model
# string while differing on adapter or effort. Pre-arm rows (all NULL) stay False.
- "review_arm_fallback": any(persisted) and resolved != persisted,
- "validator_model": VALIDATION_MODEL,
- "validator_reasoning_effort": VALIDATION_REASONING_EFFORT.value if VALIDATION_REASONING_EFFORT else None,
+ "review_arm_fallback": mode != REVIEW_MODE_FLASH and any(persisted) and resolved != persisted,
+ "validator_model": validator.model,
+ "validator_reasoning_effort": validator.reasoning_effort.value,
"resolution_model": RESOLUTION_MODEL,
"resolution_reasoning_effort": RESOLUTION_REASONING_EFFORT.value if RESOLUTION_REASONING_EFFORT else None,
}
+
+
+def finding_routing_properties(report: ReviewReport, finding: ReviewIssueFinding) -> dict[str, str | bool | None]:
+ """Flash does not change the report's arm, so its outcomes need the finding's saved model pins.
+
+ Full outcomes keep the report-level arm semantics. Findings without a readable context retain
+ the legacy labels and an unknown mode; an absent snapshot cannot establish that Flash ran.
+ """
+ context = None
+ if finding.validation_context is not None:
+ try:
+ context = _FindingModelContext.model_validate_json(finding.validation_context)
+ except ValidationError:
+ pass
+ properties = review_routing_properties(report, review_mode=context.review_mode if context else None)
+ if context is not None and context.review_mode == REVIEW_MODE_FLASH:
+ properties.update(
+ review_runtime_adapter=context.review_arm.runtime_adapter.value,
+ review_model=context.review_arm.model,
+ review_reasoning_effort=context.review_arm.reasoning_effort.value,
+ validator_model=context.validation_arm.model,
+ validator_reasoning_effort=context.validation_arm.reasoning_effort.value,
+ )
+ return properties
diff --git a/products/review_hog/backend/reviewer/tests/test_constants.py b/products/review_hog/backend/reviewer/tests/test_constants.py
index 0a094d3f889e..352308b2a1b2 100644
--- a/products/review_hog/backend/reviewer/tests/test_constants.py
+++ b/products/review_hog/backend/reviewer/tests/test_constants.py
@@ -11,12 +11,16 @@ from products.review_hog.backend.reviewer.constants import (
DEDUP_REASONING_EFFORT,
DEDUP_RUNTIME_ADAPTER,
DEFAULT_REVIEW_ARM,
+ DEFAULT_VALIDATION_ARM,
+ FLASH_ARM,
HUMAN_TRIGGER_SOURCES,
RESOLUTION_MODEL,
RESOLUTION_REASONING_EFFORT,
RESOLUTION_RUNTIME_ADAPTER,
REVIEW_ARMS_BY_TIER,
REVIEW_MCP_SCOPES,
+ REVIEW_MODE_FLASH,
+ REVIEW_MODE_FULL,
REVIEW_MODEL,
REVIEW_REASONING_EFFORT,
REVIEW_RUNTIME_ADAPTER,
@@ -27,7 +31,9 @@ from products.review_hog.backend.reviewer.constants import (
ReviewTier,
is_below_human_tier,
resolve_review_arm,
+ review_arm_for_mode,
select_review_tier,
+ validation_arm_for_mode,
)
from products.review_hog.backend.temporal.types import TRIGGER_INBOX
from products.signals.backend.enums import ReportPriority
@@ -84,7 +90,11 @@ def test_sandbox_fallback_runtime_is_a_registry_supported_combo(
assert get_provider_for_runtime_adapter(adapter) == LLMProvider.ANTHROPIC
[email protected]("arm", [pytest.param(arm, id=tier.value) for tier, arm in REVIEW_ARMS_BY_TIER.items()])
+ "arm",
+ [pytest.param(arm, id=tier.value) for tier, arm in REVIEW_ARMS_BY_TIER.items()]
+ + [pytest.param(FLASH_ARM, id="flash")],
+)
def test_tier_arm_is_a_registry_supported_combo(arm: ReviewArm) -> None:
# Same lock as the pinned combos, per tier: a bad combo is persisted onto every report in the
# tier and fails only mid-review in prod. A Codex arm without "full-access" stalls every
@@ -200,3 +210,21 @@ def test_review_mcp_scopes_open_a_session_and_stay_read_only() -> None:
assert "user:read" in resolved
assert "llm_skill:read" in resolved
assert not has_write_scopes(REVIEW_MCP_SCOPES)
+
+
+ "review_mode,expected_review,expected_validation",
+ [
+ # A flash turn swaps both seats; a full turn keeps the report's own arm and the validator pins.
+ # A helper that read the pins for flash would run the expensive review under a cheap label
+ # and the analytics events, which share these helpers, would misprice every flash turn.
+ pytest.param(REVIEW_MODE_FLASH, FLASH_ARM, FLASH_ARM, id="flash"),
+ pytest.param(REVIEW_MODE_FULL, REVIEW_ARMS_BY_TIER[ReviewTier.AGENT_P2], DEFAULT_VALIDATION_ARM, id="full"),
+ ],
+)
+def test_mode_helpers_pick_both_seats(
+ review_mode: str, expected_review: ReviewArm, expected_validation: ReviewArm
+) -> None:
+ persisted = REVIEW_ARMS_BY_TIER[ReviewTier.AGENT_P2]
+ assert review_arm_for_mode(review_mode, persisted) == expected_review
+ assert validation_arm_for_mode(review_mode) == expected_validation
diff --git a/products/review_hog/backend/reviewer/tests/test_publish_review.py b/products/review_hog/backend/reviewer/tests/test_publish_review.py
index 53618d74b855..9a73239e4487 100644
--- a/products/review_hog/backend/reviewer/tests/test_publish_review.py
+++ b/products/review_hog/backend/reviewer/tests/test_publish_review.py
@@ -95,6 +95,38 @@ class TestPostGithubReview:
assert payload["commit_id"] == "deadbeef"
assert payload["comments"] == comments
+ def test_message_prefix_opens_the_promo_the_body_and_every_inline_comment(
+ self, mock_request: MagicMock, mock_paginated: MagicMock
+ ) -> None:
+ # A flash review is labeled on every message it writes. A prefix applied to the body alone
+ # would leave inline comments indistinguishable from a full review's, and one applied after
+ # redaction would bypass the credential scrub on the prefixed text.
+ _wire_readbacks(mock_paginated)
+ comments: list[ReviewComment] = [
+ {"path": "a.py", "body": "first", "side": "RIGHT", "line": 1},
+ {"path": "b.py", "body": "second", "side": "RIGHT", "line": 2},
+ ]
+
+ _post_github_review(
+ "o",
+ "r",
+ 1,
+ "body",
+ comments,
+ token="t",
+ head_sha="",
+ post_promo=True,
+ marker="m",
+ promo_marker="pm",
+ message_prefix="FLASH MODE\n",
+ )
+
+ (promo,) = _promo_posts(mock_request)
+ assert promo["body"].startswith("FLASH MODE\nPostHog Review alpha")
+ (payload,) = _review_posts(mock_request)
+ assert payload["body"] == "FLASH MODE\nbody"
+ assert [c["body"] for c in payload["comments"]] == ["FLASH MODE\nfirst", "FLASH MODE\nsecond"]
+
def test_credential_shapes_are_scrubbed_before_posting(
self, mock_request: MagicMock, mock_paginated: MagicMock
) -> None:
diff --git a/products/review_hog/backend/reviewer/tools/issue_validation.py b/products/review_hog/backend/reviewer/tools/issue_validation.py
index 8260d5b2e70e..f0e83412fb27 100644
--- a/products/review_hog/backend/reviewer/tools/issue_validation.py
+++ b/products/review_hog/backend/reviewer/tools/issue_validation.py
@@ -27,9 +27,8 @@ def build_validation_prompt(
) -> str:
"""Render the validation prompt for one issue against the live codebase.
- The keep/drop criteria aren't spliced in — the prompt instructs the agent to `skill-get` them
- over MCP — so we pass the validation skill's name and pinned version, not its body. `pr_files`
- is already narrowed to the issue's own file by the caller.
+ The prompt instructs the agent to pull the validation criteria over MCP using the skill's name
+ and pinned version. `pr_files` is already narrowed to the issue's own file by the caller.
"""
claude_code_context = prepare_code_context([issue.file], pr_files) if issue.file else ""
template, schema = load_template_and_schema("issue_validation")
diff --git a/products/review_hog/backend/reviewer/tools/issues_review.py b/products/review_hog/backend/reviewer/tools/issues_review.py
index e6a3d03755ff..159b02463902 100644
--- a/products/review_hog/backend/reviewer/tools/issues_review.py
+++ b/products/review_hog/backend/reviewer/tools/issues_review.py
@@ -71,9 +71,9 @@ def build_review_prompt(
Each (perspective × chunk) review is independent — no cross-perspective context; overlap between
perspectives is resolved downstream by deduplication. The reviewer reconstructs the chunk's intent
itself from the diff + `<pr_intent>` (its mandated investigation step), so no separate analysis
- pass is fed in. The skill's focus isn't spliced in — the prompt instructs the agent to `skill-get`
- it over MCP — so we pass the skill name and pinned version, not its body. `prior_findings` are
- problems earlier turns already found on this chunk's files; surfacing them tells the agent not to
+ pass is fed in. The prompt instructs the agent to pull the skill over MCP using its name and
+ pinned version. `prior_findings` are problems earlier turns already found on this chunk's files;
+ surfacing them tells the agent not to
re-investigate already-covered ground.
The blind-spot check adds cross-perspective context WITHIN a turn: `same_turn_findings` are issues
diff --git a/products/review_hog/backend/reviewer/tools/publish_review.py b/products/review_hog/backend/reviewer/tools/publish_review.py
index 5bb8e2563821..fe0f7afd2456 100644
--- a/products/review_hog/backend/reviewer/tools/publish_review.py
+++ b/products/review_hog/backend/reviewer/tools/publish_review.py
@@ -6,7 +6,12 @@ from posthog.egress.github.transport import GitHubRateLimitError
from products.review_hog.backend.models import ReviewReport
from products.review_hog.backend.reviewer.artefact_content import ReviewIssueFinding, ValidationVerdict
-from products.review_hog.backend.reviewer.constants import effective_priority, published_priorities_for
+from products.review_hog.backend.reviewer.constants import (
+ REVIEW_MODE_FULL,
+ effective_priority,
+ message_prefix_for_mode,
+ published_priorities_for,
+)
from products.review_hog.backend.reviewer.diff_position import build_diff_line_map, find_diff_position
from products.review_hog.backend.reviewer.models.github_meta import PRFile
from products.review_hog.backend.reviewer.models.issues_review import IssuePriority
@@ -67,6 +72,7 @@ def publish_persisted_review(
token: str,
urgency_threshold: IssuePriority,
installation_id: str | None = None,
+ review_mode: str = REVIEW_MODE_FULL,
) -> PublishOutcome:
"""Publish an already-computed review for `report_id` at `head_sha`, idempotently.
@@ -102,6 +108,7 @@ def publish_persisted_review(
post_promo=report.published_head_sha is None,
published_priorities=published_priorities_for(urgency_threshold),
installation_id=installation_id,
+ review_mode=review_mode,
)
if outcome.posted:
if report.outcomes_emitted_at is not None:
@@ -171,6 +178,7 @@ def publish_review(
post_promo: bool,
published_priorities: set[IssuePriority],
installation_id: str | None = None,
+ review_mode: str = REVIEW_MODE_FULL,
) -> PublishOutcome:
"""Publish the review to GitHub: the stored body plus inline comments from the durable rows.
@@ -222,6 +230,7 @@ def publish_review(
marker=marker,
promo_marker=_promo_marker(report_id),
installation_id=installation_id,
+ message_prefix=message_prefix_for_mode(review_mode),
)
return PublishOutcome(posted=True, review_url=review_url)
@@ -439,9 +448,12 @@ def _post_github_review(
marker: str,
promo_marker: str,
installation_id: str | None = None,
+ message_prefix: str = "",
) -> str | None:
"""Post the review to GitHub as a PR review, pinned to the reviewed `head_sha`.
+ `message_prefix` opens every message this post writes (the promo comment, the review body, each
+ inline comment), so a flash review is labeled as one wherever it shows up on the PR.
Returns the posted review's permalink, or None on the marker-found idempotency skip.
"""
# Idempotency: if our own review for this (report, head) is already on the PR — we posted it but
@@ -460,7 +472,7 @@ def _post_github_review(
installation_id=installation_id,
endpoint="/repos/{owner}/{repo}/issues/{issue_number}/comments",
json={
- "body": "PostHog Review alpha \U0001f994 "
+ "body": f"{message_prefix}PostHog Review alpha \U0001f994 "
"If you find any issues helpful - "
'please reply "valid", "invalid", etc., '
f"for evaluation purposes \U0001f64f\n\n{promo_marker}"
@@ -472,10 +484,10 @@ def _post_github_review(
# the probe isolates an unresolvable commit (stale/unreachable head) from a comment-positioning
# failure, so we post unpinned rather than failing (or dropping the inline comments).
# The review and validation sandboxes hold live tokens, and the model text arrives here unfiltered.
- body, redacted = redact_secrets(body)
+ body, redacted = redact_secrets(f"{message_prefix}{body}")
scrubbed: list[ReviewComment] = []
for comment in comments:
- comment_body, count = redact_secrets(comment["body"])
+ comment_body, count = redact_secrets(f"{message_prefix}{comment['body']}")
redacted += count
scrubbed.append({**comment, "body": comment_body})
comments = scrubbed
diff --git a/products/review_hog/backend/temporal/activities.py b/products/review_hog/backend/temporal/activities.py
index ef1da6f85941..1d285e470280 100644
--- a/products/review_hog/backend/temporal/activities.py
+++ b/products/review_hog/backend/temporal/activities.py
@@ -14,7 +14,6 @@ access goes through `database_sync_to_async(..., thread_sensitive=False)`; `@sco
`@close_db_connections` mirror the Signals report activities.
"""
-import uuid
import logging
import datetime
from collections import Counter
@@ -41,13 +40,13 @@ from products.review_hog.backend.reviewer.constants import (
CHUNKING_REASONING_EFFORT,
CHUNKING_RUNTIME_ADAPTER,
DEFAULT_URGENCY_THRESHOLD,
- VALIDATION_INITIAL_PERMISSION_MODE,
+ REVIEW_MODE_FLASH,
+ REVIEW_MODE_FULL,
VALIDATION_MAX_ATTEMPTS,
- VALIDATION_MODEL,
- VALIDATION_REASONING_EFFORT,
- VALIDATION_RUNTIME_ADAPTER,
effective_priority,
published_priorities_for,
+ review_arm_for_mode,
+ validation_arm_for_mode,
)
from products.review_hog.backend.reviewer.lazy_seed import (
sync_canonical_authoring,
@@ -77,11 +76,11 @@ from products.review_hog.backend.reviewer.persistence import (
load_valid_findings,
persist_chunk_set,
persist_commit_snapshot,
- persist_findings,
persist_perspective_results,
persist_perspective_selection,
persist_pr_snapshot,
persist_verdict,
+ replace_deduplicated_findings,
upsert_review_report,
)
from products.review_hog.backend.reviewer.sandbox.direct_llm import run_oneshot_review
@@ -104,7 +103,7 @@ from products.review_hog.backend.reviewer.status_comment import (
finalize_status_comment,
maybe_refresh_status_comment,
)
-from products.review_hog.backend.reviewer.telemetry import review_routing_properties
+from products.review_hog.backend.reviewer.telemetry import review_event_uuid, review_routing_properties
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,
@@ -173,6 +172,9 @@ class FetchPRDataInput:
trigger_source: str = TRIGGER_MANUAL
# `ReportPriority` value the trigger read before the implementation agent could write its own.
signal_priority: str | None = None
+ # This turn's mode. Read only to hold the tier back on a flash turn: the persisted arm must stay
+ # what the PR's next normal review runs on. Defaulted so pre-field payloads stay full reviews.
+ review_mode: str = REVIEW_MODE_FULL
@dataclass
@@ -270,7 +272,7 @@ class GenerateSchemasInput:
pass
-@dataclass
+@dataclass(frozen=False)
class SandboxStageInput:
"""Shared identity + turn scope for a sandbox-turn activity."""
@@ -281,6 +283,10 @@ class SandboxStageInput:
repository: str
branch: str
run_index: int
+ # What this turn runs on (`REVIEW_MODE_FULL` / `REVIEW_MODE_FLASH`); picks the reviewer and
+ # validator arms and labels every GitHub message. Keyword-only with a default so subclasses keep
+ # their positional fields and pre-field payloads deserialize as full reviews.
+ review_mode: str = field(default=REVIEW_MODE_FULL, kw_only=True)
@dataclass
@@ -365,7 +371,7 @@ class BuildBodyInput:
will_publish: bool = False
-@dataclass
+@dataclass(frozen=False)
class PublishInput:
team_id: int
report_id: str
@@ -376,6 +382,7 @@ class PublishInput:
pr_number: int
# Same snapshot as `BuildBodyInput.urgency_threshold`, so body counts and comments agree.
urgency_threshold: str = IssuePriority.CONSIDER.value
+ review_mode: str = REVIEW_MODE_FULL
@dataclass
@@ -422,6 +429,8 @@ class TrackReviewCompletedInput:
# and a person's re-trigger of an inbox report is the case the tier telemetry has to see.
# Defaulted so in-flight payloads from before the field still deserialize.
turn_trigger_source: str | None = None
+ # What THIS turn ran on; the event names the flash arm in both seats for a flash turn.
+ review_mode: str = REVIEW_MODE_FULL
@frozen
@@ -433,6 +442,7 @@ class TrackReviewStartedInput:
head_sha: str
run_index: int
turn_trigger_source: str | None
+ review_mode: str = REVIEW_MODE_FULL
@frozen
@@ -443,14 +453,16 @@ class TrackReviewFailedInput:
report_id: str
run_index: int
turn_trigger_source: str | None = None
+ review_mode: str = REVIEW_MODE_FULL
-@dataclass
+@dataclass(frozen=False)
class StatusCommentInput:
"""Kickoff / failure edits of the PR's status comment; owner/repo/pr come off the report row."""
team_id: int
report_id: str
+ review_mode: str = REVIEW_MODE_FULL
# --- Setup activities ------------------------------------------------------------------------------
@@ -465,9 +477,11 @@ def _sandbox_workflow_id_prefix(step_name: str) -> str:
return f"{activity.info().workflow_id}:{step_name}".lower()
-async def _refresh_status_comment(team_id: int, report_id: str) -> None:
+async def _refresh_status_comment(team_id: int, report_id: str, review_mode: str) -> None:
"""Refresh the PR's status comment after this activity persisted progress (debounced, best-effort)."""
- await database_sync_to_async(maybe_refresh_status_comment, thread_sensitive=False)(team_id, report_id)
+ await database_sync_to_async(maybe_refresh_status_comment, thread_sensitive=False)(
+ team_id, report_id, review_mode=review_mode
+ )
def _github_integration_exists(team_id: int) -> bool:
@@ -572,7 +586,9 @@ def _fetch_and_persist(input: FetchPRDataInput) -> ReviewMeta:
trigger_source=input.trigger_source,
# Only the creating turn routes on it: the upsert is what knows whether the row exists.
signal_priority=ReportPriority(input.signal_priority) if input.signal_priority is not None else None,
- lift_tier_on_human_trigger=True,
+ # A flash trigger never lifts: the lift rewrites the persisted arm, and the person asking for
+ # the cheap review would raise what every later normal turn costs.
+ lift_tier_on_human_trigger=input.review_mode != REVIEW_MODE_FLASH,
)
# Read the report's watermark BEFORE persist_commit_snapshot advances it, so the parent can decide
# whether this turn has anything to do. `published_head_sha == head_sha` means we already reviewed
@@ -760,7 +776,7 @@ async def split_chunks_activity(input: SandboxStageInput) -> list[int]:
)
if existing is not None:
logger.info("Reusing persisted chunk set for this turn")
- await _refresh_status_comment(input.team_id, input.report_id)
+ await _refresh_status_comment(input.team_id, input.report_id, input.review_mode)
return [chunk.chunk_id for chunk in existing.chunks]
snapshot = await database_sync_to_async(load_pr_snapshot, thread_sensitive=False)(
@@ -777,7 +793,7 @@ async def split_chunks_activity(input: SandboxStageInput) -> list[int]:
await database_sync_to_async(persist_chunk_set, thread_sensitive=False)(
team_id=input.team_id, report_id=input.report_id, head_sha=input.head_sha, chunks=planned
)
- await _refresh_status_comment(input.team_id, input.report_id)
+ await _refresh_status_comment(input.team_id, input.report_id, input.review_mode)
return [chunk.chunk_id for chunk in planned.chunks]
prompt = generate_chunking_prompt(snapshot.pr_metadata, snapshot.pr_comments, snapshot.pr_files)
@@ -817,7 +833,7 @@ async def split_chunks_activity(input: SandboxStageInput) -> list[int]:
await database_sync_to_async(persist_chunk_set, thread_sensitive=False)(
team_id=input.team_id, report_id=input.report_id, head_sha=input.head_sha, chunks=chunks
)
- await _refresh_status_comment(input.team_id, input.report_id)
+ await _refresh_status_comment(input.team_id, input.report_id, input.review_mode)
return [chunk.chunk_id for chunk in chunks.chunks]
@@ -889,7 +905,7 @@ async def select_perspectives_activity(input: SelectPerspectivesInput) -> Perspe
roster=[p.skill_name for p in input.perspectives],
selection=selection,
)
- await _refresh_status_comment(input.team_id, input.report_id)
+ await _refresh_status_comment(input.team_id, input.report_id, input.review_mode)
return PerspectiveSelectionDTO.from_model(selection)
@@ -919,9 +935,10 @@ def _prepare_review_prompt(
run_index: int,
blind_spot_check: bool,
wave_perspectives: list[LoadedPerspectiveDTO],
+ review_model: str,
) -> str | None:
"""Build the review prompt for one (perspective, chunk), or None if already reviewed this turn."""
- done = load_perspective_results(team_id=team_id, report_id=report_id, head_sha=head_sha)
+ done = load_perspective_results(team_id=team_id, report_id=report_id, head_sha=head_sha, review_model=review_model)
if (pass_number, chunk_id) in done:
return None
snapshot = load_pr_snapshot(team_id=team_id, report_id=report_id, head_sha=head_sha)
@@ -959,6 +976,14 @@ def _prepare_review_prompt(
@close_db_connections
async def review_chunk_activity(input: ReviewChunkInput) -> bool:
"""Review one chunk through one perspective (or the blind-spot check) and persist it (idempotent)."""
+ # The report's persisted arm (its tier's, decided at creation), not the module pins. Each unit
+ # resolves it against the live registry, so all units of a turn agree unless a deploy
+ # deregisters the model mid-turn — which is why a tier's arm changes in REVIEW_ARMS_BY_TIER,
+ # never by deregistering the model. A flash turn overrides it with the flash arm for this turn only.
+ persisted_arm = await database_sync_to_async(load_review_arm, thread_sensitive=False)(
+ team_id=input.team_id, report_id=input.report_id
+ )
+ arm = review_arm_for_mode(input.review_mode, persisted_arm)
prompt = await database_sync_to_async(_prepare_review_prompt, thread_sensitive=False)(
input.team_id,
input.report_id,
@@ -970,6 +995,7 @@ async def review_chunk_activity(input: ReviewChunkInput) -> bool:
input.run_index,
input.blind_spot_check,
input.wave_perspectives,
+ arm.model,
)
if prompt is None:
return True
@@ -978,13 +1004,6 @@ async def review_chunk_activity(input: ReviewChunkInput) -> bool:
if input.blind_spot_check
else f"issues-review-p{input.pass_number}-c{input.chunk_id}"
)
- # The report's persisted arm (its tier's, decided at creation), not the module pins. Each unit
- # resolves it against the live registry, so all units of a turn agree unless a deploy
- # deregisters the model mid-turn — which is why a tier's arm changes in REVIEW_ARMS_BY_TIER,
- # never by deregistering the model.
- arm = await database_sync_to_async(load_review_arm, thread_sensitive=False)(
- team_id=input.team_id, report_id=input.report_id
- )
async with Heartbeater():
review = await run_sandbox_review(
team_id=input.team_id,
@@ -1010,16 +1029,19 @@ async def review_chunk_activity(input: ReviewChunkInput) -> bool:
report_id=input.report_id,
head_sha=input.head_sha,
results={(input.pass_number, input.chunk_id): review},
+ review_model=arm.model,
)
- await _refresh_status_comment(input.team_id, input.report_id)
+ await _refresh_status_comment(input.team_id, input.report_id, input.review_mode)
return True
# --- Combine + scope-clean + dedup -----------------------------------------------------------------
-def _combine_and_clean(team_id: int, report_id: str, head_sha: str) -> list[Issue]:
- perspective_results = load_perspective_results(team_id=team_id, report_id=report_id, head_sha=head_sha)
+def _combine_and_clean(team_id: int, report_id: str, head_sha: str, review_model: str) -> list[Issue]:
+ perspective_results = load_perspective_results(
+ team_id=team_id, report_id=report_id, head_sha=head_sha, review_model=review_model
+ )
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 []
raw_issues = combine_issues(perspective_results)
@@ -1037,8 +1059,13 @@ async def dedup_activity(input: SandboxStageInput) -> DedupResult:
stages reload the issue content from the finding rows, so the unbounded issue list never crosses
a Temporal payload boundary by value.
"""
+ # Only this turn's reviewer's results are combined: a flash and a full turn can share a commit.
+ persisted_arm = await database_sync_to_async(load_review_arm, thread_sensitive=False)(
+ team_id=input.team_id, report_id=input.report_id
+ )
+ review_arm = review_arm_for_mode(input.review_mode, persisted_arm)
issues = await database_sync_to_async(_combine_and_clean, thread_sensitive=False)(
- input.team_id, input.report_id, input.head_sha
+ input.team_id, input.report_id, input.head_sha, review_arm.model
)
snapshot = await database_sync_to_async(load_pr_snapshot, thread_sensitive=False)(
team_id=input.team_id, report_id=input.report_id, head_sha=input.head_sha
@@ -1063,10 +1090,17 @@ async def dedup_activity(input: SandboxStageInput) -> DedupResult:
repository=input.repository,
workflow_id_prefix=_sandbox_workflow_id_prefix("dedup"),
)
- issue_ids = await database_sync_to_async(persist_findings, thread_sensitive=False)(
- team_id=input.team_id, report_id=input.report_id, issues=survivors, run_index=input.run_index
+ issue_ids = await database_sync_to_async(replace_deduplicated_findings, thread_sensitive=False)(
+ team_id=input.team_id,
+ report_id=input.report_id,
+ issues=survivors,
+ run_index=input.run_index,
+ head_sha=input.head_sha,
+ review_mode=input.review_mode,
+ review_arm=review_arm,
+ validation_arm=validation_arm_for_mode(input.review_mode),
)
- await _refresh_status_comment(input.team_id, input.report_id)
+ await _refresh_status_comment(input.team_id, input.report_id, input.review_mode)
return DedupResult(issue_ids=issue_ids)
@@ -1134,6 +1168,7 @@ async def validate_chunk_activity(input: ValidateChunkInput) -> ValidateChunkRes
validated = len(done)
final_attempt = activity.info().attempt >= VALIDATION_MAX_ATTEMPTS
+ validator = validation_arm_for_mode(input.review_mode)
session: MultiTurnSession | None = None
chunk_ok = False
try:
@@ -1159,10 +1194,10 @@ async def validate_chunk_activity(input: ValidateChunkInput) -> ValidateChunkRes
model_to_validate=IssueValidation,
step_name=f"validation-c{input.chunk_id}",
workflow_id_prefix=_sandbox_workflow_id_prefix(f"validation-c{input.chunk_id}"),
- runtime_adapter=VALIDATION_RUNTIME_ADAPTER,
- model=VALIDATION_MODEL,
- reasoning_effort=VALIDATION_REASONING_EFFORT,
- initial_permission_mode=VALIDATION_INITIAL_PERMISSION_MODE,
+ runtime_adapter=validator.runtime_adapter,
+ model=validator.model,
+ reasoning_effort=validator.reasoning_effort,
+ initial_permission_mode=validator.initial_permission_mode,
)
else:
validation = await continue_sandbox_session(
@@ -1207,7 +1242,7 @@ async def validate_chunk_activity(input: ValidateChunkInput) -> ValidateChunkRes
status="completed" if chunk_ok else "failed",
error=None if chunk_ok else "validation chunk failed mid-session",
)
- await _refresh_status_comment(input.team_id, input.report_id)
+ await _refresh_status_comment(input.team_id, input.report_id, input.review_mode)
return ValidateChunkResult(chunk_id=input.chunk_id, validated_count=validated)
@@ -1267,6 +1302,7 @@ def _publish(input: PublishInput) -> PublishResult:
token=token,
urgency_threshold=IssuePriority(input.urgency_threshold),
installation_id=installation_id,
+ review_mode=input.review_mode,
)
return PublishResult(posted=outcome.posted, review_url=outcome.review_url)
@@ -1353,12 +1389,16 @@ def _track_review_started(input: TrackReviewStartedInput) -> None:
posthoganalytics.capture(
distinct_id=_review_event_identity(report),
event="reviewhog_review_started",
- # Deterministic per turn, like the completed event: a parent retry re-runs the gates and
- # re-captures the same uuid, so a turn starts once however many attempts it takes.
- uuid=str(uuid.uuid5(uuid.NAMESPACE_URL, f"reviewhog_review_started:{input.report_id}:{input.run_index}")),
+ # A parent retry must not count another start for the same turn and mode.
+ uuid=review_event_uuid(
+ "reviewhog_review_started",
+ report_id=input.report_id,
+ run_index=input.run_index,
+ review_mode=input.review_mode,
+ ),
properties={
**_turn_event_properties(report, run_index=input.run_index, turn_trigger_source=input.turn_trigger_source),
- **review_routing_properties(report),
+ **review_routing_properties(report, review_mode=input.review_mode),
**_pr_size_properties(snapshot),
},
groups=groups(team=report.team),
@@ -1408,9 +1448,13 @@ def _track_review_completed(input: TrackReviewCompletedInput) -> None:
posthoganalytics.capture(
distinct_id=_review_event_identity(report),
event="reviewhog_review_completed",
- # Deterministic per turn: an activity retry that re-captures after a worker crash emits the
- # same event uuid, so ingestion dedupes it instead of double-counting the review.
- uuid=str(uuid.uuid5(uuid.NAMESPACE_URL, f"reviewhog_review_completed:{input.report_id}:{input.run_index}")),
+ # Activity retries must not double-count a completed turn within its review mode.
+ uuid=review_event_uuid(
+ "reviewhog_review_completed",
+ report_id=input.report_id,
+ run_index=input.run_index,
+ review_mode=input.review_mode,
+ ),
properties={
**_turn_event_properties(report, run_index=input.run_index, turn_trigger_source=input.turn_trigger_source),
"published": input.published,
@@ -1419,7 +1463,7 @@ def _track_review_completed(input: TrackReviewCompletedInput) -> None:
"findings_must_fix": valid_by_priority.get(IssuePriority.MUST_FIX, 0),
"findings_should_fix": valid_by_priority.get(IssuePriority.SHOULD_FIX, 0),
"findings_consider": valid_by_priority.get(IssuePriority.CONSIDER, 0),
- **review_routing_properties(report),
+ **review_routing_properties(report, review_mode=input.review_mode),
**_pr_size_properties(snapshot),
"duration_seconds": duration_seconds,
},
@@ -1455,13 +1499,16 @@ def _track_review_failed(input: TrackReviewFailedInput) -> None:
posthoganalytics.capture(
distinct_id=_review_event_identity(report),
event="reviewhog_review_failed",
- # Deterministic per turn, like the completed event: repeated failures of the same turn (a
- # re-trigger that dies again before finalize bumps run_count) dedupe to one event, so
- # completion rate counts turns, not attempts.
- uuid=str(uuid.uuid5(uuid.NAMESPACE_URL, f"reviewhog_review_failed:{input.report_id}:{input.run_index}")),
+ # Failures of the same turn and mode dedupe so retries do not lower its completion rate.
+ uuid=review_event_uuid(
+ "reviewhog_review_failed",
+ report_id=input.report_id,
+ run_index=input.run_index,
+ review_mode=input.review_mode,
+ ),
properties={
**_turn_event_properties(report, run_index=input.run_index, turn_trigger_source=input.turn_trigger_source),
- **review_routing_properties(report),
+ **review_routing_properties(report, review_mode=input.review_mode),
},
groups=groups(team=report.team),
send_feature_flags=True,
@@ -1485,9 +1532,10 @@ async def track_review_failed_activity(input: TrackReviewFailedInput) -> None:
The completed event alone hides failures: a run that dies never emits it, so an arm of the
reviewer-model experiment that crashes on its hardest PRs would silently shed them from every
per-review metric. This event is the denominator's other half, but do NOT naively sum event
- counts: the parent workflow retry makes fail-then-complete at the same (report_id, run_index)
- common, so a turn counts as failed only when it has a failed event and NO completed event
- (anti-join on report_id + run_index). Best-effort, like the completed event.
+ counts: a parent retry can fail and then complete at the same (report_id, run_index, review_mode),
+ so a turn counts as failed only when that combination has a failed event and no completed event.
+ Anti-join on report_id + run_index + review_mode, treating an absent mode as Full for legacy events.
+ Best-effort, like the completed event.
"""
await database_sync_to_async(_track_review_failed_safe, thread_sensitive=False)(input)
@@ -1504,7 +1552,9 @@ async def post_status_comment_activity(input: StatusCommentInput) -> None:
Dispatched only on the publish path once every gate has passed. Best-effort inside
(`ensure_status_comment` swallows failures), so it can't fail the review.
"""
- await database_sync_to_async(ensure_status_comment, thread_sensitive=False)(input.team_id, input.report_id)
+ await database_sync_to_async(ensure_status_comment, thread_sensitive=False)(
+ input.team_id, input.report_id, review_mode=input.review_mode
+ )
@activity.defn
@@ -1515,12 +1565,12 @@ async def finalize_status_comment_activity(input: FinalizeStatusCommentInput) ->
await database_sync_to_async(finalize_status_comment, thread_sensitive=False)(input)
-def _fail_run(team_id: int, report_id: str) -> None:
+def _fail_run(team_id: int, report_id: str, review_mode: str = REVIEW_MODE_FULL) -> None:
# The idle write comes first so a GitHub failure below can't skip it: on publishing runs
# finalize defers going idle to the publish stage, so a run dying between finalize and publish
# would otherwise sit ACTIVE (reading as in-progress in the UI) until the staleness cutoff.
ReviewReport.objects.for_team(team_id).filter(id=report_id).update(status=ReviewReport.Status.IDLE)
- fail_status_comment(team_id, report_id)
+ fail_status_comment(team_id, report_id, review_mode=review_mode)
@activity.defn
@@ -1532,7 +1582,7 @@ async def fail_status_comment_activity(input: StatusCommentInput) -> None:
The idle write lives in this activity rather than as its own workflow command so in-flight
histories replay unchanged (new unconditional commands break replay determinism).
"""
- await database_sync_to_async(_fail_run, thread_sensitive=False)(input.team_id, input.report_id)
+ await database_sync_to_async(_fail_run, thread_sensitive=False)(input.team_id, input.report_id, input.review_mode)
# --- The signals report's code_review receipt --------------------------------------------------------
diff --git a/products/review_hog/backend/temporal/client.py b/products/review_hog/backend/temporal/client.py
index 58775d2d9ec6..31701bcbbb25 100644
--- a/products/review_hog/backend/temporal/client.py
+++ b/products/review_hog/backend/temporal/client.py
@@ -39,6 +39,7 @@ from temporalio.service import RPCError, RPCStatusCode
from posthog.models.team.team import Team
from posthog.temporal.common.client import sync_connect
+from products.review_hog.backend.reviewer.constants import REVIEW_MODE_FULL
from products.review_hog.backend.reviewer.tools.github_meta import PRParser
from products.review_hog.backend.temporal.types import (
TRIGGER_MANUAL,
@@ -93,6 +94,7 @@ def _build_inputs(
head_branch: str | None,
resolve_comments: bool | None = None,
signal_priority: ReportPriority | None = None,
+ review_mode: str = REVIEW_MODE_FULL,
) -> tuple[ReviewPRWorkflowInputs, str]:
"""Validate the review target, the team, and build the workflow inputs + deterministic id.
@@ -129,6 +131,7 @@ def _build_inputs(
signal_priority=signal_priority.value if signal_priority is not None else None,
head_branch=head_branch,
resolve_comments=resolve_comments,
+ review_mode=review_mode,
)
return inputs, workflow_id
@@ -145,6 +148,7 @@ def execute_review_pr_workflow(
repository: str | None = None,
head_branch: str | None = None,
resolve_comments: bool | None = None,
+ review_mode: str = REVIEW_MODE_FULL,
) -> str:
"""Start `ReviewPRWorkflow`, block until it completes, and return the `ReviewReport` id.
@@ -164,6 +168,7 @@ def execute_review_pr_workflow(
repository=repository,
head_branch=head_branch,
resolve_comments=resolve_comments,
+ review_mode=review_mode,
)
# `sync_connect` is @async_to_sync, so call it from sync code (outside any running loop); the
@@ -198,6 +203,7 @@ def start_review_pr_workflow(
repository: str | None = None,
head_branch: str | None = None,
resolve_comments: bool | None = None,
+ review_mode: str = REVIEW_MODE_FULL,
) -> str:
"""Start `ReviewPRWorkflow` without blocking and return the workflow id.
@@ -223,10 +229,14 @@ def start_review_pr_workflow(
repository=repository,
head_branch=head_branch,
resolve_comments=resolve_comments,
+ review_mode=review_mode,
)
client = sync_connect()
- logger.info(f"Starting ReviewPRWorkflow {workflow_id} on {settings.VIDEO_EXPORT_TASK_QUEUE} (publish={publish})")
+ logger.info(
+ f"Starting ReviewPRWorkflow {workflow_id} on {settings.VIDEO_EXPORT_TASK_QUEUE} "
+ f"(publish={publish}, review_mode={review_mode})"
+ )
# async_to_sync erases start_workflow's overloads, so mypy binds the wrong one.
start_workflow = cast(Callable[..., Any], async_to_sync(client.start_workflow))
start_workflow(
diff --git a/products/review_hog/backend/temporal/types.py b/products/review_hog/backend/temporal/types.py
index 698efbe56df2..eb3271577f61 100644
--- a/products/review_hog/backend/temporal/types.py
+++ b/products/review_hog/backend/temporal/types.py
@@ -6,6 +6,8 @@ input without importing the workflow code (which pulls in the heavy activity dep
from posthog.dataclasses import frozen
+from products.review_hog.backend.reviewer.constants import REVIEW_MODE_FULL
+
# How a review run was triggered. Gates are trigger-aware: label → `review_labeled_prs`,
# inbox → `review_inbox_prs`, manual (CLI/eval) and ui (an explicit human ask from the Code review
# scene) → ungated. Plain strings (not an Enum) so Temporal payloads stay forward/backward-compatible
@@ -66,6 +68,10 @@ class ReviewPRWorkflowInputs:
# (False), while payloads serialized under the old `bool = False` default decode to an explicit
# False — in both cases the dispatch never fires for old histories, exactly as they ran.
resolve_comments: bool | None = None
+ # What this turn runs on (`REVIEW_MODE_FULL` / `REVIEW_MODE_FLASH`). Per turn, never persisted:
+ # a flash turn must not change what the PR's next normal review runs on. Defaulted so in-flight
+ # payloads from before the field still deserialize as full reviews.
+ review_mode: str = REVIEW_MODE_FULL
@property
def repository(self) -> str:
@@ -79,6 +85,7 @@ class ReviewPRWorkflowInputs:
"pr_number": self.pr_number,
"head_branch": self.head_branch,
"trigger_source": self.trigger_source,
+ "review_mode": self.review_mode,
}
diff --git a/products/review_hog/backend/temporal/workflow.py b/products/review_hog/backend/temporal/workflow.py
index f5789d05ce23..c711a35e150f 100644
--- a/products/review_hog/backend/temporal/workflow.py
+++ b/products/review_hog/backend/temporal/workflow.py
@@ -29,6 +29,7 @@ from products.review_hog.backend.reviewer.constants import (
BLIND_SPOT_PASS_NUMBER,
FAN_OUT_FAILURE_FLOOR,
MAX_CONCURRENT_SANDBOXES,
+ REVIEW_MODE_FLASH,
VALIDATION_MAX_ATTEMPTS,
)
from products.review_hog.backend.reviewer.status_comment import FinalizeStatusCommentInput
@@ -188,6 +189,7 @@ class ReviewPerspectivesWorkflow:
repository=inputs.repository,
branch=inputs.branch,
run_index=inputs.run_index,
+ review_mode=inputs.review_mode,
perspectives=ordered,
),
start_to_close_timeout=_SANDBOX_TIMEOUT,
@@ -217,6 +219,7 @@ class ReviewPerspectivesWorkflow:
repository=inputs.repository,
branch=inputs.branch,
run_index=inputs.run_index,
+ review_mode=inputs.review_mode,
chunk_id=chunk_id,
pass_number=pass_number,
skill_name=skill_name,
@@ -332,6 +335,7 @@ class ValidateIssuesWorkflow:
repository=inputs.repository,
branch=inputs.branch,
run_index=inputs.run_index,
+ review_mode=inputs.review_mode,
chunk_id=chunk_id,
issue_ids=chunk_issue_ids,
skill_name=skill.skill_name,
@@ -421,6 +425,7 @@ class ReviewPRWorkflow:
signal_report_id=inputs.signal_report_id,
trigger_source=inputs.trigger_source,
signal_priority=inputs.signal_priority,
+ review_mode=inputs.review_mode,
),
start_to_close_timeout=_FETCH_TIMEOUT,
retry_policy=_RETRY,
@@ -500,6 +505,7 @@ class ReviewPRWorkflow:
head_sha=head_sha,
run_index=meta.run_index,
turn_trigger_source=inputs.trigger_source,
+ review_mode=inputs.review_mode,
),
start_to_close_timeout=_QUICK_TIMEOUT,
retry_policy=_RETRY,
@@ -519,7 +525,7 @@ class ReviewPRWorkflow:
try:
await workflow.execute_activity(
post_status_comment_activity,
- StatusCommentInput(team_id=inputs.team_id, report_id=report_id),
+ StatusCommentInput(team_id=inputs.team_id, report_id=report_id, review_mode=inputs.review_mode),
start_to_close_timeout=_QUICK_TIMEOUT,
retry_policy=_RETRY,
)
@@ -549,6 +555,7 @@ class ReviewPRWorkflow:
repository=repository,
branch=branch,
run_index=meta.run_index,
+ review_mode=inputs.review_mode,
)
workflow.logger.info("STAGE 2/7 · Split into chunks")
@@ -573,6 +580,7 @@ class ReviewPRWorkflow:
repository=stage.repository,
branch=stage.branch,
run_index=stage.run_index,
+ review_mode=stage.review_mode,
chunk_ids=chunk_ids,
acting_user_id=acting_user_id,
),
@@ -603,6 +611,7 @@ class ReviewPRWorkflow:
repository=stage.repository,
branch=stage.branch,
run_index=stage.run_index,
+ review_mode=stage.review_mode,
issue_ids=dedup.issue_ids,
acting_user_id=acting_user_id,
),
@@ -643,6 +652,7 @@ class ReviewPRWorkflow:
# for a branch target.
pr_number=meta.pr_number,
urgency_threshold=acting.urgency_threshold,
+ review_mode=inputs.review_mode,
),
start_to_close_timeout=_QUICK_TIMEOUT,
retry_policy=_RETRY,
@@ -659,7 +669,7 @@ class ReviewPRWorkflow:
try:
await workflow.execute_activity(
fail_status_comment_activity,
- StatusCommentInput(team_id=inputs.team_id, report_id=report_id),
+ StatusCommentInput(team_id=inputs.team_id, report_id=report_id, review_mode=inputs.review_mode),
start_to_close_timeout=_QUICK_TIMEOUT,
retry_policy=_RETRY,
)
@@ -682,6 +692,7 @@ class ReviewPRWorkflow:
report_id=report_id,
run_index=meta.run_index,
turn_trigger_source=inputs.trigger_source,
+ review_mode=inputs.review_mode,
),
start_to_close_timeout=_QUICK_TIMEOUT,
retry_policy=_RETRY,
@@ -704,6 +715,7 @@ class ReviewPRWorkflow:
published=posted,
workflow_started_at=workflow.info().start_time.isoformat(),
turn_trigger_source=inputs.trigger_source,
+ review_mode=inputs.review_mode,
),
start_to_close_timeout=_QUICK_TIMEOUT,
retry_policy=_RETRY,
@@ -724,6 +736,7 @@ class ReviewPRWorkflow:
urgency_threshold=acting.urgency_threshold,
review_url=publish_result.review_url if publish_result is not None else None,
resolved_from=acting.resolved_from,
+ review_mode=inputs.review_mode,
),
start_to_close_timeout=_QUICK_TIMEOUT,
retry_policy=_RETRY,
@@ -755,6 +768,11 @@ class ReviewPRWorkflow:
if inputs.resolve_comments is not None
else (inputs.publish and acting.resolve_comments)
)
+ # A flash turn never writes code, whatever the override or the setting says: the trigger pins
+ # the override off, and this is the guarantee for any other producer of a flash input.
+ if resolve_after and inputs.review_mode == REVIEW_MODE_FLASH:
+ workflow.logger.info("Flash review: the resolution stage is never chained")
+ resolve_after = False
if resolve_after and meta.pr_number is not None:
workflow.logger.info("Dispatching the resolution stage for this PR")
try:
diff --git a/products/review_hog/backend/tests/test_fetch_review_tier.py b/products/review_hog/backend/tests/test_fetch_review_tier.py
index ff4cbedd277b..3e2a7aebd683 100644
--- a/products/review_hog/backend/tests/test_fetch_review_tier.py
+++ b/products/review_hog/backend/tests/test_fetch_review_tier.py
@@ -1,12 +1,16 @@
+from dataclasses import replace
+
from posthog.test.base import BaseTest
-from unittest.mock import patch
+from unittest.mock import MagicMock, patch
from django.test import override_settings
from products.review_hog.backend.models import ReviewReport
+from products.review_hog.backend.reviewer.constants import DEFAULT_REVIEW_ARM, REVIEW_MODE_FLASH
from products.review_hog.backend.reviewer.models.github_meta import PRMetadata
+from products.review_hog.backend.reviewer.persistence import load_review_arm
from products.review_hog.backend.temporal.activities import FetchPRDataInput, _fetch_and_persist
-from products.review_hog.backend.temporal.types import TRIGGER_INBOX
+from products.review_hog.backend.temporal.types import TRIGGER_INBOX, TRIGGER_UI
from products.signals.backend.models import SignalReport
_MODULE = "products.review_hog.backend.temporal.activities"
@@ -34,7 +38,9 @@ def _pr_metadata() -> PRMetadata:
class TestFetchDecidesTheTier(BaseTest):
@patch(f"{_MODULE}._installation_auth", return_value=("tok", "9876543"))
@patch(f"{_MODULE}.PRFetcher")
- def test_inbox_fetch_routes_a_new_report_by_its_signal_reports_priority(self, mock_fetcher, _auth) -> None:
+ def test_fetch_keeps_the_created_tier_until_a_full_human_review(
+ self, mock_fetcher: MagicMock, _auth: MagicMock
+ ) -> None:
# The tier is only as good as this wiring: a fetch that forgets to hand the trigger's
# priority to the upsert routes every agent PR as unprioritized, which is silently xhigh.
signal_report = SignalReport.objects.create(
@@ -43,24 +49,42 @@ class TestFetchDecidesTheTier(BaseTest):
mock_fetcher.return_value.fetch_pr_data.return_value = (_pr_metadata(), [], [], "")
with override_settings(REVIEWHOG_TEAM_IDS=[self.team.id]):
- meta = _fetch_and_persist(
- FetchPRDataInput(
- team_id=self.team.id,
- user_id=1,
- repository="o/r",
- owner="o",
- repo="r",
- pr_number=9,
- pr_url="https://github.com/o/r/pull/9",
- signal_report_id=str(signal_report.id),
- trigger_source=TRIGGER_INBOX,
- signal_priority="P3",
- )
+ fetch_input = FetchPRDataInput(
+ team_id=self.team.id,
+ user_id=1,
+ repository="o/r",
+ owner="o",
+ repo="r",
+ pr_number=9,
+ pr_url="https://github.com/o/r/pull/9",
+ signal_report_id=str(signal_report.id),
+ trigger_source=TRIGGER_INBOX,
+ signal_priority="P3",
)
+ meta = _fetch_and_persist(fetch_input)
- row = ReviewReport.objects.for_team(self.team.id).get(id=meta.report_id)
- assert (row.review_tier, row.review_signal_priority, row.review_reasoning_effort) == (
- "agent_p3_p4",
- "P3",
- "low",
- )
+ row = ReviewReport.objects.for_team(self.team.id).get(id=meta.report_id)
+ assert (row.review_tier, row.review_signal_priority, row.review_reasoning_effort) == (
+ "agent_p3_p4",
+ "P3",
+ "low",
+ )
+ original_arm = load_review_arm(team_id=self.team.id, report_id=meta.report_id)
+
+ _fetch_and_persist(replace(fetch_input, trigger_source=TRIGGER_UI, review_mode=REVIEW_MODE_FLASH))
+ row.refresh_from_db()
+ assert (row.review_tier, row.review_signal_priority, row.review_reasoning_effort) == (
+ "agent_p3_p4",
+ "P3",
+ "low",
+ )
+ assert load_review_arm(team_id=self.team.id, report_id=meta.report_id) == original_arm
+
+ _fetch_and_persist(replace(fetch_input, trigger_source=TRIGGER_UI))
+ row.refresh_from_db()
+ assert (row.review_tier, row.review_signal_priority, row.review_reasoning_effort) == (
+ "human",
+ "P3",
+ "xhigh",
+ )
+ assert load_review_arm(team_id=self.team.id, report_id=meta.report_id) == DEFAULT_REVIEW_ARM
diff --git a/products/review_hog/backend/tests/test_outcome_classify.py b/products/review_hog/backend/tests/test_outcome_classify.py
index a6e9b1b410f1..97ec5b46de44 100644
--- a/products/review_hog/backend/tests/test_outcome_classify.py
+++ b/products/review_hog/backend/tests/test_outcome_classify.py
@@ -1,4 +1,6 @@
+import json
from collections import defaultdict
+from dataclasses import asdict
from datetime import timedelta
from types import SimpleNamespace
from typing import Any
@@ -11,6 +13,7 @@ from unittest.mock import AsyncMock, patch
from django.utils import timezone
from asgiref.sync import async_to_sync
+from parameterized import parameterized
from temporalio.exceptions import ApplicationError
from posthog.models.team import Team
@@ -23,10 +26,16 @@ from products.review_hog.backend.reviewer.artefact_content import (
parse_artefact_content,
)
from products.review_hog.backend.reviewer.constants import (
+ DEFAULT_REVIEW_ARM,
+ DEFAULT_VALIDATION_ARM,
+ FLASH_ARM,
OUTCOME_JUDGE_FAILURE_STREAK,
OUTCOME_JUDGE_REASONING_MAX_CHARS,
OUTCOME_MAX_JUDGE_CALLS_PER_REPORT,
+ REVIEW_MODE_FLASH,
+ REVIEW_MODE_FULL,
VALIDATION_MODEL,
+ VALIDATION_REASONING_EFFORT,
)
from products.review_hog.backend.reviewer.models.issues_review import IssuePriority, LineRange
from products.review_hog.backend.reviewer.outcomes.classify import (
@@ -128,26 +137,54 @@ class TestClassifyReportDecision:
assert captured[0]["properties"]["outcome"] == "ignored"
assert captured[0]["properties"]["classification_method"] == "judge_rejected"
- def test_the_outcome_event_carries_the_review_arm(self):
- # Per-tier precision splits this event by the report's arm as it stands when the outcome is
- # classified: a row in a cheaper tier must label its findings with that tier and effort, not
- # the default pins.
+ @parameterized.expand(
+ [
+ ("legacy", None, "gpt-5.6-sol"),
+ ("unreadable", "unreadable", "gpt-5.6-sol"),
+ ("full", REVIEW_MODE_FULL, "gpt-5.6-sol"),
+ ("flash", REVIEW_MODE_FLASH, "gpt-5.6-sol"),
+ ("flash_with_stale_report_arm", REVIEW_MODE_FLASH, "gpt-removed"),
+ ]
+ )
+ def test_the_outcome_event_carries_the_review_arm(
+ self, _name: str, context_mode: str | None, report_model: str
+ ) -> None:
report = ReviewReport(
repository="o/r",
pr_number=7,
review_tier="agent_p2",
review_runtime_adapter="codex",
- review_model="gpt-5.6-sol",
+ review_model=report_model,
review_reasoning_effort="medium",
review_initial_permission_mode="full-access",
)
- captured, _judge = self._run(inputs=self._inputs(comment=None, compare_files=_TOUCHING), report=report)
+ inputs = self._inputs(comment=None, compare_files=_TOUCHING)
+ is_flash = context_mode == REVIEW_MODE_FLASH
+ if context_mode in (REVIEW_MODE_FULL, REVIEW_MODE_FLASH):
+ inputs.published[0].finding.validation_context = json.dumps(
+ {
+ "head_sha": "base_sha",
+ "review_mode": context_mode,
+ "review_arm": asdict(FLASH_ARM if is_flash else DEFAULT_REVIEW_ARM),
+ "validation_arm": asdict(FLASH_ARM if is_flash else DEFAULT_VALIDATION_ARM),
+ }
+ )
+ else:
+ inputs.published[0].finding.validation_context = context_mode
+
+ with patch("products.review_hog.backend.reviewer.constants.FLASH_ARM", DEFAULT_REVIEW_ARM):
+ captured, _judge = self._run(inputs=inputs, report=report)
props = captured[0]["properties"]
assert props["review_tier"] == "agent_p2"
- assert props["review_model"] == "gpt-5.6-sol"
+ assert props["review_mode"] == (context_mode if context_mode in (REVIEW_MODE_FULL, REVIEW_MODE_FLASH) else None)
+ assert props["review_runtime_adapter"] == "codex"
+ assert props["review_model"] == (FLASH_ARM.model if is_flash else report_model)
assert props["review_reasoning_effort"] == "medium"
assert props["review_arm_fallback"] is False
- assert props["validator_model"] == VALIDATION_MODEL
+ assert props["validator_model"] == (FLASH_ARM.model if is_flash else VALIDATION_MODEL)
+ assert props["validator_reasoning_effort"] == (
+ FLASH_ARM.reasoning_effort.value if is_flash else VALIDATION_REASONING_EFFORT.value
+ )
def test_the_judges_reasoning_is_persisted_with_the_outcome(self):
# The ruling is the only record of why a finding was classified as it was; the diff it read
diff --git a/products/review_hog/backend/tests/test_persistence.py b/products/review_hog/backend/tests/test_persistence.py
index 2fe9e0de0ec2..048312799743 100644
--- a/products/review_hog/backend/tests/test_persistence.py
+++ b/products/review_hog/backend/tests/test_persistence.py
@@ -1,4 +1,5 @@
import uuid
+from dataclasses import replace
from typing import TypeVar
from posthog.test.base import BaseTest
@@ -14,7 +15,15 @@ from products.review_hog.backend.reviewer.artefact_content import (
ValidationVerdict,
parse_artefact_content,
)
-from products.review_hog.backend.reviewer.constants import DEFAULT_REVIEW_ARM, REVIEW_ARMS_BY_TIER, ReviewTier
+from products.review_hog.backend.reviewer.constants import (
+ DEFAULT_REVIEW_ARM,
+ DEFAULT_VALIDATION_ARM,
+ FLASH_ARM,
+ REVIEW_ARMS_BY_TIER,
+ REVIEW_MODE_FLASH,
+ REVIEW_MODE_FULL,
+ ReviewTier,
+)
from products.review_hog.backend.reviewer.models.github_meta import PRComment, 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, LineRange
@@ -37,12 +46,14 @@ from products.review_hog.backend.reviewer.persistence import (
persist_pr_snapshot,
persist_verdict,
persist_verdicts,
+ replace_deduplicated_findings,
upsert_review_report,
)
from products.review_hog.backend.temporal.types import TRIGGER_INBOX, TRIGGER_LABEL, TRIGGER_UI
from products.signals.backend.artefact_attribution import ArtefactAttribution
from products.signals.backend.artefact_schemas import Commit
from products.signals.backend.enums import ReportPriority
+from products.tasks.backend.facade.run_config import ReasoningEffort
_ContentT = TypeVar("_ContentT")
@@ -514,7 +525,20 @@ class TestPersistResults(BaseTest):
)
assert rows.count() == 1
- def test_load_run_issues_round_trips_persisted_findings_by_id(self) -> None:
+ @parameterized.expand(
+ [
+ ("same_context", True),
+ ("changed_claim", False),
+ ("ordinal_collision", False),
+ ("changed_reviewer", False),
+ ("changed_validator", False),
+ ("changed_effort", False),
+ ("changed_mode", False),
+ ("changed_head", False),
+ ("empty", False),
+ ]
+ )
+ def test_load_run_issues_round_trips_persisted_findings_by_id(self, change: str, reuses_verdict: bool) -> None:
# Validate + body-build reload issues from the finding rows by id (only ids cross Temporal
# payloads): a drift between _to_finding/_from_finding, or a broken id reconstruction from
# issue_key, would silently feed validation wrong or missing issues.
@@ -538,12 +562,60 @@ class TestPersistResults(BaseTest):
source_perspective="review-hog-blind-spots-general",
)
report_id = upsert_review_report(team_id=self.team.id, repository="o/r", pr_url="u", pr_metadata=_pr_metadata())
- persisted = persist_findings(team_id=self.team.id, report_id=report_id, issues=[a, b], run_index=1)
+ head_sha = "sha-1"
+ review_mode = REVIEW_MODE_FLASH
+ review_arm = FLASH_ARM
+ validation_arm = FLASH_ARM
+
+ def replace_snapshot(issues: list[Issue]) -> list[str]:
+ return replace_deduplicated_findings(
+ team_id=self.team.id,
+ report_id=report_id,
+ issues=issues,
+ run_index=1,
+ head_sha=head_sha,
+ review_mode=review_mode,
+ review_arm=review_arm,
+ validation_arm=validation_arm,
+ )
+
+ persisted = replace_snapshot([a, b])
assert persisted == ["1-2-1", "1000-2-1"]
assert load_run_issues(team_id=self.team.id, report_id=report_id, run_index=1, issue_ids=persisted) == [a, b]
# The id filter scopes to the requested subset (a chunk's slice of the survivors).
assert load_run_issues(team_id=self.team.id, report_id=report_id, run_index=1, issue_ids=["1000-2-1"]) == [b]
+ persist_verdicts(
+ team_id=self.team.id,
+ report_id=report_id,
+ issues=[a, b],
+ run_index=1,
+ validations={issue.id: IssueValidation(is_valid=True, argumentation="real") for issue in (a, b)},
+ )
+
+ current = [a]
+ if change == "changed_claim":
+ current = [a.model_copy(update={"issue": "A different claim at the same anchor"})]
+ elif change == "ordinal_collision":
+ current = [a.model_copy(update={"file": "another.py"})]
+ elif change == "changed_reviewer":
+ review_arm = DEFAULT_REVIEW_ARM
+ elif change == "changed_validator":
+ validation_arm = DEFAULT_VALIDATION_ARM
+ elif change == "changed_effort":
+ validation_arm = replace(FLASH_ARM, reasoning_effort=ReasoningEffort.HIGH)
+ elif change == "changed_mode":
+ review_mode = REVIEW_MODE_FULL
+ elif change == "changed_head":
+ head_sha = "sha-2"
+ elif change == "empty":
+ current = []
+
+ assert replace_snapshot(current) == [issue.id for issue in current]
+ assert load_run_issues(team_id=self.team.id, report_id=report_id, run_index=1, issue_ids=persisted) == current
+ validations = load_run_validations(team_id=self.team.id, report_id=report_id, run_index=1, issues=[a, b])
+ assert set(validations) == ({a.id} if reuses_verdict else set())
+ assert len(load_valid_findings(team_id=self.team.id, report_id=report_id, run_index=1)) == int(reuses_verdict)
class TestLoadValidFindings(BaseTest):
@@ -612,8 +684,34 @@ class TestLoadValidFindings(BaseTest):
validation=IssueValidation(is_valid=True, argumentation="real"),
run_index=1,
)
+ finalize_review_report(
+ team_id=self.team.id, report_id=report_id, body_markdown="stored review", run_index=1, head_sha="sha-1"
+ )
+ prior_rows = list(
+ ReviewReportArtefact.objects.for_team(self.team.id).filter(report_id=report_id).values_list("id", "content")
+ )
+ with self.assertRaisesMessage(ValueError, "Cannot replace findings from a completed review turn"):
+ replace_deduplicated_findings(
+ team_id=self.team.id,
+ report_id=report_id,
+ issues=[],
+ run_index=1,
+ head_sha="sha-1",
+ review_mode=REVIEW_MODE_FLASH,
+ review_arm=FLASH_ARM,
+ validation_arm=FLASH_ARM,
+ )
new = _issue("1-1-1", file="b.py", title="run-2 finding", issue="real")
- persist_findings(team_id=self.team.id, report_id=report_id, issues=[new], run_index=2)
+ replace_deduplicated_findings(
+ team_id=self.team.id,
+ report_id=report_id,
+ issues=[new],
+ run_index=2,
+ head_sha="sha-2",
+ review_mode=REVIEW_MODE_FULL,
+ review_arm=DEFAULT_REVIEW_ARM,
+ validation_arm=DEFAULT_VALIDATION_ARM,
+ )
persist_verdict(
team_id=self.team.id,
report_id=report_id,
@@ -628,6 +726,14 @@ class TestLoadValidFindings(BaseTest):
assert [f.title for f, _ in load_valid_findings(team_id=self.team.id, report_id=report_id, run_index=1)] == [
"run-1 finding"
]
+ assert (
+ list(
+ ReviewReportArtefact.objects.for_team(self.team.id)
+ .filter(report_id=report_id, id__in=[row_id for row_id, _ in prior_rows])
+ .values_list("id", "content")
+ )
+ == prior_rows
+ )
class TestLoadRunValidations(BaseTest):
@@ -780,16 +886,33 @@ class TestWorkingState(BaseTest):
assert load_chunk_set(team_id=self.team.id, report_id=self.report_id, head_sha="sha-aaa") is None
- def test_perspective_results_round_trip_keyed_by_pass_and_chunk(self) -> None:
+ def test_perspective_results_round_trip_keyed_by_pass_chunk_and_model(self) -> None:
results = {
(1, 1): IssuesReview(issues=[_issue("1-1-1")]),
(2, 1): IssuesReview(issues=[_issue("2-1-1")]),
}
- persist_perspective_results(team_id=self.team.id, report_id=self.report_id, head_sha="sha-aaa", results=results)
- loaded = load_perspective_results(team_id=self.team.id, report_id=self.report_id, head_sha="sha-aaa")
+ persist_perspective_results(
+ team_id=self.team.id, report_id=self.report_id, head_sha="sha-aaa", results=results, review_model="sol"
+ )
+ loaded = load_perspective_results(
+ team_id=self.team.id, report_id=self.report_id, head_sha="sha-aaa", review_model="sol"
+ )
assert set(loaded.keys()) == {(1, 1), (2, 1)}
assert loaded[(1, 1)].issues[0].id == "1-1-1"
- assert load_perspective_results(team_id=self.team.id, report_id=self.report_id, head_sha="sha-bbb") == {}
+ assert (
+ load_perspective_results(
+ team_id=self.team.id, report_id=self.report_id, head_sha="sha-bbb", review_model="sol"
+ )
+ == {}
+ )
+ # A flash turn and a full turn can share a commit: the full turn must not resume the flash
+ # turn's rows (it would skip its own reviewer entirely), and the reverse holds too.
+ assert (
+ load_perspective_results(
+ team_id=self.team.id, report_id=self.report_id, head_sha="sha-aaa", review_model="glm"
+ )
+ == {}
+ )
class TestPersistCommitSnapshot(BaseTest):
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 b6bb7609e55f..adb49f1ba10f 100644
--- a/products/review_hog/backend/tests/test_publish_review_command.py
+++ b/products/review_hog/backend/tests/test_publish_review_command.py
@@ -8,7 +8,11 @@ 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.constants import (
+ DEFAULT_URGENCY_THRESHOLD,
+ REVIEW_MODE_FLASH,
+ REVIEW_MODE_FULL,
+)
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
@@ -47,6 +51,7 @@ class TestPublishReviewCommand(BaseTest):
*,
run_count: int,
head_sha: str = "sha7",
+ completed_head_sha: str | None = None,
markdown: str = "# body",
run_urgency_threshold: str | None = None,
) -> str:
@@ -56,6 +61,7 @@ class TestPublishReviewCommand(BaseTest):
ReviewReport.objects.for_team(self.team.id).filter(id=report_id).update(
run_count=run_count,
head_sha=head_sha,
+ completed_head_sha=completed_head_sha,
report_markdown=markdown,
run_urgency_threshold=run_urgency_threshold,
)
@@ -71,9 +77,12 @@ class TestPublishReviewCommand(BaseTest):
with pytest.raises(CommandError, match="hasn't completed a run"):
call_command("publish_review", pr_url=_URL, team_id=self.team.id)
+ @parameterized.expand([(None, REVIEW_MODE_FULL), (REVIEW_MODE_FLASH, REVIEW_MODE_FLASH)])
@patch(_STALE, return_value=None)
@patch(_PUBLISH, return_value=PublishOutcome(posted=True))
- def test_publishes_latest_completed_run_with_no_recompute(self, mock_publish: MagicMock, _stale: MagicMock) -> None:
+ def test_publishes_latest_completed_run_with_no_recompute(
+ self, review_mode: str | None, expected_mode: str, mock_publish: MagicMock, _stale: MagicMock
+ ) -> None:
# The standalone publish targets the last completed turn — run_index == run_count, at the
# report's reviewed head_sha — and reuses the shared DB-driven publish path (no workflow).
report_id = self._report(run_count=2, head_sha="sha7")
@@ -81,17 +90,37 @@ class TestPublishReviewCommand(BaseTest):
integration.get_access_token.return_value = "tok"
integration.github_installation_id = "9876543"
+ args = ["--review-mode", review_mode] if review_mode else []
with patch(_INTEGRATION, return_value=integration):
- call_command("publish_review", pr_url=_URL, team_id=self.team.id)
+ call_command("publish_review", *args, pr_url=_URL, team_id=self.team.id)
assert mock_publish.call_count == 1
kwargs = mock_publish.call_args.kwargs
assert kwargs["report_id"] == report_id
assert kwargs["run_index"] == 2
assert kwargs["head_sha"] == "sha7"
+ assert kwargs["review_mode"] == expected_mode
# The installation id rides along so the publish calls are metered against the right budget.
assert kwargs["installation_id"] == "9876543"
+ @patch(_STALE, return_value=None)
+ @patch(_PUBLISH, return_value=PublishOutcome(posted=True))
+ def test_publishes_the_head_the_completed_turn_reviewed(self, mock_publish: MagicMock, _stale: MagicMock) -> None:
+ # `head_sha` advances when a turn STARTS, so a turn that fetched a new commit and then failed
+ # leaves it past the findings this command publishes. Pairing turn 2 with that newer head
+ # would position its comments against a diff it never reviewed and record the published-head
+ # watermark there, which then suppresses the publish of a later turn at that same commit.
+ self._report(run_count=2, head_sha="sha9", completed_head_sha="sha7")
+ 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)
+
+ kwargs = mock_publish.call_args.kwargs
+ assert (kwargs["run_index"], kwargs["head_sha"]) == (2, "sha7")
+
@parameterized.expand(
[
("stamped", "must_fix", IssuePriority.MUST_FIX),
diff --git a/products/review_hog/backend/tests/test_review_activity.py b/products/review_hog/backend/tests/test_review_activity.py
index 3d88a35afab5..7de07bd4f352 100644
--- a/products/review_hog/backend/tests/test_review_activity.py
+++ b/products/review_hog/backend/tests/test_review_activity.py
@@ -10,6 +10,8 @@ from products.review_hog.backend.reviewer.constants import (
CHUNKING_REASONING_EFFORT,
CHUNKING_RUNTIME_ADAPTER,
DEFAULT_REVIEW_ARM,
+ FLASH_ARM,
+ REVIEW_MODE_FLASH,
ReviewArm,
)
from products.review_hog.backend.reviewer.models.github_meta import PRFile, PRMetadata
@@ -142,6 +144,37 @@ async def test_split_chunks_activity_routes_llm_chunking_by_oneshot_gate(additio
)
+async def test_review_chunk_activity_flash_turn_runs_on_the_flash_arm_and_stamps_the_cache() -> None:
+ mock_review = AsyncMock(return_value=IssuesReview(issues=[]))
+ mock_persist = MagicMock()
+ mock_prepare = MagicMock(return_value="review-prompt")
+ env = ActivityEnvironment()
+ with (
+ patch(f"{_MODULE}.Heartbeater"),
+ patch(f"{_MODULE}._prepare_review_prompt", mock_prepare),
+ patch(f"{_MODULE}.load_review_arm", return_value=DEFAULT_REVIEW_ARM),
+ patch(f"{_MODULE}.persist_perspective_results", mock_persist),
+ patch(f"{_MODULE}.run_sandbox_review", mock_review),
+ ):
+ assert await env.run(review_chunk_activity, _review_input(review_mode=REVIEW_MODE_FLASH)) is True
+
+ kwargs = mock_review.call_args.kwargs
+ assert (
+ kwargs["runtime_adapter"],
+ kwargs["model"],
+ kwargs["reasoning_effort"],
+ kwargs["initial_permission_mode"],
+ ) == (
+ FLASH_ARM.runtime_adapter,
+ FLASH_ARM.model,
+ FLASH_ARM.reasoning_effort,
+ FLASH_ARM.initial_permission_mode,
+ )
+ assert mock_prepare.call_args.args[-1] == FLASH_ARM.model
+ assert mock_persist.call_args.kwargs["review_model"] == FLASH_ARM.model
+
+
@pytest.mark.asyncio
async def test_review_chunk_activity_runs_on_the_reports_persisted_arm() -> None:
# The arm plumbing's core contract: the perspective-review sandbox turn runs on the REPORT's
@@ -157,16 +190,19 @@ async def test_review_chunk_activity_runs_on_the_reports_persisted_arm() -> None
initial_permission_mode=None,
)
mock_review = AsyncMock(return_value=IssuesReview(issues=[]))
+ mock_prepare = MagicMock(return_value="review-prompt")
env = ActivityEnvironment()
with (
patch(f"{_MODULE}.Heartbeater"),
- patch(f"{_MODULE}._prepare_review_prompt", return_value="review-prompt"),
+ patch(f"{_MODULE}._prepare_review_prompt", mock_prepare),
patch(f"{_MODULE}.load_review_arm", return_value=arm),
patch(f"{_MODULE}.persist_perspective_results"),
patch(f"{_MODULE}.run_sandbox_review", mock_review),
):
assert await env.run(review_chunk_activity, _review_input()) is True
+ assert mock_prepare.call_args.args[-1] == arm.model
+
kwargs = mock_review.call_args.kwargs
assert (
kwargs["runtime_adapter"],
diff --git a/products/review_hog/backend/tests/test_review_completed_tracking.py b/products/review_hog/backend/tests/test_review_completed_tracking.py
index 0e7eee84923b..c7fa5765b2eb 100644
--- a/products/review_hog/backend/tests/test_review_completed_tracking.py
+++ b/products/review_hog/backend/tests/test_review_completed_tracking.py
@@ -11,6 +11,9 @@ from parameterized import parameterized
from products.review_hog.backend.models import ReviewReport
from products.review_hog.backend.reviewer.constants import (
DEFAULT_REVIEW_ARM,
+ FLASH_ARM,
+ REVIEW_MODE_FLASH,
+ REVIEW_MODE_FULL,
REVIEW_MODEL,
VALIDATION_MODEL,
VALIDATION_REASONING_EFFORT,
@@ -90,7 +93,12 @@ class TestTrackReviewCompleted(BaseTest):
)
def _tracking_input(
- self, report_id: str, *, published: bool = True, turn_trigger_source: str = "manual"
+ self,
+ report_id: str,
+ *,
+ published: bool = True,
+ turn_trigger_source: str = "manual",
+ review_mode: str = REVIEW_MODE_FULL,
) -> TrackReviewCompletedInput:
return TrackReviewCompletedInput(
team_id=self.team.id,
@@ -100,6 +108,7 @@ class TestTrackReviewCompleted(BaseTest):
published=published,
workflow_started_at=(datetime.now(UTC) - timedelta(seconds=90)).isoformat(),
turn_trigger_source=turn_trigger_source,
+ review_mode=review_mode,
)
@parameterized.expand([(True,), (False,)])
@@ -155,6 +164,7 @@ class TestTrackReviewCompleted(BaseTest):
assert props["findings_must_fix"] == 0 # downgraded by the validator's adjusted_priority
assert props["findings_should_fix"] == 1
assert props["findings_consider"] == 0
+ assert props["review_mode"] == "full"
assert props["review_model"] == REVIEW_MODEL
assert props["review_runtime_adapter"] == DEFAULT_REVIEW_ARM.runtime_adapter.value
assert props["review_reasoning_effort"] == DEFAULT_REVIEW_ARM.reasoning_effort.value
@@ -184,35 +194,42 @@ class TestTrackReviewCompleted(BaseTest):
assert props["findings_total"] == 0
@parameterized.expand([("completed",), ("failed",), ("started",)])
- def test_event_uuid_is_stable_across_retries(self, event: str) -> None:
- # A Temporal retry after a successful capture re-emits the event; a stable uuid lets
- # ingestion dedupe it instead of double-counting the turn.
+ def test_event_uuid_is_stable_across_retries_and_separate_for_each_mode(self, event: str) -> None:
report_id = self._review_report()
emit = {
- "completed": lambda: _track_review_completed(self._tracking_input(report_id)),
- "failed": lambda: _track_review_failed(
+ "completed": lambda mode: _track_review_completed(self._tracking_input(report_id, review_mode=mode)),
+ "failed": lambda mode: _track_review_failed(
TrackReviewFailedInput(
- team_id=self.team.id, report_id=report_id, run_index=1, turn_trigger_source="manual"
+ team_id=self.team.id,
+ report_id=report_id,
+ run_index=1,
+ turn_trigger_source="manual",
+ review_mode=mode,
)
),
- "started": lambda: _track_review_started(
+ "started": lambda mode: _track_review_started(
TrackReviewStartedInput(
team_id=self.team.id,
report_id=report_id,
head_sha="sha1",
run_index=1,
turn_trigger_source="manual",
+ review_mode=mode,
)
),
}[event]
with patch("products.review_hog.backend.temporal.activities.posthoganalytics.capture") as capture:
- emit()
- emit()
+ emit(REVIEW_MODE_FULL)
+ emit(REVIEW_MODE_FULL)
+ emit(REVIEW_MODE_FLASH)
+ emit(REVIEW_MODE_FLASH)
- first, second = capture.call_args_list
- assert first.kwargs["uuid"]
- assert first.kwargs["uuid"] == second.kwargs["uuid"]
+ full, full_retry, flash, flash_retry = capture.call_args_list
+ assert full.kwargs["uuid"] == str(uuid.uuid5(uuid.NAMESPACE_URL, f"reviewhog_review_{event}:{report_id}:1"))
+ assert full.kwargs["uuid"] == full_retry.kwargs["uuid"]
+ assert flash.kwargs["uuid"] == flash_retry.kwargs["uuid"]
+ assert full.kwargs["uuid"] != flash.kwargs["uuid"]
def test_capture_failure_is_swallowed(self) -> None:
# Telemetry must never fail a review — losing this guard would fail review turns on any
@@ -306,6 +323,43 @@ class TestTrackReviewCompleted(BaseTest):
# failure against the completion of the same turn.
assert len({call.kwargs["uuid"] for call in (completed, failed, started)}) == 3
+ @parameterized.expand([("current_model", REVIEW_MODEL), ("stale_model", "gpt-9-vanished")])
+ def test_flash_turn_events_name_the_flash_arm_in_both_seats(self, _name: str, model: str) -> None:
+ # The cost comparison splits on review_mode and reads the reviewer and validator models off
+ # the same events; a flash turn reporting the stored Sol/Opus pins would price every flash
+ # review as a full one and contaminate the per-arm dashboards.
+ report_id = self._review_report()
+ ReviewReport.objects.for_team(self.team.id).filter(id=report_id).update(review_model=model)
+
+ with patch("products.review_hog.backend.temporal.activities.posthoganalytics.capture") as capture:
+ _track_review_completed(self._tracking_input(report_id, review_mode=REVIEW_MODE_FLASH))
+ _track_review_failed(
+ TrackReviewFailedInput(
+ team_id=self.team.id, report_id=report_id, run_index=1, review_mode=REVIEW_MODE_FLASH
+ )
+ )
+ _track_review_started(
+ TrackReviewStartedInput(
+ team_id=self.team.id,
+ report_id=report_id,
+ head_sha="sha1",
+ run_index=1,
+ turn_trigger_source="ui",
+ review_mode=REVIEW_MODE_FLASH,
+ )
+ )
+
+ for call in capture.call_args_list:
+ props = call.kwargs["properties"]
+ assert props["review_mode"] == "flash"
+ assert props["review_model"] == FLASH_ARM.model
+ assert props["review_reasoning_effort"] == FLASH_ARM.reasoning_effort.value
+ assert props["validator_model"] == FLASH_ARM.model
+ assert props["validator_reasoning_effort"] == FLASH_ARM.reasoning_effort.value
+ assert props["review_arm_fallback"] is False
+ # The tier stays the report's: flash is a per-turn switch, not a tier.
+ assert props["review_tier"] == "human"
+
@parameterized.expand(
[
("stale_model", "codex", "gpt-9-vanished", "high", "full-access"),
diff --git a/products/review_hog/backend/tests/test_reviews_api.py b/products/review_hog/backend/tests/test_reviews_api.py
index 87ac6fb94ea4..67b90f86acc5 100644
--- a/products/review_hog/backend/tests/test_reviews_api.py
+++ b/products/review_hog/backend/tests/test_reviews_api.py
@@ -298,12 +298,14 @@ class TestRecentReviewsAPI(APIBaseTest):
report_id=report_id,
head_sha="old-sha",
results={(1, 1): _issues_review(9)},
+ review_model="m",
)
persist_perspective_results(
team_id=self.team.id,
report_id=report_id,
head_sha="new-sha",
results={(1, 1): _issues_review(2), (2, 1): _issues_review(1), (1000, 1): _issues_review(1)},
+ review_model="m",
)
# A stale-head selection must not surface; the reviewed head's one aggregates to run/skipped.
persist_perspective_selection(
@@ -439,6 +441,7 @@ class TestRecentReviewsAPI(APIBaseTest):
report_id=running_id,
head_sha="sha1",
results={(1, 1): _issues_review(1), (2, 1): _issues_review(0)},
+ review_model="m",
)
# No persisted plan (a fallback run): the dense estimate — 2 chunks × (3 canonical
# perspectives + the blind-spot sweep) = 8 expected reads.
@@ -474,6 +477,7 @@ class TestRecentReviewsAPI(APIBaseTest):
report_id=running_id,
head_sha="sha1",
results={(1000, 0): _issues_review(0)},
+ review_model="m",
)
assert self.client.get(self.url).json()["results"][0]["progress"] == {
"review_stage": "deduplicating",
diff --git a/products/review_hog/backend/tests/test_run_review_command.py b/products/review_hog/backend/tests/test_run_review_command.py
new file mode 100644
index 000000000000..68d3882b5599
--- /dev/null
+++ b/products/review_hog/backend/tests/test_run_review_command.py
@@ -0,0 +1,50 @@
+from io import StringIO
+
+from unittest.mock import patch
+
+from django.core.management import call_command
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+
+from products.review_hog.backend.reviewer.constants import REVIEW_MODE_FLASH, REVIEW_MODE_FULL
+
+
+class TestRunReviewCommand(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("default", [], REVIEW_MODE_FULL, False),
+ ("full", ["--review-mode", "full"], REVIEW_MODE_FULL, False),
+ ("flash", ["--review-mode", "flash"], REVIEW_MODE_FLASH, False),
+ ("flash_publish", ["--review-mode", "flash", "--publish"], REVIEW_MODE_FLASH, True),
+ ]
+ )
+ def test_dispatches_selected_mode_with_opt_in_publishing(
+ self, _name: str, args: list[str], expected_mode: str, expected_publish: bool
+ ) -> None:
+ output = StringIO()
+ with patch(
+ "products.review_hog.backend.management.commands.run_review.execute_review_pr_workflow",
+ return_value="report-id",
+ ) as execute:
+ call_command(
+ "run_review",
+ "--pr-url",
+ "https://github.com/PostHog/posthog/pull/7",
+ "--team-id",
+ "1",
+ "--user-id",
+ "2",
+ *args,
+ stdout=output,
+ )
+
+ execute.assert_called_once_with(
+ pr_url="https://github.com/PostHog/posthog/pull/7",
+ team_id=1,
+ user_id=2,
+ publish=expected_publish,
+ acting_user_id=2,
+ review_mode=expected_mode,
+ )
+ assert f"· {expected_mode} · {'publish' if expected_publish else 'no-publish'}" in output.getvalue()
diff --git a/products/review_hog/backend/tests/test_status_comment.py b/products/review_hog/backend/tests/test_status_comment.py
index bfa3d9cbf3e6..472fc77b15d9 100644
--- a/products/review_hog/backend/tests/test_status_comment.py
+++ b/products/review_hog/backend/tests/test_status_comment.py
@@ -9,6 +9,7 @@ from django.utils import timezone
from parameterized import parameterized
from products.review_hog.backend.models import ReviewReport
+from products.review_hog.backend.reviewer.constants import REVIEW_MODE_FLASH, REVIEW_MODE_FULL
from products.review_hog.backend.reviewer.models.github_meta import PRMetadata
from products.review_hog.backend.reviewer.models.issue_validation import IssueValidation
from products.review_hog.backend.reviewer.models.issues_review import Issue, IssuePriority, LineRange
@@ -21,6 +22,7 @@ from products.review_hog.backend.reviewer.status_comment import (
fail_status_comment,
finalize_status_comment,
maybe_refresh_status_comment,
+ render_failed_body,
render_final_body,
render_in_progress_body,
render_resolution_final_section,
@@ -52,6 +54,32 @@ class TestRenderInProgressBody:
assert status_marker("rid") in body # the marker is what makes edit-in-place reuse possible
+class TestFlashPrefix:
+ @parameterized.expand(
+ [
+ ("in_progress", lambda mode: render_in_progress_body("rid", None, review_mode=mode)),
+ (
+ "final",
+ lambda mode: render_final_body(
+ "rid",
+ counts=dict.fromkeys(IssuePriority, 0),
+ published_count=0,
+ held_back_count=0,
+ threshold=IssuePriority.CONSIDER,
+ review_url=None,
+ review_mode=mode,
+ ),
+ ),
+ ("failed", lambda mode: render_failed_body("rid", review_mode=mode)),
+ ]
+ )
+ def test_every_status_body_opens_with_the_prefix_only_in_flash(self, _name: str, render) -> None:
+ # The status comment is rewritten in every state; a state that forgot the prefix would read
+ # as a full review mid-run or at the end, and a full run must never carry it.
+ assert render(REVIEW_MODE_FLASH).startswith("FLASH MODE\n### ")
+ assert not render(REVIEW_MODE_FULL).startswith("FLASH MODE")
+
+
class TestRenderFinalBody:
@parameterized.expand(
[
@@ -223,9 +251,10 @@ class TestEnsureStatusComment(BaseTest):
mock_request.return_value.json.return_value = {"id": 777}
report = self._report()
- ensure_status_comment(self.team.id, str(report.id))
+ ensure_status_comment(self.team.id, str(report.id), review_mode=REVIEW_MODE_FLASH)
assert _posts(mock_request) == ["/repos/o/r/issues/123/comments"]
+ assert mock_request.call_args.kwargs["json"]["body"].startswith("FLASH MODE\n")
report.refresh_from_db()
assert report.status_comment_id == 777
assert report.status_comment_edited_at is not None
@@ -381,11 +410,14 @@ class TestFinalizeStatusComment(BaseTest):
report.status_comment_id = 555
report.save(update_fields=["status_comment_id"])
- fail_status_comment(self.team.id, report_id)
+ fail_status_comment(self.team.id, report_id, review_mode=REVIEW_MODE_FLASH)
assert _patches(mock_request) == ["/repos/o/r/issues/comments/555"]
body = mock_request.call_args.kwargs["json"]["body"]
assert "couldn't finish this review" in body
+ # The entry point threads the turn's mode into the renderer; a dropped kwarg here would
+ # leave a dead flash run reading as a full one.
+ assert body.startswith("FLASH MODE\n")
class TestResolutionSection:
diff --git a/products/review_hog/backend/tests/test_temporal_workflow.py b/products/review_hog/backend/tests/test_temporal_workflow.py
index 93f756f4f229..0d9b97a6f86b 100644
--- a/products/review_hog/backend/tests/test_temporal_workflow.py
+++ b/products/review_hog/backend/tests/test_temporal_workflow.py
@@ -27,6 +27,7 @@ from products.review_hog.backend.temporal.activities import (
AppendCodeReviewArtefactInput,
BuildBodyInput,
DedupResult,
+ FetchPRDataInput,
GenerateSchemasInput,
LoadBlindSpotsInput,
LoadedBlindSpotsSkillDTO,
@@ -41,6 +42,7 @@ from products.review_hog.backend.temporal.activities import (
ReviewChunkInput,
ReviewMeta,
SelectPerspectivesInput,
+ StatusCommentInput,
SyncReviewSkillsInput,
TrackReviewCompletedInput,
TrackReviewFailedInput,
@@ -113,6 +115,7 @@ async def _run_full_review_pr_workflow(
fail_review_units: frozenset[tuple[int, int]] = frozenset(),
resolve_comments_setting: bool = False,
input_resolve_comments: bool | None = None,
+ review_mode: str = "full",
) -> dict:
# Runs the real ReviewPRWorkflow with activity stand-ins, recording what fanned out + published.
# already_published / empty_diff drive the early-exit gates; acting_user_id None means the author
@@ -144,12 +147,20 @@ async def _run_full_review_pr_workflow(
# snapshot; input_resolve_comments is the per-run override on the workflow input.
StubResolvePRWorkflow.dispatches.clear()
+ # The mode every consumer received, keyed by stage: the arms, the prefix, and the events all key
+ # off it, so a stage that drops it silently runs (or labels) a flash turn as a full one.
+ mode_calls: dict[str, set[str]] = {}
+
+ def _saw_mode(stage: str, mode: str) -> None:
+ mode_calls.setdefault(stage, set()).add(mode)
+
@activity.defn(name="validate_github_integration_activity")
async def validate_integration(input) -> None:
return None
@activity.defn(name="fetch_pr_data_activity")
- async def fetch(input) -> ReviewMeta:
+ async def fetch(input: FetchPRDataInput) -> ReviewMeta:
+ _saw_mode("fetch", input.review_mode)
return ReviewMeta(
report_id="rep-1",
head_sha="sha1",
@@ -204,6 +215,7 @@ async def _run_full_review_pr_workflow(
@activity.defn(name="select_perspectives_activity")
async def select_perspectives(input: SelectPerspectivesInput) -> PerspectiveSelectionDTO | None:
+ _saw_mode("select", input.review_mode)
if fail_selection:
raise ApplicationError("selector down", non_retryable=True)
return selection
@@ -215,6 +227,7 @@ async def _run_full_review_pr_workflow(
@activity.defn(name="review_chunk_activity")
async def review(input: ReviewChunkInput) -> bool:
+ _saw_mode("review", input.review_mode)
review_calls.append(
(
input.pass_number,
@@ -242,6 +255,7 @@ async def _run_full_review_pr_workflow(
@activity.defn(name="validate_chunk_activity")
async def validate_chunk(input: ValidateChunkInput) -> ValidateChunkResult:
+ _saw_mode("validate", input.review_mode)
validate_calls.append(input.chunk_id)
return ValidateChunkResult(chunk_id=input.chunk_id, validated_count=len(input.issue_ids))
@@ -253,6 +267,7 @@ async def _run_full_review_pr_workflow(
@activity.defn(name="publish_review_activity")
async def publish_act(input: PublishInput) -> PublishResult:
+ _saw_mode("publish", input.review_mode)
publish_calls.append(input.pr_number)
threshold_calls.append(("publish", input.urgency_threshold))
return PublishResult(posted=True, review_url=_REVIEW_URL)
@@ -267,11 +282,13 @@ async def _run_full_review_pr_workflow(
return None
@activity.defn(name="post_status_comment_activity")
- async def post_status(input) -> None:
+ async def post_status(input: StatusCommentInput) -> None:
+ _saw_mode("status", input.review_mode)
return None
@activity.defn(name="finalize_status_comment_activity")
async def finalize_status(input: FinalizeStatusCommentInput) -> None:
+ _saw_mode("status", input.review_mode)
finalize_status_calls.append((input.urgency_threshold, input.resolved_from, input.review_url))
return None
@@ -293,11 +310,13 @@ async def _run_full_review_pr_workflow(
@activity.defn(name="track_review_completed_activity")
async def track_completed(input: TrackReviewCompletedInput) -> None:
+ _saw_mode("track", input.review_mode)
track_completed_calls.append((input.run_index, input.turn_trigger_source))
return None
@activity.defn(name="track_review_started_activity")
async def track_started(input: TrackReviewStartedInput) -> None:
+ _saw_mode("track", input.review_mode)
track_started_calls.append((input.run_index, input.turn_trigger_source))
return None
@@ -357,6 +376,7 @@ async def _run_full_review_pr_workflow(
signal_report_id=signal_report_id,
head_branch=input_head_branch,
resolve_comments=input_resolve_comments,
+ review_mode=review_mode,
),
id=str(uuid.uuid4()),
task_queue=task_queue,
@@ -391,6 +411,7 @@ async def _run_full_review_pr_workflow(
"track_completed": track_completed_calls,
"track_started": track_started_calls,
"resolve_dispatches": list(StubResolvePRWorkflow.dispatches),
+ "modes": mode_calls,
}
@@ -533,6 +554,22 @@ async def test_review_pr_workflow_chains_resolution_per_setting_and_override(
assert recorded["resolve_dispatches"] == []
+async def test_review_pr_workflow_flash_turn_threads_its_mode_and_never_chains_resolution():
+ # Flash must not write code even with the strongest opt-in (an explicit True override on a
+ # publishing run), and every stage that picks an arm, labels a GitHub message, or emits an
+ # event has to receive the mode — a consumer that falls back to the default runs or labels a
+ # flash turn as a full one.
+ recorded = await _run_full_review_pr_workflow(
+ publish=True, resolve_comments_setting=True, input_resolve_comments=True, review_mode="flash"
+ )
+ assert recorded["publish"] == [7]
+ assert recorded["resolve_dispatches"] == []
+ assert recorded["modes"] == {
+ stage: {"flash"} for stage in ("fetch", "select", "review", "validate", "publish", "status", "track")
+ }
+
+
@pytest.mark.asyncio
async def test_review_pr_workflow_early_exits_when_already_published():
# A re-trigger at an already-published head: the gate returns the report id without running any
@@ -708,6 +745,8 @@ def test_review_pr_workflow_inputs_deserialize_old_payloads():
# in-flight review with a Non Deterministic Error on deploy.
assert inputs.resolve_comments is None
assert ResolveActingUserResult(acting_user_id=3).resolve_comments is False
+ # A pre-field payload is a full review: defaulting to flash would silently cheapen in-flight turns.
+ assert inputs.review_mode == "full"
async def _run_validate_workflow(*, issue_ids: list[str], validate_chunk) -> int:
diff --git a/products/review_hog/backend/tests/test_ui_trigger_api.py b/products/review_hog/backend/tests/test_ui_trigger_api.py
index df35ec397b27..73947cf9f25d 100644
--- a/products/review_hog/backend/tests/test_ui_trigger_api.py
+++ b/products/review_hog/backend/tests/test_ui_trigger_api.py
@@ -9,6 +9,8 @@ from rest_framework import status
from posthog.egress.github.transport import GitHubRateLimitError
from products.review_hog.backend.models import ReviewReport
+from products.review_hog.backend.reviewer.constants import REVIEW_ARMS_BY_TIER, ReviewTier
+from products.review_hog.backend.reviewer.persistence import load_review_arm
from products.review_hog.backend.reviewer.tools.github_client import GitHubAPIError
_START = "products.review_hog.backend.api.reviews.start_review_pr_workflow"
@@ -65,22 +67,33 @@ class TestReviewHogUiTriggerApi(APIBaseTest):
trigger_source="ui",
# None = the requester's resolve_comments setting decides whether resolution chains.
resolve_comments=None,
+ review_mode="full",
)
+ @parameterized.expand(
+ [
+ # (run_mode, expected review_mode)
+ ("review_only", "full"),
+ ("flash", "flash"),
+ ]
+ )
@patch(_META, return_value=_pr_meta())
@patch(_ACCESS, return_value=object())
@patch(_START_RESOLUTION)
@patch(_START, return_value="wf-ui-1")
- def test_review_only_mode_pins_resolution_off_for_the_run(
- self, mock_start, mock_start_resolution, _mock_access, _mock_meta
+ def test_review_only_and_flash_modes_pin_resolution_off_for_the_run(
+ self, run_mode, expected_review_mode, mock_start, mock_start_resolution, _mock_access, _mock_meta
):
- # The split button's "review without resolving": the per-run override must reach the
- # workflow as an explicit False — passing None would fall back to the user's setting.
+ # The split button's "review without resolving" and "flash": the per-run override must reach
+ # the workflow as an explicit False — passing None would fall back to the user's setting, and
+ # a flash review that resolved would write code. Flash must also carry its mode, or the
+ # workflow runs the full pipeline under a flash label.
with override_settings(REVIEWHOG_TEAM_IDS=[self.team.id]):
- resp = self._trigger("https://github.com/PostHog/posthog.com/pull/123", run_mode="review_only")
+ resp = self._trigger("https://github.com/PostHog/posthog.com/pull/123", run_mode=run_mode)
self.assertEqual(resp.status_code, status.HTTP_202_ACCEPTED, resp.content)
self.assertIs(mock_start.call_args.kwargs["resolve_comments"], False)
+ self.assertEqual(mock_start.call_args.kwargs["review_mode"], expected_review_mode)
mock_start_resolution.assert_not_called()
@patch(_META, return_value=_pr_meta(head_sha="abc123"))
@@ -151,14 +164,28 @@ class TestReviewHogUiTriggerApi(APIBaseTest):
mock_start.assert_not_called()
mock_start_resolution.assert_not_called()
+ @parameterized.expand(
+ [
+ ("full", None, ReviewTier.HUMAN),
+ ("review_only", "review_only", ReviewTier.HUMAN),
+ ("flash", "flash", ReviewTier.AGENT_P2),
+ ]
+ )
@patch(_META, return_value=_pr_meta())
@patch(_ACCESS, return_value=object())
@patch(_START, return_value="wf-ui-1")
- def test_trigger_during_a_running_cheaper_review_lifts_the_tier_and_says_so(
- self, mock_start, _mock_access, _mock_meta
- ):
- # Same join as the label path: the requester's source never reaches the fetch upsert, so the
- # lift is written here and the UI is told no new run started.
+ def test_joined_trigger_lifts_cheaper_tier_only_for_full_reviews(
+ self,
+ _name: str,
+ run_mode: str | None,
+ expected_tier: ReviewTier,
+ mock_start: MagicMock,
+ _mock_access: MagicMock,
+ _mock_meta: MagicMock,
+ ) -> None:
+ # Joined starts retain their original inputs, so Full requests need an explicit tier lift
+ # while Flash must preserve the stored arm. The response still reports the shared join.
+ original_arm = REVIEW_ARMS_BY_TIER[ReviewTier.AGENT_P2]
report = ReviewReport.objects.for_team(self.team.id).create(
team=self.team,
repository="posthog/posthog.com",
@@ -167,17 +194,23 @@ class TestReviewHogUiTriggerApi(APIBaseTest):
head_branch="fix",
base_branch="master",
review_tier="agent_p2",
- review_reasoning_effort="medium",
+ review_runtime_adapter=original_arm.runtime_adapter.value,
+ review_model=original_arm.model,
+ review_reasoning_effort=original_arm.reasoning_effort.value,
+ review_initial_permission_mode=original_arm.initial_permission_mode,
)
self.mock_busy.side_effect = lambda workflow_id: workflow_id.startswith("review-pr:")
with override_settings(REVIEWHOG_TEAM_IDS=[self.team.id]):
- resp = self._trigger("https://github.com/PostHog/posthog.com/pull/123")
+ resp = self._trigger("https://github.com/PostHog/posthog.com/pull/123", run_mode=run_mode)
self.assertEqual(resp.status_code, status.HTTP_202_ACCEPTED, resp.content)
self.assertEqual(resp.json(), {"workflow_id": "wf-ui-1", "status": "joined_running_review"})
mock_start.assert_called_once()
report.refresh_from_db()
- self.assertEqual((report.review_tier, report.review_reasoning_effort), ("human", "xhigh"))
+ self.assertEqual(report.review_tier, expected_tier.value)
+ self.assertEqual(
+ load_review_arm(team_id=self.team.id, report_id=str(report.id)), REVIEW_ARMS_BY_TIER[expected_tier]
+ )
@patch(_ACCESS, return_value=object())
@patch(_START_RESOLUTION)
diff --git a/products/review_hog/backend/tests/test_validate_activity.py b/products/review_hog/backend/tests/test_validate_activity.py
index 78fa46d513ad..fea34335bc5f 100644
--- a/products/review_hog/backend/tests/test_validate_activity.py
+++ b/products/review_hog/backend/tests/test_validate_activity.py
@@ -8,7 +8,14 @@ from unittest.mock import AsyncMock, MagicMock, patch
from temporalio.testing import ActivityEnvironment
from products.review_hog.backend.reviewer.artefact_content import PRSnapshotArtefact
-from products.review_hog.backend.reviewer.constants import VALIDATION_MAX_ATTEMPTS
+from products.review_hog.backend.reviewer.constants import (
+ DEFAULT_VALIDATION_ARM,
+ FLASH_ARM,
+ REVIEW_MODE_FLASH,
+ REVIEW_MODE_FULL,
+ VALIDATION_MAX_ATTEMPTS,
+ ReviewArm,
+)
from products.review_hog.backend.reviewer.models.github_meta import PRMetadata
from products.review_hog.backend.reviewer.models.issue_validation import IssueValidation
from products.review_hog.backend.reviewer.models.issues_review import Issue, IssuePriority, LineRange
@@ -35,7 +42,7 @@ def _verdict() -> IssueValidation:
return IssueValidation(is_valid=True, argumentation="checks out")
-def _input(issues: list[Issue]) -> ValidateChunkInput:
+def _input(issues: list[Issue], review_mode: str = REVIEW_MODE_FULL) -> ValidateChunkInput:
return ValidateChunkInput(
team_id=1,
user_id=2,
@@ -44,6 +51,7 @@ def _input(issues: list[Issue]) -> ValidateChunkInput:
repository="o/r",
branch="feat",
run_index=1,
+ review_mode=review_mode,
chunk_id=_CHUNK_ID,
issue_ids=[issue.id for issue in issues],
skill_name="s-val",
@@ -177,3 +185,36 @@ async def test_session_open_failure_raises_even_on_the_final_attempt() -> None:
await _env(attempt=VALIDATION_MAX_ATTEMPTS).run(validate_chunk_activity, _input([issue]))
mock_end.assert_not_awaited()
+
+
+ "review_mode,expected",
+ [
+ pytest.param(REVIEW_MODE_FULL, DEFAULT_VALIDATION_ARM, id="full"),
+ pytest.param(REVIEW_MODE_FLASH, FLASH_ARM, id="flash"),
+ ],
+)
+async def test_validation_session_opens_on_the_modes_arm(review_mode: str, expected: ReviewArm) -> None:
+ # The validator seat is chosen per turn: a flash turn that validated on the Opus pins would
+ # cost the full price under a flash label, and the pin kwargs default to None, so a dropped
+ # kwarg would silently run the agent server's default with every other assertion green.
+ issue = _issue(1)
+ mock_start = AsyncMock(return_value=(object(), _verdict()))
+ with (
+ _chunk_context(issues=[issue], done={}),
+ patch(f"{_MODULE}.persist_verdict", MagicMock(return_value=True)),
+ patch(f"{_MODULE}.start_sandbox_session", mock_start),
+ patch(f"{_MODULE}.end_sandbox_session", AsyncMock()),
+ ):
+ result = await _env(attempt=1).run(validate_chunk_activity, _input([issue], review_mode=review_mode))
+
+ assert result.validated_count == 1
+ kwargs = mock_start.call_args.kwargs
+ assert (
+ kwargs["runtime_adapter"],
+ kwargs["model"],
+ kwargs["reasoning_effort"],
+ kwargs["initial_permission_mode"],
+ ) == (expected.runtime_adapter, expected.model, expected.reasoning_effort, expected.initial_permission_mode)
+ assert 'skill-get(skill_name="s-val", version=1)' in kwargs["prompt"]
diff --git a/products/review_hog/frontend/CodeReviewScene.tsx b/products/review_hog/frontend/CodeReviewScene.tsx
index 77124c9f451b..f7f3bb68ea80 100644
--- a/products/review_hog/frontend/CodeReviewScene.tsx
+++ b/products/review_hog/frontend/CodeReviewScene.tsx
@@ -677,7 +677,7 @@ function RecentReviewsSection(): JSX.Element | null {
* "Review a pull request": paste any PR URL the project's GitHub App installation can access and
* start a publishing review, acting as the requesting user. A review resolves the PR's comment
* threads afterwards when the user's resolve_comments setting is on; the split button's side
- * actions are the per-run variants (review without resolving / resolve only). Hidden unless the
+ * actions are the per-run variants (review without resolving / resolve only / flash). Hidden unless the
* backend says this project can trigger reviews (limited to the designated ReviewHog team while
* in alpha).
*/
@@ -742,6 +742,13 @@ function TriggerReviewSection(): JSX.Element | null {
>
Only resolve existing comments
</LemonButton>
+ <LemonButton
+ fullWidth
+ onClick={() => submitTriggerReview(ReviewTriggerRequestRunModeEnumApi.Flash)}
+ tooltip="A faster, cheaper review that never resolves comments. Every message it posts is marked FLASH MODE."
+ >
+ Review in Flash mode
+ </LemonButton>
</>
),
},
diff --git a/products/review_hog/frontend/generated/api.schemas.ts b/products/review_hog/frontend/generated/api.schemas.ts
index 3c582956fa34..aa2e6612642b 100644
--- a/products/review_hog/frontend/generated/api.schemas.ts
+++ b/products/review_hog/frontend/generated/api.schemas.ts
@@ -473,6 +473,7 @@ export interface ReviewPerspectiveStatsApi {
* * `review` - review
* * `review_only` - review_only
* * `resolve_only` - resolve_only
+ * * `flash` - flash
*/
export type ReviewTriggerRequestRunModeEnumApi =
(typeof ReviewTriggerRequestRunModeEnumApi)[keyof typeof ReviewTriggerRequestRunModeEnumApi]
@@ -481,23 +482,25 @@ export const ReviewTriggerRequestRunModeEnumApi = {
Review: 'review',
ReviewOnly: 'review_only',
ResolveOnly: 'resolve_only',
+ Flash: 'flash',
} as const
export interface ReviewTriggerRequestApi {
/** GitHub pull request URL to review, e.g. 'https://github.com/PostHog/posthog.com/pull/123'. The repository must be accessible to the project's GitHub App installation. */
pr_url: string
- /** What to run on the pull request. 'review' (default) reviews it and, when the requesting user's resolve_comments setting is on, chains the resolution stage; 'review_only' reviews without resolving regardless of that setting; 'resolve_only' skips the review and only runs the resolution stage on the PR's existing unresolved review threads.
+ /** What to run on the pull request. 'review' (default) reviews it and, when the requesting user's resolve_comments setting is on, chains the resolution stage; 'review_only' reviews without resolving regardless of that setting; 'resolve_only' skips the review and only runs the resolution stage on the PR's existing unresolved review threads; 'flash' uses a lower-cost model for the review passes and validation, and never resolves comments.
*
* * `review` - review
* * `review_only` - review_only
- * * `resolve_only` - resolve_only */
+ * * `resolve_only` - resolve_only
+ * * `flash` - flash */
run_mode?: ReviewTriggerRequestRunModeEnumApi
}
export interface ReviewTriggerResponseApi {
/** Temporal workflow id for the started review run; empty when no run was started. */
workflow_id: string
- /** Run lifecycle marker: 'started' when the review was queued, 'already_reviewed' when the pull request's current commit already has a published review (no new run starts), 'joined_running_review' when a review was already in flight (no new run starts; a report in a cheaper tier is lifted to human strength for the rest of that review and every later one). */
+ /** Run lifecycle marker: 'started' when the review was queued, 'already_reviewed' when the pull request's current commit already has a published review (no new run starts), 'joined_running_review' when a review was already in flight (no new run starts and its mode stays unchanged; requests for Full mode lift a cheaper stored tier for later Full reviews, while Flash requests leave the tier unchanged). */
status: string
}
diff --git a/products/review_hog/frontend/generated/api.ts b/products/review_hog/frontend/generated/api.ts
index b56830a46f50..2591a684a288 100644
--- a/products/review_hog/frontend/generated/api.ts
+++ b/products/review_hog/frontend/generated/api.ts
@@ -254,7 +254,7 @@ export const getReviewHogReviewsTriggerCreateUrl = (projectId: string) => {
}
/**
- * Start a ReviewHog review of any pull request the project's GitHub App installation can access, and publish it back to the PR. The requesting user is the review's acting user: their enabled perspectives, blind-spot check, validator, urgency threshold, and resolution criteria drive the run, and it appears under their recent reviews. `run_mode` picks the variant: a review (which chains the resolution stage per the user's resolve_comments setting), a review without resolving, or resolution only. Nonexistent, closed, and fork PRs are rejected synchronously; a PR whose current commit already has a published review returns 'already_reviewed' without starting a run (resolve_only skips that check — settling threads on a reviewed head is its whole point), and triggering a PR whose run is currently in flight joins that run. Otherwise non-blocking: returns the Temporal workflow id immediately while the run executes in the worker.
+ * Start a ReviewHog review of any pull request the project's GitHub App installation can access, and publish it back to the PR. The requesting user is the review's acting user: their enabled perspectives, blind-spot check, validator, urgency threshold, and resolution criteria drive the run, and it appears under their recent reviews. `run_mode` picks the variant: a review (which chains the resolution stage per the user's resolve_comments setting), a review without resolving, resolution only, or a lower-cost Flash review that never resolves comments. Nonexistent, closed, and fork PRs are rejected synchronously; a PR whose current commit already has a published review returns 'already_reviewed' without starting a run (resolve_only skips that check — settling threads on a reviewed head is its whole point), and triggering a PR whose run is currently in flight joins that run. Otherwise non-blocking: returns the Temporal workflow id immediately while the run executes in the worker.
* @summary Start a review of a pull request
*/
export const reviewHogReviewsTriggerCreate = async (
diff --git a/products/review_hog/frontend/generated/api.zod.ts b/products/review_hog/frontend/generated/api.zod.ts
index b69649c99013..f24067ba342d 100644
--- a/products/review_hog/frontend/generated/api.zod.ts
+++ b/products/review_hog/frontend/generated/api.zod.ts
@@ -47,7 +47,7 @@ export const ReviewHogResolutionPartialUpdateBody = /* @__PURE__ */ zod.object({
})
/**
- * Start a ReviewHog review of any pull request the project's GitHub App installation can access, and publish it back to the PR. The requesting user is the review's acting user: their enabled perspectives, blind-spot check, validator, urgency threshold, and resolution criteria drive the run, and it appears under their recent reviews. `run_mode` picks the variant: a review (which chains the resolution stage per the user's resolve_comments setting), a review without resolving, or resolution only. Nonexistent, closed, and fork PRs are rejected synchronously; a PR whose current commit already has a published review returns 'already_reviewed' without starting a run (resolve_only skips that check — settling threads on a reviewed head is its whole point), and triggering a PR whose run is currently in flight joins that run. Otherwise non-blocking: returns the Temporal workflow id immediately while the run executes in the worker.
+ * Start a ReviewHog review of any pull request the project's GitHub App installation can access, and publish it back to the PR. The requesting user is the review's acting user: their enabled perspectives, blind-spot check, validator, urgency threshold, and resolution criteria drive the run, and it appears under their recent reviews. `run_mode` picks the variant: a review (which chains the resolution stage per the user's resolve_comments setting), a review without resolving, resolution only, or a lower-cost Flash review that never resolves comments. Nonexistent, closed, and fork PRs are rejected synchronously; a PR whose current commit already has a published review returns 'already_reviewed' without starting a run (resolve_only skips that check — settling threads on a reviewed head is its whole point), and triggering a PR whose run is currently in flight joins that run. Otherwise non-blocking: returns the Temporal workflow id immediately while the run executes in the worker.
* @summary Start a review of a pull request
*/
export const reviewHogReviewsTriggerCreateBodyRunModeDefault = `review`
@@ -59,11 +59,13 @@ export const ReviewHogReviewsTriggerCreateBody = /* @__PURE__ */ zod.object({
"GitHub pull request URL to review, e.g. 'https:\/\/github.com\/PostHog\/posthog.com\/pull\/123'. The repository must be accessible to the project's GitHub App installation."
),
run_mode: zod
- .enum(['review', 'review_only', 'resolve_only'])
- .describe('\* `review` - review\n\* `review_only` - review_only\n\* `resolve_only` - resolve_only')
+ .enum(['review', 'review_only', 'resolve_only', 'flash'])
+ .describe(
+ '\* `review` - review\n\* `review_only` - review_only\n\* `resolve_only` - resolve_only\n\* `flash` - flash'
+ )
.default(reviewHogReviewsTriggerCreateBodyRunModeDefault)
.describe(
- "What to run on the pull request. 'review' (default) reviews it and, when the requesting user's resolve_comments setting is on, chains the resolution stage; 'review_only' reviews without resolving regardless of that setting; 'resolve_only' skips the review and only runs the resolution stage on the PR's existing unresolved review threads.\n\n\* `review` - review\n\* `review_only` - review_only\n\* `resolve_only` - resolve_only"
+ "What to run on the pull request. 'review' (default) reviews it and, when the requesting user's resolve_comments setting is on, chains the resolution stage; 'review_only' reviews without resolving regardless of that setting; 'resolve_only' skips the review and only runs the resolution stage on the PR's existing unresolved review threads; 'flash' uses a lower-cost model for the review passes and validation, and never resolves comments.\n\n\* `review` - review\n\* `review_only` - review_only\n\* `resolve_only` - resolve_only\n\* `flash` - flash"
),
})
diff --git a/products/review_hog/frontend/reviewHogSettingsLogic.test.ts b/products/review_hog/frontend/reviewHogSettingsLogic.test.ts
index f33b86456f69..87396c3a326f 100644
--- a/products/review_hog/frontend/reviewHogSettingsLogic.test.ts
+++ b/products/review_hog/frontend/reviewHogSettingsLogic.test.ts
@@ -186,6 +186,32 @@ describe('reviewHogSettingsLogic', () => {
expect(requestBody).toMatchObject({ run_mode: 'resolve_only' })
})
+ it('a flash run sends its mode and arms the review watch like a review', async () => {
+ // Flash creates a report row like any review, so the watch must arm; dropping run_mode
+ // would silently run the full pipeline (and resolve comments) under the flash button.
+ let requestBody: Record<string, unknown> | null = null
+ useMocks({
+ post: {
+ '/api/projects/:team_id/review_hog/reviews/trigger/': async ({ request }) => {
+ requestBody = (await request.json()) as Record<string, unknown>
+ return [202, { workflow_id: 'wf-flash-1', status: 'started' }]
+ },
+ },
+ })
+ logic.mount()
+ await expectLogic(logic).toDispatchActions([
+ 'loadRecentReviewsSuccess',
+ 'applyDefaultReviewsScope',
+ 'loadRecentReviewsSuccess',
+ ])
+ logic.actions.setTriggerPrUrl('https://github.com/PostHog/posthog.com/pull/1')
+
+ await expectLogic(logic, () => logic.actions.submitTriggerReview(ReviewTriggerRequestRunModeEnumApi.Flash))
+ .toDispatchActions(['submitTriggerReview', 'startTriggeredReviewWatch', 'submitTriggerReviewFinished'])
+ .toMatchValues({ triggeringReview: false, triggerPrUrl: '' })
+ expect(requestBody).toMatchObject({ run_mode: 'flash' })
+ })
+
it.each([
['already_reviewed', 200, ''],
['joined_running_review', 202, 'wf-running'],
diff --git a/products/review_hog/frontend/reviewHogSettingsLogic.ts b/products/review_hog/frontend/reviewHogSettingsLogic.ts
index 9f04fc087605..4c25a0b73acb 100644
--- a/products/review_hog/frontend/reviewHogSettingsLogic.ts
+++ b/products/review_hog/frontend/reviewHogSettingsLogic.ts
@@ -653,7 +653,8 @@ export const reviewHogSettingsLogic = kea<reviewHogSettingsLogicType>([
submitAdoptSkillFinished: true,
setTriggerPrUrl: (prUrl: string) => ({ prUrl }),
// Starts a run on the pasted PR URL: a review (which resolves comments per the user's
- // setting), a review without resolving, or a resolve-only run — the split button's variants.
+ // setting), a review without resolving, a resolve-only run, or a flash review — the split
+ // button's variants.
// The listener self-guards on `triggeringReview`, so a repeat dispatch mid-flight (Enter
// spam, double click) is a no-op regardless of the source.
submitTriggerReview: (
@@ -1450,9 +1451,7 @@ export const reviewHogSettingsLogic = kea<reviewHogSettingsLogicType>([
)
} else if (response.status === 'joined_running_review') {
// No run started — the request joined the review already in flight.
- lemonToast.info(
- 'A review is already running on this pull request. Trigger it again after it finishes to run a full review.'
- )
+ lemonToast.info('A review is already running on this pull request. Find it under recent reviews.')
} else if (runMode === ReviewTriggerRequestRunModeEnumApi.ResolveOnly) {
// Resolve-only runs don't create the report activity the review watch polls for,
// so a toast is the feedback: progress shows up on the pull request itself.
diff --git a/products/review_hog/mcp/tools.yaml b/products/review_hog/mcp/tools.yaml
index 2e61eb7868e2..153ab0ba79d9 100644
--- a/products/review_hog/mcp/tools.yaml
+++ b/products/review_hog/mcp/tools.yaml
@@ -81,13 +81,14 @@ tools:
App installation. `run_mode` picks the variant: `review` (the default) reviews the PR, publishes the review
to it, and then chains the comment-resolution stage when the requesting user's `resolve_comments` setting is
on; `review_only` reviews without resolving; `resolve_only` skips the review and only works the PR's
- existing unresolved review threads. IMPORTANT: resolve-capable runs write to the PR itself. They may push
- signed fix commits to the PR's branch, reply to review threads, and resolve bot-authored threads. Nothing is
- deleted and the commits are plain appends, but the actions are public to everyone on the PR. Non-blocking:
- returns a `workflow_id` and `status` of `started` while the run executes. If the PR's current commit already
- has a published review it returns `already_reviewed` without starting a run (`resolve_only` skips that
- check, since resolving is useful exactly then), and triggering a PR whose review is already running joins
- the in-flight run. Poll progress with `review-hog-reviews-list` and read the finished findings with
+ existing unresolved review threads; `flash` reviews and publishes on a lower-cost model, and never resolves
+ comments or pushes fixes. IMPORTANT: resolve-capable runs write to the PR itself. They may push signed fix
+ commits to the PR's branch, reply to review threads, and resolve bot-authored threads. Nothing is deleted
+ and the commits are plain appends, but the actions are public to everyone on the PR. Non-blocking: returns a
+ `workflow_id` and `status` of `started` while the run executes. If the PR's current commit already has a
+ published review it returns `already_reviewed` without starting a run (`resolve_only` skips that check,
+ since resolving is useful exactly then), and triggering a PR whose review is already running joins the
+ in-flight run. Poll progress with `review-hog-reviews-list` and read the finished findings with
`review-hog-reviews-get`.
feature_flag: review-hog
review-hog-settings-partial-update:
diff --git a/products/signals/frontend/inbox/components/detail/ArtefactLogList.stories.tsx b/products/signals/frontend/inbox/components/detail/ArtefactLogList.stories.tsx
index ddb60ff9b9bb..a0c84705bee0 100644
--- a/products/signals/frontend/inbox/components/detail/ArtefactLogList.stories.tsx
+++ b/products/signals/frontend/inbox/components/detail/ArtefactLogList.stories.tsx
@@ -77,6 +77,7 @@ type Story = StoryObj<typeof meta>
export const ReplacementLifecycle: Story = {}
export const RevisionLimit: Story = {
+ parameters: { mockDate: '2026-09-17T10:00:00Z' },
args: {
artefacts: [
{
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 693d97f91fca..2c0b9eea82a8 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -9714,7 +9714,7 @@
"feature_flag": "review-hog"
},
"review-hog-reviews-trigger": {
- "description": "Start a ReviewHog run on a pull request. Pass the PR as `pr_url` (e.g. `https://github.com/PostHog/posthog/pull/123`); the repository must be accessible to the project's GitHub App installation. `run_mode` picks the variant: `review` (the default) reviews the PR, publishes the review to it, and then chains the comment-resolution stage when the requesting user's `resolve_comments` setting is on; `review_only` reviews without resolving; `resolve_only` skips the review and only works the PR's existing unresolved review threads. IMPORTANT: resolve-capable runs write to the PR itself. They may push signed fix commits to the PR's branch, reply to review threads, and resolve bot-authored threads. Nothing is deleted and the commits are plain appends, but the actions are public to everyone on the PR. Non-blocking: returns a `workflow_id` and `status` of `started` while the run executes. If the PR's current commit already has a published review it returns `already_reviewed` without starting a run (`resolve_only` skips that check, since resolving is useful exactly then), and triggering a PR whose review is already running joins the in-flight run. Poll progress with `review-hog-reviews-list` and read the finished findings with `review-hog-reviews-get`.",
+ "description": "Start a ReviewHog run on a pull request. Pass the PR as `pr_url` (e.g. `https://github.com/PostHog/posthog/pull/123`); the repository must be accessible to the project's GitHub App installation. `run_mode` picks the variant: `review` (the default) reviews the PR, publishes the review to it, and then chains the comment-resolution stage when the requesting user's `resolve_comments` setting is on; `review_only` reviews without resolving; `resolve_only` skips the review and only works the PR's existing unresolved review threads; `flash` reviews and publishes on a lower-cost model, and never resolves comments or pushes fixes. IMPORTANT: resolve-capable runs write to the PR itself. They may push signed fix commits to the PR's branch, reply to review threads, and resolve bot-authored threads. Nothing is deleted and the commits are plain appends, but the actions are public to everyone on the PR. Non-blocking: returns a `workflow_id` and `status` of `started` while the run executes. If the PR's current commit already has a published review it returns `already_reviewed` without starting a run (`resolve_only` skips that check, since resolving is useful exactly then), and triggering a PR whose review is already running joins the in-flight run. Poll progress with `review-hog-reviews-list` and read the finished findings with `review-hog-reviews-get`.",
"category": "ReviewHog",
"feature": "review_hog",
"summary": "Trigger a ReviewHog review",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index 49f3ecb4c590..ba77b3a93ec0 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -10286,7 +10286,7 @@
"feature_flag": "review-hog"
},
"review-hog-reviews-trigger": {
- "description": "Start a ReviewHog run on a pull request. Pass the PR as `pr_url` (e.g. `https://github.com/PostHog/posthog/pull/123`); the repository must be accessible to the project's GitHub App installation. `run_mode` picks the variant: `review` (the default) reviews the PR, publishes the review to it, and then chains the comment-resolution stage when the requesting user's `resolve_comments` setting is on; `review_only` reviews without resolving; `resolve_only` skips the review and only works the PR's existing unresolved review threads. IMPORTANT: resolve-capable runs write to the PR itself. They may push signed fix commits to the PR's branch, reply to review threads, and resolve bot-authored threads. Nothing is deleted and the commits are plain appends, but the actions are public to everyone on the PR. Non-blocking: returns a `workflow_id` and `status` of `started` while the run executes. If the PR's current commit already has a published review it returns `already_reviewed` without starting a run (`resolve_only` skips that check, since resolving is useful exactly then), and triggering a PR whose review is already running joins the in-flight run. Poll progress with `review-hog-reviews-list` and read the finished findings with `review-hog-reviews-get`.",
+ "description": "Start a ReviewHog run on a pull request. Pass the PR as `pr_url` (e.g. `https://github.com/PostHog/posthog/pull/123`); the repository must be accessible to the project's GitHub App installation. `run_mode` picks the variant: `review` (the default) reviews the PR, publishes the review to it, and then chains the comment-resolution stage when the requesting user's `resolve_comments` setting is on; `review_only` reviews without resolving; `resolve_only` skips the review and only works the PR's existing unresolved review threads; `flash` reviews and publishes on a lower-cost model, and never resolves comments or pushes fixes. IMPORTANT: resolve-capable runs write to the PR itself. They may push signed fix commits to the PR's branch, reply to review threads, and resolve bot-authored threads. Nothing is deleted and the commits are plain appends, but the actions are public to everyone on the PR. Non-blocking: returns a `workflow_id` and `status` of `started` while the run executes. If the PR's current commit already has a published review it returns `already_reviewed` without starting a run (`resolve_only` skips that check, since resolving is useful exactly then), and triggering a PR whose review is already running joins the in-flight run. Poll progress with `review-hog-reviews-list` and read the finished findings with `review-hog-reviews-get`.",
"category": "ReviewHog",
"feature": "review_hog",
"summary": "Trigger a ReviewHog review",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 15769b39d84b..8a453aced875 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -82555,6 +82555,7 @@ export namespace Schemas {
* * `review` - review
* * `review_only` - review_only
* * `resolve_only` - resolve_only
+ * * `flash` - flash
*/
export type ReviewTriggerRequestRunModeEnum = typeof ReviewTriggerRequestRunModeEnum[keyof typeof ReviewTriggerRequestRunModeEnum];
@@ -82563,23 +82564,25 @@ export namespace Schemas {
Review: 'review',
ReviewOnly: 'review_only',
ResolveOnly: 'resolve_only',
+ Flash: 'flash',
} as const;
export interface ReviewTriggerRequest {
/** GitHub pull request URL to review, e.g. 'https://github.com/PostHog/posthog.com/pull/123'. The repository must be accessible to the project's GitHub App installation. */
pr_url: string;
- /** What to run on the pull request. 'review' (default) reviews it and, when the requesting user's resolve_comments setting is on, chains the resolution stage; 'review_only' reviews without resolving regardless of that setting; 'resolve_only' skips the review and only runs the resolution stage on the PR's existing unresolved review threads.
+ /** What to run on the pull request. 'review' (default) reviews it and, when the requesting user's resolve_comments setting is on, chains the resolution stage; 'review_only' reviews without resolving regardless of that setting; 'resolve_only' skips the review and only runs the resolution stage on the PR's existing unresolved review threads; 'flash' uses a lower-cost model for the review passes and validation, and never resolves comments.
*
* * `review` - review
* * `review_only` - review_only
- * * `resolve_only` - resolve_only */
+ * * `resolve_only` - resolve_only
+ * * `flash` - flash */
run_mode?: ReviewTriggerRequestRunModeEnum;
}
export interface ReviewTriggerResponse {
/** Temporal workflow id for the started review run; empty when no run was started. */
workflow_id: string;
- /** Run lifecycle marker: 'started' when the review was queued, 'already_reviewed' when the pull request's current commit already has a published review (no new run starts), 'joined_running_review' when a review was already in flight (no new run starts; a report in a cheaper tier is lifted to human strength for the rest of that review and every later one). */
+ /** Run lifecycle marker: 'started' when the review was queued, 'already_reviewed' when the pull request's current commit already has a published review (no new run starts), 'joined_running_review' when a review was already in flight (no new run starts and its mode stays unchanged; requests for Full mode lift a cheaper stored tier for later Full reviews, while Flash requests leave the tier unchanged). */
status: string;
}
diff --git a/services/mcp/src/generated/review_hog/api.ts b/services/mcp/src/generated/review_hog/api.ts
index 09b29a865faa..f39073d5c9bb 100644
--- a/services/mcp/src/generated/review_hog/api.ts
+++ b/services/mcp/src/generated/review_hog/api.ts
@@ -56,7 +56,7 @@ export const ReviewHogReviewsRetrieveParams = () => zod.object({
})
/**
- * Start a ReviewHog review of any pull request the project's GitHub App installation can access, and publish it back to the PR. The requesting user is the review's acting user: their enabled perspectives, blind-spot check, validator, urgency threshold, and resolution criteria drive the run, and it appears under their recent reviews. `run_mode` picks the variant: a review (which chains the resolution stage per the user's resolve_comments setting), a review without resolving, or resolution only. Nonexistent, closed, and fork PRs are rejected synchronously; a PR whose current commit already has a published review returns 'already_reviewed' without starting a run (resolve_only skips that check — settling threads on a reviewed head is its whole point), and triggering a PR whose run is currently in flight joins that run. Otherwise non-blocking: returns the Temporal workflow id immediately while the run executes in the worker.
+ * Start a ReviewHog review of any pull request the project's GitHub App installation can access, and publish it back to the PR. The requesting user is the review's acting user: their enabled perspectives, blind-spot check, validator, urgency threshold, and resolution criteria drive the run, and it appears under their recent reviews. `run_mode` picks the variant: a review (which chains the resolution stage per the user's resolve_comments setting), a review without resolving, resolution only, or a lower-cost Flash review that never resolves comments. Nonexistent, closed, and fork PRs are rejected synchronously; a PR whose current commit already has a published review returns 'already_reviewed' without starting a run (resolve_only skips that check — settling threads on a reviewed head is its whole point), and triggering a PR whose run is currently in flight joins that run. Otherwise non-blocking: returns the Temporal workflow id immediately while the run executes in the worker.
* @summary Start a review of a pull request
*/
export const ReviewHogReviewsTriggerCreateParams = () => zod.object({
@@ -76,10 +76,12 @@ export const ReviewHogReviewsTriggerCreateBody = () => zod.object({
"GitHub pull request URL to review, e.g. 'https:\/\/github.com\/PostHog\/posthog.com\/pull\/123'. The repository must be accessible to the project's GitHub App installation."
),
run_mode: zod
- .enum(['review', 'review_only', 'resolve_only'])
- .describe('\* `review` - review\n\* `review_only` - review_only\n\* `resolve_only` - resolve_only')
+ .enum(['review', 'review_only', 'resolve_only', 'flash'])
+ .describe(
+ '\* `review` - review\n\* `review_only` - review_only\n\* `resolve_only` - resolve_only\n\* `flash` - flash'
+ )
.default(reviewHogReviewsTriggerCreateBodyRunModeDefault)
.describe(
- "What to run on the pull request. 'review' (default) reviews it and, when the requesting user's resolve_comments setting is on, chains the resolution stage; 'review_only' reviews without resolving regardless of that setting; 'resolve_only' skips the review and only runs the resolution stage on the PR's existing unresolved review threads.\n\n\* `review` - review\n\* `review_only` - review_only\n\* `resolve_only` - resolve_only"
+ "What to run on the pull request. 'review' (default) reviews it and, when the requesting user's resolve_comments setting is on, chains the resolution stage; 'review_only' reviews without resolving regardless of that setting; 'resolve_only' skips the review and only runs the resolution stage on the PR's existing unresolved review threads; 'flash' uses a lower-cost model for the review passes and validation, and never resolves comments.\n\n\* `review` - review\n\* `review_only` - review_only\n\* `resolve_only` - resolve_only\n\* `flash` - flash"
),
})