Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(review-hog): skip follow-up reviews when a push changes nothing reviewable (#112459)

Julian Bez2154c42edffd
diff --git a/products/review_hog/ARCHITECTURE.md b/products/review_hog/ARCHITECTURE.md
index 07f240283347..b17b871829e2 100644
--- a/products/review_hog/ARCHITECTURE.md
+++ b/products/review_hog/ARCHITECTURE.md
@@ -754,6 +754,12 @@ It waits for an active resolution stage and runs each review in a `review-pr` ch
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.
+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), `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` and `merge_only` 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, and the System One probability and model.
+The first automatic review and every label, UI, inbox, and manual trigger never reach the gate.
**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
diff --git a/products/review_hog/backend/reviewer/constants.py b/products/review_hog/backend/reviewer/constants.py
index f9225f352f1b..148691784aa1 100644
--- a/products/review_hog/backend/reviewer/constants.py
+++ b/products/review_hog/backend/reviewer/constants.py
@@ -69,8 +69,8 @@ REVIEW_MODE_FLASH = "flash"
# Bump a mode's (major, minor) with a pipeline or design change. Prompt, skill, and model pin edits
# change the turn fingerprint (`reviewer/fingerprint.py`) instead.
REVIEWHOG_VERSIONS: dict[str, tuple[int, int]] = {
- REVIEW_MODE_FULL: (1, 1),
- REVIEW_MODE_FLASH: (1, 1),
+ REVIEW_MODE_FULL: (1, 2),
+ REVIEW_MODE_FLASH: (1, 2),
}
diff --git a/products/review_hog/backend/reviewer/push_gate.py b/products/review_hog/backend/reviewer/push_gate.py
new file mode 100644
index 000000000000..b1d9db02ef62
--- /dev/null
+++ b/products/review_hog/backend/reviewer/push_gate.py
@@ -0,0 +1,303 @@
+"""The push gate: decides whether an automatic follow-up review turn is worth its cost.
+
+Every push to an opted-in author's PR starts an automatic turn, and a follow-up turn re-reviews the
+whole PR. The gate looks at the PR's own commits since the last automatically reviewed head. It never
+sees a first review or a human trigger: the workflow calls it only for automatic follow-ups.
+
+The rules, in order. The first rule that matches gives the reason:
+
+1. `no_new_commits`: the PR has no commit it did not have at the last reviewed head (a force-push back).
+2. `merge_only`: the PR's full diff against its base is the same at both heads (a base merge or a
+ rebase). A merge that changes the PR's own lines runs the review.
+3. `docs_only`: the new own commits touch only docs, lockfiles, snapshots, images, and generated files.
+4. `system_one_below_threshold`: System One rates the new own commits below a threshold.
+
+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
+open: the turn runs.
+
+The rules, the non-code file list, the System One question, and the state follow the offline study
+in `review-eval/production/push-gate`. The threshold is only valid for the state built the same way.
+"""
+
+import re
+import logging
+from typing import Any, Literal
+
+import requests
+
+from posthog.dataclasses import frozen
+from posthog.egress.github.transport import GitHubRateLimitError
+from posthog.llm.system_one import NoulAnswer, NoulQuestion, SystemOneNotConfigured, SystemOneRequestFailed
+from posthog.llm.system_one_client import build_system_one_client
+
+from products.review_hog.backend.reviewer.tools.github_client import GitHubAPIError, github_api_request
+from products.review_hog.backend.reviewer.tools.github_meta import GITHUB_COMPARE_FILES_CAP, PRParser
+
+logger = logging.getLogger(__name__)
+
+# A rule that is off only records the skip it would make, so production data can calibrate it first.
+SKIP_NO_NEW_COMMITS = True
+SKIP_MERGE_ONLY = True
+SKIP_DOCS_ONLY = False
+SKIP_SYSTEM_ONE = False
+
+# 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.
+PUSH_GATE_MODEL = "posthog/hogference/jevk5-fp8-0.2"
+SYSTEM_ONE_SKIP_BELOW = 0.30
+# The study sent states up to 64k tokens, at about 3.5 characters per token of code.
+MAX_STATE_CHARS = 224_000
+SYSTEM_ONE_TIMEOUT_SECONDS = 15.0
+# Each new own commit costs one GitHub call to read its patch.
+MAX_OWN_COMMITS = 20
+# GitHub's compare endpoint pages its commit list at this size.
+_COMPARE_COMMITS_PER_PAGE = 100
+
+_QUESTION_ID = "alters"
+# The commits stay in the state, so text from the pull request can never become an instruction.
+_ALTERS_QUESTION = NoulQuestion(
+ instructions=(
+ "Read the code change in the state. Could this change alter the behavior of the code "
+ "or introduce a bug? Answer true if it could, false if it is only cosmetic, a rename, "
+ "formatting, a comment, documentation or a test-only tweak that cannot affect behavior."
+ ),
+)
+
+_NON_CODE_FILE = re.compile(
+ "|".join(
+ [
+ r"(^|/)(pnpm-lock\.yaml|uv\.lock|package-lock\.json|yarn\.lock|Cargo\.lock|poetry\.lock|flox/manifest\.lock|\.flox/env/manifest\.lock)$",
+ r"\.md$",
+ r"\.mdx$",
+ r"(^|/)docs/",
+ r"(^|/)generated/",
+ r"\.generated\.",
+ r"(^|/)__snapshots__/",
+ r"\.ambr$",
+ r"\.snap$",
+ r"\.(png|jpg|jpeg|gif|svg|webp)$",
+ r"(^|/)(openapi|schema)\.json$",
+ r"(^|/)api\.(schemas|zod)\.ts$",
+ r"(^|/)frontend/src/queries/schema\.json$",
+ r"(^|/)posthog/schema\.py$",
+ ]
+ )
+)
+
+SkipReason = Literal["no_new_commits", "merge_only", "docs_only", "system_one_below_threshold"]
+RunReason = Literal[
+ "commits_removed",
+ "system_one_above_threshold",
+ "system_one_unavailable",
+ "interdiff_too_large",
+ "compare_unavailable",
+ "snapshot_unavailable",
+]
+
+
+@frozen
+class PushGateDecision:
+ skip: bool
+ # Whether a rule matched, switched on or not. A match with its rule off is a shadow decision.
+ would_skip: bool
+ reason: SkipReason | RunReason
+ probability: float | None = None
+ model: str | None = None
+ own_commits: int | None = None
+
+
+@frozen
+class _ChangedFile:
+ filename: str
+ changes: int
+ patch: str | None
+
+
+@frozen
+class _ChangedLine:
+ type: str
+ code: str
+
+
+@frozen
+class _PRDiff:
+ """The PR as `base...head`: its commits, the merge commits among them, and its full diff."""
+
+ commit_shas: list[str]
+ merge_shas: set[str]
+ files: list[_ChangedFile]
+
+
+def _rule_enabled(reason: SkipReason) -> bool:
+ if reason == "no_new_commits":
+ return SKIP_NO_NEW_COMMITS
+ if reason == "merge_only":
+ return SKIP_MERGE_ONLY
+ if reason == "docs_only":
+ return SKIP_DOCS_ONLY
+ return SKIP_SYSTEM_ONE
+
+
+def _matched(
+ reason: SkipReason, *, own_commits: int | None = None, probability: float | None = None, model: str | None = None
+) -> PushGateDecision:
+ return PushGateDecision(
+ skip=_rule_enabled(reason),
+ would_skip=True,
+ reason=reason,
+ probability=probability,
+ model=model,
+ own_commits=own_commits,
+ )
+
+
+def _runs(
+ reason: RunReason, *, own_commits: int | None = None, probability: float | None = None, model: str | None = None
+) -> PushGateDecision:
+ return PushGateDecision(
+ skip=False,
+ would_skip=False,
+ reason=reason,
+ probability=probability,
+ model=model,
+ own_commits=own_commits,
+ )
+
+
+def _changed_files(payload: dict[str, Any]) -> list[_ChangedFile]:
+ return [
+ _ChangedFile(filename=file["filename"], changes=file.get("changes", 0), patch=file.get("patch"))
+ for file in payload.get("files") or []
+ ]
+
+
+def _own_lines(files: list[_ChangedFile]) -> dict[str, list[_ChangedLine]] | None:
+ """The PR's added and removed lines per file, without line numbers, which shift when the base moves."""
+ lines: dict[str, list[_ChangedLine]] = {}
+ for file in files:
+ if file.patch is None and file.changes:
+ # GitHub left the patch out, so the lines of this file cannot be compared.
+ return None
+ changes = PRParser.parse_patch(file.patch or "")
+ lines[file.filename] = [
+ _ChangedLine(type=change.type, code=change.code) for change in changes if change.type != "context"
+ ]
+ return lines
+
+
+def _same_full_diff(previous: _PRDiff, current: _PRDiff) -> bool:
+ previous_lines = _own_lines(previous.files)
+ return previous_lines is not None and previous_lines == _own_lines(current.files)
+
+
+class PushGate:
+ def __init__(self, *, team_id: int, repository: str, token: str, installation_id: str | None) -> None:
+ self.team_id = team_id
+ self.repository = repository
+ self._token = token
+ self._installation_id = installation_id
+
+ def _get(self, path: str, *, endpoint: str, params: dict[str, str | int] | None = None) -> dict[str, Any] | None:
+ try:
+ return github_api_request(
+ "GET",
+ f"/repos/{self.repository}{path}",
+ token=self._token,
+ installation_id=self._installation_id,
+ endpoint=f"/repos/{{owner}}/{{repo}}{endpoint}",
+ params=params,
+ ).json()
+ except (GitHubAPIError, GitHubRateLimitError, requests.RequestException) as error:
+ logger.warning("Push gate could not read %s from GitHub: %s", endpoint, type(error).__name__)
+ return None
+
+ def _pr_diff(self, base_branch: str, head_sha: str) -> _PRDiff | None:
+ """The PR at `head_sha`, or None when GitHub cannot return all of it in one page."""
+ comparison = self._get(
+ f"/compare/{base_branch}...{head_sha}",
+ endpoint="/compare/{basehead}",
+ params={"per_page": _COMPARE_COMMITS_PER_PAGE},
+ )
+ if comparison is None:
+ return None
+ commits: list[dict[str, Any]] = comparison.get("commits") or []
+ files = _changed_files(comparison)
+ if comparison.get("total_commits", 0) > len(commits) or len(files) >= GITHUB_COMPARE_FILES_CAP:
+ return None
+ return _PRDiff(
+ commit_shas=[commit["sha"] for commit in commits],
+ merge_shas={commit["sha"] for commit in commits if len(commit.get("parents") or []) > 1},
+ files=files,
+ )
+
+ def _commit_files(self, shas: list[str]) -> list[_ChangedFile] | None:
+ files: list[_ChangedFile] = []
+ for sha in shas:
+ commit = self._get(f"/commits/{sha}", endpoint="/commits/{ref}")
+ if commit is None:
+ return None
+ files.extend(_changed_files(commit))
+ return files
+
+ def _ask_system_one(self, code_files: list[_ChangedFile], own_commits: int) -> PushGateDecision:
+ if any(file.patch is None for file in code_files):
+ return _runs("interdiff_too_large", own_commits=own_commits)
+ state = "\n\n".join(f"--- {file.filename}\n{file.patch}" for file in code_files)
+ if len(state) > MAX_STATE_CHARS:
+ return _runs("interdiff_too_large", own_commits=own_commits)
+ try:
+ client = build_system_one_client(
+ model=PUSH_GATE_MODEL,
+ ai_product="review_hog",
+ team_id=self.team_id,
+ timeout=SYSTEM_ONE_TIMEOUT_SECONDS,
+ )
+ result = client.decide(state=state, questions={_QUESTION_ID: _ALTERS_QUESTION})
+ except (SystemOneNotConfigured, SystemOneRequestFailed) as error:
+ logger.warning("Push gate could not reach System One: %s", type(error).__name__)
+ return _runs("system_one_unavailable", own_commits=own_commits)
+ answer = result.answers[_QUESTION_ID]
+ if not isinstance(answer, NoulAnswer):
+ return _runs("system_one_unavailable", own_commits=own_commits)
+ if answer.probability < SYSTEM_ONE_SKIP_BELOW:
+ return _matched(
+ "system_one_below_threshold",
+ own_commits=own_commits,
+ probability=answer.probability,
+ model=result.model,
+ )
+ return _runs(
+ "system_one_above_threshold", own_commits=own_commits, probability=answer.probability, model=result.model
+ )
+
+ 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`."""
+ 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:
+ return _runs("compare_unavailable")
+ # Commits that came in with a merge from the base branch are on the base, so `base...head`
+ # leaves them out and only the merge commit itself is new.
+ previous_shas = set(previous.commit_shas)
+ new_shas = [sha for sha in current.commit_shas if sha not in previous_shas]
+ if not new_shas:
+ if _same_full_diff(previous, current):
+ return _matched("no_new_commits")
+ # A force-push back to an earlier commit adds no commit but removes changes the last review saw.
+ return _runs("commits_removed")
+ own_shas = [sha for sha in new_shas if sha not in current.merge_shas]
+ if _same_full_diff(previous, current):
+ return _matched("merge_only", own_commits=len(own_shas))
+ if not own_shas:
+ # A merge that changed the PR's own lines (conflict resolution) carries code nobody reviewed.
+ return _runs("interdiff_too_large", own_commits=0)
+ if len(own_shas) > MAX_OWN_COMMITS:
+ return _runs("interdiff_too_large", own_commits=len(own_shas))
+ own_files = self._commit_files(own_shas)
+ if own_files is None:
+ return _runs("compare_unavailable", own_commits=len(own_shas))
+ code_files = [file for file in own_files if not _NON_CODE_FILE.search(file.filename)]
+ if not code_files:
+ return _matched("docs_only", own_commits=len(own_shas))
+ return self._ask_system_one(code_files, own_commits=len(own_shas))
diff --git a/products/review_hog/backend/temporal/__init__.py b/products/review_hog/backend/temporal/__init__.py
index 20e04ac90a8f..bbbc70b142b1 100644
--- a/products/review_hog/backend/temporal/__init__.py
+++ b/products/review_hog/backend/temporal/__init__.py
@@ -5,6 +5,7 @@ from products.review_hog.backend.temporal.activities import (
fail_status_comment_activity,
fetch_pr_data_activity,
finalize_status_comment_activity,
+ gate_push_activity,
generate_schemas_activity,
load_blind_spots_skill_activity,
load_perspectives_activity,
@@ -55,6 +56,7 @@ ACTIVITIES = [
validate_github_integration_activity,
fetch_pr_data_activity,
resolve_acting_user_activity,
+ gate_push_activity,
sync_review_skills_activity,
generate_schemas_activity,
split_chunks_activity,
diff --git a/products/review_hog/backend/temporal/activities.py b/products/review_hog/backend/temporal/activities.py
index d0dc04e63d95..6d2731cb5bc6 100644
--- a/products/review_hog/backend/temporal/activities.py
+++ b/products/review_hog/backend/temporal/activities.py
@@ -19,6 +19,7 @@ import datetime
from collections import Counter
from dataclasses import dataclass, field
from typing import TYPE_CHECKING
+from uuid import NAMESPACE_URL, uuid5
import posthoganalytics
from temporalio import activity
@@ -85,6 +86,7 @@ from products.review_hog.backend.reviewer.persistence import (
replace_deduplicated_findings,
upsert_review_report,
)
+from products.review_hog.backend.reviewer.push_gate import SYSTEM_ONE_SKIP_BELOW, PushGate, PushGateDecision
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 (
@@ -212,6 +214,8 @@ class ReviewMeta:
empty_diff: bool = False
already_completed: bool = False
pr_open: bool = True
+ # None means no automatic review has run on the PR, so the push gate stays off for this turn.
+ automatic_reviewed_head_sha: str | None = None
@dataclass
@@ -487,6 +491,19 @@ class TrackReviewFailedInput:
flash_reasoning_effort: str = ReasoningEffort.MEDIUM.value
+@frozen
+class GatePushInput:
+ """An automatic follow-up turn for the push gate to judge."""
+
+ team_id: int
+ report_id: str
+ repository: str
+ previous_head_sha: str
+ head_sha: str
+ run_index: int
+ review_mode: str
+
+
@dataclass(frozen=False)
class StatusCommentInput:
"""Kickoff / failure edits of the PR's status comment; owner/repo/pr come off the report row."""
@@ -684,6 +701,7 @@ def _fetch_and_persist(input: FetchPRDataInput) -> ReviewMeta:
empty_diff=pr_number is None and not pr_files,
already_completed=already_completed,
pr_open=pr_metadata.state == "open",
+ automatic_reviewed_head_sha=report.automatic_reviewed_head_sha,
)
@@ -1538,6 +1556,66 @@ 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) -> 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.
+ uuid=str(
+ uuid5(NAMESPACE_URL, f"reviewhog_push_gate_decided:{input.report_id}:{input.head_sha}:{input.review_mode}")
+ ),
+ properties={
+ **_turn_event_properties(report, run_index=input.run_index, turn_trigger_source=TRIGGER_AUTOMATIC),
+ "review_mode": input.review_mode,
+ "head_sha": input.head_sha,
+ "previous_head_sha": input.previous_head_sha,
+ "skipped": decision.skip,
+ "would_skip": decision.would_skip,
+ "reason": decision.reason,
+ "system_one_probability": decision.probability,
+ "system_one_model": decision.model,
+ "system_one_skip_below": SYSTEM_ONE_SKIP_BELOW,
+ "own_commits": decision.own_commits,
+ },
+ groups=groups(team=report.team),
+ )
+
+
+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)
+ 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(
+ team_id=input.team_id, repository=input.repository, token=token, installation_id=installation_id
+ ).decide(
+ previous_head_sha=input.previous_head_sha,
+ head_sha=input.head_sha,
+ base_branch=current.pr_metadata.base_branch,
+ )
+ if 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)
+ except Exception:
+ logger.exception("Failed to capture reviewhog_push_gate_decided for report %s; continuing", input.report_id)
+ return decision
+
+
+@scoped_temporal()
+@close_db_connections
+async def gate_push_activity(input: GatePushInput) -> PushGateDecision:
+ """Decide whether an automatic follow-up turn reviews this push (see `reviewer/push_gate.py`).
+
+ A skip returns the report to rest, because the turn ends before any stage that would.
+ """
+ return await database_sync_to_async(_gate_push, thread_sensitive=False)(input)
+
+
def _track_review_completed(input: TrackReviewCompletedInput) -> None:
report = ReviewReport.objects.for_team(input.team_id).select_related("acting_user", "team").get(id=input.report_id)
findings = load_turn_findings(team_id=input.team_id, report_id=input.report_id, run_index=input.run_index)
diff --git a/products/review_hog/backend/temporal/workflow.py b/products/review_hog/backend/temporal/workflow.py
index 9e826068bac9..ad1941efe660 100644
--- a/products/review_hog/backend/temporal/workflow.py
+++ b/products/review_hog/backend/temporal/workflow.py
@@ -40,6 +40,7 @@ from products.review_hog.backend.temporal.activities import (
BuildBodyInput,
DedupResult,
FetchPRDataInput,
+ GatePushInput,
GenerateSchemasInput,
LoadBlindSpotsInput,
LoadedBlindSpotsSkillDTO,
@@ -70,6 +71,7 @@ from products.review_hog.backend.temporal.activities import (
fail_status_comment_activity,
fetch_pr_data_activity,
finalize_status_comment_activity,
+ gate_push_activity,
generate_schemas_activity,
load_blind_spots_skill_activity,
load_perspectives_activity,
@@ -521,6 +523,34 @@ class ReviewPRWorkflow:
return report_id
acting_user_id = acting.acting_user_id
+ # Only an automatic follow-up is gated. The first automatic review of a PR and every human
+ # trigger always run. The gate fails open: an activity failure reviews the push.
+ if (
+ workflow.patched("reviewhog-push-gate-2026-10")
+ and inputs.trigger_source == TRIGGER_AUTOMATIC
+ and meta.automatic_reviewed_head_sha is not None
+ ):
+ try:
+ gate = await workflow.execute_activity(
+ gate_push_activity,
+ GatePushInput(
+ team_id=inputs.team_id,
+ report_id=report_id,
+ repository=repository,
+ previous_head_sha=meta.automatic_reviewed_head_sha,
+ head_sha=head_sha,
+ run_index=meta.run_index,
+ review_mode=inputs.review_mode,
+ ),
+ start_to_close_timeout=_QUICK_TIMEOUT,
+ retry_policy=_RETRY,
+ )
+ if gate.skip:
+ workflow.logger.info(f"Automatic review skipped by the push gate ({gate.reason})")
+ return report_id
+ except ActivityError:
+ workflow.logger.warning("The push gate failed; reviewing the push")
+
# The turn passed every gate and is about to spend sandboxes: one started event per turn,
# the counterpart of the completed/failed pair below. Best-effort like both of them.
if workflow.patched("track-review-started-2026-09"):
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 c0c0cb50cb7b..e7def82f1b4f 100644
--- a/products/review_hog/backend/tests/test_fetch_review_tier.py
+++ b/products/review_hog/backend/tests/test_fetch_review_tier.py
@@ -67,6 +67,7 @@ class TestFetchDecidesTheTier(BaseTest):
assert meta.already_completed is complete
assert meta.pr_open is (state == "open")
+ assert meta.automatic_reviewed_head_sha == automatic_head
expected_status = "closed" if state == "closed" else "idle" if complete else "active"
assert report.status == expected_status
diff --git a/products/review_hog/backend/tests/test_push_gate.py b/products/review_hog/backend/tests/test_push_gate.py
new file mode 100644
index 000000000000..d93ea7cfe17f
--- /dev/null
+++ b/products/review_hog/backend/tests/test_push_gate.py
@@ -0,0 +1,211 @@
+from typing import Any
+
+from unittest.mock import MagicMock, patch
+
+from parameterized import parameterized
+
+from 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.tools.github_client import GitHubAPIError
+
+_MODULE = "products.review_hog.backend.reviewer.push_gate"
+_BILLING = "@@ -10,1 +10,1 @@\n- return amount\n+ return amount * 100"
+_BILLING_AFTER_MERGE = "@@ -40,1 +40,1 @@\n- return amount\n+ return amount * 100"
+_BILLING_FIX = "@@ -10,1 +10,1 @@\n- return amount * 100\n+ return round(amount * 100)"
+
+
+def _file(filename: str, patch: str | None = "@@ -1 +1 @@\n-a\n+b") -> dict[str, Any]:
+ return {"filename": filename, "changes": 2, "patch": patch}
+
+
+def _commit(sha: str, *, merge: bool = False) -> dict[str, Any]:
+ return {"sha": sha, "parents": [{"sha": "p1"}, {"sha": "p2"}] if merge else [{"sha": "p1"}]}
+
+
+def _pr(commits: list[dict[str, Any]], files: list[dict[str, Any]]) -> dict[str, Any]:
+ return {"total_commits": len(commits), "commits": commits, "files": files}
+
+
+def _push(
+ *,
+ new_commits: list[dict[str, Any]],
+ pr_files: list[dict[str, Any]],
+ own_commit_files: list[dict[str, Any]] | None = None,
+) -> dict[str, dict[str, Any] | None]:
+ return {
+ "compare/master...old": _pr([_commit("a")], [_file("posthog/billing.py", _BILLING)]),
+ "compare/master...new": _pr(new_commits, pr_files),
+ "commits/c": {"files": own_commit_files or []},
+ }
+
+
+def _github(responses: dict[str, dict[str, Any] | None]):
+ def request(method: str, path: str, **kwargs: Any) -> MagicMock:
+ response = responses[path.removeprefix("/repos/PostHog/posthog/")]
+ if response is None:
+ raise GitHubAPIError("gone", status=404)
+ return MagicMock(json=MagicMock(return_value=response))
+
+ return request
+
+
+def _decide(responses: dict[str, dict[str, Any] | None], system_one: MagicMock | None = None) -> 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())),
+ ):
+ return PushGate(team_id=1, repository="PostHog/posthog", token="t", installation_id="9").decide(
+ previous_head_sha="old", head_sha="new", base_branch="master"
+ )
+
+
+def _system_one(probability: float) -> MagicMock:
+ client = MagicMock()
+ client.decide.return_value = SystemOneResult(
+ model=PUSH_GATE_MODEL, answers={"alters": NoulAnswer(probability=probability)}, input_tokens=10
+ )
+ return client
+
+
+_CODE_PUSH = _push(
+ new_commits=[_commit("a"), _commit("c")],
+ pr_files=[_file("posthog/billing.py", _BILLING_FIX), _file("README.md")],
+ own_commit_files=[_file("posthog/billing.py", _BILLING_FIX), _file("README.md")],
+)
+
+
+ [
+ (
+ "force_push_back",
+ _push(new_commits=[_commit("a")], pr_files=[_file("posthog/billing.py", _BILLING)]),
+ "no_new_commits",
+ True,
+ ),
+ # Master's commits are on the base, so only the merge commit is new, and the PR's lines only moved.
+ (
+ "base_merge",
+ _push(
+ new_commits=[_commit("a"), _commit("m", merge=True)],
+ pr_files=[_file("posthog/billing.py", _BILLING_AFTER_MERGE)],
+ ),
+ "merge_only",
+ True,
+ ),
+ (
+ "rebase",
+ _push(new_commits=[_commit("a2")], pr_files=[_file("posthog/billing.py", _BILLING_AFTER_MERGE)]),
+ "merge_only",
+ True,
+ ),
+ # ReviewHog never reviews lockfiles, yet a lockfile bump is the author's own change, not a merge.
+ (
+ "lockfile_bump",
+ _push(
+ new_commits=[_commit("a"), _commit("c")],
+ pr_files=[_file("posthog/billing.py", _BILLING), _file("pnpm-lock.yaml")],
+ own_commit_files=[_file("pnpm-lock.yaml")],
+ ),
+ "docs_only",
+ False,
+ ),
+ (
+ "docs_and_generated_files",
+ _push(
+ new_commits=[_commit("a"), _commit("c")],
+ pr_files=[_file("posthog/billing.py", _BILLING), _file("README.md")],
+ own_commit_files=[_file("README.md"), _file("frontend/src/generated/core/api.ts")],
+ ),
+ "docs_only",
+ False,
+ ),
+ ]
+)
+def test_push_gate_matches_pushes_without_own_code_changes(
+ _name: str, responses: dict[str, dict[str, Any] | None], reason: str, skip: bool
+) -> None:
+ system_one = _system_one(0.99)
+ decision = _decide(responses, system_one)
+ assert (decision.would_skip, decision.skip, decision.reason) == (True, skip, reason)
+ system_one.decide.assert_not_called()
+
+
+ [
+ ("likely_behavior_change_runs", 0.8, False, False, False, "system_one_above_threshold"),
+ ("shadow_skip_while_switched_off", 0.2, False, True, False, "system_one_below_threshold"),
+ ("skip_once_switched_on", 0.2, True, True, True, "system_one_below_threshold"),
+ ]
+)
+def test_push_gate_asks_system_one_about_own_code_commits(
+ _name: str, probability: float, enabled: bool, would_skip: bool, skip: bool, reason: str
+) -> None:
+ system_one = _system_one(probability)
+ with patch(f"{_MODULE}.SKIP_SYSTEM_ONE", enabled):
+ decision = _decide(_CODE_PUSH, system_one)
+ assert (decision.would_skip, decision.skip, decision.reason, decision.probability, decision.model) == (
+ would_skip,
+ skip,
+ reason,
+ probability,
+ PUSH_GATE_MODEL,
+ )
+ call = system_one.decide.call_args.kwargs
+ # The threshold was calibrated on exactly this state: own code patches, docs dropped.
+ assert call["state"] == f"--- posthog/billing.py\n{_BILLING_FIX}"
+ assert "round" not in str(call["questions"]["alters"].instructions)
+
+
+ [
+ ("not_configured", SystemOneNotConfigured("no gateway")),
+ ("request_failed", SystemOneRequestFailed("HTTP 500", status_code=500)),
+ ]
+)
+def test_push_gate_reviews_the_push_when_system_one_is_unavailable(_name: str, error: Exception) -> None:
+ system_one = MagicMock()
+ system_one.decide.side_effect = error
+ with patch(f"{_MODULE}.SKIP_SYSTEM_ONE", True):
+ decision = _decide(_CODE_PUSH, system_one)
+ assert (decision.skip, decision.would_skip, decision.reason) == (False, False, "system_one_unavailable")
+
+
+ [
+ (
+ "merge_resolves_conflict",
+ _push(
+ new_commits=[_commit("a"), _commit("m", merge=True)],
+ pr_files=[_file("posthog/billing.py", _BILLING_FIX)],
+ ),
+ "interdiff_too_large",
+ ),
+ ("compare_gone", {**_CODE_PUSH, "compare/master...new": None}, "compare_unavailable"),
+ (
+ "force_push_drops_commit",
+ {
+ "compare/master...old": _pr([_commit("a"), _commit("c")], [_file("posthog/billing.py", _BILLING_FIX)]),
+ "compare/master...new": _pr([_commit("a")], [_file("posthog/billing.py", _BILLING)]),
+ },
+ "commits_removed",
+ ),
+ (
+ "patch_left_out",
+ _push(
+ new_commits=[_commit("a"), _commit("c")],
+ pr_files=[_file("posthog/billing.py", None)],
+ own_commit_files=[_file("posthog/billing.py", None)],
+ ),
+ "interdiff_too_large",
+ ),
+ ]
+)
+def test_push_gate_reviews_a_push_it_cannot_see(
+ _name: str, responses: dict[str, dict[str, Any] | None], reason: str
+) -> None:
+ system_one = _system_one(0.0)
+ with patch(f"{_MODULE}.SKIP_SYSTEM_ONE", True):
+ decision = _decide(responses, system_one)
+ assert (decision.skip, decision.reason) == (False, reason)
+ system_one.decide.assert_not_called()
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 afbb29b01b30..64d4d302f3f5 100644
--- a/products/review_hog/backend/tests/test_review_completed_tracking.py
+++ b/products/review_hog/backend/tests/test_review_completed_tracking.py
@@ -28,10 +28,13 @@ from products.review_hog.backend.reviewer.persistence import (
persist_verdicts,
upsert_review_report,
)
+from products.review_hog.backend.reviewer.push_gate import PushGateDecision
from products.review_hog.backend.temporal.activities import (
+ GatePushInput,
TrackReviewCompletedInput,
TrackReviewFailedInput,
TrackReviewStartedInput,
+ _gate_push,
_track_review_completed,
_track_review_completed_safe,
_track_review_failed,
@@ -247,6 +250,61 @@ class TestTrackReviewCompleted(BaseTest):
assert flash.kwargs["uuid"] == flash_retry.kwargs["uuid"]
assert full.kwargs["uuid"] != flash.kwargs["uuid"]
+ def test_a_skipped_push_rests_the_report_and_counts_once_per_head(self) -> None:
+ # A skipped turn ends before any stage that returns the report to rest, and a skipped turn
+ # keeps the next turn's run_index, so a run_index-keyed event would merge two skipped pushes.
+ report_id = self._review_report()
+ for head_sha in ("sha1", "sha2"):
+ persist_pr_snapshot(
+ team_id=self.team.id,
+ report_id=report_id,
+ head_sha=head_sha,
+ pr_metadata=_pr_metadata(),
+ pr_comments=[],
+ pr_files=[],
+ )
+ decision = PushGateDecision(
+ skip=True,
+ would_skip=True,
+ reason="system_one_below_threshold",
+ probability=0.03,
+ model="jevk5",
+ own_commits=2,
+ )
+
+ with (
+ patch("products.review_hog.backend.temporal.activities._installation_auth", return_value=("tok", None)),
+ patch("products.review_hog.backend.temporal.activities.PushGate") as gate,
+ patch("products.review_hog.backend.temporal.activities.posthoganalytics.capture") as capture,
+ ):
+ gate.return_value.decide.return_value = decision
+ for head_sha in ("sha1", "sha2"):
+ assert (
+ _gate_push(
+ GatePushInput(
+ team_id=self.team.id,
+ report_id=report_id,
+ repository="o/r",
+ previous_head_sha="sha0",
+ head_sha=head_sha,
+ run_index=2,
+ review_mode=REVIEW_MODE_FLASH,
+ )
+ )
+ == decision
+ )
+
+ assert ReviewReport.objects.for_team(self.team.id).get(id=report_id).status == ReviewReport.Status.IDLE
+ first, second = capture.call_args_list
+ assert first.kwargs["event"] == "reviewhog_push_gate_decided"
+ props = first.kwargs["properties"]
+ assert (props["skipped"], props["reason"], props["system_one_probability"]) == (
+ True,
+ "system_one_below_threshold",
+ 0.03,
+ )
+ assert first.kwargs["uuid"] != second.kwargs["uuid"]
+
def test_capture_failure_is_swallowed(self) -> None:
# Telemetry must never fail a review — losing this guard would fail review turns on any
# analytics outage.
diff --git a/products/review_hog/backend/tests/test_temporal_workflow.py b/products/review_hog/backend/tests/test_temporal_workflow.py
index 3f992f33c889..401fa62c57f3 100644
--- a/products/review_hog/backend/tests/test_temporal_workflow.py
+++ b/products/review_hog/backend/tests/test_temporal_workflow.py
@@ -22,6 +22,7 @@ from temporalio.worker import Worker
from products.review_hog.backend.reviewer.constants import BLIND_SPOT_PASS_NUMBER, VALIDATION_MAX_ATTEMPTS
from products.review_hog.backend.reviewer.fingerprint import ReviewHogMarker
+from products.review_hog.backend.reviewer.push_gate import PushGateDecision
from products.review_hog.backend.reviewer.status_comment import FinalizeStatusCommentInput
from products.review_hog.backend.reviewer.tools.select_perspectives import ChunkSelectionDTO, PerspectiveSelectionDTO
from products.review_hog.backend.temporal.activities import (
@@ -29,6 +30,7 @@ from products.review_hog.backend.temporal.activities import (
BuildBodyInput,
DedupResult,
FetchPRDataInput,
+ GatePushInput,
GenerateSchemasInput,
LoadBlindSpotsInput,
LoadedBlindSpotsSkillDTO,
@@ -124,6 +126,9 @@ async def _run_full_review_pr_workflow(
review_authored_prs: bool = False,
already_completed: bool = False,
pr_open: bool = True,
+ automatic_reviewed_head_sha: str | None = None,
+ gate_skips: bool = False,
+ fail_gate: bool = False,
) -> 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
@@ -185,6 +190,18 @@ async def _run_full_review_pr_workflow(
empty_diff=empty_diff,
already_completed=already_completed,
pr_open=pr_open,
+ automatic_reviewed_head_sha=automatic_reviewed_head_sha,
+ )
+
+ gate_calls: list[str] = []
+
+ @activity.defn(name="gate_push_activity")
+ async def gate_push(input: GatePushInput) -> PushGateDecision:
+ gate_calls.append(input.previous_head_sha)
+ if fail_gate:
+ raise ApplicationError("compare exploded", non_retryable=True)
+ return PushGateDecision(
+ skip=gate_skips, would_skip=gate_skips, reason="merge_only" if gate_skips else "system_one_above_threshold"
)
@activity.defn(name="resolve_acting_user_activity")
@@ -302,9 +319,12 @@ async def _run_full_review_pr_workflow(
receipt_calls.append((input.outcome, input.review_url))
return None
+ status_posts: list[str] = []
+
@activity.defn(name="post_status_comment_activity")
async def post_status(input: StatusCommentInput) -> None:
_saw_mode("status", input.review_mode)
+ status_posts.append(input.report_id)
return None
@activity.defn(name="finalize_status_comment_activity")
@@ -361,6 +381,7 @@ async def _run_full_review_pr_workflow(
activities=[
validate_integration,
fetch,
+ gate_push,
resolve_acting_user,
sync_skills,
gen_schemas,
@@ -440,6 +461,8 @@ async def _run_full_review_pr_workflow(
"modes": mode_calls,
"efforts": effort_calls,
"markers": marker_calls,
+ "gate": gate_calls,
+ "status_posts": status_posts,
}
@@ -626,6 +649,42 @@ async def test_automatic_reviews_recheck_consent_and_skip_completed_or_closed_pr
assert bool(recorded["publish"]) is expected_review
+ "trigger_source,reviewed_head,gate_skips,fail_gate,expected_gate,expected_review",
+ [
+ ("automatic", None, True, False, [], True),
+ ("label", "sha0", True, False, [], True),
+ ("manual", "sha0", True, False, [], True),
+ ("automatic", "sha0", True, False, ["sha0"], False),
+ ("automatic", "sha0", False, False, ["sha0"], True),
+ # A broken gate must not silence automatic reviews.
+ ("automatic", "sha0", True, True, ["sha0"], True),
+ ],
+)
+async def test_push_gate_judges_only_automatic_follow_ups(
+ trigger_source: str,
+ reviewed_head: str | None,
+ gate_skips: bool,
+ fail_gate: bool,
+ expected_gate: list[str],
+ expected_review: bool,
+) -> None:
+ recorded = await _run_full_review_pr_workflow(
+ publish=True,
+ trigger_source=trigger_source,
+ review_mode="flash",
+ review_authored_prs=True,
+ automatic_reviewed_head_sha=reviewed_head,
+ gate_skips=gate_skips,
+ fail_gate=fail_gate,
+ )
+ assert recorded["gate"] == expected_gate
+ assert bool(recorded["review"]) is expected_review
+ assert bool(recorded["status_posts"]) is expected_review
+ assert bool(recorded["track_started"]) is expected_review
+
+
@pytest.mark.asyncio
async def test_review_pr_workflow_early_exits_when_already_published():
# A re-trigger at an already-published head: the gate returns the report id without running any