: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): throttle automatic follow-up reviews per pull request (#116849)
Julian Bezf604f0a69a7e
diff --git a/products/review_hog/ARCHITECTURE.md b/products/review_hog/ARCHITECTURE.mdindex 6c6d56e0b4f9..311de4139fd4 100644--- a/products/review_hog/ARCHITECTURE.md+++ b/products/review_hog/ARCHITECTURE.md@@ -939,11 +939,12 @@ 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), `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.+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`), `draft` (the PR is a draft and no earlier rule skips the push), and `throttled` (the PR spent its review budget).+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 after the gate's other reads: 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.+The `throttled` rule keeps a token bucket per PR in Redis (`PUSH_BUDGET`): it holds two reviews and gets one back every 30 minutes. Only a push that every earlier rule lets through takes a token, so a draft push or a merge from the base costs nothing. A push that finds the bucket empty waits for the next trigger like any other skip. A Redis failure reviews the push. A head pays once: a turn that runs again at the same head, as an activity retry or a retried `review-pr` child, does not take a second token. A retry after a denial asks the bucket again, so it cannot get past the budget. The first review and human triggers never reach the gate, so they neither take nor need a token.+Each rule has a `SKIP_*` switch. `no_new_commits`, `reviewhog_commits_only`, `merge_only`, `draft`, and `throttled` 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`, 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.+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 and the reason, so a draft or throttle skip and a later review 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.diff --git a/products/review_hog/backend/reviewer/push_gate.py b/products/review_hog/backend/reviewer/push_gate.pyindex 4e3345972bea..a93e4261b02c 100644--- a/products/review_hog/backend/reviewer/push_gate.py+++ b/products/review_hog/backend/reviewer/push_gate.py@@ -16,6 +16,11 @@ The rules, in order. The first rule that matches gives the reason:6. `draft`: the PR is a draft and no rule above skips the push. A draft cannot merge, and marking itready 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.+7. `throttled`: the PR spent its review budget. Each PR has a token bucket (Turner 1986) that holds+ `PUSH_BUDGET.burst` reviews and gets one back every `3600 / PUSH_BUDGET.per_hour` seconds. A push+ that every rule above lets through takes a token, and a push that finds the bucket empty waits:+ the next turn that runs reviews everything since the last reviewed head. This caps bursts of+ pushes, and it never schedules a review on its own.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@@ -30,11 +35,14 @@ import loggingfrom typing import Any, Literalimport requests+from redis.exceptions import RedisErrorfrom posthog.dataclasses import frozenfrom posthog.egress.github.transport import GitHubRateLimitErrorfrom posthog.llm.system_one import NoulAnswer, NoulQuestion, SystemOneNotConfigured, SystemOneRequestFailedfrom posthog.llm.system_one_client import build_system_one_client+from posthog.redis import get_client+from posthog.token_bucket import BucketUnavailable, Budget, consumefrom products.review_hog.backend.app_identity import posthog_app_loginfrom products.review_hog.backend.reviewer.tools.github_client import GitHubAPIError, github_api_request, matches_app_bot@@ -49,6 +57,12 @@ SKIP_MERGE_ONLY = TrueSKIP_DOCS_ONLY = FalseSKIP_SYSTEM_ONE = FalseSKIP_DRAFT = True+SKIP_THROTTLED = True++# Picked by the replay in `review-eval/experiments/2026-10-14-review-throttle`.+PUSH_BUDGET = Budget(burst=2, per_hour=2)+# Longer than a turn and its retry take, so a retried turn finds that its head paid already.+_PAID_HEAD_TTL_SECONDS = 6 * 3600# 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.@@ -94,7 +108,13 @@ _NON_CODE_FILE = re.compile()SkipReason = Literal[- "no_new_commits", "reviewhog_commits_only", "merge_only", "docs_only", "system_one_below_threshold", "draft"+ "no_new_commits",+ "reviewhog_commits_only",+ "merge_only",+ "docs_only",+ "system_one_below_threshold",+ "draft",+ "throttled",]RunReason = Literal["commits_removed",@@ -160,6 +180,8 @@ def _rule_enabled(reason: SkipReason) -> bool:return SKIP_DOCS_ONLYif reason == "draft":return SKIP_DRAFT+ if reason == "throttled":+ return SKIP_THROTTLEDreturn SKIP_SYSTEM_ONE@@ -377,3 +399,32 @@ def apply_draft_rule(decision: PushGateDecision, *, draft: bool) -> PushGateDecimodel=decision.model,own_code_lines=decision.own_code_lines,)+++def apply_throttle(decision: PushGateDecision, *, report_id: str, head_sha: str) -> PushGateDecision:+ """Rule 7, last: a push that the rules before it skip takes no token. Without Redis the push runs.++ A head pays once. A failed turn runs again as a new activity or a new child workflow, and a+ retry that charged again could find the bucket empty and drop a review that passed the budget.+ """+ if decision.skip:+ return decision+ paid_key = f"reviewhog_push_budget_paid:{report_id}:{head_sha}"+ client = get_client()+ try:+ first_charge = client.set(paid_key, 1, nx=True, ex=_PAID_HEAD_TTL_SECONDS)+ except RedisError:+ return decision+ if not first_charge:+ return decision+ bucket = consume(f"reviewhog_push_budget:{report_id}", PUSH_BUDGET)+ if isinstance(bucket, BucketUnavailable) or bucket.allowed:+ return decision+ client.delete(paid_key)+ return _matched(+ "throttled",+ 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/temporal/activities.py b/products/review_hog/backend/temporal/activities.pyindex 61ce4529e84c..03932c9fc33a 100644--- a/products/review_hog/backend/temporal/activities.py+++ b/products/review_hog/backend/temporal/activities.py@@ -121,6 +121,7 @@ from products.review_hog.backend.reviewer.push_gate import (PushGate,PushGateDecision,apply_draft_rule,+ apply_throttle,)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_published@@ -2261,12 +2262,12 @@ def _track_push_gate_decided(input: GatePushInput, decision: PushGateDecision, ddistinct_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. 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.+ # pushes in a row share one. The draft state and the reason are in the key too, because one head+ # can get a draft or throttle skip and later a review, after the PR is marked ready or the bucket refills.uuid=str(uuid5(NAMESPACE_URL,- f"reviewhog_push_gate_decided:{input.report_id}:{input.head_sha}:{input.review_mode}:{draft}",+ f"reviewhog_push_gate_decided:{input.report_id}:{input.head_sha}:{input.review_mode}:{draft}:{decision.reason}",)),properties={@@ -2322,13 +2323,14 @@ def _gate_push(input: GatePushInput) -> PushGateDecision: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.+ # drops the ready request for the head this turn gates. So a draft skip reads GitHub again after the+ # gate's other reads, 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 = Falsedecision = push_decision+ decision = apply_throttle(decision, report_id=input.report_id, head_sha=input.head_sha)if decision.skip:ReviewReport.objects.for_team(input.team_id).filter(id=input.report_id).update(status=ReviewReport.Status.IDLE)try:diff --git a/products/review_hog/backend/tests/test_push_gate.py b/products/review_hog/backend/tests/test_push_gate.pyindex 0983e54999a4..8005a633b79d 100644--- a/products/review_hog/backend/tests/test_push_gate.py+++ b/products/review_hog/backend/tests/test_push_gate.py@@ -1,12 +1,24 @@+from collections.abc import Iterator+from datetime import UTC, datetime, timedeltafrom typing import Any+import pytest+import time_machinefrom unittest.mock import MagicMock, patchfrom 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, apply_draft_rule+from posthog.redis import TEST_clear_clients+from posthog.token_bucket import BucketUnavailable, TEST_reset_scripts++from products.review_hog.backend.reviewer.push_gate import (+ PUSH_GATE_MODEL,+ PushGate,+ PushGateDecision,+ apply_draft_rule,+ apply_throttle,+)from products.review_hog.backend.reviewer.tools.github_client import GitHubAPIError_MODULE = "products.review_hog.backend.reviewer.push_gate"@@ -322,3 +334,57 @@ def test_push_gate_skips_a_draft_push_and_keeps_the_system_one_answer(decision.model,decision.own_code_lines,) == expected+++def empty_redis() -> Iterator[None]:+ TEST_clear_clients()+ TEST_reset_scripts()+ yield+ TEST_clear_clients()+ TEST_reset_scripts()+++def test_push_gate_throttles_the_third_push_in_half_an_hour(empty_redis: None) -> None:+ reviewed = PushGateDecision(skip=False, would_skip=False, reason="system_one_above_threshold", probability=0.9)+ draft = PushGateDecision(skip=True, would_skip=True, reason="draft")+ pushes = [+ # A push that an earlier rule skips takes no token.+ (0, "pr-a", "a1", draft),+ (0, "pr-a", "a2", reviewed),+ (1, "pr-a", "a3", reviewed),+ # A retried turn at a head that paid already runs without a second token.+ (2, "pr-a", "a3", reviewed),+ (2, "pr-b", "b1", reviewed),+ (3, "pr-a", "a4", reviewed),+ # A retry after a denial asks the bucket again.+ (4, "pr-a", "a4", reviewed),+ # One token comes back 30 minutes after the first one went.+ (31, "pr-a", "a5", reviewed),+ (32, "pr-a", "a6", reviewed),+ ]+ start = datetime(2026, 10, 14, 12, 0, tzinfo=UTC)+ outcomes = []+ with time_machine.travel(start, tick=False) as clock:+ for minutes, report_id, head_sha, decision in pushes:+ clock.move_to(start + timedelta(minutes=minutes))+ result = apply_throttle(decision, report_id=report_id, head_sha=head_sha)+ outcomes.append((result.skip, result.reason, result.probability))++ assert outcomes == [+ (True, "draft", None),+ (False, "system_one_above_threshold", 0.9),+ (False, "system_one_above_threshold", 0.9),+ (False, "system_one_above_threshold", 0.9),+ (False, "system_one_above_threshold", 0.9),+ (True, "throttled", 0.9),+ (True, "throttled", 0.9),+ (False, "system_one_above_threshold", 0.9),+ (True, "throttled", 0.9),+ ]+++def test_push_gate_reviews_the_push_when_redis_is_down(empty_redis: None) -> None:+ reviewed = PushGateDecision(skip=False, would_skip=False, reason="system_one_above_threshold")+ with patch(f"{_MODULE}.consume", return_value=BucketUnavailable(error="down")):+ assert apply_throttle(reviewed, report_id="pr-a", head_sha="a1") == reviewed