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): automatically review authored prs in flash mode (#103789)

Alex Lebedev0344a885c796
diff --git a/docs/internal/sandboxes-setup-guide.md b/docs/internal/sandboxes-setup-guide.md
index ad2599951fb6..f3ea226cb8ef 100644
--- a/docs/internal/sandboxes-setup-guide.md
+++ b/docs/internal/sandboxes-setup-guide.md
@@ -196,14 +196,42 @@ 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.
+ReviewHog Flash uses `gpt-5.6-luna` for review, blind-spot checks, and validation.
+The **ReviewHog Flash - Experimental** subsection under **What gets reviewed** on the Code review page groups the automatic Flash review toggle and **Flash strength** setting.
+These settings apply only to Flash reviews.
+**Flash strength** selects **Medium** (`medium`, the default) or **Extra high** (`xhigh`) for all of your Flash reviews, including automatic, UI, and CLI requests.
+Each turn saves the effort it starts with, so a settings change applies to later turns.
+The shared `FLASH_ARM` and `flash_arm_for_effort` in `products/review_hog/backend/reviewer/constants.py` pin 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.
+
+**Review all your PRs in Flash mode** is off by default.
+Turn it on in Code review to review PRs you author in `PostHog/posthog` when they open or receive new commits, including drafts.
+The head branch must belong to `PostHog/posthog`; fork PRs are excluded.
+Enabling it does not review existing PRs immediately; an existing PR becomes eligible on its next push.
+Only one review runs per PR, and pushes during a review coalesce into a follow-up for the latest head.
+An explicit Full request also runs after an active Flash review when that head still needs a Full review.
+Turning the setting off stops future and pending automatic starts; a running review finishes.
+Automatic Flash uses your existing severity threshold and never resolves comments or changes the PR branch.
+
+To change this setting from the CLI for a selected user:
+
+```bash
+.codex/with-flox python manage.py enable_authored_pr_reviews \
+ --team-id 1 --user-ids 1 --effort medium
+.codex/with-flox python manage.py disable_authored_pr_reviews \
+ --team-id 1 --user-ids 1
+```
+
+Use `--effort xhigh` to select Extra high; omitting `--effort` preserves the saved choice.
+Disabling automatic reviews also preserves that choice for manual Flash reviews.
+Both commands accept `--dry-run`.
+Omitting `--user-ids` changes every active member of the team's organization.
+
To run Flash locally, use `run_review --review-mode flash` from the repository root:
```bash
@@ -215,16 +243,16 @@ To run Flash locally, use `run_review --review-mode flash` from the repository r
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.
+An active turn keeps its settings snapshot, 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, model, and reasoning effort.
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.
+When recovering a failed publish with `python manage.py publish_review`, the command infers Full or Flash from the completed turn's findings.
+Legacy findings without a stored mode default to Full, and an explicit `--review-mode` must match the stored mode.
Recovery uses the completed turn's commit when recorded, even if a newer unfinished turn has fetched another commit.
### Agent run telemetry (optional)
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 609e6e713667..2ae9462cdefa 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -11164,6 +11164,14 @@ snapshots:
hash: v1.k794b7964.074d7d64c384134bfd4c223d57cd339854d39bc4283b7d9b239d4c83d78e30fb._jPmYLjyiEistYmpwqii497iwY6LHQ1WQ4nzk9aMTDs
scenes-app-workflows-createaitaskconnectors--unavailable-connector--light:
hash: v1.k794b7964.c4fdab3ab5190ace67d354d7010b49cbd37e9ec72feaa3fab9760d1f1010c8b0.S5qBDGrQNUo7qygcV1_MG_nu9RWeaMnoOFrYdhnV97E
+ scenes-code-review--default--dark:
+ hash: v1.k794b7964.99d5413f62da6fd79189c3e3e74b4c29d0623a8bda4fdb2afc3358a79e131745.95vWL4i-5X2UOK7he1TWDQMJpt_BSa3XRSugibzJG-I
+ scenes-code-review--default--light:
+ hash: v1.k794b7964.283e9ea199eed12b5798fb775e39035fa35e9c753b8ad1bf7167440e3af35afd.RIyVmxpZZ0-OT4gDMOXyjjfZ9LMV4EzLP4o75VVULCM
+ scenes-code-review--narrow--dark:
+ hash: v1.k794b7964.e3159cbdd891243ab7fada6687ea215fbcad26b36ad9eec8c5bbe16750e8c8c4.nBWAH2u4lWuYa0rK2SeXB7TK1cx6Uolc13mvvXWXMrM
+ scenes-code-review--narrow--light:
+ hash: v1.k794b7964.80e7047478c38b7788af6d97e1f6c6ac9b81b818b49a80bff3e9b7a005bff0f5._mk-hCUP8zXV3Ub-CCRdEvHQusrsmTlHjDp9-BmFcNk
scenes-dashboards-customize-breakdown-colors--customize-breakdown-colors--dark:
hash: v1.k794b7964.cf89a12669d5221b2441fbfb4439b8b1b38191943438a2c1a220444148329954.B4ew6uW3gZCbPU_3vTOggsOyHojRlyvuXxh5FZnlO-0
scenes-dashboards-customize-breakdown-colors--customize-breakdown-colors--light:
diff --git a/posthog/ingress/README.md b/posthog/ingress/README.md
index a95923320ccc..d34501a785f8 100644
--- a/posthog/ingress/README.md
+++ b/posthog/ingress/README.md
@@ -65,20 +65,20 @@ Three duties fall on the incarnation rather than on `BearerJwt`, and none is enf
## Endpoints
-| Provider | Path | App | Consumers | Product code |
-| ------------ | ------------------------------------------------------- | -------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- |
-| `github` | `/webhooks/github`, `/webhooks/github/pr` | `posthog` | `installation_lifecycle`, `installation_repositories` (core), `conversations`, `error_tracking_external_references`, `loops`, `tasks_pr_backstop`, `tasks_pr_review`, `workflows` | `products/{tasks,conversations,error_tracking,workflows}/backend/webhook_consumers.py` |
-| `github` | `/webhooks/stamphog/github` | `stamphog` | `stamphog_review` | `products/stamphog/backend/webhook_consumers.py` |
-| `slack` | `/api/conversations/v1/slack/events` | `supporthog` | `conversations_slack` | `products/conversations/backend/webhook_consumers.py` |
-| `slack` | `/api/conversations/v1/slack/interactivity` | `supporthog_interactivity` | `conversations_slack_interactivity` | `products/conversations/backend/webhook_consumers.py` |
-| `teams` | `/api/conversations/v1/teams/events` | `supporthog` | `conversations_teams` | `products/conversations/backend/webhook_consumers.py` |
-| `pandadoc` | `/api/legal_documents/pandadoc` | `default` | `legal_documents_signatures` | `products/legal_documents/backend/webhook_consumers.py` |
-| `vapi` | `/api/user_interviews/vapi_webhook/` | `default` | `user_interviews_vapi` | `products/user_interviews/backend/webhook_consumers.py` |
-| `mailgun` | `/api/conversations/v1/email/inbound` | `inbound` | `conversations_email_inbound` | `products/conversations/backend/webhook_consumers.py` |
-| `mailgun` | `/api/conversations/v1/email/outbound` | `outbound` | `conversations_email_outbound` | `products/conversations/backend/webhook_consumers.py` |
-| `mailgun` | `/api/conversations/v1/email/capture` | `capture` | `conversations_email_capture` | `products/conversations/backend/webhook_consumers.py` |
-| `sns` | `/webhooks/workflows/ses-events` | `default` | `workflows_ses_events` | `products/workflows/backend/webhook_consumers.py` |
-| `customerio` | `/api/projects/<team_id>/messaging/customerio/webhook/` | none | none, it is the DRF adapter path | `products/messaging/backend/api/customerio_webhook.py` |
+| Provider | Path | App | Consumers | Product code |
+| ------------ | ------------------------------------------------------- | -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------- |
+| `github` | `/webhooks/github`, `/webhooks/github/pr` | `posthog` | `installation_lifecycle`, `installation_repositories` (core), `conversations`, `error_tracking_external_references`, `loops`, `review_hog_authored_prs`, `tasks_pr_backstop`, `tasks_pr_review`, `workflows` | `products/{tasks,conversations,error_tracking,review_hog,workflows}/backend/webhook_consumers.py` |
+| `github` | `/webhooks/stamphog/github` | `stamphog` | `stamphog_review` | `products/stamphog/backend/webhook_consumers.py` |
+| `slack` | `/api/conversations/v1/slack/events` | `supporthog` | `conversations_slack` | `products/conversations/backend/webhook_consumers.py` |
+| `slack` | `/api/conversations/v1/slack/interactivity` | `supporthog_interactivity` | `conversations_slack_interactivity` | `products/conversations/backend/webhook_consumers.py` |
+| `teams` | `/api/conversations/v1/teams/events` | `supporthog` | `conversations_teams` | `products/conversations/backend/webhook_consumers.py` |
+| `pandadoc` | `/api/legal_documents/pandadoc` | `default` | `legal_documents_signatures` | `products/legal_documents/backend/webhook_consumers.py` |
+| `vapi` | `/api/user_interviews/vapi_webhook/` | `default` | `user_interviews_vapi` | `products/user_interviews/backend/webhook_consumers.py` |
+| `mailgun` | `/api/conversations/v1/email/inbound` | `inbound` | `conversations_email_inbound` | `products/conversations/backend/webhook_consumers.py` |
+| `mailgun` | `/api/conversations/v1/email/outbound` | `outbound` | `conversations_email_outbound` | `products/conversations/backend/webhook_consumers.py` |
+| `mailgun` | `/api/conversations/v1/email/capture` | `capture` | `conversations_email_capture` | `products/conversations/backend/webhook_consumers.py` |
+| `sns` | `/webhooks/workflows/ses-events` | `default` | `workflows_ses_events` | `products/workflows/backend/webhook_consumers.py` |
+| `customerio` | `/api/projects/<team_id>/messaging/customerio/webhook/` | none | none, it is the DRF adapter path | `products/messaging/backend/api/customerio_webhook.py` |
The owner of the third-party App registration owns the route.
The customer-facing GitHub App is shared across products, so its two endpoints are declared in `posthog/urls.py`.
diff --git a/posthog/ingress/github/README.md b/posthog/ingress/github/README.md
index e8c10a9f8d9b..ef6a46a2b3a0 100644
--- a/posthog/ingress/github/README.md
+++ b/posthog/ingress/github/README.md
@@ -44,7 +44,7 @@ See [Regional forwarding](../README.md#regional-forwarding) for the lane the pro
## Consumers
- `posthog/ingress/github/provider.py` registers `installation_lifecycle` and `installation_repositories` on the `posthog` app.
-- `products/{tasks,conversations,error_tracking,workflows}/backend/webhook_consumers.py` register the product consumers on the `posthog` app.
+- `products/{tasks,conversations,error_tracking,review_hog,workflows}/backend/webhook_consumers.py` register the product consumers on the `posthog` app.
- `products/stamphog/backend/webhook_consumers.py` registers `stamphog_review` on the `stamphog` app.
The Error Tracking consumer handles opened and edited issues and pull requests from repository owners, members, and collaborators.
diff --git a/products/review_hog/ARCHITECTURE.md b/products/review_hog/ARCHITECTURE.md
index b92979d6e491..ef7c7bf546bc 100644
--- a/products/review_hog/ARCHITECTURE.md
+++ b/products/review_hog/ARCHITECTURE.md
@@ -39,11 +39,13 @@ in flight, with the detail in DECISIONS.md.
## Status & next
-ReviewHog runs end-to-end: label / UI / inbox triggers → the Temporal pipeline → published PR review. The
-current focus is productionizing the reviewer-topology eval and tightening the finder/validator balance
-(validator strictness, fewer junk candidates, the coverage gap); the **loop** — a living, multi-turn review that
-re-checks on new commits/comments and implements fixes — is designed but not built. The single-turn pipeline
-below is its per-turn body. The **resolution stage** — a post-review, standalone-capable stage that triages every
+ReviewHog runs end-to-end: label / UI / inbox / automatic authored-PR triggers → the Temporal pipeline → published PR review.
+Opted-in authors receive Flash reviews on new PRs and pushes in `PostHog/posthog`, including drafts.
+The per-PR queue serializes reviews and coalesces automatic pushes into a follow-up for the latest head.
+The current focus is productionizing the reviewer-topology eval and tightening the finder/validator balance
+(validator strictness, fewer junk candidates, the coverage gap).
+The broader **loop** that reacts to comments and implements fixes is designed but not built; the pipeline below is the body of each review turn.
+The **resolution stage** — a post-review, standalone-capable stage that triages every
unresolved review thread and implements the worth-and-safe ones directly on the PR branch — is **built and
live-qualified** (e2e on its own PR #72074, 2026-07-18 — verdicts, findings, and the GO call in
`eval/experiments/2026-07-resolution-e2e/FINAL_REPORT.md`): `ResolvePRWorkflow` (`backend/temporal/resolution.py`) drives one warm writable sandbox
@@ -91,7 +93,7 @@ and MUST land before the resolution stage runs on PRs the team does not own:
the Tasks facade threading the policy in, plus a sandbox image rebuild), which is why it is a gate rather
than a fix in this repo.
-**Reviewing includes resolving**: a published review chains into the stage when the acting user's
+**Full reviews can include resolving**: a published Full review chains into the stage when the acting user's
`resolve_comments` setting is on (default on; the toggle sits with the trigger opt-outs on the Code review scene,
which also carries a single-active resolution-criteria skill block and a split Review button with
review-without-resolving / resolve-only side actions). Standalone entry: `POST /api/review_hog/resolve`, the
@@ -109,8 +111,8 @@ The reviews API exposes it as the row's `resolution` field ("Resolving comments
the PR status comment carries a marker-delimited resolution section (`update_resolution_status_comment` — spliced into the review's comment, created on demand for standalone runs, failure-edited on the final attempt),
with a patched workflow-level backstop (`fail_resolution_activity`, fired from `ResolvePRWorkflow`'s except) covering the deaths the activity handler can't see — prepare failures, timeouts, cancellation, worker death — by idling the report and writing the failed section from the persisted work-list,
and each queued thread's opening comment gets a best-effort 👀 reaction (queue marker; never removed).
-The **busy-guard** (`temporal/client.py::workflow_running`, fail-open describe on the deterministic ids) refuses a review start while the PR's `resolve-pr` runs and a standalone resolution while `review-pr` runs —
-Temporal's same-id joining can't see across the two workflows; the chained post-publish dispatch is exempt by construction.
+The API's **busy-guard** (`temporal/client.py::workflow_running`, fail-open describe on the deterministic IDs) refuses a review request while the PR's `resolve-pr` runs and a standalone resolution while its review queue runs.
+Automatic requests remain in the review queue until resolution finishes; the chained post-publish resolution starts within the active review turn.
**TODO (SOON) — react to thread replies: answer and act when a human responds to an escalated (or any settled) thread.**
The per-thread mechanics already exist and are e2e-proven: a new human comment beats the verdict watermark and
@@ -215,7 +217,8 @@ head_sha-scoped DB resume makes the redo cheap.
## Pipeline
-The orchestration is a Temporal workflow: `ReviewPRWorkflow` (`backend/temporal/workflow.py`) drives the setup
+`ReviewPRQueueWorkflow` (`backend/temporal/scheduling.py`) serializes requests for a PR and starts each turn as a child workflow.
+`ReviewPRWorkflow` (`backend/temporal/workflow.py`) drives the setup
activities → two fan-out **child workflows** (perspective review / validate) → finishing activities, each stage an
activity in `backend/temporal/activities.py`. Only small values cross boundaries (`report_id` + `head_sha` + unit
keys / JSON issue slices); every activity reloads its inputs from the per-turn `pr_snapshot` artefact, so no big
@@ -419,18 +422,20 @@ P3/P4 → low, no readable judgment
→ `agent_unprioritized` at xhigh with a warning. One exception to stickiness: a person's trigger (label / UI /
CLI) that starts a **review** of a report in a cheaper tier lifts it to `human` for that and every later turn,
never the reverse; a resolve-only run upserts the same row but does not lift (`lift_tier_on_human_trigger`). A
-person's trigger that lands while the report's review is still running joins that run (`USE_EXISTING`), so the
-trigger endpoints write the lift themselves (`lift_review_tier_for_joined_trigger`) and answer
-`joined_running_review`: the turn's remaining units and every later turn run at human strength. The
-cheaper arms are rolled out per team through the `REVIEWHOG_TEAM_IDS` dogfood gate; other teams record their tier
+person's Full trigger that lands while the report's review is still running signals the existing queue and preserves a pending Full request.
+The trigger endpoints write the lift themselves (`lift_review_tier_for_joined_trigger`) and answer
+`joined_running_review`; remaining Full units and later Full turns use the human tier, while an active Flash turn keeps its Flash arm.
+The cheaper arms are rolled out per team through the `REVIEWHOG_TEAM_IDS` dogfood gate; other teams record their tier
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). 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`
+one arm, `FLASH_ARM` (`gpt-5.6-luna`, Codex with `full-access`), for that turn only.
+`flash_arm_for_effort` selects the acting user's saved `medium` (default) or `xhigh` effort, snapshotted when the turn starts.
+The preference applies to automatic, UI, and CLI Flash requests.
+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)
@@ -591,9 +596,9 @@ 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. 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
+ `pr_snapshot` artefacts. A `perspective_result` is stamped with the reviewer model and reasoning effort that wrote it and is only
+ reused by a turn running that configuration: 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 without the required stamps 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`
@@ -634,7 +639,7 @@ 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`.
+ Add `--review-mode flash` for Luna review and validation at the acting user's saved effort (`medium` by default, or `xhigh`), 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**
@@ -644,14 +649,18 @@ See [DECISIONS.md](./DECISIONS.md) for the "reuse the leaf, own the model" bound
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.
+ The command infers Full or Flash from the completed turn's findings, defaulting to Full for legacy unstamped runs.
+ An explicit `--review-mode` must match the stored mode.
- **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>
[--user-ids <id> ...] [--dry-run]` sets `review_inbox_prs` on every active org member's `ReviewUserSettings`
(or only the listed users, each of whom must be an org member). `{enable,disable}_stamphog_inbox_reviews` is
- the same pair for `stamphog_review_inbox_prs`, and `{enable,disable}_comment_resolution` for `resolve_comments`;
- each command touches only its own toggle. A run creates rows only when the requested value differs from the
+ the same pair for `stamphog_review_inbox_prs`, and `{enable,disable}_comment_resolution` for `resolve_comments`.
+ `{enable,disable}_authored_pr_reviews` controls `review_authored_prs`, the default-off automatic Flash setting.
+ `enable_authored_pr_reviews` also accepts `--effort medium` or `--effort xhigh` to set the user's effort for all Flash requests; omitting it preserves the saved choice.
+ Disabling automatic reviews preserves the effort preference and lets running reviews finish while stopping future and pending automatic starts.
+ Each command changes only its named toggle and any explicit effort choice. A run creates rows only when the requested value differs from the
field's default (a missing row already reads as the default) and otherwise flips existing rows. A deliberate
operator action because the per-user defaults are the budget and posture gates; members who join later keep
the default until a re-run. Shared logic: `backend/settings_toggles.py`.
@@ -674,22 +683,34 @@ See [DECISIONS.md](./DECISIONS.md) for the "reuse the leaf, own the model" bound
The sandbox `repository` is the PR's own `owner/repo`, derived from the PR URL.
- **Prod label trigger** (settings, `posthog/settings/access.py`) — `REVIEWHOG_TRIGGER_TOKEN` (shared secret),
`REVIEWHOG_TEAM_ID` (the run team), `REVIEWHOG_RUN_USER_ID` (optional; falls back to the integration creator).
+- **Automatic authored-PR trigger** uses the first `REVIEWHOG_TEAM_IDS` entry and requires a matching GitHub installation on that team.
+ The PR author's linked GitHub identity must map to an active member of the team's organization with `review_authored_prs` enabled.
-**Triggers.** Five entry points drive the same `ReviewPRWorkflow`: the `run_review` CLI (manual / eval), the
+**Triggers.** Six entry points feed the same per-PR `ReviewPRQueueWorkflow`: 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; 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
+also carries the review-without-resolving, resolve-only, and **flash** variants; Flash 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**
+whoever controls the run, the sandbox agent included), **MCP tools**
(`review-hog-reviews-{trigger,list,get}`, defined in `products/review_hog/mcp/tools.yaml` and gated on the
-`review-hog` feature flag) that drive the same reviews viewset with a personal API key or OAuth token. The UI and
-MCP paths are one surface: the viewset carries the grantable `review_hog` scope (`review_hog:read` for list /
+`review-hog` feature flag) that drive the same reviews viewset with a personal API key or OAuth token, and **automatic authored-PR Flash reviews**.
+The automatic trigger consumes signed GitHub `pull_request` deliveries through `review_hog_authored_prs` and queues a Celery task for identity and opt-in checks.
+It accepts `opened` and `synchronize` for open `PostHog/posthog` PRs whose head and base belong to that repository, including drafts.
+Enabling the setting performs no backfill; existing PRs become eligible on their next push.
+The turn rechecks the author's opt-in before starting and uses their saved severity threshold; Flash never starts resolution.
+The UI and MCP paths are one surface: the viewset carries the grantable `review_hog` scope (`review_hog:read` for list /
retrieve / perspective_stats, `review_hog:write` for trigger) rather than INTERNAL, and the trigger action keeps
the `REVIEWHOG_TEAM_ID` dogfood gate and its synchronous URL / App-access / fork / open-state checks regardless of
caller. See [DECISIONS.md](./DECISIONS.md) for each trigger's auth / scope / identity rules.
+The `review-pr-queue` workflow keeps the existing per-PR workflow ID and records requests through signals.
+It has at most one pending request each for Full, manual Flash, and automatic Flash, taking explicit requests before automatic ones.
+It waits for an active resolution stage and runs each review in a `review-pr` child workflow with the existing retry and comment behavior.
+An explicit Full request remains pending during an active Flash turn and runs if that head still needs a Full review.
+Automatic pushes coalesce to the latest head; turning off the authored-PR setting prevents pending automatic reviews from starting without canceling a running turn.
+`automatic_reviewed_head_sha` advances only after publication succeeds or finds nothing to publish, so a failed publication can retry and an empty review does not repeat.
+
**Review surfaces (Code review scene).** The reviews API's `scope=mine` ("For you") matches reports where the
viewer is the **acting user OR the PR's author** — `author_login` compared case-insensitively against the
viewer's linked GitHub login (`User.get_github_login()`, the reverse of the author→user mapping the reviewer
diff --git a/products/review_hog/backend/api/reviews.py b/products/review_hog/backend/api/reviews.py
index 230220e5a3ef..b170c8bdba29 100644
--- a/products/review_hog/backend/api/reviews.py
+++ b/products/review_hog/backend/api/reviews.py
@@ -49,6 +49,7 @@ from products.review_hog.backend.reviewer.progress import (
snapshot_stats,
turn_stats,
)
+from products.review_hog.backend.reviewer.review_state import review_already_published
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, PRMetadata, PRParser
from products.review_hog.backend.temporal.client import (
@@ -278,10 +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 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)."
+ "pull request's current commit already has a published review in the requested mode, "
+ "'joined_running_review' when a review was already in flight and the request joined its queue. "
+ "A requested Full review waits for an active Flash review."
)
@@ -838,7 +838,8 @@ class ReviewRecentReviewsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet
report = (
ReviewReport.objects.for_team(team_id).filter(repository__iexact=repository, pr_number=pr_number).first()
)
- if report is not None and pr_meta.head_sha and report.published_head_sha == pr_meta.head_sha:
+ review_mode = REVIEW_MODE_FLASH if run_mode == RUN_MODE_FLASH else REVIEW_MODE_FULL
+ if report is not None and review_already_published(report, pr_meta.head_sha or "", review_mode):
# The workflow would early-exit before resolving the acting user anyway — say so instead
# of answering "started" for a run that will do nothing.
return Response(
@@ -859,7 +860,8 @@ class ReviewRecentReviewsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet
trigger_source=TRIGGER_UI,
# 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,
+ review_mode=review_mode,
+ requested_head_sha=pr_meta.head_sha,
)
if joins_running_review:
# Flash is excluded for the same reason the fetch upsert excludes it: the lift rewrites
diff --git a/products/review_hog/backend/api/settings.py b/products/review_hog/backend/api/settings.py
index 4c60278e0cf8..8125eb99c5fe 100644
--- a/products/review_hog/backend/api/settings.py
+++ b/products/review_hog/backend/api/settings.py
@@ -43,6 +43,18 @@ class ReviewUserSettingsSerializer(serializers.ModelSerializer):
"branch, and reply on every thread. On by default; turning it off makes reviews stop at "
"publishing.",
)
+ review_authored_prs = serializers.BooleanField(
+ required=False,
+ help_text="Automatically review pull requests authored by this user in PostHog/posthog in Flash mode. "
+ "Off by default. Flash reviews post findings without resolving comments.",
+ )
+ flash_reasoning_effort = serializers.ChoiceField(
+ required=False,
+ choices=ReviewUserSettings.FlashReasoningEffort.choices,
+ help_text="Reasoning effort for this user's automatic and manually requested Flash reviews: "
+ "'medium' (default) or 'xhigh'. Applies to both review and validation. "
+ "Saved independently of the automatic-review toggle.",
+ )
urgency_threshold = serializers.ChoiceField(
required=False,
choices=ReviewUserSettings.UrgencyThreshold.choices,
@@ -67,6 +79,8 @@ class ReviewUserSettingsSerializer(serializers.ModelSerializer):
"stamphog_review_inbox_prs",
"review_labeled_prs",
"resolve_comments",
+ "review_authored_prs",
+ "flash_reasoning_effort",
"urgency_threshold",
"can_trigger_reviews",
"stamphog_connected",
diff --git a/products/review_hog/backend/api/trigger.py b/products/review_hog/backend/api/trigger.py
index f53442e52ad6..c66366ac88e9 100644
--- a/products/review_hog/backend/api/trigger.py
+++ b/products/review_hog/backend/api/trigger.py
@@ -56,8 +56,7 @@ class ReviewHogTriggerResponseSerializer(serializers.Serializer):
workflow_id = serializers.CharField(help_text="Temporal workflow id for the started review run.")
status = serializers.CharField(
help_text="Run lifecycle marker: 'started' when the review was queued, 'joined_running_review' when a "
- "review of this pull request 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)."
+ "review of this pull request was already in flight. A requested Full review waits for an active Flash review."
)
diff --git a/products/review_hog/backend/automatic_reviews.py b/products/review_hog/backend/automatic_reviews.py
new file mode 100644
index 000000000000..d910ae686c86
--- /dev/null
+++ b/products/review_hog/backend/automatic_reviews.py
@@ -0,0 +1,171 @@
+import logging
+from collections.abc import Mapping
+from typing import Literal
+
+from django.conf import settings
+
+from prometheus_client import Counter
+
+from posthog.dataclasses import frozen
+from posthog.models.integration import Integration
+from posthog.otel_metrics import OtelInstrumentFactory
+
+from products.review_hog.backend.models import ReviewUserSettings
+
+AUTOMATIC_REVIEW_REPOSITORY = "PostHog/posthog"
+
+logger = logging.getLogger(__name__)
+_otel = OtelInstrumentFactory("review_hog")
+
+AuthoredPRReviewOutcome = Literal["no_team", "installation_mismatch", "author_unmapped", "not_opted_in", "started"]
+
+# A rejected dispatch returns normally, so Celery records the task as successful and no workflow
+# starts to report the skip. Without this counter a misconfigured deploy or a drifted installation
+# id stops every automatic review with no signal: "started" falling to zero next to a rise in
+# another outcome names the cause.
+AUTHORED_PR_REVIEW_TOTAL = Counter(
+ "posthog_review_hog_authored_pr_review_total",
+ "Automatic review dispatch decisions for authored PRs, keyed by outcome",
+ labelnames=["outcome"],
+)
+
+
+def _observe_dispatch(outcome: AuthoredPRReviewOutcome) -> None:
+ AUTHORED_PR_REVIEW_TOTAL.labels(outcome=outcome).inc()
+ _otel.record_counter_twin(AUTHORED_PR_REVIEW_TOTAL, 1, {"outcome": outcome})
+
+
+def _mapping(value: object) -> Mapping[str, object]:
+ return value if isinstance(value, Mapping) else {}
+
+
+def _allowed_repository(value: object) -> bool:
+ full_name = _mapping(value).get("full_name")
+ return isinstance(full_name, str) and full_name.lower() == AUTOMATIC_REVIEW_REPOSITORY.lower()
+
+
+def authored_reviews_enabled(*, team_id: int, user_id: int) -> bool:
+ return (
+ ReviewUserSettings.objects.for_team(team_id)
+ .filter(
+ user_id=user_id,
+ review_authored_prs=True,
+ user__is_active=True,
+ user__organization_membership__organization__team__id=team_id,
+ )
+ .exists()
+ )
+
+
+@frozen
+class AuthoredPRReview:
+ installation_id: str
+ author_login: str
+ pr_number: int
+ head_sha: str
+
+ @classmethod
+ def from_payload(cls, payload: Mapping[str, object]) -> "AuthoredPRReview | None":
+ if payload.get("action") not in ("opened", "synchronize"):
+ return None
+ pull_request = _mapping(payload.get("pull_request"))
+ if pull_request.get("state") != "open" or pull_request.get("merged"):
+ return None
+ head = _mapping(pull_request.get("head"))
+ base = _mapping(pull_request.get("base"))
+ if not all(
+ _allowed_repository(repo) for repo in (payload.get("repository"), head.get("repo"), base.get("repo"))
+ ):
+ return None
+
+ installation_id = _mapping(payload.get("installation")).get("id")
+ author_login = _mapping(pull_request.get("user")).get("login")
+ pr_number = pull_request.get("number")
+ head_sha = head.get("sha")
+ if (
+ not isinstance(installation_id, int)
+ or isinstance(installation_id, bool)
+ or installation_id < 1
+ or not isinstance(pr_number, int)
+ or isinstance(pr_number, bool)
+ or pr_number < 1
+ or not isinstance(author_login, str)
+ or not author_login.strip()
+ or not isinstance(head_sha, str)
+ or not head_sha.strip()
+ ):
+ return None
+ return cls(
+ installation_id=str(installation_id),
+ author_login=author_login.strip().lower(),
+ pr_number=pr_number,
+ head_sha=head_sha,
+ )
+
+ def start(self) -> None:
+ # These clients pull in the sandbox runtime; enqueueing a webhook must not load it.
+ from products.review_hog.backend.reviewer.constants import REVIEW_MODE_FLASH # noqa: PLC0415
+ from products.review_hog.backend.temporal.client import start_review_pr_workflow # noqa: PLC0415
+ from products.review_hog.backend.temporal.types import TRIGGER_AUTOMATIC # noqa: PLC0415
+ from products.signals.backend.report_generation.resolve_reviewers import ( # noqa: PLC0415
+ resolve_org_github_login_to_users,
+ )
+
+ if not settings.REVIEWHOG_TEAM_IDS:
+ logger.warning("No ReviewHog team is configured; skipping automatic review of PR #%s", self.pr_number)
+ _observe_dispatch("no_team")
+ return
+ team_id = settings.REVIEWHOG_TEAM_IDS[0]
+ if not Integration.objects.filter(team_id=team_id, kind="github", integration_id=self.installation_id).exists():
+ logger.warning(
+ "Team %s has no GitHub integration for installation %s; skipping automatic review of PR #%s",
+ team_id,
+ self.installation_id,
+ self.pr_number,
+ )
+ _observe_dispatch("installation_mismatch")
+ return
+ author = resolve_org_github_login_to_users(team_id, [self.author_login]).get(self.author_login)
+ if author is None:
+ logger.info(
+ "PR author '%s' is not a PostHog org user on team %s; skipping automatic review of PR #%s",
+ self.author_login,
+ team_id,
+ self.pr_number,
+ )
+ _observe_dispatch("author_unmapped")
+ return
+ # The high-volume branch: most authors on the repository have not opted in. The counter
+ # carries the signal, so this one stays out of the logs.
+ if not authored_reviews_enabled(team_id=team_id, user_id=author.id):
+ _observe_dispatch("not_opted_in")
+ return
+ start_review_pr_workflow(
+ pr_url=f"https://github.com/{AUTOMATIC_REVIEW_REPOSITORY}/pull/{self.pr_number}",
+ team_id=team_id,
+ user_id=author.id,
+ acting_user_id=author.id,
+ publish=True,
+ resolve_comments=False,
+ review_mode=REVIEW_MODE_FLASH,
+ trigger_source=TRIGGER_AUTOMATIC,
+ requested_head_sha=self.head_sha,
+ )
+ # After the start, so a retried task cannot count a dispatch it never made.
+ _observe_dispatch("started")
+
+
+def enqueue_authored_pr_review(payload: Mapping[str, object]) -> None:
+ review = AuthoredPRReview.from_payload(payload)
+ if review is None:
+ return
+ from products.review_hog.backend.tasks import ( # noqa: PLC0415 - keeps Celery off the registry import path
+ process_authored_pr_event,
+ )
+
+ process_authored_pr_event.delay(
+ installation_id=review.installation_id,
+ author_login=review.author_login,
+ pr_number=review.pr_number,
+ head_sha=review.head_sha,
+ )
diff --git a/products/review_hog/backend/facade/__init__.py b/products/review_hog/backend/facade/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/review_hog/backend/facade/github.py b/products/review_hog/backend/facade/github.py
new file mode 100644
index 000000000000..926adf686db8
--- /dev/null
+++ b/products/review_hog/backend/facade/github.py
@@ -0,0 +1,3 @@
+from products.review_hog.backend.automatic_reviews import enqueue_authored_pr_review
+
+__all__ = ["enqueue_authored_pr_review"]
diff --git a/products/review_hog/backend/management/commands/disable_authored_pr_reviews.py b/products/review_hog/backend/management/commands/disable_authored_pr_reviews.py
new file mode 100644
index 000000000000..77267ad9209c
--- /dev/null
+++ b/products/review_hog/backend/management/commands/disable_authored_pr_reviews.py
@@ -0,0 +1,10 @@
+from products.review_hog.backend.management.toggle_command import SettingsToggleCommand
+
+
+class Command(SettingsToggleCommand):
+ help = (
+ "Turn off automatic Flash reviews of authored PRs (review_authored_prs) for every active member of the "
+ "organization that owns the given team, or for the given user ids. Preserves Flash reasoning effort."
+ )
+ field = "review_authored_prs"
+ enabled = False
diff --git a/products/review_hog/backend/management/commands/enable_authored_pr_reviews.py b/products/review_hog/backend/management/commands/enable_authored_pr_reviews.py
new file mode 100644
index 000000000000..e50bb245b716
--- /dev/null
+++ b/products/review_hog/backend/management/commands/enable_authored_pr_reviews.py
@@ -0,0 +1,10 @@
+from products.review_hog.backend.management.toggle_command import SettingsToggleCommand
+
+
+class Command(SettingsToggleCommand):
+ help = (
+ "Turn on automatic Flash reviews of authored PRs (review_authored_prs) for every active member of the "
+ "organization that owns the given team, or for the given user ids."
+ )
+ field = "review_authored_prs"
+ enabled = True
diff --git a/products/review_hog/backend/management/commands/publish_review.py b/products/review_hog/backend/management/commands/publish_review.py
index 66f4d064c285..8af5452b5028 100644
--- a/products/review_hog/backend/management/commands/publish_review.py
+++ b/products/review_hog/backend/management/commands/publish_review.py
@@ -13,6 +13,7 @@ from products.review_hog.backend.reviewer.constants import (
REVIEW_MODE_FULL,
)
from products.review_hog.backend.reviewer.models.issues_review import IssuePriority
+from products.review_hog.backend.reviewer.review_state import review_mode_for_run
from products.review_hog.backend.reviewer.tools.github_client import GitHubAPIError, github_api_request
from products.review_hog.backend.reviewer.tools.github_meta import PRParser
from products.review_hog.backend.reviewer.tools.publish_review import publish_persisted_review
@@ -60,8 +61,8 @@ class Command(BaseCommand):
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",
+ default=None,
+ help="Mode that produced the stored review; inferred from the completed run when omitted",
)
def handle(self, *args: Any, **options: Any) -> None:
@@ -87,6 +88,15 @@ class Command(BaseCommand):
if not head_sha:
raise CommandError(f"Review for {repository}#{pr_number} has no reviewed head_sha; nothing to publish.")
+ # The latest completed turn's findings live under run_index == run_count: fetch sets
+ # run_index = run_count + 1, and finalize bumps run_count after they're persisted.
+ run_index = report.run_count
+ review_mode = review_mode_for_run(report, run_index)
+ if options["review_mode"] is not None and options["review_mode"] != review_mode:
+ raise CommandError(
+ f"The stored review used {review_mode} mode. Omit --review-mode or use --review-mode {review_mode}."
+ )
+
github = GitHubIntegration.first_for_team_repository(team_id, repository)
if github is None:
raise CommandError(
@@ -106,9 +116,6 @@ class Command(BaseCommand):
if warning:
self.stdout.write(self.style.WARNING(warning))
- # The latest completed turn's findings live under run_index == run_count: fetch sets
- # run_index = run_count + 1, and finalize bumps run_count after they're persisted.
- run_index = report.run_count
self.stdout.write(
self.style.MIGRATE_HEADING(
f"ReviewHog ▶ publishing {repository}#{pr_number} · report {report.id} · head {head_sha[:12]}"
@@ -129,7 +136,7 @@ class Command(BaseCommand):
token=token,
urgency_threshold=_run_threshold(report.run_urgency_threshold),
installation_id=installation_id,
- review_mode=options["review_mode"],
+ review_mode=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/toggle_command.py b/products/review_hog/backend/management/toggle_command.py
index 5bb2d77868d0..e54b0d450038 100644
--- a/products/review_hog/backend/management/toggle_command.py
+++ b/products/review_hog/backend/management/toggle_command.py
@@ -12,7 +12,8 @@ from django.core.management.base import BaseCommand, CommandError, CommandParser
from posthog.models.scoping.manager import TeamScopeError
from posthog.models.team import Team
-from products.review_hog.backend.settings_toggles import ToggleField, UsersNotInOrganization, apply_toggle, plan_toggle
+from products.review_hog.backend.models import ReviewUserSettings
+from products.review_hog.backend.settings_toggles import ToggleField, apply_toggle, plan_toggle
class SettingsToggleCommand(BaseCommand):
@@ -38,16 +39,24 @@ class SettingsToggleCommand(BaseCommand):
action="store_true",
help="Print what would change without touching the database.",
)
+ if self.field == "review_authored_prs" and self.enabled:
+ parser.add_argument(
+ "--effort",
+ choices=ReviewUserSettings.FlashReasoningEffort.values,
+ help="Set these users' Flash reasoning effort. Omit to preserve their saved preference.",
+ )
def handle(self, *args: Any, **options: Any) -> None:
try:
+ effort = options.get("effort")
plan = plan_toggle(
team_id=options["team_id"],
field=self.field,
enabled=self.enabled,
user_ids=options.get("user_ids"),
+ flash_reasoning_effort=ReviewUserSettings.FlashReasoningEffort(effort) if effort is not None else None,
)
- except (TeamScopeError, Team.DoesNotExist, UsersNotInOrganization) as err:
+ except (TeamScopeError, Team.DoesNotExist, ValueError) as err:
raise CommandError(str(err)) from err
changed = ", ".join(str(user_id) for user_id in plan.changed_user_ids) or "none"
diff --git a/products/review_hog/backend/migrations/0032_authored_pr_review_settings.py b/products/review_hog/backend/migrations/0032_authored_pr_review_settings.py
new file mode 100644
index 000000000000..ab9db67a1a2d
--- /dev/null
+++ b/products/review_hog/backend/migrations/0032_authored_pr_review_settings.py
@@ -0,0 +1,37 @@
+# Generated by Django 5.2.17 on 2026-09-21 13:53
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("review_hog", "0031_reviewreport_review_signal_priority_and_more"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="reviewreport",
+ name="automatic_reviewed_head_sha",
+ field=models.CharField(blank=True, max_length=64, null=True),
+ ),
+ migrations.AddField(
+ model_name="reviewreport",
+ name="published_heads_by_mode",
+ field=models.JSONField(blank=True, null=True),
+ ),
+ migrations.AddField(
+ model_name="reviewusersettings",
+ name="flash_reasoning_effort",
+ field=models.CharField(
+ choices=[("medium", "Medium"), ("xhigh", "Extra high")],
+ db_default="medium",
+ default="medium",
+ max_length=10,
+ ),
+ ),
+ migrations.AddField(
+ model_name="reviewusersettings",
+ name="review_authored_prs",
+ field=models.BooleanField(db_default=False, default=False),
+ ),
+ ]
diff --git a/products/review_hog/backend/migrations/max_migration.txt b/products/review_hog/backend/migrations/max_migration.txt
index 93239dcc1b47..a880077fe368 100644
--- a/products/review_hog/backend/migrations/max_migration.txt
+++ b/products/review_hog/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0031_reviewreport_review_signal_priority_and_more
+0032_authored_pr_review_settings
diff --git a/products/review_hog/backend/models.py b/products/review_hog/backend/models.py
index 87b3b7ffb208..84446214eb86 100644
--- a/products/review_hog/backend/models.py
+++ b/products/review_hog/backend/models.py
@@ -63,16 +63,18 @@ class ReviewReport(UUIDModel, TeamScopedRootMixin):
# turn START. Read paths pairing stats/links with the completed turn's findings anchor here, so an
# in-flight or crashed turn's metadata never splices onto the previous turn's findings.
completed_head_sha = models.CharField(max_length=64, null=True, blank=True)
+ # Only a successful publish or no-findings turn suppresses automatic retries.
+ automatic_reviewed_head_sha = models.CharField(max_length=64, null=True, blank=True)
# The urgency threshold the last COMPLETED turn's body/publish gated on — stamped at finalize
# (alongside `run_count` / `completed_head_sha`) from the same resolve snapshot both consumed,
# so the detail view buckets published vs held-back findings truthfully even when the acting
# user's settings later change. Null for pre-column turns (readers fall back to the viewer's
# own setting as an approximation).
run_urgency_threshold = models.CharField(max_length=20, null=True, blank=True)
- # Idempotency watermark — the head the review was last *published* to GitHub for (distinct from
- # `head_sha`, what was reviewed). Publishing skips when this equals the current head, so an
- # activity retry / re-trigger can't double-post the review or the one-time alpha promo comment.
+ # Latest published head for outcome tracking and compatibility reads.
published_head_sha = models.CharField(max_length=64, null=True, blank=True)
+ # Each mode has its own marker so a Flash review cannot suppress Full publication.
+ published_heads_by_mode = models.JSONField(null=True, blank=True)
# The urgency threshold in force at each publish, keyed by the `run_index` that published, as
# `{"1": "consider", "2": "must_fix"}`. Outcome classification reconstructs the published finding
# set from this, since the user's live setting can change after publish. Keyed per turn rather
@@ -379,6 +381,9 @@ class ReviewUserSettings(UUIDModel, TeamScopedRootMixin):
StamphogRepoConfig covering the PR's repository.
`resolve_comments` is the resolution stage's opt-out (default on — reviewing includes resolving):
when on, every published review of the user's PRs chains into the resolution stage.
+ `review_authored_prs` opts into automatic Flash reviews of the user's own PRs independently of
+ the inbox and label triggers. `flash_reasoning_effort` also applies to manually requested Flash
+ reviews, so disabling the automatic trigger preserves that preference.
"""
class UrgencyThreshold(models.TextChoices):
@@ -387,6 +392,10 @@ class ReviewUserSettings(UUIDModel, TeamScopedRootMixin):
SHOULD_FIX = "should_fix"
MUST_FIX = "must_fix"
+ class FlashReasoningEffort(models.TextChoices):
+ MEDIUM = "medium", "Medium"
+ XHIGH = "xhigh", "Extra high"
+
# FKs to the hot posthog_team / posthog_user tables use db_constraint=False so creating this
# table takes no lock on the parents (app-level enforcement only).
team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, related_name="+", db_constraint=False)
@@ -395,6 +404,13 @@ class ReviewUserSettings(UUIDModel, TeamScopedRootMixin):
stamphog_review_inbox_prs = models.BooleanField(default=False, db_default=False)
review_labeled_prs = models.BooleanField(default=True, db_default=True)
resolve_comments = models.BooleanField(default=True, db_default=True)
+ review_authored_prs = models.BooleanField(default=False, db_default=False)
+ flash_reasoning_effort = models.CharField(
+ max_length=10,
+ choices=FlashReasoningEffort.choices,
+ default=FlashReasoningEffort.MEDIUM,
+ db_default=FlashReasoningEffort.MEDIUM.value,
+ )
urgency_threshold = models.CharField(
max_length=20,
choices=UrgencyThreshold.choices,
diff --git a/products/review_hog/backend/reviewer/artefact_content.py b/products/review_hog/backend/reviewer/artefact_content.py
index 40a5121c8812..d6f10f18596e 100644
--- a/products/review_hog/backend/reviewer/artefact_content.py
+++ b/products/review_hog/backend/reviewer/artefact_content.py
@@ -251,9 +251,8 @@ class PerspectiveSelectionArtefact(BaseModel):
class PerspectiveResultArtefact(BaseModel):
"""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.
+ The complete reviewer arm keys the resume because different efforts can review the same commit.
+ Rows without an arm are not reused: their model alone cannot establish the reasoning budget.
"""
head_sha: str = Field(description="PR head commit this review was computed for.")
@@ -261,6 +260,9 @@ class PerspectiveResultArtefact(BaseModel):
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.")
+ review_config: str | None = Field(
+ default=None, description="Serialized reviewer configuration 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 47a9b199bc14..b37eae810589 100644
--- a/products/review_hog/backend/reviewer/constants.py
+++ b/products/review_hog/backend/reviewer/constants.py
@@ -82,9 +82,19 @@ 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:
+def flash_arm_for_effort(reasoning_effort: str) -> ReviewArm:
+ if reasoning_effort == ReasoningEffort.XHIGH.value:
+ return replace(FLASH_ARM, reasoning_effort=ReasoningEffort.XHIGH)
+ if reasoning_effort != ReasoningEffort.MEDIUM.value:
+ logger.warning("Unknown Flash reasoning effort %s; using medium", reasoning_effort)
+ return FLASH_ARM
+
+
+def review_arm_for_mode(
+ review_mode: str, persisted: ReviewArm, *, flash_reasoning_effort: str = ReasoningEffort.MEDIUM.value
+) -> 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
+ return flash_arm_for_effort(flash_reasoning_effort) if review_mode == REVIEW_MODE_FLASH else persisted
class ReviewTier(StrEnum):
@@ -133,8 +143,8 @@ _TIER_BY_PRIORITY: dict[ReportPriority, ReviewTier] = {
# The trigger sources (`temporal/types.py`) that carry an explicit ask for a review: a label, the
# CLI, or the Code review scene and its MCP tool (both stamped `ui`, so an agent driving the MCP
-# tool on someone's behalf counts as that person asking). Only the inbox trigger fires with nobody
-# asking, and a trigger from this set on an inbox-created report lifts its tier
+# tool on someone's behalf counts as that person asking). Inbox and automatic authored-PR triggers
+# fire without a per-PR request. A trigger from this set on an inbox-created report lifts its tier
# (`upsert_review_report`). Spelled out here because persistence cannot import the temporal
# package (its `__init__` imports the activities, which import persistence); `test_constants.py`
# locks the set to the trigger constants.
@@ -227,9 +237,11 @@ DEFAULT_VALIDATION_ARM = ReviewArm(
)
-def validation_arm_for_mode(review_mode: str) -> ReviewArm:
+def validation_arm_for_mode(
+ review_mode: str, *, flash_reasoning_effort: str = ReasoningEffort.MEDIUM.value
+) -> 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
+ return flash_arm_for_effort(flash_reasoning_effort) if review_mode == REVIEW_MODE_FLASH else DEFAULT_VALIDATION_ARM
# RESOLUTION MODEL
diff --git a/products/review_hog/backend/reviewer/persistence.py b/products/review_hog/backend/reviewer/persistence.py
index 41e8c0eaf5cc..ce0833c57d22 100644
--- a/products/review_hog/backend/reviewer/persistence.py
+++ b/products/review_hog/backend/reviewer/persistence.py
@@ -395,9 +395,9 @@ def persist_perspective_results(
report_id: str,
head_sha: str,
results: dict[tuple[int, int], IssuesReview],
- review_model: str,
+ review_arm: ReviewArm,
) -> None:
- """Append one `perspective_result` artefact per (pass, chunk) reviewed this turn, stamped with its model."""
+ """Append one `perspective_result` artefact per (pass, chunk), stamped with its reviewer configuration."""
if not results:
return
with transaction.atomic():
@@ -410,29 +410,29 @@ def persist_perspective_results(
pass_number=pass_number,
chunk_id=chunk_id,
review=review,
- review_model=review_model,
+ review_model=review_arm.model,
+ review_config=json.dumps(asdict(review_arm), sort_keys=True),
),
attribution=ArtefactAttribution.system(),
)
def load_perspective_results(
- *, team_id: int, report_id: str, head_sha: str, review_model: str
+ *, team_id: int, report_id: str, head_sha: str, review_arm: ReviewArm
) -> 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 (pass, chunk) reviews already computed with this arm (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.
+ The cache is per commit, so another model or effort's findings must not skip this reviewer's work.
"""
out: dict[tuple[int, int], IssuesReview] = {}
+ review_config = json.dumps(asdict(review_arm), sort_keys=True)
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:
+ if content.review_config != review_config:
continue
out[(content.pass_number, content.chunk_id)] = content.review
return out
diff --git a/products/review_hog/backend/reviewer/review_state.py b/products/review_hog/backend/reviewer/review_state.py
new file mode 100644
index 000000000000..2280af1919a9
--- /dev/null
+++ b/products/review_hog/backend/reviewer/review_state.py
@@ -0,0 +1,33 @@
+import json
+
+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.persistence import load_turn_findings
+
+
+def review_mode_for_run(report: ReviewReport, run_index: int) -> str:
+ for finding, _ in load_turn_findings(team_id=report.team_id, report_id=str(report.id), run_index=run_index):
+ if finding.validation_context:
+ try:
+ context = json.loads(finding.validation_context)
+ except (TypeError, ValueError):
+ continue
+ if isinstance(context, dict):
+ mode = context.get("review_mode")
+ if isinstance(mode, str) and mode in (REVIEW_MODE_FULL, REVIEW_MODE_FLASH):
+ return mode
+ return REVIEW_MODE_FULL
+
+
+def published_heads_by_mode(report: ReviewReport) -> dict[str, str]:
+ if report.published_heads_by_mode is not None:
+ return dict(report.published_heads_by_mode)
+ if not report.published_head_sha:
+ return {}
+ # Older reports stored the mode on findings, before publication had separate watermarks.
+ run_index = max((int(index) for index in (report.published_head_shas or {})), default=report.run_count)
+ return {review_mode_for_run(report, run_index): report.published_head_sha}
+
+
+def review_already_published(report: ReviewReport, head_sha: str, review_mode: str) -> bool:
+ return bool(head_sha) and published_heads_by_mode(report).get(review_mode) == head_sha
diff --git a/products/review_hog/backend/reviewer/telemetry.py b/products/review_hog/backend/reviewer/telemetry.py
index e297a92d3235..536e209cc2ae 100644
--- a/products/review_hog/backend/reviewer/telemetry.py
+++ b/products/review_hog/backend/reviewer/telemetry.py
@@ -17,6 +17,7 @@ from products.review_hog.backend.reviewer.constants import (
review_arm_for_mode,
validation_arm_for_mode,
)
+from products.tasks.backend.facade.run_config import ReasoningEffort
if TYPE_CHECKING:
from products.review_hog.backend.models import ReviewReport
@@ -37,7 +38,12 @@ def review_event_uuid(event_name: str, *, report_id: str, run_index: int, review
return str(uuid5(NAMESPACE_URL, identity))
-def review_routing_properties(report: ReviewReport, *, review_mode: str | None = None) -> dict[str, str | bool | None]:
+def review_routing_properties(
+ report: ReviewReport,
+ *,
+ review_mode: str | None = None,
+ flash_reasoning_effort: str = ReasoningEffort.MEDIUM.value,
+) -> 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
@@ -65,8 +71,8 @@ def review_routing_properties(report: ReviewReport, *, review_mode: str | None =
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)
+ arm = review_arm_for_mode(mode, stored_arm, flash_reasoning_effort=flash_reasoning_effort)
+ validator = validation_arm_for_mode(mode, flash_reasoning_effort=flash_reasoning_effort)
return {
"review_mode": review_mode,
"review_tier": report.review_tier,
diff --git a/products/review_hog/backend/reviewer/tests/test_constants.py b/products/review_hog/backend/reviewer/tests/test_constants.py
index 352308b2a1b2..c4b64e42d635 100644
--- a/products/review_hog/backend/reviewer/tests/test_constants.py
+++ b/products/review_hog/backend/reviewer/tests/test_constants.py
@@ -1,3 +1,5 @@
+from dataclasses import replace
+
import pytest
from posthog.temporal.oauth import has_write_scopes, resolve_scopes
@@ -35,7 +37,7 @@ from products.review_hog.backend.reviewer.constants import (
select_review_tier,
validation_arm_for_mode,
)
-from products.review_hog.backend.temporal.types import TRIGGER_INBOX
+from products.review_hog.backend.temporal.types import TRIGGER_AUTOMATIC, TRIGGER_INBOX
from products.signals.backend.enums import ReportPriority
from products.tasks.backend.facade.run_config import (
LLMProvider,
@@ -160,12 +162,12 @@ def test_only_tiers_cheaper_than_human_lift_on_a_human_trigger(tier: ReviewTier,
assert is_below_human_tier(tier) is expected
-def test_human_triggers_cover_every_trigger_but_the_inbox() -> None:
+def test_human_triggers_exclude_automatic_triggers() -> None:
# The set is spelled out in constants.py (persistence cannot import the temporal package). A
# trigger added to types.py but not here would leave a person's ask on a cheap tier, so the
# expected set is derived from the module rather than spelled out a second time.
every_trigger = {value for name, value in vars(trigger_types).items() if name.startswith("TRIGGER_")}
- assert HUMAN_TRIGGER_SOURCES == every_trigger - {TRIGGER_INBOX}
+ assert HUMAN_TRIGGER_SOURCES == every_trigger - {TRIGGER_INBOX, TRIGGER_AUTOMATIC}
# A registry-valid arm that differs from the default pins on every field, so honored-verbatim
@@ -213,18 +215,27 @@ def test_review_mcp_scopes_open_a_session_and_stay_read_only() -> None:
@pytest.mark.parametrize(
- "review_mode,expected_review,expected_validation",
+ "review_mode,effort,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"),
+ pytest.param(REVIEW_MODE_FLASH, "medium", FLASH_ARM, FLASH_ARM, id="flash-medium"),
+ pytest.param(
+ REVIEW_MODE_FLASH,
+ "xhigh",
+ replace(FLASH_ARM, reasoning_effort=ReasoningEffort.XHIGH),
+ replace(FLASH_ARM, reasoning_effort=ReasoningEffort.XHIGH),
+ id="flash-xhigh",
+ ),
+ pytest.param(
+ REVIEW_MODE_FULL, "xhigh", 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
+ review_mode: str, effort: 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
+ assert review_arm_for_mode(review_mode, persisted, flash_reasoning_effort=effort) == expected_review
+ assert validation_arm_for_mode(review_mode, flash_reasoning_effort=effort) == expected_validation
diff --git a/products/review_hog/backend/reviewer/tools/publish_review.py b/products/review_hog/backend/reviewer/tools/publish_review.py
index fe0f7afd2456..934fc0ac4f50 100644
--- a/products/review_hog/backend/reviewer/tools/publish_review.py
+++ b/products/review_hog/backend/reviewer/tools/publish_review.py
@@ -2,11 +2,14 @@ import logging
from dataclasses import dataclass
from typing import Any, Required, TypedDict
+from django.db import transaction
+
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 (
+ REVIEW_MODE_FLASH,
REVIEW_MODE_FULL,
effective_priority,
message_prefix_for_mode,
@@ -16,6 +19,7 @@ from products.review_hog.backend.reviewer.diff_position import build_diff_line_m
from products.review_hog.backend.reviewer.models.github_meta import PRFile
from products.review_hog.backend.reviewer.models.issues_review import IssuePriority
from products.review_hog.backend.reviewer.persistence import load_pr_snapshot, load_valid_findings
+from products.review_hog.backend.reviewer.review_state import published_heads_by_mode, review_already_published
from products.review_hog.backend.reviewer.tools.github_client import (
GitHubAPIError,
github_api_get_paginated,
@@ -88,7 +92,7 @@ def publish_persisted_review(
event loop.
"""
report = ReviewReport.objects.for_team(team_id).get(id=report_id)
- if report.published_head_sha == head_sha:
+ if review_already_published(report, head_sha, review_mode):
logger.info(f"Review for {owner}/{repo}#{pr_number} already published at {head_sha}; skipping")
_mark_report_idle(team_id, report_id)
return PublishOutcome(posted=False)
@@ -123,40 +127,50 @@ def publish_persisted_review(
report_id,
head_sha,
)
- report.published_head_sha = head_sha
- # Recorded per turn, never overwritten: this turn posted only its own findings, so an
- # earlier turn's threshold stays the truth about what that turn put on the PR.
- report.published_urgency_thresholds = {
- **(report.published_urgency_thresholds or {}),
- str(run_index): urgency_threshold.value,
- }
- # The base a later sweep compares this turn's findings against. Without it every finding is
- # compared from the newest publish, so a fix landing between two turns falls outside the diff.
- report.published_head_shas = {**(report.published_head_shas or {}), str(run_index): head_sha}
- # Idle lands in the same save as the watermark, so no reader can see the published head
- # with the report still counting as in-progress.
- report.status = ReviewReport.Status.IDLE
- report.save(
- update_fields=[
- "published_head_sha",
- "published_urgency_thresholds",
- "published_head_shas",
- "status",
- "updated_at",
- ]
- )
+ # Every map below merges into the row's CURRENT value, so it has to be re-read under a row
+ # lock: the snapshot above predates the GitHub post, and a publish that finished during it
+ # would be overwritten. The standalone publish command runs outside the per-PR queue, so a
+ # Flash and a Full publication really can land in this block at once, each dropping the
+ # other's mode watermark. Nothing slow runs inside the lock — the posting is already done.
+ with transaction.atomic():
+ locked = ReviewReport.objects.for_team(team_id).select_for_update().get(id=report_id)
+ locked.published_heads_by_mode = {**published_heads_by_mode(locked), review_mode: head_sha}
+ locked.published_head_sha = head_sha
+ # Recorded per turn, never overwritten: this turn posted only its own findings, so an
+ # earlier turn's threshold stays the truth about what that turn put on the PR.
+ locked.published_urgency_thresholds = {
+ **(locked.published_urgency_thresholds or {}),
+ str(run_index): urgency_threshold.value,
+ }
+ # The base a later sweep compares this turn's findings against. Without it every finding is
+ # compared from the newest publish, so a fix landing between two turns falls outside the diff.
+ locked.published_head_shas = {**(locked.published_head_shas or {}), str(run_index): head_sha}
+ # Idle lands in the same save as the watermark, so no reader can see the published head
+ # with the report still counting as in-progress.
+ locked.status = ReviewReport.Status.IDLE
+ locked.save(
+ update_fields=[
+ "published_head_sha",
+ "published_heads_by_mode",
+ "published_urgency_thresholds",
+ "published_head_shas",
+ "status",
+ "updated_at",
+ ]
+ )
else:
_mark_report_idle(team_id, report_id)
return outcome
-def _review_marker(report_id: str, head_sha: str) -> str:
+def _review_marker(report_id: str, head_sha: str, review_mode: str | None = None) -> str:
"""A hidden marker (HTML comment) embedded in the review body for publish idempotency.
Posting isn't atomic with saving the `published_head_sha` watermark; if we crash between them, the
marker lets the retry spot its own already-posted review and skip.
"""
- return f"<!-- reviewhog:published:{report_id}:{head_sha} -->"
+ suffix = f":{review_mode}" if review_mode is not None else ""
+ return f"<!-- reviewhog:published:{report_id}:{head_sha}{suffix} -->"
def _promo_marker(report_id: str) -> str:
@@ -197,7 +211,7 @@ def publish_review(
logger.info(f"Publishing review for {owner}/{repo}#{pr_number}")
report = ReviewReport.objects.for_team(team_id).get(id=report_id)
- marker = _review_marker(report_id, head_sha)
+ marker = _review_marker(report_id, head_sha, review_mode)
body = f"{report.report_markdown}\n\n{marker}"
valid_findings = load_valid_findings(team_id=team_id, report_id=report_id, run_index=run_index)
@@ -231,6 +245,8 @@ def publish_review(
promo_marker=_promo_marker(report_id),
installation_id=installation_id,
message_prefix=message_prefix_for_mode(review_mode),
+ legacy_marker=_review_marker(report_id, head_sha),
+ review_mode=review_mode,
)
return PublishOutcome(posted=True, review_url=review_url)
@@ -385,7 +401,15 @@ def _build_inline_comments(
def _review_already_posted(
- owner: str, repo: str, pr_number: int, marker: str, *, token: str, installation_id: str | None
+ owner: str,
+ repo: str,
+ pr_number: int,
+ marker: str,
+ *,
+ token: str,
+ installation_id: str | None,
+ legacy_marker: str | None = None,
+ review_mode: str = REVIEW_MODE_FULL,
) -> bool:
"""True if a review carrying this run's `marker` is already on the PR (we posted, then crashed).
@@ -397,7 +421,16 @@ def _review_already_posted(
"""
try:
return any(
- is_app_bot_author(review.get("user")) and marker in (review.get("body") or "")
+ is_app_bot_author(review.get("user"))
+ and (
+ marker in (review.get("body") or "")
+ or (
+ legacy_marker is not None
+ and legacy_marker in (review.get("body") or "")
+ and (review.get("body") or "").startswith(message_prefix_for_mode(REVIEW_MODE_FLASH))
+ == (review_mode == REVIEW_MODE_FLASH)
+ )
+ )
for review in github_api_get_paginated(
f"/repos/{owner}/{repo}/pulls/{pr_number}/reviews",
token=token,
@@ -449,6 +482,8 @@ def _post_github_review(
promo_marker: str,
installation_id: str | None = None,
message_prefix: str = "",
+ legacy_marker: str | None = None,
+ review_mode: str = REVIEW_MODE_FULL,
) -> str | None:
"""Post the review to GitHub as a PR review, pinned to the reviewed `head_sha`.
@@ -458,7 +493,16 @@ def _post_github_review(
"""
# Idempotency: if our own review for this (report, head) is already on the PR — we posted it but
# crashed before saving the watermark — don't double-post (the body carries the same marker).
- if _review_already_posted(owner, repo, pr_number, marker, token=token, installation_id=installation_id):
+ if _review_already_posted(
+ owner,
+ repo,
+ pr_number,
+ marker,
+ token=token,
+ installation_id=installation_id,
+ legacy_marker=legacy_marker,
+ review_mode=review_mode,
+ ):
logger.info(f"Review for {owner}/{repo}#{pr_number} at {head_sha[:12]} already on PR (marker found); skipping")
return None
diff --git a/products/review_hog/backend/settings_toggles.py b/products/review_hog/backend/settings_toggles.py
index e2058dd9e8f2..ec2fd996de19 100644
--- a/products/review_hog/backend/settings_toggles.py
+++ b/products/review_hog/backend/settings_toggles.py
@@ -1,12 +1,12 @@
"""Bulk on/off for the per-user boolean toggles on `ReviewUserSettings`.
-The inbox toggles (`review_inbox_prs`, `stamphog_review_inbox_prs`) default to off per user because
-they are the budget gate for 100%-coverage review cost, and `resolve_comments` defaults to on
+The inbox and authored PR toggles default to off per user because they are the budget gate for
+100%-coverage review cost, and `resolve_comments` defaults to on
because reviewing includes resolving. Flipping any of them for a whole team is a deliberate operator
action rather than a default change. The `enable_*` / `disable_*` management commands are thin
wrappers over `plan_toggle` + `apply_toggle`: one toggle, one direction, for every active member of
-the team's organization or for an explicit list of user ids. Other fields on existing rows are
-untouched, users can still change the toggle in the Code review settings afterwards, and members
+the team's organization or for an explicit list of user ids. Authored PR opt-in can also set the
+Flash effort; all other fields stay untouched. Users can change the settings afterwards, and members
who join later keep the default until a command is re-run.
"""
@@ -22,7 +22,7 @@ from posthog.models.team import Team
from products.review_hog.backend.models import ReviewUserSettings
-ToggleField = Literal["review_inbox_prs", "stamphog_review_inbox_prs", "resolve_comments"]
+ToggleField = Literal["review_inbox_prs", "stamphog_review_inbox_prs", "resolve_comments", "review_authored_prs"]
def toggle_default(field: ToggleField) -> bool:
@@ -46,11 +46,12 @@ class TogglePlan:
# Users with no row yet. Empty when the requested value is the field's default, because a
# missing row already reads as the default.
to_create: tuple[int, ...]
- to_flip: tuple[int, ...]
+ to_update: tuple[int, ...]
+ flash_reasoning_effort: ReviewUserSettings.FlashReasoningEffort | None = None
@property
def changed_user_ids(self) -> tuple[int, ...]:
- return self.to_create + self.to_flip
+ return self.to_create + self.to_update
@property
def already_set(self) -> int:
@@ -59,15 +60,21 @@ class TogglePlan:
@property
def summary(self) -> str:
verb = "enable" if self.enabled else "disable"
+ effort = f", flash_reasoning_effort: {self.flash_reasoning_effort.value}" if self.flash_reasoning_effort else ""
return (
- f"team {self.team_id}, {self.field}: {self.target_count} target user(s), "
- f"{len(self.to_create)} row(s) to create, {len(self.to_flip)} existing row(s) to {verb}, "
- f"{self.already_set} already {verb}d"
+ f"team {self.team_id}, {self.field} {verb}d{effort}: {self.target_count} target user(s), "
+ f"{len(self.to_create)} row(s) to create, {len(self.to_update)} existing row(s) to update, "
+ f"{self.already_set} already set"
)
def plan_toggle(
- *, team_id: int, field: ToggleField, enabled: bool, user_ids: Sequence[int] | None = None
+ *,
+ team_id: int,
+ field: ToggleField,
+ enabled: bool,
+ user_ids: Sequence[int] | None = None,
+ flash_reasoning_effort: ReviewUserSettings.FlashReasoningEffort | None = None,
) -> TogglePlan:
"""Work out which `ReviewUserSettings` rows a bulk toggle change touches, without writing.
@@ -75,6 +82,9 @@ def plan_toggle(
when an explicit id is not a member of the team's organization, so a typo fails loudly instead
of silently changing nothing.
"""
+ if flash_reasoning_effort is not None and (field != "review_authored_prs" or not enabled):
+ raise ValueError("Flash effort can only be set when enabling authored PR reviews")
+
# Environment ids resolve to the root team, mirroring the settings API: the rows must land
# on the same team the workflow's `ReviewUserSettings.load` reads them from.
team_id = resolve_effective_team_id(team_id)
@@ -93,8 +103,17 @@ def plan_toggle(
row.user_id: row
for row in ReviewUserSettings.objects.for_team(team_id, canonical=True).filter(user_id__in=target_ids)
}
- to_flip = tuple(
- user_id for user_id in target_ids if user_id in existing and getattr(existing[user_id], field) is not enabled
+ to_update = tuple(
+ user_id
+ for user_id in target_ids
+ if user_id in existing
+ and (
+ getattr(existing[user_id], field) is not enabled
+ or (
+ flash_reasoning_effort is not None
+ and existing[user_id].flash_reasoning_effort != flash_reasoning_effort
+ )
+ )
)
missing = tuple(user_id for user_id in target_ids if user_id not in existing)
to_create = missing if enabled is not toggle_default(field) else ()
@@ -104,23 +123,26 @@ def plan_toggle(
enabled=enabled,
target_count=len(target_ids),
to_create=to_create,
- to_flip=to_flip,
+ to_update=to_update,
+ flash_reasoning_effort=flash_reasoning_effort,
)
def apply_toggle(plan: TogglePlan) -> None:
rows = ReviewUserSettings.objects.for_team(plan.team_id, canonical=True)
+ updates: dict[str, bool | str] = {plan.field: plan.enabled}
+ if plan.flash_reasoning_effort is not None:
+ updates["flash_reasoning_effort"] = plan.flash_reasoning_effort.value
with transaction.atomic():
- to_flip = list(rows.filter(user_id__in=plan.to_flip))
+ to_update = list(rows.filter(user_id__in=plan.to_update))
for user_id in plan.to_create:
# get_or_create because a settings GET auto-creates rows with the model defaults: a
# user opening the Code review tab between the plan and this write must end at the
# requested value, not crash the run on the unique (team, user) constraint.
- row, created = rows.get_or_create(
- team_id=plan.team_id, user_id=user_id, defaults={plan.field: plan.enabled}
- )
+ row, created = rows.get_or_create(team_id=plan.team_id, user_id=user_id, defaults=updates)
if not created:
- to_flip.append(row)
- for row in to_flip:
- setattr(row, plan.field, plan.enabled)
- row.save(update_fields=[plan.field, "updated_at"])
+ to_update.append(row)
+ for row in to_update:
+ for field, value in updates.items():
+ setattr(row, field, value)
+ row.save(update_fields=[*updates, "updated_at"])
diff --git a/products/review_hog/backend/tasks.py b/products/review_hog/backend/tasks.py
new file mode 100644
index 000000000000..3a5846bc1c2f
--- /dev/null
+++ b/products/review_hog/backend/tasks.py
@@ -0,0 +1,22 @@
+from celery import shared_task
+
+from products.review_hog.backend.automatic_reviews import AuthoredPRReview
+
+
+@shared_task(
+ ignore_result=True,
+ acks_late=True,
+ reject_on_worker_lost=True,
+ autoretry_for=(Exception,),
+ max_retries=5,
+ retry_backoff=True,
+ retry_backoff_max=300,
+ retry_jitter=True,
+)
+def process_authored_pr_event(*, installation_id: str, author_login: str, pr_number: int, head_sha: str) -> None:
+ AuthoredPRReview(
+ installation_id=installation_id,
+ author_login=author_login,
+ pr_number=pr_number,
+ head_sha=head_sha,
+ ).start()
diff --git a/products/review_hog/backend/temporal/__init__.py b/products/review_hog/backend/temporal/__init__.py
index 478d2d681077..4dcc0729a26c 100644
--- a/products/review_hog/backend/temporal/__init__.py
+++ b/products/review_hog/backend/temporal/__init__.py
@@ -33,6 +33,7 @@ from products.review_hog.backend.temporal.resolution import (
fail_resolution_activity,
resolve_threads_activity,
)
+from products.review_hog.backend.temporal.scheduling import ReviewPRQueueWorkflow, review_resolution_running_activity
from products.review_hog.backend.temporal.workflow import (
ReviewPerspectivesWorkflow,
ReviewPRWorkflow,
@@ -40,6 +41,7 @@ from products.review_hog.backend.temporal.workflow import (
)
WORKFLOWS = [
+ ReviewPRQueueWorkflow,
ReviewPRWorkflow,
ReviewPerspectivesWorkflow,
ValidateIssuesWorkflow,
@@ -48,6 +50,7 @@ WORKFLOWS = [
]
ACTIVITIES = [
+ review_resolution_running_activity,
validate_github_integration_activity,
fetch_pr_data_activity,
resolve_acting_user_activity,
diff --git a/products/review_hog/backend/temporal/activities.py b/products/review_hog/backend/temporal/activities.py
index 1d285e470280..2f1b2deeadd8 100644
--- a/products/review_hog/backend/temporal/activities.py
+++ b/products/review_hog/backend/temporal/activities.py
@@ -33,6 +33,7 @@ from posthog.temporal.common.heartbeat import Heartbeater
from posthog.temporal.common.scoped import scoped_temporal
from posthog.temporal.common.utils import close_db_connections
+from products.review_hog.backend.automatic_reviews import authored_reviews_enabled
from products.review_hog.backend.models import ReviewReport, ReviewUserSettings
from products.review_hog.backend.reviewer.constants import (
CHUNKING_MODEL,
@@ -43,6 +44,7 @@ from products.review_hog.backend.reviewer.constants import (
REVIEW_MODE_FLASH,
REVIEW_MODE_FULL,
VALIDATION_MAX_ATTEMPTS,
+ ReviewArm,
effective_priority,
published_priorities_for,
review_arm_for_mode,
@@ -83,6 +85,7 @@ from products.review_hog.backend.reviewer.persistence import (
replace_deduplicated_findings,
upsert_review_report,
)
+from products.review_hog.backend.reviewer.review_state import review_already_published
from products.review_hog.backend.reviewer.sandbox.direct_llm import run_oneshot_review
from products.review_hog.backend.reviewer.sandbox.executor import (
MultiTurnSession,
@@ -135,12 +138,13 @@ from products.review_hog.backend.reviewer.tools.split_pr_into_chunks import (
plan_deterministic_chunks,
reconcile_chunks,
)
-from products.review_hog.backend.temporal.types import TRIGGER_LABEL, TRIGGER_MANUAL
+from products.review_hog.backend.temporal.types import TRIGGER_AUTOMATIC, TRIGGER_LABEL, TRIGGER_MANUAL
from products.signals.backend.artefact_attribution import ArtefactAttribution
from products.signals.backend.artefact_schemas import CodeReview, CodeReviewCounts
from products.signals.backend.enums import ReportPriority
from products.signals.backend.models import SignalReport, SignalReportArtefact
from products.signals.backend.report_generation.resolve_reviewers import resolve_org_github_login_to_users
+from products.tasks.backend.facade.run_config import ReasoningEffort
if TYPE_CHECKING:
from products.review_hog.backend.reviewer.artefact_content import PRSnapshotArtefact
@@ -177,7 +181,7 @@ class FetchPRDataInput:
review_mode: str = REVIEW_MODE_FULL
-@dataclass
+@dataclass(frozen=False)
class ReviewMeta:
"""Small fetch result the parent threads through the rest of the run (no big payloads)."""
@@ -205,6 +209,8 @@ class ReviewMeta:
# A branch target whose compare diff has no reviewable files ("pushed nothing"): the parent
# self-skips the turn before any sandbox spend.
empty_diff: bool = False
+ already_completed: bool = False
+ pr_open: bool = True
@dataclass
@@ -224,7 +230,7 @@ class ResolveActingUserInput:
default_user_id: int | None = None
-@dataclass
+@dataclass(frozen=False)
class ResolveActingUserResult:
# The user whose enabled perspectives drive this review; None when nothing in the resolution
# chain maps to a PostHog org user — the parent then skips the review.
@@ -242,6 +248,8 @@ class ResolveActingUserResult:
# — the SKIP value — so pre-field histories replay deterministically (the chained dispatch is a
# new workflow command; old runs must never reach it on replay). The model default is True.
resolve_comments: bool = False
+ review_authored_prs: bool = False
+ flash_reasoning_effort: str = ReasoningEffort.MEDIUM.value
@dataclass
@@ -287,6 +295,7 @@ class SandboxStageInput:
# 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)
+ flash_reasoning_effort: str = field(default=ReasoningEffort.MEDIUM.value, kw_only=True)
@dataclass
@@ -383,6 +392,7 @@ class PublishInput:
# Same snapshot as `BuildBodyInput.urgency_threshold`, so body counts and comments agree.
urgency_threshold: str = IssuePriority.CONSIDER.value
review_mode: str = REVIEW_MODE_FULL
+ trigger_source: str = TRIGGER_MANUAL
@dataclass
@@ -431,6 +441,7 @@ class TrackReviewCompletedInput:
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
+ flash_reasoning_effort: str = ReasoningEffort.MEDIUM.value
@frozen
@@ -443,6 +454,7 @@ class TrackReviewStartedInput:
run_index: int
turn_trigger_source: str | None
review_mode: str = REVIEW_MODE_FULL
+ flash_reasoning_effort: str = ReasoningEffort.MEDIUM.value
@frozen
@@ -454,6 +466,7 @@ class TrackReviewFailedInput:
run_index: int
turn_trigger_source: str | None = None
review_mode: str = REVIEW_MODE_FULL
+ flash_reasoning_effort: str = ReasoningEffort.MEDIUM.value
@dataclass(frozen=False)
@@ -594,7 +607,8 @@ def _fetch_and_persist(input: FetchPRDataInput) -> ReviewMeta:
# whether this turn has anything to do. `published_head_sha == head_sha` means we already reviewed
# and posted this exact head; new comments are surfaced for visibility but don't gate yet.
report = ReviewReport.objects.for_team(input.team_id).get(id=report_id)
- already_published = bool(head_sha) and report.published_head_sha == head_sha
+ already_published = review_already_published(report, head_sha, input.review_mode)
+ already_completed = bool(head_sha) and report.automatic_reviewed_head_sha == head_sha
# This turn's index. run_count (completed turns) only bumps at finalize, so a turn that fails and
# resumes reuses the same index while a fresh turn gets a new one.
run_index = report.run_count + 1
@@ -628,6 +642,12 @@ def _fetch_and_persist(input: FetchPRDataInput) -> ReviewMeta:
pr_comments=pr_comments,
pr_files=pr_files,
)
+ if already_published or (
+ input.trigger_source == TRIGGER_AUTOMATIC and (already_completed or pr_metadata.state != "open")
+ ):
+ ReviewReport.objects.for_team(input.team_id).filter(id=report_id).update(
+ status=ReviewReport.Status.IDLE if pr_metadata.state == "open" else ReviewReport.Status.CLOSED
+ )
return ReviewMeta(
report_id=report_id,
head_sha=head_sha,
@@ -644,6 +664,8 @@ def _fetch_and_persist(input: FetchPRDataInput) -> ReviewMeta:
pr_number=pr_number,
pr_url=pr_url,
empty_diff=pr_number is None and not pr_files,
+ already_completed=already_completed,
+ pr_open=pr_metadata.state == "open",
)
@@ -677,6 +699,14 @@ def _resolve_acting_user(input: ResolveActingUserInput) -> ResolveActingUserResu
# the trigger already resolved. Other triggers keep the author-only contract and skip.
if acting_user_id is None and input.trigger_source == TRIGGER_LABEL:
acting_user_id, resolved_from = input.default_user_id, "default"
+ if input.trigger_source == TRIGGER_AUTOMATIC and (
+ acting_user_id is None or not authored_reviews_enabled(team_id=input.team_id, user_id=acting_user_id)
+ ):
+ if input.report_id is not None:
+ ReviewReport.objects.for_team(input.team_id).filter(id=input.report_id).update(
+ status=ReviewReport.Status.IDLE
+ )
+ return ResolveActingUserResult(acting_user_id=None)
if acting_user_id is None:
return ResolveActingUserResult(acting_user_id=None)
if resolved_from == "default":
@@ -705,6 +735,12 @@ def _resolve_acting_user(input: ResolveActingUserInput) -> ResolveActingUserResu
# Same author-protection shape as `review_labeled_prs`: the borrowed default user's personal
# switch never governs someone else's PR — an unmapped author gets the default posture (on).
resolve_comments=settings.resolve_comments if resolved_from in ("author", "override") else True,
+ review_authored_prs=settings.review_authored_prs if resolved_from in ("author", "override") else False,
+ flash_reasoning_effort=(
+ str(settings.flash_reasoning_effort)
+ if resolved_from in ("author", "override")
+ else ReasoningEffort.MEDIUM.value
+ ),
)
@@ -935,10 +971,10 @@ def _prepare_review_prompt(
run_index: int,
blind_spot_check: bool,
wave_perspectives: list[LoadedPerspectiveDTO],
- review_model: str,
+ review_arm: ReviewArm,
) -> 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, review_model=review_model)
+ done = load_perspective_results(team_id=team_id, report_id=report_id, head_sha=head_sha, review_arm=review_arm)
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)
@@ -983,7 +1019,7 @@ async def review_chunk_activity(input: ReviewChunkInput) -> bool:
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)
+ arm = review_arm_for_mode(input.review_mode, persisted_arm, flash_reasoning_effort=input.flash_reasoning_effort)
prompt = await database_sync_to_async(_prepare_review_prompt, thread_sensitive=False)(
input.team_id,
input.report_id,
@@ -995,7 +1031,7 @@ async def review_chunk_activity(input: ReviewChunkInput) -> bool:
input.run_index,
input.blind_spot_check,
input.wave_perspectives,
- arm.model,
+ arm,
)
if prompt is None:
return True
@@ -1029,7 +1065,7 @@ 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,
+ review_arm=arm,
)
await _refresh_status_comment(input.team_id, input.report_id, input.review_mode)
return True
@@ -1038,9 +1074,9 @@ async def review_chunk_activity(input: ReviewChunkInput) -> bool:
# --- Combine + scope-clean + dedup -----------------------------------------------------------------
-def _combine_and_clean(team_id: int, report_id: str, head_sha: str, review_model: str) -> list[Issue]:
+def _combine_and_clean(team_id: int, report_id: str, head_sha: str, review_arm: ReviewArm) -> list[Issue]:
perspective_results = load_perspective_results(
- team_id=team_id, report_id=report_id, head_sha=head_sha, review_model=review_model
+ team_id=team_id, report_id=report_id, head_sha=head_sha, review_arm=review_arm
)
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 []
@@ -1063,9 +1099,11 @@ async def dedup_activity(input: SandboxStageInput) -> DedupResult:
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)
+ review_arm = review_arm_for_mode(
+ input.review_mode, persisted_arm, flash_reasoning_effort=input.flash_reasoning_effort
+ )
issues = await database_sync_to_async(_combine_and_clean, thread_sensitive=False)(
- input.team_id, input.report_id, input.head_sha, review_arm.model
+ input.team_id, input.report_id, input.head_sha, review_arm
)
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
@@ -1098,7 +1136,7 @@ async def dedup_activity(input: SandboxStageInput) -> DedupResult:
head_sha=input.head_sha,
review_mode=input.review_mode,
review_arm=review_arm,
- validation_arm=validation_arm_for_mode(input.review_mode),
+ validation_arm=validation_arm_for_mode(input.review_mode, flash_reasoning_effort=input.flash_reasoning_effort),
)
await _refresh_status_comment(input.team_id, input.report_id, input.review_mode)
return DedupResult(issue_ids=issue_ids)
@@ -1168,7 +1206,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)
+ validator = validation_arm_for_mode(input.review_mode, flash_reasoning_effort=input.flash_reasoning_effort)
session: MultiTurnSession | None = None
chunk_ok = False
try:
@@ -1304,6 +1342,10 @@ def _publish(input: PublishInput) -> PublishResult:
installation_id=installation_id,
review_mode=input.review_mode,
)
+ if input.trigger_source == TRIGGER_AUTOMATIC:
+ ReviewReport.objects.for_team(input.team_id).filter(id=input.report_id).update(
+ automatic_reviewed_head_sha=input.head_sha
+ )
return PublishResult(posted=outcome.posted, review_url=outcome.review_url)
@@ -1398,7 +1440,9 @@ def _track_review_started(input: TrackReviewStartedInput) -> None:
),
properties={
**_turn_event_properties(report, run_index=input.run_index, turn_trigger_source=input.turn_trigger_source),
- **review_routing_properties(report, review_mode=input.review_mode),
+ **review_routing_properties(
+ report, review_mode=input.review_mode, flash_reasoning_effort=input.flash_reasoning_effort
+ ),
**_pr_size_properties(snapshot),
},
groups=groups(team=report.team),
@@ -1463,7 +1507,9 @@ 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_mode=input.review_mode),
+ **review_routing_properties(
+ report, review_mode=input.review_mode, flash_reasoning_effort=input.flash_reasoning_effort
+ ),
**_pr_size_properties(snapshot),
"duration_seconds": duration_seconds,
},
@@ -1508,7 +1554,9 @@ def _track_review_failed(input: TrackReviewFailedInput) -> None:
),
properties={
**_turn_event_properties(report, run_index=input.run_index, turn_trigger_source=input.turn_trigger_source),
- **review_routing_properties(report, review_mode=input.review_mode),
+ **review_routing_properties(
+ report, review_mode=input.review_mode, flash_reasoning_effort=input.flash_reasoning_effort
+ ),
},
groups=groups(team=report.team),
send_feature_flags=True,
diff --git a/products/review_hog/backend/temporal/client.py b/products/review_hog/backend/temporal/client.py
index 31701bcbbb25..95af5574aa7c 100644
--- a/products/review_hog/backend/temporal/client.py
+++ b/products/review_hog/backend/temporal/client.py
@@ -5,12 +5,12 @@ Four entry points across two workflows. Each workflow pairs a **blocking** CLI t
`start_workflow`); the blocking form returns the `ReviewReport` id, the non-blocking form returns
the workflow id and fires and forget (the run happens in the worker).
-`ReviewPRWorkflow` — the single-turn review:
+`ReviewPRQueueWorkflow` serializes requests and runs each turn in `ReviewPRWorkflow`:
- `execute_review_pr_workflow` — used by the `run_review` management command so the CLI eval loop
stays intact: run, see the outcome, read the report (stage progress streams in the worker log via
`workflow.logger`).
-- `start_review_pr_workflow` — used by the production triggers (the label endpoint and the inbox
- TaskRun-completion receiver); the report id is created when the run's fetch activity executes.
+- `start_review_pr_workflow` — used by production triggers; signals preserve new heads and Full
+ requests that arrive during an active review. Fetch creates the report id when a turn starts.
`ResolvePRWorkflow` — triaging and settling a PR's unresolved review threads:
- `execute_resolution_workflow` — the CLI entry (`run_resolution`), mirroring
@@ -44,6 +44,7 @@ from products.review_hog.backend.reviewer.tools.github_meta import PRParser
from products.review_hog.backend.temporal.types import (
TRIGGER_MANUAL,
ResolvePRWorkflowInputs,
+ ReviewPRQueueInputs,
ReviewPRWorkflowInputs,
resolve_pr_workflow_id,
review_branch_workflow_id,
@@ -53,9 +54,8 @@ from products.signals.backend.enums import ReportPriority
logger = logging.getLogger(__name__)
-# Retry the whole review once on a hard failure; the re-run resumes (reuses persisted
-# chunk/perspective/verdict rows for the same head) rather than redoing the work.
-_PARENT_RETRY = RetryPolicy(maximum_attempts=2)
+# Resolution retries resume from the persisted thread watermarks.
+_RESOLUTION_RETRY = RetryPolicy(maximum_attempts=2)
def workflow_running(workflow_id: str) -> bool:
@@ -95,6 +95,7 @@ def _build_inputs(
resolve_comments: bool | None = None,
signal_priority: ReportPriority | None = None,
review_mode: str = REVIEW_MODE_FULL,
+ requested_head_sha: str | None = None,
) -> tuple[ReviewPRWorkflowInputs, str]:
"""Validate the review target, the team, and build the workflow inputs + deterministic id.
@@ -132,6 +133,7 @@ def _build_inputs(
head_branch=head_branch,
resolve_comments=resolve_comments,
review_mode=review_mode,
+ requested_head_sha=requested_head_sha,
)
return inputs, workflow_id
@@ -150,7 +152,7 @@ def execute_review_pr_workflow(
resolve_comments: bool | None = None,
review_mode: str = REVIEW_MODE_FULL,
) -> str:
- """Start `ReviewPRWorkflow`, block until it completes, and return the `ReviewReport` id.
+ """Start or signal the review queue, wait for it to finish, and return the `ReviewReport` id.
`team_id` / `user_id` are explicit identity (the team the review persists under; the user the
sandbox tasks run as). `publish` defaults off so a CLI run never posts unless asked.
@@ -177,15 +179,16 @@ def execute_review_pr_workflow(
logger.info(f"Running ReviewPRWorkflow {workflow_id} on {settings.VIDEO_EXPORT_TASK_QUEUE} (publish={publish})")
return asyncio.run(
client.execute_workflow(
- "review-pr",
- inputs,
+ "review-pr-queue",
+ ReviewPRQueueInputs(requests=[inputs]),
id=workflow_id,
task_queue=settings.VIDEO_EXPORT_TASK_QUEUE,
# A new turn may start once the prior one finishes (the living-report re-review);
# re-triggering while a run is in flight joins that run rather than erroring.
id_reuse_policy=WorkflowIDReusePolicy.ALLOW_DUPLICATE,
id_conflict_policy=WorkflowIDConflictPolicy.USE_EXISTING,
- retry_policy=_PARENT_RETRY,
+ start_signal="request_review",
+ start_signal_args=[inputs],
)
)
@@ -204,8 +207,9 @@ def start_review_pr_workflow(
head_branch: str | None = None,
resolve_comments: bool | None = None,
review_mode: str = REVIEW_MODE_FULL,
+ requested_head_sha: str | None = None,
) -> str:
- """Start `ReviewPRWorkflow` without blocking and return the workflow id.
+ """Start or signal the review queue without blocking and return the workflow id.
For the production triggers: the caller returns immediately while the review runs in the worker.
`publish` is required (the caller decides explicitly). Safe to call from a synchronous DRF action
@@ -213,9 +217,8 @@ def start_review_pr_workflow(
likewise. `acting_user_id` defaults None so the workflow resolves the PR author itself (the label
trigger has not fetched the PR, so it cannot know the author); the inbox trigger sets it.
- Re-triggering the same target while a review is in flight (e.g. a push fires `synchronize`) joins
- the running workflow via `USE_EXISTING` rather than raising `WorkflowAlreadyStartedError` — so
- the trigger never errors on a normal push. (Re-reviewing a mid-flight new head is the loop's job.)
+ A signal records requests that arrive during a review. Automatic pushes coalesce to the latest
+ head; explicit Full requests wait for an active Flash review without being discarded.
"""
inputs, workflow_id = _build_inputs(
team_id=team_id,
@@ -230,6 +233,7 @@ def start_review_pr_workflow(
head_branch=head_branch,
resolve_comments=resolve_comments,
review_mode=review_mode,
+ requested_head_sha=requested_head_sha,
)
client = sync_connect()
@@ -240,13 +244,14 @@ def start_review_pr_workflow(
# 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(
- "review-pr",
- inputs,
+ "review-pr-queue",
+ ReviewPRQueueInputs(requests=[inputs]),
id=workflow_id,
task_queue=settings.VIDEO_EXPORT_TASK_QUEUE,
id_reuse_policy=WorkflowIDReusePolicy.ALLOW_DUPLICATE,
id_conflict_policy=WorkflowIDConflictPolicy.USE_EXISTING,
- retry_policy=_PARENT_RETRY,
+ start_signal="request_review",
+ start_signal_args=[inputs],
)
return workflow_id
@@ -306,7 +311,7 @@ def execute_resolution_workflow(
# new run may start once the prior finished (per-thread watermarks make it incremental).
id_reuse_policy=WorkflowIDReusePolicy.ALLOW_DUPLICATE,
id_conflict_policy=WorkflowIDConflictPolicy.USE_EXISTING,
- retry_policy=_PARENT_RETRY,
+ retry_policy=_RESOLUTION_RETRY,
)
)
@@ -333,6 +338,6 @@ def start_resolution_workflow(
task_queue=settings.VIDEO_EXPORT_TASK_QUEUE,
id_reuse_policy=WorkflowIDReusePolicy.ALLOW_DUPLICATE,
id_conflict_policy=WorkflowIDConflictPolicy.USE_EXISTING,
- retry_policy=_PARENT_RETRY,
+ retry_policy=_RESOLUTION_RETRY,
)
return workflow_id
diff --git a/products/review_hog/backend/temporal/scheduling.py b/products/review_hog/backend/temporal/scheduling.py
new file mode 100644
index 000000000000..095e85376c70
--- /dev/null
+++ b/products/review_hog/backend/temporal/scheduling.py
@@ -0,0 +1,116 @@
+import json
+from datetime import timedelta
+
+from temporalio import activity, workflow
+from temporalio.client import WorkflowExecutionStatus
+from temporalio.common import RetryPolicy, WorkflowIDReusePolicy
+from temporalio.exceptions import ChildWorkflowError
+from temporalio.service import RPCError, RPCStatusCode
+
+from posthog.temporal.common.client import async_connect
+
+from products.review_hog.backend.reviewer.constants import REVIEW_MODE_FLASH, REVIEW_MODE_FULL
+from products.review_hog.backend.temporal.types import (
+ TRIGGER_AUTOMATIC,
+ ReviewPRQueueInputs,
+ ReviewPRWorkflowInputs,
+ resolve_pr_workflow_id,
+)
+
+
+class ReviewRequestQueue:
+ def __init__(self, active: ReviewPRWorkflowInputs | None = None) -> None:
+ self.active = active
+ self.pending: dict[str, ReviewPRWorkflowInputs] = {}
+
+ def add(self, request: ReviewPRWorkflowInputs) -> None:
+ if self.active is not None:
+ if (
+ request.team_id != self.active.team_id
+ or request.repository.lower() != self.active.repository.lower()
+ or request.pr_number != self.active.pr_number
+ or request.head_branch != self.active.head_branch
+ ):
+ return
+ if (
+ request.review_mode == self.active.review_mode
+ and request.requested_head_sha == self.active.requested_head_sha
+ and request.publish == self.active.publish
+ and request.acting_user_id == self.active.acting_user_id
+ and request.resolve_comments == self.active.resolve_comments
+ and (request.trigger_source == TRIGGER_AUTOMATIC) == (self.active.trigger_source == TRIGGER_AUTOMATIC)
+ ):
+ return
+ key = TRIGGER_AUTOMATIC if request.trigger_source == TRIGGER_AUTOMATIC else request.review_mode
+ self.pending[key] = request
+
+ def take(self) -> ReviewPRWorkflowInputs:
+ # Explicit requests take precedence over another automatic follow-up.
+ key = next(key for key in (REVIEW_MODE_FULL, REVIEW_MODE_FLASH, TRIGGER_AUTOMATIC) if key in self.pending)
+ self.active = self.pending.pop(key)
+ return self.active
+
+
+async def review_resolution_running_activity(input: ReviewPRWorkflowInputs) -> bool:
+ if input.pr_number is None:
+ return False
+ client = await async_connect()
+ workflow_id = resolve_pr_workflow_id(
+ team_id=input.team_id, owner=input.owner, repo=input.repo, pr_number=input.pr_number
+ )
+ try:
+ description = await client.get_workflow_handle(workflow_id).describe()
+ except RPCError as error:
+ if error.status == RPCStatusCode.NOT_FOUND:
+ return False
+ raise
+ return description.status == WorkflowExecutionStatus.RUNNING
+
+
[email protected](name="review-pr-queue")
+class ReviewPRQueueWorkflow:
+ @workflow.init
+ def __init__(self, inputs: ReviewPRQueueInputs) -> None:
+ self._requests = ReviewRequestQueue()
+ for request in inputs.requests:
+ self._requests.add(request)
+
+ @staticmethod
+ def parse_inputs(inputs: list[str]) -> ReviewPRQueueInputs:
+ data = json.loads(inputs[0])
+ return ReviewPRQueueInputs(requests=[ReviewPRWorkflowInputs(**request) for request in data["requests"]])
+
+ @workflow.signal
+ def request_review(self, request: ReviewPRWorkflowInputs) -> None:
+ self._requests.add(request)
+
+ @workflow.run
+ async def run(self, inputs: ReviewPRQueueInputs) -> str:
+ result = ""
+ while self._requests.pending:
+ request = self._requests.take()
+ while await workflow.execute_activity(
+ review_resolution_running_activity,
+ request,
+ start_to_close_timeout=timedelta(seconds=30),
+ retry_policy=RetryPolicy(maximum_interval=timedelta(minutes=1)),
+ ):
+ await workflow.sleep(timedelta(seconds=15))
+ try:
+ result = await workflow.execute_child_workflow(
+ "review-pr",
+ request,
+ id=f"{workflow.info().workflow_id}/turn",
+ result_type=str,
+ id_reuse_policy=WorkflowIDReusePolicy.ALLOW_DUPLICATE,
+ retry_policy=RetryPolicy(maximum_attempts=2),
+ )
+ except ChildWorkflowError:
+ if not self._requests.pending:
+ raise
+ workflow.logger.exception("Review failed; processing the next requested review")
+ self._requests.active = None
+ if self._requests.pending and workflow.info().is_continue_as_new_suggested():
+ workflow.continue_as_new(ReviewPRQueueInputs(requests=list(self._requests.pending.values())))
+ return result
diff --git a/products/review_hog/backend/temporal/types.py b/products/review_hog/backend/temporal/types.py
index eb3271577f61..1d1aadbc03fe 100644
--- a/products/review_hog/backend/temporal/types.py
+++ b/products/review_hog/backend/temporal/types.py
@@ -16,6 +16,7 @@ TRIGGER_LABEL = "label"
TRIGGER_INBOX = "inbox"
TRIGGER_MANUAL = "manual"
TRIGGER_UI = "ui"
+TRIGGER_AUTOMATIC = "automatic"
@frozen
@@ -72,6 +73,7 @@ class ReviewPRWorkflowInputs:
# 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
+ requested_head_sha: str | None = None
@property
def repository(self) -> str:
@@ -89,6 +91,11 @@ class ReviewPRWorkflowInputs:
}
+@frozen
+class ReviewPRQueueInputs:
+ requests: list[ReviewPRWorkflowInputs]
+
+
@frozen
class ResolvePRWorkflowInputs:
"""Input for one `ResolvePRWorkflow` run (the resolution stage on one PR).
diff --git a/products/review_hog/backend/temporal/workflow.py b/products/review_hog/backend/temporal/workflow.py
index c711a35e150f..3e3076182a52 100644
--- a/products/review_hog/backend/temporal/workflow.py
+++ b/products/review_hog/backend/temporal/workflow.py
@@ -86,10 +86,13 @@ from products.review_hog.backend.temporal.activities import (
validate_chunk_activity,
validate_github_integration_activity,
)
+from products.review_hog.backend.temporal.scheduling import ReviewPRQueueWorkflow, ReviewRequestQueue
from products.review_hog.backend.temporal.types import (
+ TRIGGER_AUTOMATIC,
TRIGGER_INBOX,
TRIGGER_LABEL,
ResolvePRWorkflowInputs,
+ ReviewPRQueueInputs,
ReviewPRWorkflowInputs,
resolve_pr_workflow_id,
)
@@ -190,6 +193,7 @@ class ReviewPerspectivesWorkflow:
branch=inputs.branch,
run_index=inputs.run_index,
review_mode=inputs.review_mode,
+ flash_reasoning_effort=inputs.flash_reasoning_effort,
perspectives=ordered,
),
start_to_close_timeout=_SANDBOX_TIMEOUT,
@@ -220,6 +224,7 @@ class ReviewPerspectivesWorkflow:
branch=inputs.branch,
run_index=inputs.run_index,
review_mode=inputs.review_mode,
+ flash_reasoning_effort=inputs.flash_reasoning_effort,
chunk_id=chunk_id,
pass_number=pass_number,
skill_name=skill_name,
@@ -336,6 +341,7 @@ class ValidateIssuesWorkflow:
branch=inputs.branch,
run_index=inputs.run_index,
review_mode=inputs.review_mode,
+ flash_reasoning_effort=inputs.flash_reasoning_effort,
chunk_id=chunk_id,
issue_ids=chunk_issue_ids,
skill_name=skill.skill_name,
@@ -360,6 +366,14 @@ class ValidateIssuesWorkflow:
class ReviewPRWorkflow:
"""Single-turn PR review: setup → split → review → dedup (incl. combine) → validate → build → publish."""
+ @workflow.init
+ def __init__(self, inputs: ReviewPRWorkflowInputs) -> None:
+ self._requests = ReviewRequestQueue(active=inputs)
+
+ @workflow.signal
+ def request_review(self, request: ReviewPRWorkflowInputs) -> None:
+ self._requests.add(request)
+
@staticmethod
def parse_inputs(inputs: list[str]) -> ReviewPRWorkflowInputs:
return ReviewPRWorkflowInputs(**json.loads(inputs[0]))
@@ -397,6 +411,11 @@ class ReviewPRWorkflow:
)
except Exception:
workflow.logger.warning("Could not remove the ReviewHog trigger label")
+ if self._requests.pending:
+ requests = list(self._requests.pending.values())
+ if not completed and not terminal:
+ requests.insert(0, inputs)
+ workflow.continue_as_new(ReviewPRQueueInputs(requests=requests), workflow=ReviewPRQueueWorkflow.run)
async def _run(self, inputs: ReviewPRWorkflowInputs) -> str:
repository = inputs.repository
@@ -454,6 +473,9 @@ class ReviewPRWorkflow:
f"Branch '{branch}' has no reviewable diff against its base (pushed nothing); skipping"
)
return report_id
+ if inputs.trigger_source == TRIGGER_AUTOMATIC and (meta.already_completed or not meta.pr_open):
+ workflow.logger.info("Automatic review skipped: the PR is closed or this head is already complete")
+ return report_id
# Resolve the acting user whose enabled perspectives apply: the PR author, or the explicit
# override the CLI and inbox triggers set. The label trigger falls back to the default run
@@ -491,6 +513,9 @@ class ReviewPRWorkflow:
if inputs.trigger_source == TRIGGER_INBOX and not acting.review_inbox_prs:
workflow.logger.info(f"Acting user {acting.acting_user_id} has inbox reviews turned off; skipping review")
return report_id
+ if inputs.trigger_source == TRIGGER_AUTOMATIC and not acting.review_authored_prs:
+ workflow.logger.info("Automatic reviews are disabled for the author; skipping review")
+ return report_id
acting_user_id = acting.acting_user_id
# The turn passed every gate and is about to spend sandboxes: one started event per turn,
@@ -506,6 +531,7 @@ class ReviewPRWorkflow:
run_index=meta.run_index,
turn_trigger_source=inputs.trigger_source,
review_mode=inputs.review_mode,
+ flash_reasoning_effort=acting.flash_reasoning_effort,
),
start_to_close_timeout=_QUICK_TIMEOUT,
retry_policy=_RETRY,
@@ -556,6 +582,7 @@ class ReviewPRWorkflow:
branch=branch,
run_index=meta.run_index,
review_mode=inputs.review_mode,
+ flash_reasoning_effort=acting.flash_reasoning_effort,
)
workflow.logger.info("STAGE 2/7 · Split into chunks")
@@ -581,6 +608,7 @@ class ReviewPRWorkflow:
branch=stage.branch,
run_index=stage.run_index,
review_mode=stage.review_mode,
+ flash_reasoning_effort=stage.flash_reasoning_effort,
chunk_ids=chunk_ids,
acting_user_id=acting_user_id,
),
@@ -612,6 +640,7 @@ class ReviewPRWorkflow:
branch=stage.branch,
run_index=stage.run_index,
review_mode=stage.review_mode,
+ flash_reasoning_effort=stage.flash_reasoning_effort,
issue_ids=dedup.issue_ids,
acting_user_id=acting_user_id,
),
@@ -653,6 +682,7 @@ class ReviewPRWorkflow:
pr_number=meta.pr_number,
urgency_threshold=acting.urgency_threshold,
review_mode=inputs.review_mode,
+ trigger_source=inputs.trigger_source,
),
start_to_close_timeout=_QUICK_TIMEOUT,
retry_policy=_RETRY,
@@ -693,6 +723,7 @@ class ReviewPRWorkflow:
run_index=meta.run_index,
turn_trigger_source=inputs.trigger_source,
review_mode=inputs.review_mode,
+ flash_reasoning_effort=acting.flash_reasoning_effort,
),
start_to_close_timeout=_QUICK_TIMEOUT,
retry_policy=_RETRY,
@@ -716,6 +747,7 @@ class ReviewPRWorkflow:
workflow_started_at=workflow.info().start_time.isoformat(),
turn_trigger_source=inputs.trigger_source,
review_mode=inputs.review_mode,
+ flash_reasoning_effort=acting.flash_reasoning_effort,
),
start_to_close_timeout=_QUICK_TIMEOUT,
retry_policy=_RETRY,
diff --git a/products/review_hog/backend/tests/test_acting_user.py b/products/review_hog/backend/tests/test_acting_user.py
index 09da7f0ba56c..acbd6c980e4a 100644
--- a/products/review_hog/backend/tests/test_acting_user.py
+++ b/products/review_hog/backend/tests/test_acting_user.py
@@ -5,7 +5,7 @@ from social_django.models import UserSocialAuth
from products.review_hog.backend.models import ReviewReport, ReviewUserSettings
from products.review_hog.backend.temporal.activities import ResolveActingUserInput, _resolve_acting_user
-from products.review_hog.backend.temporal.types import TRIGGER_LABEL, TRIGGER_MANUAL
+from products.review_hog.backend.temporal.types import TRIGGER_AUTOMATIC, TRIGGER_LABEL, TRIGGER_MANUAL
_SELF = "SELF"
@@ -46,6 +46,48 @@ class TestResolveActingUser(BaseTest):
assert result.review_inbox_prs is False
assert result.urgency_threshold == "consider"
assert result.resolve_comments is True
+ assert result.review_authored_prs is False
+ assert result.flash_reasoning_effort == "medium"
+
+ @parameterized.expand(
+ [
+ ("enabled", True, True, True),
+ ("opted_out", False, True, True),
+ ("inactive", True, False, True),
+ ("left_organization", True, True, False),
+ ]
+ )
+ def test_automatic_trigger_rechecks_eligible_author(
+ self, _name: str, opted_in: bool, active: bool, member: bool
+ ) -> None:
+ report = ReviewReport.objects.for_team(self.team.id).create(
+ team_id=self.team.id,
+ repository="PostHog/posthog",
+ pr_number=7,
+ pr_url="https://github.com/PostHog/posthog/pull/7",
+ head_branch="feat",
+ base_branch="main",
+ )
+ ReviewUserSettings.objects.for_team(self.team.id).create(
+ team_id=self.team.id, user_id=self.user.id, review_authored_prs=opted_in
+ )
+ self.user.is_active = active
+ self.user.save(update_fields=["is_active"])
+ if not member:
+ self.user.organization_memberships.filter(organization=self.organization).delete()
+ result = _resolve_acting_user(
+ ResolveActingUserInput(
+ team_id=self.team.id,
+ author_login="octocat",
+ override_user_id=self.user.id,
+ trigger_source=TRIGGER_AUTOMATIC,
+ report_id=str(report.id),
+ )
+ )
+ eligible = opted_in and active and member
+ assert result.acting_user_id == (self.user.id if eligible else None)
+ report.refresh_from_db()
+ assert report.status == (ReviewReport.Status.ACTIVE if eligible else ReviewReport.Status.IDLE)
def test_settings_row_flows_into_the_result(self) -> None:
# The user's saved settings must reach the workflow — if resolve stops loading any of them,
@@ -59,6 +101,8 @@ class TestResolveActingUser(BaseTest):
review_inbox_prs=True,
urgency_threshold=ReviewUserSettings.UrgencyThreshold.MUST_FIX,
resolve_comments=False,
+ review_authored_prs=True,
+ flash_reasoning_effort=ReviewUserSettings.FlashReasoningEffort.XHIGH,
)
result = _resolve_acting_user(
ResolveActingUserInput(team_id=self.team.id, author_login="octocat", override_user_id=None)
@@ -69,6 +113,8 @@ class TestResolveActingUser(BaseTest):
# The opt-out must reach the workflow — hardwiring the snapshot on would strip users of the
# only lever that stops reviews from writing to their PRs.
assert result.resolve_comments is False
+ assert result.review_authored_prs is True
+ assert result.flash_reasoning_effort == "xhigh"
def test_label_trigger_falls_back_to_the_run_user(self) -> None:
# Unmapped author on a labeled PR → the run user the trigger already resolved, passed
@@ -129,7 +175,10 @@ class TestResolveActingUser(BaseTest):
# must not decide what lands on someone ELSE's PR — a default-resolved run gates at the
# built-in default. Personal resolutions (author, requester override) keep the saved value.
ReviewUserSettings.objects.for_team(self.team.id).create(
- team_id=self.team.id, user_id=self.user.id, urgency_threshold=ReviewUserSettings.UrgencyThreshold.MUST_FIX
+ team_id=self.team.id,
+ user_id=self.user.id,
+ urgency_threshold=ReviewUserSettings.UrgencyThreshold.MUST_FIX,
+ flash_reasoning_effort=ReviewUserSettings.FlashReasoningEffort.XHIGH,
)
as_author = _resolve_acting_user(
ResolveActingUserInput(
@@ -137,12 +186,14 @@ class TestResolveActingUser(BaseTest):
)
)
assert (as_author.resolved_from, as_author.urgency_threshold) == ("author", "must_fix")
+ assert as_author.flash_reasoning_effort == "xhigh"
as_override = _resolve_acting_user(
ResolveActingUserInput(
team_id=self.team.id, author_login="ghost", override_user_id=self.user.id, trigger_source=TRIGGER_LABEL
)
)
assert (as_override.resolved_from, as_override.urgency_threshold) == ("override", "must_fix")
+ assert as_override.flash_reasoning_effort == "xhigh"
as_default = _resolve_acting_user(
ResolveActingUserInput(
team_id=self.team.id,
@@ -153,6 +204,7 @@ class TestResolveActingUser(BaseTest):
)
)
assert (as_default.resolved_from, as_default.urgency_threshold) == ("default", "consider")
+ assert as_default.flash_reasoning_effort == "medium"
def test_resolve_stamps_the_acting_user_onto_the_report(self) -> None:
# "Your recent reviews" filters on this stamp — if resolve stops writing it, the list goes empty.
diff --git a/products/review_hog/backend/tests/test_automatic_reviews.py b/products/review_hog/backend/tests/test_automatic_reviews.py
new file mode 100644
index 000000000000..0cbd64efeaf0
--- /dev/null
+++ b/products/review_hog/backend/tests/test_automatic_reviews.py
@@ -0,0 +1,266 @@
+import hmac
+import json
+from collections.abc import Mapping
+
+from posthog.test.base import BaseTest
+from unittest.mock import MagicMock, patch
+
+from django.core.cache import caches
+from django.http import HttpResponse
+from django.test import RequestFactory, SimpleTestCase, override_settings
+
+from parameterized import parameterized
+from prometheus_client import REGISTRY
+from social_django.models import UserSocialAuth
+
+from posthog.ingress.dispatch.dedup import INGRESS_DEDUP_CACHE_ALIAS
+from posthog.ingress.dispatch.dispatcher import WebhookDispatcher
+from posthog.ingress.dispatch.loading import reset_consumer_registry
+from posthog.ingress.dispatch.registry import ConsumerRegistry
+from posthog.ingress.github.provider import SPECS, build_github_provider
+from posthog.ingress.test import LOCMEM_CACHES
+from posthog.ingress.views import build_webhook_view
+from posthog.models.integration import Integration
+from posthog.models.organization import OrganizationMembership
+from posthog.models.team import Team
+
+from products.review_hog.backend.automatic_reviews import enqueue_authored_pr_review
+from products.review_hog.backend.models import ReviewUserSettings
+from products.review_hog.backend.tasks import process_authored_pr_event
+from products.review_hog.backend.webhook_consumers import WEBHOOK_CONSUMERS
+
+_QUEUE = "products.review_hog.backend.tasks.process_authored_pr_event.delay"
+_START = "products.review_hog.backend.temporal.client.start_review_pr_workflow"
+_SECRET = "test-review-hog-webhook-secret"
+_HEAD_SHA = "a" * 40
+_DISPATCH_METRIC = "posthog_review_hog_authored_pr_review_total"
+
+
+def _dispatch_count(outcome: str) -> float:
+ return REGISTRY.get_sample_value(_DISPATCH_METRIC, {"outcome": outcome}) or 0.0
+
+
+def _payload(*, action: str = "opened", draft: bool = False) -> dict[str, object]:
+ return {
+ "action": action,
+ "installation": {"id": 1234},
+ "repository": {"full_name": "PostHog/posthog"},
+ "pull_request": {
+ "number": 42,
+ "state": "open",
+ "draft": draft,
+ "merged": False,
+ "user": {"login": "OctoCat"},
+ "head": {"sha": _HEAD_SHA, "repo": {"full_name": "posthog/PostHog"}},
+ "base": {"repo": {"full_name": "PostHog/posthog"}},
+ },
+ }
+
+
+@override_settings(CACHES=LOCMEM_CACHES)
+class TestAuthoredPRWebhook(SimpleTestCase):
+ def setUp(self) -> None:
+ reset_consumer_registry()
+ caches[INGRESS_DEDUP_CACHE_ALIAS].clear()
+ self.addCleanup(reset_consumer_registry)
+ self.addCleanup(caches[INGRESS_DEDUP_CACHE_ALIAS].clear)
+ self.factory = RequestFactory()
+ self.view = build_webhook_view(build_github_provider("posthog"))
+ dispatcher = WebhookDispatcher(ConsumerRegistry(providers=SPECS, consumers=WEBHOOK_CONSUMERS))
+ self.enterContext(patch("posthog.ingress.views.get_dispatcher", return_value=dispatcher))
+ self.secret = self.enterContext(
+ patch("posthog.ingress.github.provider.get_instance_setting", return_value=_SECRET)
+ )
+
+ def _post(self, body: bytes, *, event: str = "pull_request", signature: str | None = None) -> HttpResponse:
+ request = self.factory.post(
+ "/webhooks/github/",
+ data=body,
+ content_type="application/json",
+ headers={
+ "X-GitHub-Event": event,
+ "X-GitHub-Delivery": "authored-pr-delivery",
+ "X-Hub-Signature-256": signature or "sha256=" + hmac.digest(_SECRET.encode(), body, "sha256").hex(),
+ },
+ )
+ return self.view(request)
+
+ @parameterized.expand([("opened", False), ("opened", True), ("synchronize", False), ("synchronize", True)])
+ @patch(_QUEUE)
+ def test_signed_eligible_events_enqueue_once(self, action: str, draft: bool, enqueue: MagicMock) -> None:
+ body = json.dumps(_payload(action=action, draft=draft)).encode()
+
+ assert self._post(body).status_code == 202
+ assert self._post(body).status_code == 202
+
+ enqueue.assert_called_once_with(
+ installation_id="1234", author_login="octocat", pr_number=42, head_sha=_HEAD_SHA
+ )
+
+ @parameterized.expand(
+ [
+ ("not_a_pr_event", "issues", None, False, False, 202),
+ ("invalid_signature", "pull_request", "sha256=" + "0" * 64, False, False, 403),
+ ("invalid_body", "pull_request", None, True, False, 400),
+ ("missing_secret", "pull_request", None, False, True, 500),
+ ]
+ )
+ @patch(_QUEUE)
+ def test_refused_deliveries_do_not_enqueue(
+ self,
+ _name: str,
+ event: str,
+ signature: str | None,
+ invalid_body: bool,
+ missing_secret: bool,
+ expected_status: int,
+ enqueue: MagicMock,
+ ) -> None:
+ body = b"not json" if invalid_body else json.dumps(_payload()).encode()
+ if missing_secret:
+ self.secret.return_value = None
+
+ response = self._post(body, event=event, signature=signature)
+
+ assert response.status_code == expected_status
+ enqueue.assert_not_called()
+
+ @patch(_QUEUE)
+ def test_non_post_does_not_enqueue(self, enqueue: MagicMock) -> None:
+ assert self.view(self.factory.get("/webhooks/github/")).status_code == 405
+ enqueue.assert_not_called()
+
+ @parameterized.expand(
+ [
+ ("label", ("action",), "labeled"),
+ ("ready_for_review", ("action",), "ready_for_review"),
+ ("closed", ("pull_request", "state"), "closed"),
+ ("merged", ("pull_request", "merged"), True),
+ ("fork", ("pull_request", "head", "repo", "full_name"), "octocat/posthog"),
+ ("deleted_fork", ("pull_request", "head", "repo"), None),
+ ("other_repository", ("repository", "full_name"), "PostHog/another-repo"),
+ ("other_base", ("pull_request", "base", "repo", "full_name"), "PostHog/another-repo"),
+ ("no_installation", ("installation",), None),
+ ("no_author", ("pull_request", "user"), None),
+ ("no_head", ("pull_request", "head", "sha"), ""),
+ ]
+ )
+ @patch(_QUEUE)
+ def test_ineligible_pull_requests_do_not_enqueue(
+ self, _name: str, path: tuple[str, ...], value: object, enqueue: MagicMock
+ ) -> None:
+ payload = _payload()
+ target = payload
+ for part in path[:-1]:
+ nested = target[part]
+ assert isinstance(nested, dict)
+ target = nested
+ target[path[-1]] = value
+
+ assert self._post(json.dumps(payload).encode()).status_code == 202
+
+ enqueue.assert_not_called()
+
+
+class TestAuthoredPRReviewTask(BaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.enterContext(override_settings(REVIEWHOG_TEAM_IDS=[self.team.id]))
+ self.integration = Integration.objects.create(
+ team=self.team, kind="github", integration_id="1234", config={"installation_id": "1234"}
+ )
+ self.github_identity = UserSocialAuth.objects.create(
+ user=self.user, provider="github", uid="review-author", extra_data={"login": "OctoCat"}
+ )
+ self.preferences = ReviewUserSettings.objects.for_team(self.team.id).create(
+ team_id=self.team.id, user_id=self.user.id, review_authored_prs=True
+ )
+
+ def _queued_event(self) -> Mapping[str, object]:
+ with patch(_QUEUE) as enqueue:
+ enqueue_authored_pr_review(_payload())
+ enqueue.assert_called_once()
+ return enqueue.call_args.kwargs
+
+ @patch(_START)
+ def test_opted_in_author_schedules_flash_on_the_configured_team(self, start: MagicMock) -> None:
+ started_before = _dispatch_count("started")
+
+ process_authored_pr_event.run(**self._queued_event())
+
+ start.assert_called_once_with(
+ pr_url="https://github.com/PostHog/posthog/pull/42",
+ team_id=self.team.id,
+ user_id=self.user.id,
+ acting_user_id=self.user.id,
+ publish=True,
+ resolve_comments=False,
+ review_mode="flash",
+ trigger_source="automatic",
+ requested_head_sha=_HEAD_SHA,
+ )
+ assert _dispatch_count("started") - started_before == 1.0
+
+ @parameterized.expand(
+ [
+ ("disabled", "not_opted_in"),
+ ("unset", "not_opted_in"),
+ ("inactive", "not_opted_in"),
+ ("left_org", "author_unmapped"),
+ ("unmapped", "author_unmapped"),
+ ]
+ )
+ @patch(_START)
+ def test_queued_events_recheck_author_consent_and_membership(
+ self, change: str, expected_outcome: str, start: MagicMock
+ ) -> None:
+ queued = self._queued_event()
+ if change == "disabled":
+ self.preferences.review_authored_prs = False
+ self.preferences.save(update_fields=["review_authored_prs"])
+ elif change == "unset":
+ self.preferences.delete()
+ elif change == "inactive":
+ self.user.is_active = False
+ self.user.save(update_fields=["is_active"])
+ elif change == "left_org":
+ OrganizationMembership.objects.filter(organization=self.organization, user=self.user).delete()
+ else:
+ self.github_identity.delete()
+ outcome_before = _dispatch_count(expected_outcome)
+
+ process_authored_pr_event.run(**queued)
+
+ start.assert_not_called()
+ assert _dispatch_count(expected_outcome) - outcome_before == 1.0
+
+ @parameterized.expand(
+ [
+ ("missing_installation", "installation_mismatch"),
+ ("other_team", "installation_mismatch"),
+ ("other_configured_team", "installation_mismatch"),
+ ("no_team", "no_team"),
+ ]
+ )
+ @patch(_START)
+ def test_delivery_must_match_the_configured_teams_installation(
+ self, change: str, expected_outcome: str, start: MagicMock
+ ) -> None:
+ queued = self._queued_event()
+ if change == "missing_installation":
+ self.integration.delete()
+ elif change == "no_team":
+ self.enterContext(override_settings(REVIEWHOG_TEAM_IDS=[]))
+ else:
+ other_team = Team.objects.create(organization=self.organization)
+ if change == "other_team":
+ self.integration.team = other_team
+ self.integration.save(update_fields=["team"])
+ else:
+ self.enterContext(override_settings(REVIEWHOG_TEAM_IDS=[other_team.id, self.team.id]))
+ outcome_before = _dispatch_count(expected_outcome)
+
+ process_authored_pr_event.run(**queued)
+
+ start.assert_not_called()
+ assert _dispatch_count(expected_outcome) - outcome_before == 1.0
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 3e2a7aebd683..c0c0cb50cb7b 100644
--- a/products/review_hog/backend/tests/test_fetch_review_tier.py
+++ b/products/review_hog/backend/tests/test_fetch_review_tier.py
@@ -5,6 +5,8 @@ from unittest.mock import MagicMock, patch
from django.test import override_settings
+from parameterized import parameterized
+
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
@@ -36,6 +38,38 @@ def _pr_metadata() -> PRMetadata:
class TestFetchDecidesTheTier(BaseTest):
+ @parameterized.expand([(None, "open", False), ("sha1", "open", True), (None, "closed", False)])
+ @patch(f"{_MODULE}._installation_auth", return_value=("tok", None))
+ @patch(f"{_MODULE}.PRFetcher")
+ def test_automatic_completion_requires_a_successful_publication_step(
+ self, automatic_head: str | None, state: str, complete: bool, mock_fetcher: MagicMock, _auth: MagicMock
+ ) -> None:
+ metadata = _pr_metadata().model_copy(update={"state": state})
+ mock_fetcher.return_value.fetch_pr_data.return_value = (metadata, [], [], "")
+ request = FetchPRDataInput(
+ team_id=self.team.id,
+ user_id=self.user.id,
+ repository="o/r",
+ owner="o",
+ repo="r",
+ pr_number=9,
+ review_mode="flash",
+ trigger_source="automatic",
+ )
+ first = _fetch_and_persist(request)
+ report = ReviewReport.objects.for_team(self.team.id).get(id=first.report_id)
+ report.completed_head_sha = "sha1"
+ report.automatic_reviewed_head_sha = automatic_head
+ report.save()
+
+ meta = _fetch_and_persist(request)
+ report.refresh_from_db()
+
+ assert meta.already_completed is complete
+ assert meta.pr_open is (state == "open")
+ expected_status = "closed" if state == "closed" else "idle" if complete else "active"
+ assert report.status == expected_status
+
@patch(f"{_MODULE}._installation_auth", return_value=("tok", "9876543"))
@patch(f"{_MODULE}.PRFetcher")
def test_fetch_keeps_the_created_tier_until_a_full_human_review(
diff --git a/products/review_hog/backend/tests/test_persistence.py b/products/review_hog/backend/tests/test_persistence.py
index 048312799743..a354500e53c9 100644
--- a/products/review_hog/backend/tests/test_persistence.py
+++ b/products/review_hog/backend/tests/test_persistence.py
@@ -11,6 +11,7 @@ from parameterized import parameterized
from products.review_hog.backend.models import ReviewReport, ReviewReportArtefact
from products.review_hog.backend.reviewer.artefact_content import (
ChunkSetArtefact,
+ PerspectiveResultArtefact,
ReviewIssueFinding,
ValidationVerdict,
parse_artefact_content,
@@ -886,22 +887,50 @@ 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_chunk_and_model(self) -> None:
+ def test_perspective_results_round_trip_keyed_by_pass_chunk_and_arm(self) -> None:
results = {
(1, 1): IssuesReview(issues=[_issue("1-1-1")]),
(2, 1): IssuesReview(issues=[_issue("2-1-1")]),
}
+ ReviewReportArtefact.add_working_state(
+ team_id=self.team.id,
+ report_id=self.report_id,
+ content=PerspectiveResultArtefact(
+ head_sha="sha-aaa", pass_number=1, chunk_id=1, review=results[(1, 1)], review_model=FLASH_ARM.model
+ ),
+ attribution=ArtefactAttribution.system(),
+ )
+ assert (
+ load_perspective_results(
+ team_id=self.team.id, report_id=self.report_id, head_sha="sha-aaa", review_arm=FLASH_ARM
+ )
+ == {}
+ )
persist_perspective_results(
- team_id=self.team.id, report_id=self.report_id, head_sha="sha-aaa", results=results, review_model="sol"
+ team_id=self.team.id, report_id=self.report_id, head_sha="sha-aaa", results=results, review_arm=FLASH_ARM
+ )
+ stronger_arm = replace(FLASH_ARM, reasoning_effort=ReasoningEffort.XHIGH)
+ assert (
+ load_perspective_results(
+ team_id=self.team.id, report_id=self.report_id, head_sha="sha-aaa", review_arm=stronger_arm
+ )
+ == {}
+ )
+ persist_perspective_results(
+ team_id=self.team.id,
+ report_id=self.report_id,
+ head_sha="sha-aaa",
+ results={(1, 1): IssuesReview(issues=[_issue("1-1-xhigh")])},
+ review_arm=stronger_arm,
)
loaded = load_perspective_results(
- team_id=self.team.id, report_id=self.report_id, head_sha="sha-aaa", review_model="sol"
+ team_id=self.team.id, report_id=self.report_id, head_sha="sha-aaa", review_arm=FLASH_ARM
)
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", review_model="sol"
+ team_id=self.team.id, report_id=self.report_id, head_sha="sha-bbb", review_arm=FLASH_ARM
)
== {}
)
@@ -909,10 +938,15 @@ class TestWorkingState(BaseTest):
# 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"
+ team_id=self.team.id, report_id=self.report_id, head_sha="sha-aaa", review_arm=DEFAULT_REVIEW_ARM
)
== {}
)
+ stronger_results = load_perspective_results(
+ team_id=self.team.id, report_id=self.report_id, head_sha="sha-aaa", review_arm=stronger_arm
+ )
+ assert set(stronger_results) == {(1, 1)}
+ assert stronger_results[(1, 1)].issues[0].id == "1-1-xhigh"
class TestPersistCommitSnapshot(BaseTest):
diff --git a/products/review_hog/backend/tests/test_publish_idempotency.py b/products/review_hog/backend/tests/test_publish_idempotency.py
index fd6421f747e5..c3a61cb3a30a 100644
--- a/products/review_hog/backend/tests/test_publish_idempotency.py
+++ b/products/review_hog/backend/tests/test_publish_idempotency.py
@@ -1,4 +1,5 @@
from collections.abc import Callable, Iterator
+from dataclasses import replace
from typing import Any
from posthog.test.base import BaseTest
@@ -6,7 +7,10 @@ from unittest.mock import patch
from django.test import override_settings
+from parameterized import parameterized
+
from products.review_hog.backend.models import ReviewReport
+from products.review_hog.backend.reviewer.constants import message_prefix_for_mode
from products.review_hog.backend.reviewer.models.github_meta import PRMetadata
from products.review_hog.backend.reviewer.persistence import upsert_review_report
from products.review_hog.backend.reviewer.tools.github_client import GitHubAPIError
@@ -74,6 +78,24 @@ def test_review_already_posted_proceeds_when_readback_fails() -> None:
assert _review_posted(_review_marker("rep-1", "sha1"), [], boom=True) is False
+def test_legacy_markers_only_suppress_reviews_in_the_same_mode() -> None:
+ legacy = _review_marker("rep-1", "sha1")
+ for posted_mode in ("full", "flash"):
+ review = {"body": f"{message_prefix_for_mode(posted_mode)}body\n{legacy}", "user": {"type": "Bot"}}
+ with patch(_PAGINATED, side_effect=_paginated([review])):
+ for requested_mode in ("full", "flash"):
+ assert _review_already_posted(
+ "o",
+ "r",
+ 1,
+ _review_marker("rep-1", "sha1", requested_mode),
+ token="t",
+ installation_id=None,
+ legacy_marker=legacy,
+ review_mode=requested_mode,
+ ) is (posted_mode == requested_mode)
+
+
def test_promo_already_posted_detects_the_markered_comment() -> None:
# The promo posts before the review, so a retry after a transient review failure re-enters
# with published_head_sha still unset — the marker is what stops a second promo comment.
@@ -134,6 +156,46 @@ class TestPublishIdempotency(BaseTest):
)
return report_id
+ @parameterized.expand([("full_then_flash", "full", "flash"), ("flash_then_full", "flash", "full")])
+ @patch(_PUBLISH)
+ @patch(_SNAPSHOT, return_value=None)
+ @patch(_AUTH, return_value=("tok", None))
+ def test_distinct_modes_publish_once_each_at_the_same_head(
+ self, _name, first_mode, second_mode, _auth, _snapshot, mock_publish
+ ) -> None:
+ mock_publish.return_value = PublishOutcome(posted=True)
+ report_id = self._report()
+ first = replace(_publish_input(self.team.id, report_id, "sha1"), review_mode=first_mode)
+ second = replace(first, review_mode=second_mode, run_index=2)
+ for item in (first, second, first, second):
+ _publish(item)
+ assert mock_publish.call_count == 2
+ report = ReviewReport.objects.for_team(self.team.id).get(id=report_id)
+ assert report.published_heads_by_mode == {"full": "sha1", "flash": "sha1"}
+
+ @patch(_PUBLISH)
+ @patch(_SNAPSHOT, return_value=None)
+ @patch(_AUTH, return_value=("tok", None))
+ def test_publication_write_keeps_a_watermark_that_landed_while_posting(
+ self, _auth, _snapshot, mock_publish
+ ) -> None:
+ report_id = self._report()
+
+ def post_while_the_other_mode_publishes(**_kwargs: Any) -> PublishOutcome:
+ # The standalone publish command runs outside the per-PR queue, so a Flash publication
+ # can commit while this Full one is still posting to GitHub.
+ ReviewReport.objects.for_team(self.team.id).filter(id=report_id).update(
+ published_heads_by_mode={"flash": "sha1"}, published_head_shas={"9": "sha1"}
+ )
+ return PublishOutcome(posted=True)
+
+ mock_publish.side_effect = post_while_the_other_mode_publishes
+ _publish(_publish_input(self.team.id, report_id, "sha1"))
+
+ report = ReviewReport.objects.for_team(self.team.id).get(id=report_id)
+ assert report.published_heads_by_mode == {"flash": "sha1", "full": "sha1"}
+ assert report.published_head_shas == {"9": "sha1", "1": "sha1"}
+
@patch(_PUBLISH)
@patch(_SNAPSHOT, return_value=None)
@patch(_AUTH, return_value=("tok", "9876543"))
@@ -186,9 +248,20 @@ class TestPublishIdempotency(BaseTest):
# later turn with a valid finding can still publish at the same head.
mock_publish.return_value = PublishOutcome(posted=False)
report_id = self._report()
- _publish(_publish_input(self.team.id, report_id, "sha1"))
+ _publish(replace(_publish_input(self.team.id, report_id, "sha1"), trigger_source="automatic"))
assert mock_publish.call_count == 1
report = ReviewReport.objects.for_team(self.team.id).get(id=report_id)
assert report.published_head_sha is None
+ assert report.automatic_reviewed_head_sha == "sha1"
# No watermark, but the turn is over: the no-post exit still restores rest.
assert report.status == ReviewReport.Status.IDLE
+
+ @patch(_PUBLISH, side_effect=RuntimeError("GitHub unavailable"))
+ @patch(_SNAPSHOT, return_value=None)
+ @patch(_AUTH, return_value=("tok", None))
+ def test_failed_publication_does_not_complete_an_automatic_review(self, _auth, _snapshot, _publish_mock) -> None:
+ report_id = self._report()
+ with self.assertRaises(RuntimeError):
+ _publish(replace(_publish_input(self.team.id, report_id, "sha1"), trigger_source="automatic"))
+ report = ReviewReport.objects.for_team(self.team.id).get(id=report_id)
+ assert report.automatic_reviewed_head_sha is None
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 adb49f1ba10f..701bd35b9f62 100644
--- a/products/review_hog/backend/tests/test_publish_review_command.py
+++ b/products/review_hog/backend/tests/test_publish_review_command.py
@@ -1,3 +1,5 @@
+import json
+
import pytest
from posthog.test.base import BaseTest
from unittest.mock import MagicMock, patch
@@ -7,7 +9,8 @@ from django.core.management.base import CommandError
from parameterized import parameterized
-from products.review_hog.backend.models import ReviewReport
+from products.review_hog.backend.models import ReviewReport, ReviewReportArtefact
+from products.review_hog.backend.reviewer.artefact_content import ReviewIssueFinding
from products.review_hog.backend.reviewer.constants import (
DEFAULT_URGENCY_THRESHOLD,
REVIEW_MODE_FLASH,
@@ -17,6 +20,7 @@ from products.review_hog.backend.reviewer.models.github_meta import PRMetadata
from products.review_hog.backend.reviewer.models.issues_review import IssuePriority
from products.review_hog.backend.reviewer.persistence import upsert_review_report
from products.review_hog.backend.reviewer.tools.publish_review import PublishOutcome
+from products.signals.backend.artefact_attribution import ArtefactAttribution
_PUBLISH = "products.review_hog.backend.management.commands.publish_review.publish_persisted_review"
_INTEGRATION = (
@@ -67,6 +71,23 @@ class TestPublishReviewCommand(BaseTest):
)
return report_id
+ def _finding_mode(self, report_id: str, run_index: int, mode: str | None) -> None:
+ ReviewReportArtefact.append_finding(
+ team_id=self.team.id,
+ report_id=report_id,
+ content=ReviewIssueFinding(
+ issue_key=f"r{run_index}:a.py:1:logic:1",
+ run_index=run_index,
+ validation_context=json.dumps({"review_mode": mode}) if mode is not None else None,
+ title="Missing guard",
+ file="a.py",
+ body="The value can be absent.",
+ suggestion="Check the value before using it.",
+ priority=IssuePriority.SHOULD_FIX,
+ ),
+ attribution=ArtefactAttribution.system(),
+ )
+
def test_errors_when_no_review_exists(self) -> None:
with pytest.raises(CommandError, match="No review found"):
call_command("publish_review", pr_url=_URL, team_id=self.team.id)
@@ -77,15 +98,30 @@ 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)])
+ @parameterized.expand(
+ [
+ (None, None, REVIEW_MODE_FULL),
+ (None, REVIEW_MODE_FLASH, REVIEW_MODE_FLASH),
+ (REVIEW_MODE_FLASH, REVIEW_MODE_FLASH, REVIEW_MODE_FLASH),
+ (None, REVIEW_MODE_FULL, REVIEW_MODE_FULL),
+ ]
+ )
@patch(_STALE, return_value=None)
@patch(_PUBLISH, return_value=PublishOutcome(posted=True))
def test_publishes_latest_completed_run_with_no_recompute(
- self, review_mode: str | None, expected_mode: str, mock_publish: MagicMock, _stale: MagicMock
+ self,
+ review_mode: str | None,
+ stored_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")
+ earlier_mode = REVIEW_MODE_FULL if expected_mode == REVIEW_MODE_FLASH else REVIEW_MODE_FLASH
+ self._finding_mode(report_id, 1, earlier_mode)
+ self._finding_mode(report_id, 2, stored_mode)
integration = MagicMock()
integration.get_access_token.return_value = "tok"
integration.github_installation_id = "9876543"
@@ -103,6 +139,15 @@ class TestPublishReviewCommand(BaseTest):
# The installation id rides along so the publish calls are metered against the right budget.
assert kwargs["installation_id"] == "9876543"
+ @parameterized.expand([(REVIEW_MODE_FLASH, REVIEW_MODE_FULL), (REVIEW_MODE_FULL, REVIEW_MODE_FLASH)])
+ def test_rejects_a_mode_that_differs_from_the_stored_review(self, stored_mode: str, requested_mode: str) -> None:
+ report_id = self._report(run_count=1)
+ self._finding_mode(report_id, 1, stored_mode)
+ with patch(_INTEGRATION) as integration:
+ with pytest.raises(CommandError, match=f"The stored review used {stored_mode} mode"):
+ call_command("publish_review", "--review-mode", requested_mode, pr_url=_URL, team_id=self.team.id)
+ integration.assert_not_called()
+
@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:
diff --git a/products/review_hog/backend/tests/test_review_activity.py b/products/review_hog/backend/tests/test_review_activity.py
index 7de07bd4f352..6c144ba6aab0 100644
--- a/products/review_hog/backend/tests/test_review_activity.py
+++ b/products/review_hog/backend/tests/test_review_activity.py
@@ -1,3 +1,5 @@
+from dataclasses import replace
+
import pytest
from unittest.mock import AsyncMock, MagicMock, patch
@@ -145,7 +147,12 @@ async def test_split_chunks_activity_routes_llm_chunking_by_oneshot_gate(additio
@pytest.mark.asyncio
-async def test_review_chunk_activity_flash_turn_runs_on_the_flash_arm_and_stamps_the_cache() -> None:
[email protected]("effort", [ReasoningEffort.MEDIUM, ReasoningEffort.XHIGH])
[email protected]("blind_spot_check", [False, True])
+async def test_review_chunk_activity_flash_turn_runs_on_the_flash_arm_and_stamps_the_cache(
+ effort: ReasoningEffort, blind_spot_check: bool
+) -> None:
+ expected = replace(FLASH_ARM, reasoning_effort=effort)
mock_review = AsyncMock(return_value=IssuesReview(issues=[]))
mock_persist = MagicMock()
mock_prepare = MagicMock(return_value="review-prompt")
@@ -157,7 +164,17 @@ async def test_review_chunk_activity_flash_turn_runs_on_the_flash_arm_and_stamps
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
+ assert (
+ await env.run(
+ review_chunk_activity,
+ _review_input(
+ review_mode=REVIEW_MODE_FLASH,
+ flash_reasoning_effort=effort.value,
+ blind_spot_check=blind_spot_check,
+ ),
+ )
+ is True
+ )
kwargs = mock_review.call_args.kwargs
assert (
@@ -166,13 +183,13 @@ async def test_review_chunk_activity_flash_turn_runs_on_the_flash_arm_and_stamps
kwargs["reasoning_effort"],
kwargs["initial_permission_mode"],
) == (
- FLASH_ARM.runtime_adapter,
- FLASH_ARM.model,
- FLASH_ARM.reasoning_effort,
- FLASH_ARM.initial_permission_mode,
+ expected.runtime_adapter,
+ expected.model,
+ expected.reasoning_effort,
+ expected.initial_permission_mode,
)
- assert mock_prepare.call_args.args[-1] == FLASH_ARM.model
- assert mock_persist.call_args.kwargs["review_model"] == FLASH_ARM.model
+ assert mock_prepare.call_args.args[-1] == expected
+ assert mock_persist.call_args.kwargs["review_arm"] == expected
@pytest.mark.asyncio
@@ -201,7 +218,7 @@ async def test_review_chunk_activity_runs_on_the_reports_persisted_arm() -> None
):
assert await env.run(review_chunk_activity, _review_input()) is True
- assert mock_prepare.call_args.args[-1] == arm.model
+ assert mock_prepare.call_args.args[-1] == arm
kwargs = mock_review.call_args.kwargs
assert (
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 c7fa5765b2eb..c16e4a7cced8 100644
--- a/products/review_hog/backend/tests/test_review_completed_tracking.py
+++ b/products/review_hog/backend/tests/test_review_completed_tracking.py
@@ -99,6 +99,7 @@ class TestTrackReviewCompleted(BaseTest):
published: bool = True,
turn_trigger_source: str = "manual",
review_mode: str = REVIEW_MODE_FULL,
+ flash_reasoning_effort: str = "medium",
) -> TrackReviewCompletedInput:
return TrackReviewCompletedInput(
team_id=self.team.id,
@@ -109,6 +110,7 @@ class TestTrackReviewCompleted(BaseTest):
workflow_started_at=(datetime.now(UTC) - timedelta(seconds=90)).isoformat(),
turn_trigger_source=turn_trigger_source,
review_mode=review_mode,
+ flash_reasoning_effort=flash_reasoning_effort,
)
@parameterized.expand([(True,), (False,)])
@@ -323,8 +325,14 @@ 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:
+ @parameterized.expand(
+ [
+ ("medium", REVIEW_MODEL, "medium"),
+ ("xhigh", REVIEW_MODEL, "xhigh"),
+ ("stale_model", "gpt-9-vanished", "xhigh"),
+ ]
+ )
+ def test_flash_turn_events_name_the_flash_arm_in_both_seats(self, _name: str, model: str, effort: 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.
@@ -332,10 +340,16 @@ class TestTrackReviewCompleted(BaseTest):
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_completed(
+ self._tracking_input(report_id, review_mode=REVIEW_MODE_FLASH, flash_reasoning_effort=effort)
+ )
_track_review_failed(
TrackReviewFailedInput(
- team_id=self.team.id, report_id=report_id, run_index=1, review_mode=REVIEW_MODE_FLASH
+ team_id=self.team.id,
+ report_id=report_id,
+ run_index=1,
+ review_mode=REVIEW_MODE_FLASH,
+ flash_reasoning_effort=effort,
)
)
_track_review_started(
@@ -346,6 +360,7 @@ class TestTrackReviewCompleted(BaseTest):
run_index=1,
turn_trigger_source="ui",
review_mode=REVIEW_MODE_FLASH,
+ flash_reasoning_effort=effort,
)
)
@@ -353,9 +368,9 @@ class TestTrackReviewCompleted(BaseTest):
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["review_reasoning_effort"] == effort
assert props["validator_model"] == FLASH_ARM.model
- assert props["validator_reasoning_effort"] == FLASH_ARM.reasoning_effort.value
+ assert props["validator_reasoning_effort"] == effort
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"
diff --git a/products/review_hog/backend/tests/test_review_scheduling.py b/products/review_hog/backend/tests/test_review_scheduling.py
new file mode 100644
index 000000000000..9cf3a27c6d69
--- /dev/null
+++ b/products/review_hog/backend/tests/test_review_scheduling.py
@@ -0,0 +1,166 @@
+import uuid
+import asyncio
+from dataclasses import replace
+from datetime import timedelta
+
+import pytest
+
+from temporalio import activity, workflow
+from temporalio.common import RetryPolicy, WorkflowIDConflictPolicy
+from temporalio.exceptions import ApplicationError
+from temporalio.testing import WorkflowEnvironment
+from temporalio.worker import UnsandboxedWorkflowRunner, Worker
+
+from products.review_hog.backend.temporal.scheduling import ReviewPRQueueWorkflow, ReviewRequestQueue
+from products.review_hog.backend.temporal.types import ReviewPRQueueInputs, ReviewPRWorkflowInputs
+
+
[email protected](name="review-pr")
+class ScheduledReviewStub:
+ @workflow.run
+ async def run(self, inputs: ReviewPRWorkflowInputs) -> str:
+ return await workflow.execute_activity(
+ "record_scheduled_review",
+ inputs,
+ result_type=str,
+ start_to_close_timeout=timedelta(minutes=1),
+ retry_policy=RetryPolicy(maximum_attempts=1),
+ )
+
+
[email protected]("fail_first", [False, True])
+async def test_pushes_coalesce_and_full_requests_survive_an_active_flash_review(fail_first: bool) -> None:
+ entered = asyncio.Event()
+ release = asyncio.Event()
+ reviews: list[ReviewPRWorkflowInputs] = []
+ first = ReviewPRWorkflowInputs(
+ team_id=1,
+ user_id=1,
+ owner="PostHog",
+ repo="posthog",
+ pr_number=7,
+ review_mode="flash",
+ trigger_source="automatic",
+ requested_head_sha="a",
+ publish=True,
+ )
+
+ @activity.defn(name="record_scheduled_review")
+ async def record(inputs: ReviewPRWorkflowInputs) -> str:
+ reviews.append(inputs)
+ if inputs.requested_head_sha == "a":
+ entered.set()
+ await release.wait()
+ if fail_first:
+ raise ApplicationError("Review unavailable", non_retryable=True)
+ return "report"
+
+ @activity.defn(name="review_resolution_running_activity")
+ async def resolution_running(inputs: ReviewPRWorkflowInputs) -> bool:
+ return False
+
+ async with await WorkflowEnvironment.start_time_skipping() as env:
+ queue = str(uuid.uuid4())
+ async with Worker(
+ env.client,
+ task_queue=queue,
+ workflows=[ReviewPRQueueWorkflow, ScheduledReviewStub],
+ activities=[record, resolution_running],
+ workflow_runner=UnsandboxedWorkflowRunner(),
+ ):
+ handle = await env.client.start_workflow(
+ ReviewPRQueueWorkflow.run,
+ ReviewPRQueueInputs(requests=[first]),
+ id=queue,
+ task_queue=queue,
+ id_conflict_policy=WorkflowIDConflictPolicy.USE_EXISTING,
+ start_signal="request_review",
+ start_signal_args=[first],
+ )
+ await asyncio.wait_for(entered.wait(), timeout=10)
+ for request in (
+ first,
+ replace(first, requested_head_sha="b"),
+ replace(first, requested_head_sha="c"),
+ replace(first, review_mode="full", trigger_source="ui", requested_head_sha="c"),
+ ):
+ await env.client.start_workflow(
+ ReviewPRQueueWorkflow.run,
+ ReviewPRQueueInputs(requests=[request]),
+ id=queue,
+ task_queue=queue,
+ id_conflict_policy=WorkflowIDConflictPolicy.USE_EXISTING,
+ start_signal="request_review",
+ start_signal_args=[request],
+ )
+ release.set()
+ assert await handle.result() == "report"
+
+ completed = [(review.review_mode, review.requested_head_sha) for review in reviews]
+ assert completed[-2:] == [("full", "c"), ("flash", "c")]
+ assert all(item == ("flash", "a") for item in completed[:-2])
+ assert len(completed) == (4 if fail_first else 3)
+
+
+async def test_automatic_review_waits_for_resolution_before_starting() -> None:
+ probes = 0
+ reviewed = False
+ request = ReviewPRWorkflowInputs(team_id=1, user_id=1, owner="o", repo="r", pr_number=7)
+
+ @activity.defn(name="review_resolution_running_activity")
+ async def resolution_running(inputs: ReviewPRWorkflowInputs) -> bool:
+ nonlocal probes
+ probes += 1
+ assert not reviewed
+ return probes == 1
+
+ @activity.defn(name="record_scheduled_review")
+ async def record(inputs: ReviewPRWorkflowInputs) -> str:
+ nonlocal reviewed
+ reviewed = True
+ return "report"
+
+ async with await WorkflowEnvironment.start_time_skipping() as env:
+ queue = str(uuid.uuid4())
+ async with Worker(
+ env.client,
+ task_queue=queue,
+ workflows=[ReviewPRQueueWorkflow, ScheduledReviewStub],
+ activities=[record, resolution_running],
+ workflow_runner=UnsandboxedWorkflowRunner(),
+ ):
+ assert (
+ await env.client.execute_workflow(
+ ReviewPRQueueWorkflow.run, ReviewPRQueueInputs(requests=[request]), id=queue, task_queue=queue
+ )
+ == "report"
+ )
+ assert reviewed
+ assert probes == 2
+
+
[email protected]("resolve_comments,expect_pending", [(False, False), (None, True)])
+def test_a_repeated_full_request_waits_when_it_changes_comment_resolution(
+ resolve_comments: bool | None, expect_pending: bool
+) -> None:
+ active = ReviewPRWorkflowInputs(
+ team_id=1,
+ user_id=1,
+ owner="PostHog",
+ repo="posthog",
+ pr_number=7,
+ review_mode="full",
+ trigger_source="ui",
+ requested_head_sha="a",
+ publish=True,
+ acting_user_id=1,
+ resolve_comments=False,
+ )
+ request = replace(active, resolve_comments=resolve_comments)
+ queue = ReviewRequestQueue(active=active)
+
+ queue.add(request)
+
+ assert queue.pending == ({"full": request} if expect_pending else {})
diff --git a/products/review_hog/backend/tests/test_reviews_api.py b/products/review_hog/backend/tests/test_reviews_api.py
index 67b90f86acc5..55a1217d52d7 100644
--- a/products/review_hog/backend/tests/test_reviews_api.py
+++ b/products/review_hog/backend/tests/test_reviews_api.py
@@ -19,6 +19,7 @@ from products.review_hog.backend.reviewer.artefact_content import (
ThreadVerdictArtefact,
ValidationVerdict,
)
+from products.review_hog.backend.reviewer.constants import DEFAULT_REVIEW_ARM
from products.review_hog.backend.reviewer.models.github_meta import PRFile, PRMetadata
from products.review_hog.backend.reviewer.models.issues_review import Issue, IssuePriority, IssuesReview, LineRange
from products.review_hog.backend.reviewer.models.perspective_selection import (
@@ -298,14 +299,14 @@ class TestRecentReviewsAPI(APIBaseTest):
report_id=report_id,
head_sha="old-sha",
results={(1, 1): _issues_review(9)},
- review_model="m",
+ review_arm=DEFAULT_REVIEW_ARM,
)
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",
+ review_arm=DEFAULT_REVIEW_ARM,
)
# A stale-head selection must not surface; the reviewed head's one aggregates to run/skipped.
persist_perspective_selection(
@@ -441,7 +442,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",
+ review_arm=DEFAULT_REVIEW_ARM,
)
# No persisted plan (a fallback run): the dense estimate — 2 chunks × (3 canonical
# perspectives + the blind-spot sweep) = 8 expected reads.
@@ -477,7 +478,7 @@ class TestRecentReviewsAPI(APIBaseTest):
report_id=running_id,
head_sha="sha1",
results={(1000, 0): _issues_review(0)},
- review_model="m",
+ review_arm=DEFAULT_REVIEW_ARM,
)
assert self.client.get(self.url).json()["results"][0]["progress"] == {
"review_stage": "deduplicating",
diff --git a/products/review_hog/backend/tests/test_settings_api.py b/products/review_hog/backend/tests/test_settings_api.py
index 76a0e36bbdf8..b6e04402ea52 100644
--- a/products/review_hog/backend/tests/test_settings_api.py
+++ b/products/review_hog/backend/tests/test_settings_api.py
@@ -1,9 +1,12 @@
from posthog.test.base import APIBaseTest
+from django.test import SimpleTestCase
+
from parameterized import parameterized
from posthog.models import Team, User
+from products.review_hog.backend.api.settings import ReviewUserSettingsSerializer
from products.review_hog.backend.models import ReviewUserSettings
from products.skills.backend.models.skills import LLMSkill
from products.stamphog.backend.facade.testing import seed_repo_config
@@ -28,6 +31,8 @@ class TestReviewUserSettingsAPI(APIBaseTest):
"stamphog_review_inbox_prs": False, # opt-in: a real approval must never be a default
"review_labeled_prs": True,
"resolve_comments": True,
+ "review_authored_prs": False,
+ "flash_reasoning_effort": "medium",
"urgency_threshold": "consider",
"can_trigger_reviews": False, # REVIEWHOG_TEAM_IDS is empty in tests
"stamphog_connected": False, # no synced+enabled repo config in this project
@@ -39,7 +44,13 @@ class TestReviewUserSettingsAPI(APIBaseTest):
# stops accepting it (e.g. marked read-only) would silently no-op the switch.
res = self.client.patch(
self.url,
- {"urgency_threshold": "must_fix", "stamphog_review_inbox_prs": True, "resolve_comments": False},
+ {
+ "urgency_threshold": "must_fix",
+ "stamphog_review_inbox_prs": True,
+ "resolve_comments": False,
+ "review_authored_prs": True,
+ "flash_reasoning_effort": "xhigh",
+ },
format="json",
)
@@ -49,8 +60,17 @@ class TestReviewUserSettingsAPI(APIBaseTest):
assert row.urgency_threshold == "must_fix"
assert row.stamphog_review_inbox_prs is True
assert row.resolve_comments is False
+ assert row.review_authored_prs is True
+ assert row.flash_reasoning_effort == "xhigh"
assert row.review_labeled_prs is True # untouched field keeps its default
+ disabled = self.client.patch(self.url, {"review_authored_prs": False}, format="json")
+
+ assert disabled.status_code == 200
+ disabled_row = ReviewUserSettings.objects.for_team(self.team.id).get(user_id=self.user.id)
+ assert disabled_row.review_authored_prs is False
+ assert disabled_row.flash_reasoning_effort == "xhigh"
+
@parameterized.expand(
[
# (name, enabled, installation_id, connected_by_user_id, expected) — "connected" must mean
@@ -85,13 +105,19 @@ class TestReviewUserSettingsAPI(APIBaseTest):
def test_settings_are_per_user(self) -> None:
# One user's opt-out must not leak into a teammate's row — the gate reads the PR author's.
other = User.objects.create_and_join(self.organization, "[email protected]", None)
- self.client.patch(self.url, {"review_labeled_prs": False}, format="json")
+ self.client.patch(
+ self.url,
+ {"review_labeled_prs": False, "review_authored_prs": True, "flash_reasoning_effort": "xhigh"},
+ format="json",
+ )
self.client.force_login(other)
res = self.client.get(self.url)
assert res.status_code == 200
assert res.json()["review_labeled_prs"] is True
+ assert res.json()["review_authored_prs"] is False
+ assert res.json()["flash_reasoning_effort"] == "medium"
def test_get_seeds_the_authoring_skill_idempotently(self) -> None:
# The settings GET is the tab's always-called endpoint, so it must make the authoring guide
@@ -119,3 +145,12 @@ class TestReviewUserSettingsAPI(APIBaseTest):
row = ReviewUserSettings.objects.for_team(self.team.id).get(user_id=self.user.id)
assert row.team_id == self.team.id
assert row.urgency_threshold == "must_fix"
+
+
+class TestReviewUserSettingsValidation(SimpleTestCase):
+ @parameterized.expand(["low", "high"])
+ def test_flash_effort_rejects_values_outside_its_supported_choices(self, effort: str) -> None:
+ serializer = ReviewUserSettingsSerializer(data={"flash_reasoning_effort": effort}, partial=True)
+
+ assert not serializer.is_valid()
+ assert "flash_reasoning_effort" in serializer.errors
diff --git a/products/review_hog/backend/tests/test_settings_toggle_commands.py b/products/review_hog/backend/tests/test_settings_toggle_commands.py
index c7236916bec3..cc415688b7ba 100644
--- a/products/review_hog/backend/tests/test_settings_toggle_commands.py
+++ b/products/review_hog/backend/tests/test_settings_toggle_commands.py
@@ -1,3 +1,5 @@
+from io import StringIO
+
from posthog.test.base import BaseTest
from django.core.management import call_command
@@ -13,7 +15,13 @@ from products.review_hog.backend.settings_toggles import ToggleField, toggle_def
REVIEWHOG: ToggleField = "review_inbox_prs"
STAMPHOG: ToggleField = "stamphog_review_inbox_prs"
RESOLVE: ToggleField = "resolve_comments"
-OTHER_FIELD: dict[ToggleField, ToggleField] = {REVIEWHOG: STAMPHOG, STAMPHOG: REVIEWHOG, RESOLVE: REVIEWHOG}
+AUTHORED: ToggleField = "review_authored_prs"
+OTHER_FIELD: dict[ToggleField, ToggleField] = {
+ REVIEWHOG: STAMPHOG,
+ STAMPHOG: REVIEWHOG,
+ RESOLVE: REVIEWHOG,
+ AUTHORED: REVIEWHOG,
+}
COMMANDS = [
("enable_inbox_reviews", REVIEWHOG, True),
("disable_inbox_reviews", REVIEWHOG, False),
@@ -21,6 +29,8 @@ COMMANDS = [
("disable_stamphog_inbox_reviews", STAMPHOG, False),
("enable_comment_resolution", RESOLVE, True),
("disable_comment_resolution", RESOLVE, False),
+ ("enable_authored_pr_reviews", AUTHORED, True),
+ ("disable_authored_pr_reviews", AUTHORED, False),
]
@@ -43,6 +53,7 @@ class TestSettingsToggleCommands(BaseTest):
**{field: not enabled, OTHER_FIELD[field]: not enabled},
urgency_threshold=ReviewUserSettings.UrgencyThreshold.MUST_FIX,
+ flash_reasoning_effort=ReviewUserSettings.FlashReasoningEffort.XHIGH,
)
inactive_member = self._member("[email protected]", **{field: not enabled})
inactive_member.is_active = False
@@ -57,6 +68,7 @@ class TestSettingsToggleCommands(BaseTest):
assert getattr(opposite_row, field) is enabled
assert getattr(opposite_row, OTHER_FIELD[field]) is not enabled
assert opposite_row.urgency_threshold == ReviewUserSettings.UrgencyThreshold.MUST_FIX
+ assert opposite_row.flash_reasoning_effort == "xhigh"
if enabled is not toggle_default(field):
for member in (self.user, member_without_row):
row = self._row(member)
@@ -72,16 +84,23 @@ class TestSettingsToggleCommands(BaseTest):
assert getattr(inactive_row, field) is not enabled
assert self._row(outsider) is None
- @parameterized.expand([("enable_inbox_reviews", True), ("disable_inbox_reviews", False)])
- def test_user_ids_change_only_those_users(self, command: str, enabled: bool) -> None:
- target = self._member("[email protected]", review_inbox_prs=not enabled)
- untouched = self._member("[email protected]", review_inbox_prs=not enabled)
+ @parameterized.expand(
+ [
+ ("enable_inbox_reviews", REVIEWHOG, True),
+ ("disable_inbox_reviews", REVIEWHOG, False),
+ ("enable_authored_pr_reviews", AUTHORED, True),
+ ("disable_authored_pr_reviews", AUTHORED, False),
+ ]
+ )
+ def test_user_ids_change_only_those_users(self, command: str, field: ToggleField, enabled: bool) -> None:
+ target = self._member("[email protected]", **{field: not enabled})
+ untouched = self._member("[email protected]", **{field: not enabled})
call_command(command, team_id=self.team.id, user_ids=[target.id])
target_row, untouched_row = self._row(target), self._row(untouched)
- assert target_row is not None and target_row.review_inbox_prs is enabled
- assert untouched_row is not None and untouched_row.review_inbox_prs is not enabled
+ assert target_row is not None and getattr(target_row, field) is enabled
+ assert untouched_row is not None and getattr(untouched_row, field) is not enabled
assert self._row(self.user) is None
def test_user_ids_outside_the_org_fail_before_writing(self) -> None:
@@ -106,3 +125,48 @@ class TestSettingsToggleCommands(BaseTest):
row = self._row(member)
assert row is not None and row.review_inbox_prs is not enabled
assert self._row(self.user) is None
+
+ @parameterized.expand(["medium", "xhigh"])
+ def test_authored_opt_in_sets_effort_for_new_and_already_enabled_users(self, effort: str) -> None:
+ opposite_effort = "xhigh" if effort == "medium" else "medium"
+ opted_in = self._member(
+ "[email protected]", review_authored_prs=True, flash_reasoning_effort=opposite_effort
+ )
+ untouched = self._member(
+ "[email protected]", review_authored_prs=True, flash_reasoning_effort=opposite_effort
+ )
+
+ call_command(
+ "enable_authored_pr_reviews", team_id=self.team.id, user_ids=[self.user.id, opted_in.id], effort=effort
+ )
+
+ for user in (self.user, opted_in):
+ row = self._row(user)
+ assert row is not None and row.review_authored_prs is True
+ assert row.flash_reasoning_effort == effort
+ untouched_row = self._row(untouched)
+ assert untouched_row is not None and untouched_row.flash_reasoning_effort == opposite_effort
+
+ def test_authored_effort_dry_run_includes_already_enabled_users_without_writing(self) -> None:
+ opted_in = self._member("[email protected]", review_authored_prs=True)
+ output = StringIO()
+
+ call_command(
+ "enable_authored_pr_reviews",
+ team_id=self.team.id,
+ user_ids=[opted_in.id],
+ effort="xhigh",
+ dry_run=True,
+ stdout=output,
+ )
+
+ row = self._row(opted_in)
+ assert row is not None and row.flash_reasoning_effort == "medium"
+ assert f"Would change user id(s): {opted_in.id}" in output.getvalue()
+ assert "flash_reasoning_effort: xhigh" in output.getvalue()
+
+ def test_authored_invalid_effort_fails_before_writing(self) -> None:
+ with self.assertRaises(CommandError):
+ call_command("enable_authored_pr_reviews", team_id=self.team.id, effort="high")
+
+ assert self._row(self.user) is None
diff --git a/products/review_hog/backend/tests/test_temporal_workflow.py b/products/review_hog/backend/tests/test_temporal_workflow.py
index 0d9b97a6f86b..6e0a19ac7b8b 100644
--- a/products/review_hog/backend/tests/test_temporal_workflow.py
+++ b/products/review_hog/backend/tests/test_temporal_workflow.py
@@ -116,6 +116,10 @@ async def _run_full_review_pr_workflow(
resolve_comments_setting: bool = False,
input_resolve_comments: bool | None = None,
review_mode: str = "full",
+ flash_reasoning_effort: str = "medium",
+ review_authored_prs: bool = False,
+ already_completed: bool = False,
+ pr_open: bool = True,
) -> 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
@@ -150,6 +154,7 @@ async def _run_full_review_pr_workflow(
# 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]] = {}
+ effort_calls: dict[str, set[str]] = {}
def _saw_mode(stage: str, mode: str) -> None:
mode_calls.setdefault(stage, set()).add(mode)
@@ -174,6 +179,8 @@ async def _run_full_review_pr_workflow(
pr_number=meta_pr_number,
pr_url="u" if meta_pr_number is not None else None,
empty_diff=empty_diff,
+ already_completed=already_completed,
+ pr_open=pr_open,
)
@activity.defn(name="resolve_acting_user_activity")
@@ -187,6 +194,8 @@ async def _run_full_review_pr_workflow(
review_inbox_prs=review_inbox_prs,
resolved_from="override",
resolve_comments=resolve_comments_setting,
+ flash_reasoning_effort=flash_reasoning_effort,
+ review_authored_prs=review_authored_prs,
)
@activity.defn(name="sync_review_skills_activity")
@@ -227,6 +236,7 @@ async def _run_full_review_pr_workflow(
@activity.defn(name="review_chunk_activity")
async def review(input: ReviewChunkInput) -> bool:
+ effort_calls.setdefault("review", set()).add(input.flash_reasoning_effort)
_saw_mode("review", input.review_mode)
review_calls.append(
(
@@ -255,6 +265,7 @@ async def _run_full_review_pr_workflow(
@activity.defn(name="validate_chunk_activity")
async def validate_chunk(input: ValidateChunkInput) -> ValidateChunkResult:
+ effort_calls.setdefault("validate", set()).add(input.flash_reasoning_effort)
_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))
@@ -310,12 +321,14 @@ async def _run_full_review_pr_workflow(
@activity.defn(name="track_review_completed_activity")
async def track_completed(input: TrackReviewCompletedInput) -> None:
+ effort_calls.setdefault("track", set()).add(input.flash_reasoning_effort)
_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:
+ effort_calls.setdefault("track", set()).add(input.flash_reasoning_effort)
_saw_mode("track", input.review_mode)
track_started_calls.append((input.run_index, input.turn_trigger_source))
return None
@@ -412,6 +425,7 @@ async def _run_full_review_pr_workflow(
"track_started": track_started_calls,
"resolve_dispatches": list(StubResolvePRWorkflow.dispatches),
"modes": mode_calls,
+ "efforts": effort_calls,
}
@@ -555,19 +569,45 @@ async def test_review_pr_workflow_chains_resolution_per_setting_and_override(
@pytest.mark.asyncio
-async def test_review_pr_workflow_flash_turn_threads_its_mode_and_never_chains_resolution():
[email protected]("effort", ["medium", "xhigh"])
+async def test_review_pr_workflow_flash_turn_threads_its_mode_and_never_chains_resolution(effort: str):
# 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"
+ publish=True,
+ resolve_comments_setting=True,
+ input_resolve_comments=True,
+ review_mode="flash",
+ flash_reasoning_effort=effort,
)
assert recorded["publish"] == [7]
assert recorded["resolve_dispatches"] == []
assert recorded["modes"] == {
stage: {"flash"} for stage in ("fetch", "select", "review", "validate", "publish", "status", "track")
}
+ assert recorded["efforts"] == {stage: {effort} for stage in ("review", "validate", "track")}
+
+
+ "enabled,completed,pr_open,expected_review",
+ [(True, False, True, True), (False, False, True, False), (True, True, True, False), (True, False, False, False)],
+)
+async def test_automatic_reviews_recheck_consent_and_skip_completed_or_closed_prs(
+ enabled: bool, completed: bool, pr_open: bool, expected_review: bool
+) -> None:
+ recorded = await _run_full_review_pr_workflow(
+ publish=True,
+ trigger_source="automatic",
+ review_mode="flash",
+ review_authored_prs=enabled,
+ already_completed=completed,
+ pr_open=pr_open,
+ )
+ assert bool(recorded["review"]) is expected_review
+ assert bool(recorded["publish"]) is expected_review
@pytest.mark.asyncio
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 73947cf9f25d..9ab52fbf5b22 100644
--- a/products/review_hog/backend/tests/test_ui_trigger_api.py
+++ b/products/review_hog/backend/tests/test_ui_trigger_api.py
@@ -68,6 +68,7 @@ class TestReviewHogUiTriggerApi(APIBaseTest):
# None = the requester's resolve_comments setting decides whether resolution chains.
resolve_comments=None,
review_mode="full",
+ requested_head_sha="abc123",
)
@parameterized.expand(
@@ -289,15 +290,25 @@ class TestReviewHogUiTriggerApi(APIBaseTest):
# Published at the PR's current head: honesty response, no run. The row's lowercased
# repository pins the cross-trigger casing match (__iexact) — other triggers store the
# casing they were called with.
- ("already_reviewed_at_head", "abc123", status.HTTP_200_OK, "already_reviewed", False),
- ("head_advanced_since_publish", "older-sha", status.HTTP_202_ACCEPTED, "started", True),
+ ("already_reviewed_at_head", "abc123", None, status.HTTP_200_OK, "already_reviewed", False),
+ ("head_advanced_since_publish", "older-sha", None, status.HTTP_202_ACCEPTED, "started", True),
+ ("full_after_flash", "abc123", {"flash": "abc123"}, status.HTTP_202_ACCEPTED, "started", True),
]
)
@patch(_META, return_value=_pr_meta(head_sha="abc123"))
@patch(_ACCESS, return_value=object())
@patch(_START, return_value="wf-ui-2")
def test_already_published_head_answers_honestly(
- self, _name, published_head_sha, expected_status, expected_marker, starts, mock_start, _mock_access, _mock_meta
+ self,
+ _name,
+ published_head_sha,
+ published_modes,
+ expected_status,
+ expected_marker,
+ starts,
+ mock_start,
+ _mock_access,
+ _mock_meta,
):
ReviewReport.objects.for_team(self.team.id).create(
team_id=self.team.id,
@@ -307,6 +318,7 @@ class TestReviewHogUiTriggerApi(APIBaseTest):
head_branch="feat-branch",
base_branch="master",
published_head_sha=published_head_sha,
+ published_heads_by_mode=published_modes,
)
with override_settings(REVIEWHOG_TEAM_IDS=[self.team.id]):
resp = self._trigger("https://github.com/PostHog/posthog.com/pull/123")
diff --git a/products/review_hog/backend/tests/test_validate_activity.py b/products/review_hog/backend/tests/test_validate_activity.py
index fea34335bc5f..aafea3a112e3 100644
--- a/products/review_hog/backend/tests/test_validate_activity.py
+++ b/products/review_hog/backend/tests/test_validate_activity.py
@@ -21,6 +21,7 @@ from products.review_hog.backend.reviewer.models.issue_validation import IssueVa
from products.review_hog.backend.reviewer.models.issues_review import Issue, IssuePriority, LineRange
from products.review_hog.backend.reviewer.models.split_pr_into_chunks import Chunk, ChunksList, FileInfo
from products.review_hog.backend.temporal.activities import ValidateChunkInput, validate_chunk_activity
+from products.tasks.backend.facade.run_config import ReasoningEffort
_MODULE = "products.review_hog.backend.temporal.activities"
_CHUNK_ID = 3
@@ -188,14 +189,22 @@ async def test_session_open_failure_raises_even_on_the_final_attempt() -> None:
@pytest.mark.parametrize(
- "review_mode,expected",
+ "review_mode,effort,expected",
[
- pytest.param(REVIEW_MODE_FULL, DEFAULT_VALIDATION_ARM, id="full"),
- pytest.param(REVIEW_MODE_FLASH, FLASH_ARM, id="flash"),
+ pytest.param(REVIEW_MODE_FULL, ReasoningEffort.MEDIUM, DEFAULT_VALIDATION_ARM, id="full"),
+ pytest.param(REVIEW_MODE_FLASH, ReasoningEffort.MEDIUM, FLASH_ARM, id="flash-medium"),
+ pytest.param(
+ REVIEW_MODE_FLASH,
+ ReasoningEffort.XHIGH,
+ dataclasses.replace(FLASH_ARM, reasoning_effort=ReasoningEffort.XHIGH),
+ id="flash-xhigh",
+ ),
],
)
@pytest.mark.asyncio
-async def test_validation_session_opens_on_the_modes_arm(review_mode: str, expected: ReviewArm) -> None:
+async def test_validation_session_opens_on_the_modes_arm(
+ review_mode: str, effort: ReasoningEffort, 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.
@@ -207,7 +216,10 @@ async def test_validation_session_opens_on_the_modes_arm(review_mode: str, expec
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))
+ result = await _env(attempt=1).run(
+ validate_chunk_activity,
+ dataclasses.replace(_input([issue], review_mode=review_mode), flash_reasoning_effort=effort.value),
+ )
assert result.validated_count == 1
kwargs = mock_start.call_args.kwargs
diff --git a/products/review_hog/backend/webhook_consumers.py b/products/review_hog/backend/webhook_consumers.py
new file mode 100644
index 000000000000..7a98b5fe3b16
--- /dev/null
+++ b/products/review_hog/backend/webhook_consumers.py
@@ -0,0 +1,20 @@
+from posthog.ingress.contracts import WebhookConsumer, WebhookDelivery
+
+
+def _enqueue_authored_review(delivery: WebhookDelivery) -> None:
+ from products.review_hog.backend.facade.github import ( # noqa: PLC0415 - keeps product models off the registry import path
+ enqueue_authored_pr_review,
+ )
+
+ enqueue_authored_pr_review(delivery.payload)
+
+
+WEBHOOK_CONSUMERS = (
+ WebhookConsumer(
+ name="review_hog_authored_prs",
+ provider="github",
+ app="posthog",
+ event_types=frozenset({"pull_request"}),
+ handler=_enqueue_authored_review,
+ ),
+)
diff --git a/products/review_hog/frontend/CodeReviewScene.stories.tsx b/products/review_hog/frontend/CodeReviewScene.stories.tsx
new file mode 100644
index 000000000000..f7001c504b19
--- /dev/null
+++ b/products/review_hog/frontend/CodeReviewScene.stories.tsx
@@ -0,0 +1,74 @@
+import { Meta, StoryObj } from '@storybook/react'
+
+import { FEATURE_FLAGS } from 'lib/constants'
+
+import { mswDecorator } from '~/mocks/browser'
+
+import type {
+ PatchedReviewUserSettingsApi,
+ ReviewUserSettingsApi,
+} from 'products/review_hog/frontend/generated/api.schemas'
+
+import { CodeReviewScene } from './CodeReviewScene'
+
+const defaultSettings: ReviewUserSettingsApi = {
+ review_inbox_prs: false,
+ stamphog_review_inbox_prs: false,
+ review_labeled_prs: true,
+ resolve_comments: true,
+ review_authored_prs: false,
+ flash_reasoning_effort: 'medium',
+ urgency_threshold: 'consider',
+ can_trigger_reviews: true,
+ stamphog_connected: true,
+}
+
+const meta: Meta<typeof CodeReviewScene> = {
+ component: CodeReviewScene,
+ title: 'Scenes/Code review',
+ parameters: {
+ layout: 'fullscreen',
+ featureFlags: [FEATURE_FLAGS.REVIEW_HOG],
+ },
+ decorators: [
+ (Story, context): JSX.Element => {
+ let settings = { ...defaultSettings }
+ return mswDecorator({
+ get: {
+ '/api/projects/:team_id/review_hog/settings/': () => [200, settings],
+ '/api/projects/:team_id/review_hog/reviews/': { results: [], has_more: false },
+ '/api/projects/:team_id/review_hog/reviews/perspective_stats/': {
+ report_count: 0,
+ perspectives: [],
+ },
+ '/api/projects/:team_id/review_hog/perspectives/': [],
+ '/api/projects/:team_id/review_hog/blind_spots/': [],
+ '/api/projects/:team_id/review_hog/validators/': [],
+ '/api/projects/:team_id/review_hog/resolution/': [],
+ },
+ patch: {
+ '/api/projects/:team_id/review_hog/settings/': async ({ request }) => {
+ const update = (await request.json()) as PatchedReviewUserSettingsApi
+ settings = { ...settings, ...update }
+ return [200, settings]
+ },
+ },
+ })(Story, context)
+ },
+ ],
+}
+export default meta
+
+type Story = StoryObj<typeof CodeReviewScene>
+
+export const Default: Story = {}
+
+export const Narrow: Story = {
+ decorators: [
+ (Story): JSX.Element => (
+ <div className="max-w-130">
+ <Story />
+ </div>
+ ),
+ ],
+}
diff --git a/products/review_hog/frontend/CodeReviewScene.tsx b/products/review_hog/frontend/CodeReviewScene.tsx
index f7f3bb68ea80..e582546fb309 100644
--- a/products/review_hog/frontend/CodeReviewScene.tsx
+++ b/products/review_hog/frontend/CodeReviewScene.tsx
@@ -2,6 +2,7 @@ import { useActions, useValues } from 'kea'
import {
IconBalance,
+ IconBolt,
IconChat,
IconChevronDown,
IconDirectedGraph,
@@ -20,6 +21,7 @@ import {
LemonButton,
LemonInput,
LemonSegmentedButton,
+ LemonSelect,
LemonSkeleton,
LemonSlider,
LemonSwitch,
@@ -54,6 +56,7 @@ import type {
ReviewPerspectiveStatItemApi,
ReviewRecentReviewApi,
ReviewResolutionStatusApi,
+ ReviewUserSettingsFlashReasoningEffortEnumApi,
ReviewUserSettingsUrgencyThresholdEnumApi,
} from 'products/review_hog/frontend/generated/api.schemas'
import {
@@ -1241,6 +1244,54 @@ function TriggersSection(): JSX.Element {
/>
</div>
</LemonCard>
+ <div className="mt-2">
+ <h4 className="mb-1 text-sm font-semibold">ReviewHog Flash - Experimental</h4>
+ <p className="m-0 text-xs text-secondary">These settings apply only to Flash reviews.</p>
+ </div>
+ <LemonCard hoverEffect={false} className="divide-y divide-primary p-0">
+ <div className="flex items-center gap-4 p-4">
+ <div className="flex size-9 shrink-0 items-center justify-center rounded border border-primary bg-primary">
+ <IconBolt className="size-5" />
+ </div>
+ <div className="min-w-0 flex-1">
+ <div className="text-sm font-semibold">Review all your PRs in Flash mode</div>
+ <div className="text-xs text-secondary">
+ Automatically review PRs you author in PostHog/posthog, including drafts and new commits.
+ Starts with future PR activity.
+ </div>
+ </div>
+ <LemonSwitch
+ aria-label="Review all your PRs in Flash mode"
+ checked={settings?.review_authored_prs ?? false}
+ onChange={(checked) => updateSettings({ review_authored_prs: checked })}
+ disabledReason={switchDisabledReason}
+ loading={settingsLoading}
+ />
+ </div>
+ <div className="flex items-center gap-4 p-4">
+ <div className="flex size-9 shrink-0 items-center justify-center rounded border border-primary bg-primary">
+ <IconBalance className="size-5" />
+ </div>
+ <div className="min-w-0 flex-1">
+ <div className="text-sm font-semibold">Flash strength</div>
+ <div className="text-xs text-secondary">
+ Applies to automatic and manually requested Flash reviews. Extra high takes longer and costs
+ more.
+ </div>
+ </div>
+ <LemonSelect<ReviewUserSettingsFlashReasoningEffortEnumApi>
+ aria-label="Flash strength"
+ value={settings?.flash_reasoning_effort ?? 'medium'}
+ options={[
+ { value: 'medium', label: 'Medium' },
+ { value: 'xhigh', label: 'Extra high' },
+ ]}
+ onChange={(value) => updateSettings({ flash_reasoning_effort: value })}
+ disabledReason={switchDisabledReason}
+ loading={settingsLoading}
+ />
+ </div>
+ </LemonCard>
</section>
)
}
diff --git a/products/review_hog/frontend/generated/api.schemas.ts b/products/review_hog/frontend/generated/api.schemas.ts
index aa2e6612642b..85dde6c2d7eb 100644
--- a/products/review_hog/frontend/generated/api.schemas.ts
+++ b/products/review_hog/frontend/generated/api.schemas.ts
@@ -500,7 +500,7 @@ export interface ReviewTriggerRequestApi {
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 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). */
+ /** Run lifecycle marker: 'started' when the review was queued, 'already_reviewed' when the pull request's current commit already has a published review in the requested mode, 'joined_running_review' when a review was already in flight and the request joined its queue. A requested Full review waits for an active Flash review. */
status: string
}
@@ -509,6 +509,18 @@ export interface ReviewTriggerErrorApi {
error: string
}
+/**
+ * * `medium` - Medium
+ * * `xhigh` - Extra high
+ */
+export type ReviewUserSettingsFlashReasoningEffortEnumApi =
+ (typeof ReviewUserSettingsFlashReasoningEffortEnumApi)[keyof typeof ReviewUserSettingsFlashReasoningEffortEnumApi]
+
+export const ReviewUserSettingsFlashReasoningEffortEnumApi = {
+ Medium: 'medium',
+ Xhigh: 'xhigh',
+} as const
+
/**
* * `consider` - Consider
* * `should_fix` - Should Fix
@@ -532,6 +544,13 @@ export interface ReviewUserSettingsApi {
review_labeled_prs?: boolean
/** After a review of the user's pull requests is published, run the resolution stage: triage the PR's unresolved review threads, implement the worth-and-safe fixes on the PR branch, and reply on every thread. On by default; turning it off makes reviews stop at publishing. */
resolve_comments?: boolean
+ /** Automatically review pull requests authored by this user in PostHog/posthog in Flash mode. Off by default. Flash reviews post findings without resolving comments. */
+ review_authored_prs?: boolean
+ /** Reasoning effort for this user's automatic and manually requested Flash reviews: 'medium' (default) or 'xhigh'. Applies to both review and validation. Saved independently of the automatic-review toggle.
+ *
+ * * `medium` - Medium
+ * * `xhigh` - Extra high */
+ flash_reasoning_effort?: ReviewUserSettingsFlashReasoningEffortEnumApi
/** Minimum priority a validated finding needs to be published: 'consider' (default) publishes everything, 'should_fix' drops consider-level findings, 'must_fix' publishes only blocking issues.
*
* * `consider` - Consider
@@ -553,6 +572,13 @@ export interface PatchedReviewUserSettingsApi {
review_labeled_prs?: boolean
/** After a review of the user's pull requests is published, run the resolution stage: triage the PR's unresolved review threads, implement the worth-and-safe fixes on the PR branch, and reply on every thread. On by default; turning it off makes reviews stop at publishing. */
resolve_comments?: boolean
+ /** Automatically review pull requests authored by this user in PostHog/posthog in Flash mode. Off by default. Flash reviews post findings without resolving comments. */
+ review_authored_prs?: boolean
+ /** Reasoning effort for this user's automatic and manually requested Flash reviews: 'medium' (default) or 'xhigh'. Applies to both review and validation. Saved independently of the automatic-review toggle.
+ *
+ * * `medium` - Medium
+ * * `xhigh` - Extra high */
+ flash_reasoning_effort?: ReviewUserSettingsFlashReasoningEffortEnumApi
/** Minimum priority a validated finding needs to be published: 'consider' (default) publishes everything, 'should_fix' drops consider-level findings, 'must_fix' publishes only blocking issues.
*
* * `consider` - Consider
diff --git a/products/review_hog/frontend/generated/api.zod.ts b/products/review_hog/frontend/generated/api.zod.ts
index f24067ba342d..7f4edcb93131 100644
--- a/products/review_hog/frontend/generated/api.zod.ts
+++ b/products/review_hog/frontend/generated/api.zod.ts
@@ -98,6 +98,19 @@ export const ReviewHogSettingsPartialUpdateBody = /* @__PURE__ */ zod.object({
.describe(
"After a review of the user's pull requests is published, run the resolution stage: triage the PR's unresolved review threads, implement the worth-and-safe fixes on the PR branch, and reply on every thread. On by default; turning it off makes reviews stop at publishing."
),
+ review_authored_prs: zod
+ .boolean()
+ .optional()
+ .describe(
+ 'Automatically review pull requests authored by this user in PostHog\/posthog in Flash mode. Off by default. Flash reviews post findings without resolving comments.'
+ ),
+ flash_reasoning_effort: zod
+ .enum(['medium', 'xhigh'])
+ .describe('\* `medium` - Medium\n\* `xhigh` - Extra high')
+ .optional()
+ .describe(
+ "Reasoning effort for this user's automatic and manually requested Flash reviews: 'medium' (default) or 'xhigh'. Applies to both review and validation. Saved independently of the automatic-review toggle.\n\n\* `medium` - Medium\n\* `xhigh` - Extra high"
+ ),
urgency_threshold: zod
.enum(['consider', 'should_fix', 'must_fix'])
.describe('\* `consider` - Consider\n\* `should_fix` - Should Fix\n\* `must_fix` - Must Fix')
diff --git a/products/review_hog/frontend/reviewHogSettingsLogic.test.ts b/products/review_hog/frontend/reviewHogSettingsLogic.test.ts
index 87396c3a326f..97b0a5006506 100644
--- a/products/review_hog/frontend/reviewHogSettingsLogic.test.ts
+++ b/products/review_hog/frontend/reviewHogSettingsLogic.test.ts
@@ -229,7 +229,6 @@ describe('reviewHogSettingsLogic', () => {
])
logic.actions.setTriggerPrUrl('https://github.com/PostHog/posthog.com/pull/1')
- // Arming the watch here would poll for two minutes waiting for a run that never starts.
await expectLogic(logic, () => logic.actions.submitTriggerReview())
.toDispatchActions(['submitTriggerReview', 'loadRecentReviews', 'submitTriggerReviewFinished'])
.toNotHaveDispatchedActions(['startTriggeredReviewWatch'])
diff --git a/products/review_hog/frontend/reviewHogSettingsLogic.ts b/products/review_hog/frontend/reviewHogSettingsLogic.ts
index 4c25a0b73acb..2177017f7fee 100644
--- a/products/review_hog/frontend/reviewHogSettingsLogic.ts
+++ b/products/review_hog/frontend/reviewHogSettingsLogic.ts
@@ -1450,8 +1450,7 @@ export const reviewHogSettingsLogic = kea<reviewHogSettingsLogicType>([
'This pull request was already reviewed at its current commit. Find it under recent reviews.'
)
} 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. Find it under recent reviews.')
+ lemonToast.info('Your request joined the review queue. 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/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 60e9752048f6..7a85eabf827c 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -73627,6 +73627,18 @@ export namespace Schemas {
active?: boolean;
}
+ /**
+ * * `medium` - Medium
+ * * `xhigh` - Extra high
+ */
+ export type ReviewUserSettingsFlashReasoningEffortEnum = typeof ReviewUserSettingsFlashReasoningEffortEnum[keyof typeof ReviewUserSettingsFlashReasoningEffortEnum];
+
+
+ export const ReviewUserSettingsFlashReasoningEffortEnum = {
+ Medium: 'medium',
+ Xhigh: 'xhigh',
+ } as const;
+
/**
* * `consider` - Consider
* * `should_fix` - Should Fix
@@ -73650,6 +73662,13 @@ export namespace Schemas {
review_labeled_prs?: boolean;
/** After a review of the user's pull requests is published, run the resolution stage: triage the PR's unresolved review threads, implement the worth-and-safe fixes on the PR branch, and reply on every thread. On by default; turning it off makes reviews stop at publishing. */
resolve_comments?: boolean;
+ /** Automatically review pull requests authored by this user in PostHog/posthog in Flash mode. Off by default. Flash reviews post findings without resolving comments. */
+ review_authored_prs?: boolean;
+ /** Reasoning effort for this user's automatic and manually requested Flash reviews: 'medium' (default) or 'xhigh'. Applies to both review and validation. Saved independently of the automatic-review toggle.
+ *
+ * * `medium` - Medium
+ * * `xhigh` - Extra high */
+ flash_reasoning_effort?: ReviewUserSettingsFlashReasoningEffortEnum;
/** Minimum priority a validated finding needs to be published: 'consider' (default) publishes everything, 'should_fix' drops consider-level findings, 'must_fix' publishes only blocking issues.
*
* * `consider` - Consider
@@ -84514,7 +84533,7 @@ export namespace Schemas {
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 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). */
+ /** Run lifecycle marker: 'started' when the review was queued, 'already_reviewed' when the pull request's current commit already has a published review in the requested mode, 'joined_running_review' when a review was already in flight and the request joined its queue. A requested Full review waits for an active Flash review. */
status: string;
}
@@ -84527,6 +84546,13 @@ export namespace Schemas {
review_labeled_prs?: boolean;
/** After a review of the user's pull requests is published, run the resolution stage: triage the PR's unresolved review threads, implement the worth-and-safe fixes on the PR branch, and reply on every thread. On by default; turning it off makes reviews stop at publishing. */
resolve_comments?: boolean;
+ /** Automatically review pull requests authored by this user in PostHog/posthog in Flash mode. Off by default. Flash reviews post findings without resolving comments. */
+ review_authored_prs?: boolean;
+ /** Reasoning effort for this user's automatic and manually requested Flash reviews: 'medium' (default) or 'xhigh'. Applies to both review and validation. Saved independently of the automatic-review toggle.
+ *
+ * * `medium` - Medium
+ * * `xhigh` - Extra high */
+ flash_reasoning_effort?: ReviewUserSettingsFlashReasoningEffortEnum;
/** Minimum priority a validated finding needs to be published: 'consider' (default) publishes everything, 'should_fix' drops consider-level findings, 'must_fix' publishes only blocking issues.
*
* * `consider` - Consider