: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): log the chance of another push at the push gate (#116866)
Julian Bez8e6be11515c3
diff --git a/products/review_hog/ARCHITECTURE.md b/products/review_hog/ARCHITECTURE.mdindex 311de4139fd4..a4f301d84cf2 100644--- a/products/review_hog/ARCHITECTURE.md+++ b/products/review_hog/ARCHITECTURE.md@@ -939,12 +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), `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).+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), `next_push_likely` (the PR is not a draft, no earlier rule matched, and the chance of another automatic follow-up is at least `NEXT_PUSH_SKIP_AT`), 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.+The `next_push_likely` chance comes from a table fitted offline on closed PRs and refitted by hand. Its key is the follow-up number, capped at 8, and the PR size band (additions plus deletions: up to 200, up to 1000, more). A size cell with fewer than 10 PRs falls back to the chance for the follow-up number alone. The follow-up number is `run_index - 1`, so it also counts label and UI turns, which the fit left out.+Each rule has a `SKIP_*` switch. `no_new_commits`, `reviewhog_commits_only`, `merge_only`, `draft`, and `throttled` skip; `docs_only`, System One, and `next_push_likely` (`SKIP_NEXT_PUSH`) 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 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.+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), `pr_draft`, the draft state the gate used (null when the snapshot is unavailable), and `next_push_probability` (null on a draft and when the snapshot is unavailable; set on every other decision, also when another rule decided); 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 a93e4261b02c..ef4a684938a1 100644--- a/products/review_hog/backend/reviewer/push_gate.py+++ b/products/review_hog/backend/reviewer/push_gate.py@@ -16,7 +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+7. `next_push_likely`: on a PR that is not a draft, when no rule above matched, another automatic+ follow-up is likely to come. Skipped changes add up and the next review covers them. The chance+ comes from a table fitted offline on the follow-up number and the PR size. Every decision on a+ PR that is not a draft records the chance, also when another rule decided.+8. `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 pushthat 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@@ -32,6 +36,7 @@ in `review-eval/production/push-gate`. The threshold is only valid for the stateimport reimport logging+from dataclasses import replacefrom typing import Any, Literalimport requests@@ -57,8 +62,12 @@ SKIP_MERGE_ONLY = TrueSKIP_DOCS_ONLY = FalseSKIP_SYSTEM_ONE = FalseSKIP_DRAFT = True+# Before this goes on, `next_push_likely` must defer only once per reviewed head. A skip does not+# advance run_index, so the same chance would match every later push and no review would run.+SKIP_NEXT_PUSH = FalseSKIP_THROTTLED = True+NEXT_PUSH_SKIP_AT = 0.85# 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.@@ -76,6 +85,57 @@ MAX_OWN_COMMITS = 20# GitHub's compare endpoint pages its commit list at this size._COMPARE_COMMITS_PER_PAGE = 100+SizeBand = Literal["<=200", "201-1000", ">1000"]+++@frozen+class _NextPushCell:+ probability: float+ prs: int+++# The chance that another automatic follow-up comes after follow-up number k, from review-eval+# experiments/2026-10-14-draft-deferral (NextPushLookup), fitted on closed PostHog/posthog PRs from+# Oct 8-14 2026. A refit updates these tables by hand. Key 8 holds every follow-up from the eighth on.+_NEXT_PUSH_LAST_FOLLOW_UP = 8+_NEXT_PUSH_MIN_CELL_PRS = 10+_NEXT_PUSH_BY_FOLLOW_UP: dict[int, float] = {+ 1: 0.629,+ 2: 0.625,+ 3: 0.740,+ 4: 0.812,+ 5: 0.710,+ 6: 0.731,+ 7: 0.842,+ 8: 0.783,+}+_NEXT_PUSH_BY_FOLLOW_UP_AND_SIZE: dict[tuple[int, SizeBand], _NextPushCell] = {+ (1, "<=200"): _NextPushCell(probability=0.559, prs=111),+ (1, "201-1000"): _NextPushCell(probability=0.652, prs=69),+ (1, ">1000"): _NextPushCell(probability=1.000, prs=17),+ (2, "<=200"): _NextPushCell(probability=0.542, prs=72),+ (2, "201-1000"): _NextPushCell(probability=0.667, prs=60),+ (2, ">1000"): _NextPushCell(probability=0.800, prs=20),+ (3, "<=200"): _NextPushCell(probability=0.722, prs=36),+ (3, "201-1000"): _NextPushCell(probability=0.735, prs=49),+ (3, ">1000"): _NextPushCell(probability=0.800, prs=15),+ (4, "<=200"): _NextPushCell(probability=0.667, prs=27),+ (4, "201-1000"): _NextPushCell(probability=0.824, prs=34),+ (4, ">1000"): _NextPushCell(probability=1.000, prs=19),+ (5, "<=200"): _NextPushCell(probability=0.706, prs=17),+ (5, "201-1000"): _NextPushCell(probability=0.606, prs=33),+ (5, ">1000"): _NextPushCell(probability=0.895, prs=19),+ (6, "<=200"): _NextPushCell(probability=0.833, prs=12),+ (6, "201-1000"): _NextPushCell(probability=0.524, prs=21),+ (6, ">1000"): _NextPushCell(probability=0.895, prs=19),+ (7, "<=200"): _NextPushCell(probability=0.900, prs=10),+ (7, "201-1000"): _NextPushCell(probability=0.909, prs=11),+ (7, ">1000"): _NextPushCell(probability=0.765, prs=17),+ (8, "<=200"): _NextPushCell(probability=0.643, prs=28),+ (8, "201-1000"): _NextPushCell(probability=0.719, prs=32),+ (8, ">1000"): _NextPushCell(probability=0.842, prs=101),+}+_QUESTION_ID = "alters"# The commits stay in the state, so text from the pull request can never become an instruction._ALTERS_QUESTION = NoulQuestion(@@ -114,6 +174,7 @@ SkipReason = Literal["docs_only","system_one_below_threshold","draft",+ "next_push_likely","throttled",]RunReason = Literal[@@ -137,6 +198,7 @@ class PushGateDecision:own_commits: int | None = None# Lines the new own commits change in code files, summed per commit. Set only when the gate read every file.own_code_lines: int | None = None+ next_push_probability: float | None = None@frozen@@ -180,11 +242,35 @@ def _rule_enabled(reason: SkipReason) -> bool:return SKIP_DOCS_ONLYif reason == "draft":return SKIP_DRAFT+ if reason == "next_push_likely":+ return SKIP_NEXT_PUSHif reason == "throttled":return SKIP_THROTTLEDreturn SKIP_SYSTEM_ONE+def _size_band(pr_lines: int) -> SizeBand:+ if pr_lines <= 200:+ return "<=200"+ if pr_lines <= 1000:+ return "201-1000"+ return ">1000"+++def next_push_probability(*, follow_up: int, pr_lines: int) -> float | None:+ """The chance that another automatic follow-up comes after follow-up number `follow_up` (1-based).++ `pr_lines` is the PR's additions plus deletions.+ """+ if follow_up < 1:+ return None+ follow_up = min(follow_up, _NEXT_PUSH_LAST_FOLLOW_UP)+ cell = _NEXT_PUSH_BY_FOLLOW_UP_AND_SIZE.get((follow_up, _size_band(pr_lines)))+ if cell is not None and cell.prs >= _NEXT_PUSH_MIN_CELL_PRS:+ return cell.probability+ return _NEXT_PUSH_BY_FOLLOW_UP[follow_up]++def _matched(reason: SkipReason,*,@@ -401,8 +487,30 @@ def apply_draft_rule(decision: PushGateDecision, *, draft: bool) -> PushGateDeci)+def apply_next_push_rule(+ decision: PushGateDecision, *, follow_up: int | None, pr_lines: int | None+) -> PushGateDecision:+ """Rule 7, only for a PR that is not a draft. It records the chance also when another rule decided.++ `follow_up` is the number of this automatic follow-up (1-based) and `pr_lines` is the PR's+ additions plus deletions. Both are None when they are unknown.+ """+ probability = None+ if follow_up is not None and pr_lines is not None:+ probability = next_push_probability(follow_up=follow_up, pr_lines=pr_lines)+ if probability is not None and probability >= NEXT_PUSH_SKIP_AT and not decision.would_skip:+ decision = _matched(+ "next_push_likely",+ own_commits=decision.own_commits,+ probability=decision.probability,+ model=decision.model,+ own_code_lines=decision.own_code_lines,+ )+ return replace(decision, next_push_probability=probability)++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.+ """Rule 8, 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 aretry that charged again could find the bucket empty and drop a review that passed the budget.@@ -421,10 +529,4 @@ def apply_throttle(decision: PushGateDecision, *, report_id: str, head_sha: str)if isinstance(bucket, BucketUnavailable) or bucket.allowed:return decisionclient.delete(paid_key)- return _matched(- "throttled",- own_commits=decision.own_commits,- probability=decision.probability,- model=decision.model,- own_code_lines=decision.own_code_lines,- )+ return replace(decision, skip=_rule_enabled("throttled"), would_skip=True, reason="throttled")diff --git a/products/review_hog/backend/temporal/activities.py b/products/review_hog/backend/temporal/activities.pyindex 03932c9fc33a..60de93d2a484 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_next_push_rule,apply_throttle,)from products.review_hog.backend.reviewer.review_design import REVIEW_DESIGN_PIPELINE, REVIEW_DESIGN_SINGLE_AGENT@@ -2284,6 +2285,7 @@ def _track_push_gate_decided(input: GatePushInput, decision: PushGateDecision, d"own_commits": decision.own_commits,"own_code_lines": decision.own_code_lines,"pr_draft": draft,+ "next_push_probability": decision.next_push_probability,},groups=groups(team=report.team),)@@ -2330,6 +2332,15 @@ def _gate_push(input: GatePushInput) -> PushGateDecision:):draft = Falsedecision = push_decision+ if not draft:+ # The offline fit counted only automatic follow-ups. No turn stores its trigger, so this+ # count is the completed turns after the first review, which also includes label, UI,+ # and other human turns.+ decision = apply_next_push_rule(+ decision,+ follow_up=input.run_index - 1,+ pr_lines=current.pr_metadata.additions + current.pr_metadata.deletions,+ )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)diff --git a/products/review_hog/backend/tests/test_push_gate.py b/products/review_hog/backend/tests/test_push_gate.pyindex 8005a633b79d..ebd6a3976260 100644--- a/products/review_hog/backend/tests/test_push_gate.py+++ b/products/review_hog/backend/tests/test_push_gate.py@@ -16,8 +16,11 @@ from products.review_hog.backend.reviewer.push_gate import (PUSH_GATE_MODEL,PushGate,PushGateDecision,+ _NextPushCell,apply_draft_rule,+ apply_next_push_rule,apply_throttle,+ next_push_probability,)from products.review_hog.backend.reviewer.tools.github_client import GitHubAPIError@@ -83,7 +86,12 @@ def _github(responses: dict[str, dict[str, Any] | None]):def _decide(- responses: dict[str, dict[str, Any] | None], system_one: MagicMock | None = None, *, draft: bool = False+ responses: dict[str, dict[str, Any] | None],+ system_one: MagicMock | None = None,+ *,+ draft: bool = False,+ follow_up: int | None = None,+ pr_lines: int | None = None,) -> PushGateDecision:with (patch(f"{_MODULE}.github_api_request", side_effect=_github(responses)),@@ -93,7 +101,9 @@ def _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)+ if draft:+ return apply_draft_rule(decision, draft=True)+ return apply_next_push_rule(decision, follow_up=follow_up, pr_lines=pr_lines)def _system_one(probability: float) -> MagicMock:@@ -325,7 +335,8 @@ def test_push_gate_skips_a_draft_push_and_keeps_the_system_one_answer(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)+ decision = _decide(responses, _system_one(0.8), draft=True, follow_up=7, pr_lines=150)+ assert decision.next_push_probability is Noneassert (decision.skip,decision.would_skip,@@ -388,3 +399,56 @@ def test_push_gate_reviews_the_push_when_redis_is_down(empty_redis: None) -> Nonreviewed = 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+++ [+ ("size_cell", 1, 150, {}, 0.559),+ ("size_band_upper_edge", 1, 200, {}, 0.559),+ ("capped_at_the_eighth_follow_up", 12, 5000, {}, 0.842),+ ("small_cell_falls_back", 7, 150, {(7, "<=200"): _NextPushCell(probability=0.900, prs=9)}, 0.842),+ ("no_follow_up_yet", 0, 150, {}, None),+ ]+)+def test_next_push_probability_reads_the_size_cell_or_falls_back(+ _name: str, follow_up: int, pr_lines: int, cells: dict[Any, _NextPushCell], expected: float | None+) -> None:+ with patch.dict(f"{_MODULE}._NEXT_PUSH_BY_FOLLOW_UP_AND_SIZE", cells):+ assert next_push_probability(follow_up=follow_up, pr_lines=pr_lines) == expected+++_DOCS_PUSH = _push(+ new_commits=[_commit("a"), _commit("c")],+ pr_files=[_file("posthog/billing.py", _BILLING), _file("README.md")],+ own_commit_files=[_file("README.md")],+)+++ [+ ("below_threshold_runs", _CODE_PUSH, 0.8, 1, 150, (False, False, "system_one_above_threshold", 0.559)),+ ("at_threshold_shadow_skip", _CODE_PUSH, 0.8, 8, 5000, (False, True, "next_push_likely", 0.842)),+ ("unknown_size_runs", _CODE_PUSH, 0.8, 7, None, (False, False, "system_one_above_threshold", None)),+ ("docs_only_shadow_keeps_reason", _DOCS_PUSH, 0.8, 7, 150, (False, True, "docs_only", 0.900)),+ ("system_one_shadow_keeps_reason", _CODE_PUSH, 0.1, 7, 150, (False, True, "system_one_below_threshold", 0.900)),+ (+ "skipping_rule_keeps_reason",+ _push(new_commits=[_commit("a")], pr_files=[_file("posthog/billing.py", _BILLING)]),+ 0.8,+ 7,+ 150,+ (True, True, "no_new_commits", 0.900),+ ),+ ]+)+def test_push_gate_records_a_likely_next_push_without_skipping(+ _name: str,+ responses: dict[str, dict[str, Any] | None],+ system_one_probability: float,+ follow_up: int,+ pr_lines: int | None,+ expected: tuple[bool, bool, str, float | None],+) -> None:+ with patch(f"{_MODULE}.NEXT_PUSH_SKIP_AT", 0.842):+ decision = _decide(responses, _system_one(system_one_probability), follow_up=follow_up, pr_lines=pr_lines)+ assert (decision.skip, decision.would_skip, decision.reason, decision.next_push_probability) == expecteddiff --git a/products/review_hog/backend/tests/test_review_completed_tracking.py b/products/review_hog/backend/tests/test_review_completed_tracking.pyindex 75747622c855..9d4acd65c4d0 100644--- a/products/review_hog/backend/tests/test_review_completed_tracking.py+++ b/products/review_hog/backend/tests/test_review_completed_tracking.py@@ -345,23 +345,23 @@ class TestTrackReviewCompleted(BaseTest):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,- )+ results = [+ _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)+ for head_sha in ("sha1", "sha2")+ ]assert ReviewReport.objects.for_team(self.team.id).get(id=report_id).status == ReviewReport.Status.IDLE+ assert [(result.skip, result.reason) for result in results] == [(True, "system_one_below_threshold")] * 2first, second = capture.call_args_listassert first.kwargs["event"] == "reviewhog_push_gate_decided"props = first.kwargs["properties"]@@ -372,8 +372,9 @@ class TestTrackReviewCompleted(BaseTest):14,)assert first.kwargs["uuid"] != second.kwargs["uuid"]- # Each push reports the draft state of its own head.+ # Each push reports the draft state of its own head, and only a ready PR gets a next push chance.assert (props["pr_draft"], second.kwargs["properties"]["pr_draft"]) == (True, False)+ assert (props["next_push_probability"], second.kwargs["properties"]["next_push_probability"]) == (None, 0.559)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()