: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(review-hog): review a draft once and again when it is ready (#116819)
Julian Bez34d56199d17a
diff --git a/products/review_hog/ARCHITECTURE.md b/products/review_hog/ARCHITECTURE.mdindex a291da48a674..6c6d56e0b4f9 100644--- a/products/review_hog/ARCHITECTURE.md+++ b/products/review_hog/ARCHITECTURE.md@@ -56,7 +56,7 @@ in flight, with the detail in DECISIONS.md.## Status & nextReviewHog runs end-to-end: label / UI / inbox / automatic authored-PR triggers → the Temporal pipeline → published PR review.-Automatic Standard reviews run on new PRs and pushes, including drafts unless the owner turns them off, but never on PRs with the `skip-agent-review` label, in every repository a project reviews, for the authors that the project rule, the repository exceptions, and each person's own choices select (`backend/automatic_review_rules.py`).+Automatic Standard reviews run on new PRs and pushes, including drafts unless the owner turns them off (a draft gets one review, and the next one runs when it is marked ready), but never on PRs with the `skip-agent-review` label, in every repository a project reviews, for the authors that the project rule, the repository exceptions, and each person's own choices select (`backend/automatic_review_rules.py`).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).@@ -911,6 +911,7 @@ whoever controls the run, the sandbox agent included), **MCP tools**The automatic trigger consumes signed GitHub `pull_request` deliveries through `review_hog_authored_prs` and queues a Celery task for the ownership, identity, and rule checks.It accepts `opened`, `synchronize`, and `ready_for_review` for open PRs whose head and base belong to the delivery's repository, including drafts.A draft is skipped (`draft_skipped`) when the PR owner turned `review_drafts` off. Its first automatic review then comes from `ready_for_review`, and `automatic_reviewed_head_sha` keeps a head that was already reviewed as a draft from a second review.+A draft that is reviewed gets its first automatic review only: the push gate's `draft` rule skips the later pushes, and `ready_for_review` reviews everything since the last reviewed head, also when the author marks it ready without a push.A PR with the `skip-agent-review` label gets no automatic review (`label_skipped`). The task checks the payload labels, and the turn checks the labels its fetch reads from GitHub again, because `gh pr create --label` adds labels after the `opened` delivery.The turn ends before the status comment, so a skip leaves nothing on the PR. Removing the label does not start a review; apply the `posthog-review` label for one.The label, the `@posthog review` comment, and the UI button ignore both the switch and the skip label.@@ -938,11 +939,13 @@ An explicit Full request remains pending during an active Flash turn and runs ifAutomatic pushes coalesce to the latest head; a rule change that stops the author's automatic review 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.An automatic follow-up turn (one with an `automatic_reviewed_head_sha`) first runs the push gate (`reviewer/push_gate.py`) on the PR's own commits since that head.-Its rules, in order: `no_new_commits` (the PR gained no commit and its full diff is unchanged; a force-push that drops commits runs the review), `reviewhog_commits_only` (the ReviewHog app authored every new commit, such as resolution fixes; this includes the PostHog app's commits on self-driving PRs, which share the app identity), `merge_only` (the PR's full diff against its base is unchanged, as after a base merge or a rebase), `docs_only` (the new own commits touch only docs, lockfiles, snapshots, images, or generated files), and `system_one_below_threshold` (System One rates the own code patches below `SYSTEM_ONE_SKIP_BELOW`).-Each rule has a `SKIP_*` switch. `no_new_commits`, `reviewhog_commits_only`, and `merge_only` skip; `docs_only` and System One only record a shadow decision until production data confirms them.+Its rules, in order: `no_new_commits` (the PR gained no commit and its full diff is unchanged; a force-push that drops commits runs the review), `reviewhog_commits_only` (the ReviewHog app authored every new commit, such as resolution fixes; this includes the PostHog app's commits on self-driving PRs, which share the app identity), `merge_only` (the PR's full diff against its base is unchanged, as after a base merge or a rebase), `docs_only` (the new own commits touch only docs, lockfiles, snapshots, images, or generated files), `system_one_below_threshold` (System One rates the own code patches below `SYSTEM_ONE_SKIP_BELOW`), and `draft` (the PR is a draft and no earlier rule skips the push).+The `draft` rule reads the draft state from the turn's own PR snapshot: every turn fetches the PR before the gate and the snapshot load is latest-wins, so a PR marked ready at an unchanged head reads as ready. A draft skip reads the PR from GitHub again as the gate's last step: a PR marked ready while the turn runs sends a ready request that the queue drops, because it asks for the head the running turn gates. If the PR is ready by then, the gate uses the decision of the rules before `draft`. A failed read reviews the push. Only a PR marked ready between that read and the end of the turn keeps its changes unreviewed until the next trigger. A draft decision keeps the System One answer and `own_code_lines` of the rules that ran before it.+Each rule has a `SKIP_*` switch. `no_new_commits`, `reviewhog_commits_only`, `merge_only`, and `draft` skip; `docs_only` and System One only record a shadow decision until production data confirms them.A skipped turn posts no status comment and leaves `automatic_reviewed_head_sha` in place, so the next push is judged against the last reviewed head.-Any gate failure reviews the push. Each decision emits `reviewhog_push_gate_decided` with `skipped`, `would_skip`, the reason, the System One probability and model, `own_code_lines`, the lines the new own commits change in code files (empty when GitHub could not list every file of a commit), and `pr_draft` from the head's PR snapshot (null when it is unavailable), so skip rules that weigh push size can be calibrated offline.+Any gate failure reviews the push. Each decision emits `reviewhog_push_gate_decided` with `skipped`, `would_skip`, the reason, the System One probability and model, `own_code_lines`, the lines the new own commits change in code files (empty when GitHub could not list every file of a commit), and `pr_draft`, the draft state the gate used (null when the snapshot is unavailable); the event key includes it, so a draft skip and the review after the PR is marked ready at the same head stay two events, so skip rules that weigh push size can be calibrated offline.The first automatic review and every label, UI, inbox, and manual trigger never reach the gate.+An automatic review of a draft that posts findings ends with a note: it is the only automatic review while the PR is a draft, `@posthog review` (or the `posthog-review` label when `github-commands` is off) reviews new changes sooner, and marking the PR ready reviews them otherwise. Label and UI reviews leave the note out, because they also run for authors without automatic reviews.Reviews start only from a trigger (a push, the label, the UI, the inbox, or a manual run) and run right away.ReviewHog never schedules a review for later, for example on a timer after a skipped push: nobody waits for a review that arrives at an unknown time, and a late review can land while the PR sits in a merge queue or under a stack.A change that the gate skips gets reviewed at the next trigger, or not at all.diff --git a/products/review_hog/backend/label_reviews.py b/products/review_hog/backend/label_reviews.pyindex e11948b72436..45bccad1a96c 100644--- a/products/review_hog/backend/label_reviews.py+++ b/products/review_hog/backend/label_reviews.py@@ -74,6 +74,16 @@ def label_commands_hint(review_mode: str) -> str:return f"This Deep review started from the `{REVIEW_LABEL}` label. Comment `@posthog help` to see all commands."+def draft_review_notice(comment_commands_on: bool) -> str:+ """The note an automatic review of a draft ends with: the push gate skips the draft's later pushes."""+ trigger = "Comment `@posthog review`" if comment_commands_on else f"Add the `{REVIEW_LABEL}` label"+ return (+ "This is the only automatic review while this pull request is a draft. "+ f"{trigger} to review new changes sooner. "+ "Otherwise, a review of the new changes runs when you mark it ready for review."+ )++LabelReviewOutcome = Literal["repository_not_added","installation_mismatch",diff --git a/products/review_hog/backend/reviewer/push_gate.py b/products/review_hog/backend/reviewer/push_gate.pyindex 2616ecc119da..4e3345972bea 100644--- a/products/review_hog/backend/reviewer/push_gate.py+++ b/products/review_hog/backend/reviewer/push_gate.py@@ -13,6 +13,9 @@ The rules, in order. The first rule that matches gives the reason:rebase). A merge that changes the PR's own lines runs the review.4. `docs_only`: the new own commits touch only docs, lockfiles, snapshots, images, and generated files.5. `system_one_below_threshold`: System One rates the new own commits below a threshold.+6. `draft`: the PR is a draft and no rule above skips the push. A draft cannot merge, and marking it+ ready starts a turn that reviews everything since the last reviewed head. The rules above still run,+ so a draft decision keeps the System One answer and the push size for calibration.Each rule has its own switch. A rule that is switched off still reports the turn it would skip(`would_skip`), so production data can calibrate it before it skips anything. Every failure fails@@ -45,6 +48,7 @@ SKIP_REVIEWHOG_COMMITS_ONLY = TrueSKIP_MERGE_ONLY = TrueSKIP_DOCS_ONLY = FalseSKIP_SYSTEM_ONE = False+SKIP_DRAFT = True# The JevK5 build PostHog hosts on the ai-gateway. The study calibrated the threshold on TypeSafe's# `jev-latest`, so the shadow decisions must confirm it holds for this model before SKIP_SYSTEM_ONE goes on.@@ -90,7 +94,7 @@ _NON_CODE_FILE = re.compile()SkipReason = Literal[- "no_new_commits", "reviewhog_commits_only", "merge_only", "docs_only", "system_one_below_threshold"+ "no_new_commits", "reviewhog_commits_only", "merge_only", "docs_only", "system_one_below_threshold", "draft"]RunReason = Literal["commits_removed",@@ -154,6 +158,8 @@ def _rule_enabled(reason: SkipReason) -> bool:return SKIP_MERGE_ONLYif reason == "docs_only":return SKIP_DOCS_ONLY+ if reason == "draft":+ return SKIP_DRAFTreturn SKIP_SYSTEM_ONE@@ -324,7 +330,10 @@ class PushGate:)def decide(self, *, previous_head_sha: str, head_sha: str, base_branch: str) -> PushGateDecision:- """Judge the push from `previous_head_sha`, the last automatically reviewed head, to `head_sha`."""+ """Judge the push from `previous_head_sha`, the last automatically reviewed head, to `head_sha`.++ Rules 1 to 5 only: `apply_draft_rule` adds rule 6 on top of the result.+ """previous = self._pr_diff(base_branch, previous_head_sha)current = self._pr_diff(base_branch, head_sha)if previous is None or current is None:@@ -355,3 +364,16 @@ class PushGate:if not code_files:return _matched("docs_only", own_commits=len(own_shas), own_code_lines=0 if own_files.complete else None)return self._ask_system_one(code_files, own_commits=len(own_shas), lines_known=own_files.complete)+++def apply_draft_rule(decision: PushGateDecision, *, draft: bool) -> PushGateDecision:+ """Rule 6, on top of `PushGate.decide`. A caller that finds the PR ready after all uses the decision it got."""+ if not draft or decision.skip:+ return decision+ return _matched(+ "draft",+ own_commits=decision.own_commits,+ probability=decision.probability,+ model=decision.model,+ own_code_lines=decision.own_code_lines,+ )diff --git a/products/review_hog/backend/reviewer/tests/test_publish_review.py b/products/review_hog/backend/reviewer/tests/test_publish_review.pyindex fbd721066156..e45a0a6cfd39 100644--- a/products/review_hog/backend/reviewer/tests/test_publish_review.py+++ b/products/review_hog/backend/reviewer/tests/test_publish_review.py@@ -323,10 +323,10 @@ class TestPublishReviewGate:[# A valid finding on an off-diff line resolves zero inline comments, but the review (its body# carries it in the "Other findings" section) must still post, not be silently dropped.- ("all_off_diff", [240], 0, "full", None, "", None, False),- ("mixed", [1, 240], 1, "full", None, "", None, False),- ("all_inline", [1], 1, "full", None, "", "", False),- ("large_all_inline", [1], 1, "full", 3, "", "", False),+ ("all_off_diff", [240], 0, "full", None, "", "", None, False),+ ("mixed", [1, 240], 1, "full", None, "", "", None, False),+ ("all_inline", [1], 1, "full", None, "", "", "", False),+ ("large_all_inline", [1], 1, "full", 3, "", "", "", False),# Standard has no status comment, so its review body always says which turn it is.("standard_all_inline",@@ -335,10 +335,11 @@ class TestPublishReviewGate:"flash",None,"",+ "","**PostHog Review · Standard · reviewed `sha`**: 1 Should fix.\n\n",False,),- ("standard_mixed", [1, 240], 1, "flash", None, "", None, False),+ ("standard_mixed", [1, 240], 1, "flash", None, "", "", None, False),("standard_large_all_inline",[1],@@ -346,11 +347,12 @@ class TestPublishReviewGate:"flash",3,"",+ "","**PostHog Review · Standard · reviewed `sha`**: 1 Should fix. This pull request is large, so the"" review ran in 3 parts with less depth than usual.\n\n",True,),- ("standard_large_mixed", [1, 240], 1, "flash", 3, "", None, True),+ ("standard_large_mixed", [1, 240], 1, "flash", 3, "", "", None, True),# The footer must survive the inline-only body, which replaces the full body on GitHub.("footer_all_inline",@@ -359,6 +361,7 @@ class TestPublishReviewGate:"full",None,"Comment `@posthog help`.",+ "","Comment `@posthog help`.\n\n",False,),@@ -369,10 +372,24 @@ class TestPublishReviewGate:"flash",None,"Comment `@posthog help`.",+ "","**PostHog Review · Standard · reviewed `sha`**: 1 Should fix.\n\nComment `@posthog help`.\n\n",False,),- ("footer_mixed", [1, 240], 1, "full", None, "Comment `@posthog help`.", None, False),+ ("footer_mixed", [1, 240], 1, "full", None, "Comment `@posthog help`.", "", None, False),+ (+ "standard_findings_footer_all_inline",+ [1],+ 1,+ "flash",+ None,+ "Comment `@posthog help`.",+ "Draft notice.",+ "**PostHog Review · Standard · reviewed `sha`**: 1 Should fix.\n\nComment `@posthog help`.\n\n"+ "Draft notice.\n\n",+ False,+ ),+ ("findings_footer_mixed", [1, 240], 1, "full", None, "", "Draft notice.", None, False),])@patch(_POST)@@ -386,6 +403,7 @@ class TestPublishReviewGate:review_mode: str,capped_lens_parts: int | None,footer: str,+ findings_footer: str,inline_prefix: str | None,body_has_large_pr_note: bool,mock_report_cls: MagicMock,@@ -421,13 +439,15 @@ class TestPublishReviewGate:review_mode=review_mode,capped_lens_parts=capped_lens_parts,footer=footer,+ findings_footer=findings_footer,)assert outcome.posted is Truemock_post.assert_called_once()assert len(mock_post.call_args.args[4]) == expected_commentsmarker = mock_post.call_args.kwargs["marker"]- assert mock_post.call_args.args[3].endswith(f"{footer}\n\n{marker}" if footer else marker)+ closing = "".join(f"{part}\n\n" for part in (footer, findings_footer) if part)+ assert mock_post.call_args.args[3].endswith(f"{closing}{marker}")assert ("This pull request is large" in mock_post.call_args.args[3]) is body_has_large_pr_noteexpected_inline_body = None if inline_prefix is None else f"{inline_prefix}{marker}"assert mock_post.call_args.kwargs["inline_body"] == expected_inline_body@@ -488,6 +508,8 @@ class TestPublishReviewGate:published_priorities=_SHOULD_FIX_PUBLISHED,review_mode=review_mode,capped_lens_parts=capped_lens_parts,+ # A clean turn posts no findings, so the note below must leave this out.+ findings_footer="Draft notice.",)assert outcome.posted is Falsediff --git a/products/review_hog/backend/reviewer/tools/publish_review.py b/products/review_hog/backend/reviewer/tools/publish_review.pyindex 57ac35555027..96e937c963a8 100644--- a/products/review_hog/backend/reviewer/tools/publish_review.py+++ b/products/review_hog/backend/reviewer/tools/publish_review.py@@ -91,6 +91,7 @@ def publish_persisted_review(review_mode: str = REVIEW_MODE_FULL,capped_lens_parts: int | None = None,footer: str = "",+ draft_notice: str = "",) -> PublishOutcome:"""Publish an already-computed review for `report_id` at `head_sha`, idempotently.@@ -104,6 +105,8 @@ def publish_persisted_review(the threshold that actually gated each turn, not the user's live setting and not whicheverthreshold happened to be in force at the last publish. Reads the DB, so callers run it off theevent loop.++ `draft_notice` closes a review with findings when the turn's snapshot shows the PR as a draft."""report = ReviewReport.objects.for_team(team_id).get(id=report_id)if review_already_published(report, head_sha, review_mode):@@ -127,6 +130,7 @@ def publish_persisted_review(review_mode=review_mode,capped_lens_parts=capped_lens_parts,footer=footer,+ findings_footer=draft_notice if snapshot is not None and snapshot.pr_metadata.draft else "",)if outcome.posted:if report.outcomes_emitted_at is not None:@@ -219,6 +223,7 @@ def publish_review(review_mode: str = REVIEW_MODE_FULL,capped_lens_parts: int | None = None,footer: str = "",+ findings_footer: str = "",) -> PublishOutcome:"""Publish the review to GitHub: the stored body plus inline comments from the durable rows.@@ -234,6 +239,8 @@ def publish_review(`capped_lens_parts` is set when a single-agent turn reviewed a PR past the lens part cap. A Standardreview then carries the large pull request note, and a clean Standard turn posts a short review with it.++ `findings_footer` follows `footer` only on a review that posts findings, never on the clean-turn note."""logger.info(f"Publishing review for {owner}/{repo}#{pr_number}")@@ -244,7 +251,6 @@ def publish_review(# `footer` closes the review whichever body posts, so the inline-only body keeps it too.footer_block = f"{footer}\n\n" if footer else ""note_block = f"{large_pr_note(large_pr_parts)}\n\n" if large_pr_parts is not None else ""- body = f"{report.report_markdown}\n\n{note_block}{footer_block}{marker}"valid_findings = load_valid_findings(team_id=team_id, report_id=report_id, run_index=run_index)diff_lines = build_diff_line_map(pr_files)@@ -283,6 +289,9 @@ def publish_review(return PublishOutcome(posted=False)# An earlier clean turn's 👍 would sit next to this turn's findings and contradict them.remove_own_pr_reactions(repository, pr_number, "+1", token=token, installation_id=installation_id)+ if findings_footer:+ footer_block = f"{footer_block}{findings_footer}\n\n"+ body = f"{report.report_markdown}\n\n{note_block}{footer_block}{marker}"# When every publishable finding has its own inline comment, the body's tally repeats what the# comments already show. A Deep review then posts only the hidden marker. A Standard review keepsdiff --git a/products/review_hog/backend/temporal/activities.py b/products/review_hog/backend/temporal/activities.pyindex 469005c32d2c..61ce4529e84c 100644--- a/products/review_hog/backend/temporal/activities.py+++ b/products/review_hog/backend/temporal/activities.py@@ -21,12 +21,13 @@ from dataclasses import dataclass, fieldfrom typing import TYPE_CHECKINGfrom uuid import NAMESPACE_URL, uuid5+import requestsimport posthoganalyticsfrom temporalio import activityfrom temporalio.exceptions import ApplicationErrorfrom posthog.dataclasses import frozen-from posthog.egress.github.transport import GitHubRateLimitError+from posthog.egress.github.transport import GitHubEgressBudgetExhausted, GitHubRateLimitErrorfrom posthog.egress.limiter.policies import Priorityfrom posthog.event_usage import groupsfrom posthog.models.integration import GitHubIntegration, Integration@@ -38,7 +39,7 @@ from posthog.temporal.common.utils import close_db_connectionsfrom products.review_hog.backend.app_identity import posthog_app_loginfrom products.review_hog.backend.automatic_reviews import automatic_flash_allowed, observe_dispatchfrom products.review_hog.backend.facade.enums import ReviewRequestRefusal-from products.review_hog.backend.label_reviews import comment_commands_enabled, label_commands_hint+from products.review_hog.backend.label_reviews import comment_commands_enabled, draft_review_notice, label_commands_hintfrom products.review_hog.backend.models import ReviewProjectSettings, ReviewReport, ReviewUserSettingsfrom products.review_hog.backend.pr_owner import PullRequestOwnerResolverfrom products.review_hog.backend.preferences import ReviewPreferences@@ -115,7 +116,12 @@ from products.review_hog.backend.reviewer.progress import (in_publish_window,record_run_outcome,)-from products.review_hog.backend.reviewer.push_gate import SYSTEM_ONE_SKIP_BELOW, PushGate, PushGateDecision+from products.review_hog.backend.reviewer.push_gate import (+ SYSTEM_ONE_SKIP_BELOW,+ PushGate,+ PushGateDecision,+ apply_draft_rule,+)from products.review_hog.backend.reviewer.review_design import REVIEW_DESIGN_PIPELINE, REVIEW_DESIGN_SINGLE_AGENTfrom products.review_hog.backend.reviewer.review_state import review_already_publishedfrom products.review_hog.backend.reviewer.sandbox.direct_llm import run_oneshot_review@@ -2033,6 +2039,11 @@ def _publish(input: PublishInput) -> PublishResult:footer = ""if input.trigger_source == TRIGGER_LABEL and comment_commands_enabled(input.team_id):footer = label_commands_hint(input.review_mode)+ # Only an automatic turn can promise the review on ready: a label or UI review runs for authors+ # without automatic reviews too.+ draft_notice = ""+ if input.trigger_source == TRIGGER_AUTOMATIC:+ draft_notice = draft_review_notice(comment_commands_enabled(input.team_id))outcome = publish_persisted_review(team_id=input.team_id,report_id=input.report_id,@@ -2047,6 +2058,7 @@ def _publish(input: PublishInput) -> PublishResult:review_mode=input.review_mode,capped_lens_parts=input.capped_lens_parts,footer=footer,+ draft_notice=draft_notice,)if input.trigger_source == TRIGGER_AUTOMATIC:ReviewReport.objects.for_team(input.team_id).filter(id=input.report_id).update(@@ -2243,17 +2255,19 @@ async def track_review_started_activity(input: TrackReviewStartedInput) -> None:await database_sync_to_async(_track_review_started_safe, thread_sensitive=False)(input)-def _track_push_gate_decided(- input: GatePushInput, decision: PushGateDecision, current: "PRSnapshotArtefact | None"-) -> None:+def _track_push_gate_decided(input: GatePushInput, decision: PushGateDecision, draft: bool | None) -> None:report = ReviewReport.objects.for_team(input.team_id).select_related("acting_user", "team").get(id=input.report_id)posthoganalytics.capture(distinct_id=_review_event_identity(report),event="reviewhog_push_gate_decided",# Keyed by head, not run_index: a skipped turn keeps the next turn's run_index, so two skipped- # pushes in a row share one.+ # pushes in a row share one. The draft state is in the key too, because a draft skip and the+ # review after the PR is marked ready can judge the same head.uuid=str(- uuid5(NAMESPACE_URL, f"reviewhog_push_gate_decided:{input.report_id}:{input.head_sha}:{input.review_mode}")+ uuid5(+ NAMESPACE_URL,+ f"reviewhog_push_gate_decided:{input.report_id}:{input.head_sha}:{input.review_mode}:{draft}",+ )),properties={**_turn_event_properties(report, run_index=input.run_index, turn_trigger_source=TRIGGER_AUTOMATIC),@@ -2268,29 +2282,57 @@ def _track_push_gate_decided("system_one_skip_below": SYSTEM_ONE_SKIP_BELOW,"own_commits": decision.own_commits,"own_code_lines": decision.own_code_lines,- "pr_draft": _pr_draft(current),+ "pr_draft": draft,},groups=groups(team=report.team),)+def _pr_is_draft_now(repository: str, pr_number: int, *, token: str, installation_id: str | None) -> bool:+ """The PR's draft state on GitHub now. A failed read counts as ready, so the gate reviews the push."""+ try:+ response = github_api_request(+ "GET",+ f"/repos/{repository}/pulls/{pr_number}",+ token=token,+ endpoint="/repos/{owner}/{repo}/pulls/{pull_number}",+ installation_id=installation_id,+ )+ except (GitHubAPIError, GitHubRateLimitError, GitHubEgressBudgetExhausted, requests.RequestException):+ logger.warning("Could not re-read the draft state of %s#%s; reviewing the push", repository, pr_number)+ return False+ return response.json().get("draft") is True++def _gate_push(input: GatePushInput) -> PushGateDecision:current = load_pr_snapshot(team_id=input.team_id, report_id=input.report_id, head_sha=input.head_sha)+ draft = _pr_draft(current)if current is None:decision = PushGateDecision(skip=False, would_skip=False, reason="snapshot_unavailable")else:token, installation_id = _installation_auth(input.team_id, input.repository)- decision = PushGate(+ gate = PushGate(team_id=input.team_id, repository=input.repository, token=token, installation_id=installation_id- ).decide(+ )+ push_decision = gate.decide(previous_head_sha=input.previous_head_sha,head_sha=input.head_sha,base_branch=current.pr_metadata.base_branch,)+ decision = apply_draft_rule(push_decision, draft=bool(draft))+ # Every turn fetches the PR before the gate and the snapshot load is latest-wins, so a PR marked+ # ready before this turn reads as ready. One marked ready while this turn runs does not: the queue+ # drops the ready request for the head this turn gates. So a draft skip reads GitHub again as its+ # last step, which leaves only the moment between this read and the end of the turn.+ if decision.reason == "draft" and not _pr_is_draft_now(+ input.repository, current.pr_metadata.number, token=token, installation_id=installation_id+ ):+ draft = False+ decision = push_decisionif decision.skip:ReviewReport.objects.for_team(input.team_id).filter(id=input.report_id).update(status=ReviewReport.Status.IDLE)try:- _track_push_gate_decided(input, decision, current)+ _track_push_gate_decided(input, decision, draft)except Exception:logger.exception("Failed to capture reviewhog_push_gate_decided for report %s; continuing", input.report_id)return decisiondiff --git a/products/review_hog/backend/tests/test_publish_idempotency.py b/products/review_hog/backend/tests/test_publish_idempotency.pyindex 27e88299921b..d2a2fde2b4af 100644--- a/products/review_hog/backend/tests/test_publish_idempotency.py+++ b/products/review_hog/backend/tests/test_publish_idempotency.py@@ -17,6 +17,7 @@ from posthog.egress.github.transport import GitHubRateLimitErrorfrom posthog.models.instance_setting import override_instance_configfrom products.review_hog.backend.models import ReviewReport+from products.review_hog.backend.reviewer.artefact_content import PRSnapshotArtefactfrom products.review_hog.backend.reviewer.constants import LEGACY_FLASH_MODE_MESSAGE_PREFIXfrom products.review_hog.backend.reviewer.models.github_meta import PRMetadatafrom products.review_hog.backend.reviewer.persistence import upsert_review_report@@ -248,6 +249,48 @@ class TestPublishIdempotency(BaseTest):assert mock_publish.call_count == 1assert ReviewReport.objects.for_team(self.team.id).get(id=report_id).published_head_sha == "sha2"+ @parameterized.expand(+ [+ ("automatic_draft_with_commands", "automatic", True, True, "Comment `@posthog review` to review"),+ ("automatic_draft_without_commands", "automatic", True, False, "Add the `posthog-review` label to"),+ ("automatic_ready", "automatic", False, True, None),+ # A label review also runs for authors without automatic reviews, so it cannot promise one on ready.+ ("label_draft", "label", True, True, None),+ ]+ )+ @patch(_PUBLISH)+ @patch(_AUTH, return_value=("tok", None))+ def test_an_automatic_review_of_a_draft_says_when_the_next_review_runs(+ self,+ _name: str,+ trigger_source: str,+ draft: bool,+ commands_on: bool,+ expected_trigger: str | None,+ _auth,+ mock_publish,+ ) -> None:+ mock_publish.return_value = PublishOutcome(posted=True)+ report_id = self._report()+ snapshot = PRSnapshotArtefact(+ head_sha="sha1",+ pr_metadata=_pr_metadata("sha1").model_copy(update={"draft": draft}),+ pr_comments=[],+ pr_files=[],+ )+ with (+ patch(_SNAPSHOT, return_value=snapshot),+ patch(f"{_ACTIVITIES}.comment_commands_enabled", return_value=commands_on),+ ):+ _publish(replace(_publish_input(self.team.id, report_id, "sha1"), trigger_source=trigger_source))++ findings_footer = mock_publish.call_args.kwargs["findings_footer"]+ if expected_trigger is None:+ assert findings_footer == ""+ else:+ assert findings_footer.startswith("This is the only automatic review while this pull request is a draft.")+ assert expected_trigger in findings_footer+@patch(_PUBLISH)@patch(_SNAPSHOT, return_value=None)@patch(_AUTH, return_value=("tok", None))diff --git a/products/review_hog/backend/tests/test_push_gate.py b/products/review_hog/backend/tests/test_push_gate.pyindex 72e2fcb3dfd8..0983e54999a4 100644--- a/products/review_hog/backend/tests/test_push_gate.py+++ b/products/review_hog/backend/tests/test_push_gate.py@@ -6,7 +6,7 @@ from parameterized import parameterizedfrom posthog.llm.system_one import NoulAnswer, SystemOneNotConfigured, SystemOneRequestFailed, SystemOneResult-from products.review_hog.backend.reviewer.push_gate import PUSH_GATE_MODEL, PushGate, PushGateDecision+from products.review_hog.backend.reviewer.push_gate import PUSH_GATE_MODEL, PushGate, PushGateDecision, apply_draft_rulefrom products.review_hog.backend.reviewer.tools.github_client import GitHubAPIError_MODULE = "products.review_hog.backend.reviewer.push_gate"@@ -70,15 +70,18 @@ def _github(responses: dict[str, dict[str, Any] | None]):return request-def _decide(responses: dict[str, dict[str, Any] | None], system_one: MagicMock | None = None) -> PushGateDecision:+def _decide(+ responses: dict[str, dict[str, Any] | None], system_one: MagicMock | None = None, *, draft: bool = False+) -> PushGateDecision:with (patch(f"{_MODULE}.github_api_request", side_effect=_github(responses)),patch(f"{_MODULE}.build_system_one_client", MagicMock(return_value=system_one or MagicMock())),patch(f"{_MODULE}.posthog_app_login", return_value="reviewhog[bot]"),):- return PushGate(team_id=1, repository="PostHog/posthog", token="t", installation_id="9").decide(+ decision = PushGate(team_id=1, repository="PostHog/posthog", token="t", installation_id="9").decide(previous_head_sha="old", head_sha="new", base_branch="master")+ return apply_draft_rule(decision, draft=draft)def _system_one(probability: float) -> MagicMock:@@ -282,3 +285,40 @@ def test_push_gate_reviews_a_push_it_cannot_see(decision = _decide(responses, system_one)assert (decision.skip, decision.reason) == (False, reason)system_one.decide.assert_not_called()+++ [+ ("code_push", _CODE_PUSH, (True, True, "draft", 0.8, PUSH_GATE_MODEL, 2)),+ # A shadow match does not skip, so the draft rule decides the push.+ (+ "docs_only_shadow",+ _push(+ new_commits=[_commit("a"), _commit("c")],+ pr_files=[_file("posthog/billing.py", _BILLING), _file("README.md")],+ own_commit_files=[_file("README.md")],+ ),+ (True, True, "draft", None, None, 0),+ ),+ # A rule that skips on its own is more specific than the draft state.+ (+ "force_push_back",+ _push(new_commits=[_commit("a")], pr_files=[_file("posthog/billing.py", _BILLING)]),+ (True, True, "no_new_commits", None, None, None),+ ),+ ]+)+def test_push_gate_skips_a_draft_push_and_keeps_the_system_one_answer(+ _name: str,+ responses: dict[str, dict[str, Any] | None],+ expected: tuple[bool, bool, str, float | None, str | None, int | None],+) -> None:+ decision = _decide(responses, _system_one(0.8), draft=True)+ assert (+ decision.skip,+ decision.would_skip,+ decision.reason,+ decision.probability,+ decision.model,+ decision.own_code_lines,+ ) == expecteddiff --git a/products/review_hog/backend/tests/test_review_completed_tracking.py b/products/review_hog/backend/tests/test_review_completed_tracking.pyindex ea26ff4ea09f..75747622c855 100644--- a/products/review_hog/backend/tests/test_review_completed_tracking.py+++ b/products/review_hog/backend/tests/test_review_completed_tracking.py@@ -1,11 +1,14 @@import uuidfrom datetime import UTC, datetime, timedelta+from typing import Anyfrom posthog.test.base import BaseTest-from unittest.mock import patch+from unittest.mock import MagicMock, patchfrom parameterized import parameterized+from posthog.egress.github.transport import GitHubEgressBudgetExhausted, GitHubRateLimitError+from products.review_hog.backend.models import ReviewReportfrom products.review_hog.backend.reviewer.constants import (DEFAULT_REVIEW_ARM,@@ -28,6 +31,7 @@ from products.review_hog.backend.reviewer.persistence import ()from products.review_hog.backend.reviewer.push_gate import PushGateDecisionfrom products.review_hog.backend.reviewer.review_design import REVIEW_DESIGN_PIPELINE, REVIEW_DESIGN_SINGLE_AGENT+from products.review_hog.backend.reviewer.tools.github_client import GitHubAPIErrorfrom products.review_hog.backend.reviewer.tools.single_agent_review import FlashTurnStatsfrom products.review_hog.backend.temporal.activities import (FlashSessionStats,@@ -371,6 +375,90 @@ class TestTrackReviewCompleted(BaseTest):# Each push reports the draft state of its own head.assert (props["pr_draft"], second.kwargs["properties"]["pr_draft"]) == (True, False)+ def _gate_draft_push(self, report_id: str, live_pr: dict[str, object] | Exception) -> tuple[PushGateDecision, Any]:+ live = MagicMock(side_effect=live_pr) if isinstance(live_pr, Exception) else MagicMock()+ live.return_value.json.return_value = live_pr+ with (+ patch("products.review_hog.backend.temporal.activities._installation_auth", return_value=("tok", None)),+ patch(+ "products.review_hog.backend.reviewer.push_gate.github_api_request",+ side_effect=GitHubAPIError("gone", status=404),+ ),+ patch("products.review_hog.backend.temporal.activities.github_api_request", live),+ patch("products.review_hog.backend.temporal.activities.posthoganalytics.capture") as capture,+ ):+ decision = _gate_push(+ GatePushInput(+ team_id=self.team.id,+ report_id=report_id,+ repository="o/r",+ previous_head_sha="sha0",+ head_sha="sha1",+ run_index=2,+ review_mode=REVIEW_MODE_FLASH,+ )+ )+ return decision, capture++ @parameterized.expand(+ [+ ("still_a_draft", [True], {"draft": True}, True, "draft"),+ # The author marks the PR ready without a push: the ready turn re-fetches the same head.+ ("marked_ready_at_the_same_head", [True, False], {"draft": True}, False, "compare_unavailable"),+ # The queue drops a ready request for the head a running turn gates, so the gate reads GitHub again.+ ("marked_ready_while_the_turn_runs", [True], {"draft": False}, False, "compare_unavailable"),+ ("live_read_fails", [True], GitHubAPIError("boom", status=502), False, "compare_unavailable"),+ (+ "live_read_rate_limited",+ [True],+ GitHubRateLimitError("limited", retry_after=60),+ False,+ "compare_unavailable",+ ),+ ("live_read_over_budget", [True], GitHubEgressBudgetExhausted("shed"), False, "compare_unavailable"),+ ]+ )+ def test_the_gate_reads_the_draft_state_of_the_latest_fetch(+ self,+ _name: str,+ fetched_drafts: list[bool],+ live_pr: dict[str, object] | Exception,+ skip: bool,+ reason: str,+ ) -> None:+ report_id = self._review_report()+ for draft in fetched_drafts:+ persist_pr_snapshot(+ team_id=self.team.id,+ report_id=report_id,+ head_sha="sha1",+ pr_metadata=_pr_metadata(draft=draft),+ pr_comments=[],+ pr_files=[],+ )++ decision, _capture = self._gate_draft_push(report_id, live_pr)++ assert (decision.skip, decision.reason) == (skip, reason)++ def test_a_draft_skip_and_the_ready_decision_at_one_head_stay_two_events(self) -> None:+ report_id = self._review_report()+ persist_pr_snapshot(+ team_id=self.team.id,+ report_id=report_id,+ head_sha="sha1",+ pr_metadata=_pr_metadata(draft=True),+ pr_comments=[],+ pr_files=[],+ )++ _skip, draft_capture = self._gate_draft_push(report_id, {"draft": True})+ _review, ready_capture = self._gate_draft_push(report_id, {"draft": False})++ draft_event, ready_event = draft_capture.call_args.kwargs, ready_capture.call_args.kwargs+ assert draft_event["uuid"] != ready_event["uuid"]+ assert (draft_event["properties"]["pr_draft"], ready_event["properties"]["pr_draft"]) == (True, False)+def test_capture_failure_is_swallowed(self) -> None:# Telemetry must never fail a review — losing this guard would fail review turns on any# analytics outage.