: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 a small-change deferral at the push gate (#117687)
Julian Bez38dc47f07f66
diff --git a/products/review_hog/ARCHITECTURE.md b/products/review_hog/ARCHITECTURE.mdindex 98f22813c5a3..67c40e833f08 100644--- a/products/review_hog/ARCHITECTURE.md+++ b/products/review_hog/ARCHITECTURE.md@@ -962,13 +962,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), `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).+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), `small_change` (the compare of the last reviewed head and the push head changes 1 to `SMALL_CHANGE_MAX_NET_CODE_LINES` code lines; a per-PR Redis counter allows `SMALL_CHANGE_MAX_DEFERRALS` deferrals in a row, then the next small push runs the review), `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.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.+Each rule has a `SKIP_*` switch. `no_new_commits`, `reviewhog_commits_only`, `merge_only`, `draft`, and `throttled` skip; `docs_only`, `small_change`, 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), `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.+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), `net_code_lines` and `small_change_deferrals` (empty when the gate did not read them), `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/DECISIONS.md b/products/review_hog/DECISIONS.mdindex b4ce094d271e..fb66be718376 100644--- a/products/review_hog/DECISIONS.md+++ b/products/review_hog/DECISIONS.md@@ -198,6 +198,50 @@ read `FINAL_REPORT.md` there first (config glossary + coverage matrix + ranking)rate drops materially (toward ≤50%) on frozen-PR evals with the valid-finding set intact (item 5'scoverage matrix as the guard); kill if valid findings drop with the noise.+### ✅ BUILT 2026-10-15 — push gate: small-change deferral (shadow)++- **What.** A new push gate rule, `small_change`, sits after `docs_only` and before `system_one_below_threshold`. It+ matches a push that changes 1 to `SMALL_CHANGE_MAX_NET_CODE_LINES` (10) code lines net: the additions plus deletions+ of the GitHub compare between the last reviewed head and the push head, over files `_NON_CODE_FILE` does not match.+ A capped file list or a file without counts makes the net lines unknown, and the rule does not match. A per-PR+ counter in Redis allows `SMALL_CHANGE_MAX_DEFERRALS` (2) deferrals in a row: the next small push runs the review and+ sets the counter to 0, and so does any push the rule does not match. Without Redis the rule does not match. A retried+ turn at the same head reuses the count of its first attempt. The count is stored with a compare-and-set: when another+ turn stored a count first or the write fails, the small push runs the review (`small_change_not_stored`). `SKIP_SMALL_CHANGE = False`, so the rule only logs:+ every decision carries `net_code_lines` and `small_change_deferrals` on `reviewhog_push_gate_decided`.+- **Why.** Since Oct 14 14:33 UTC, 71% of automatic follow-up runs surfaced nothing. The chance that a run surfaces+ something grows with the net code lines of the push, and small pushes rarely surface anything.+- **Evidence.**+ - Surfacing rate by net code lines of the push (run 3+, 367 runs; run 2 under the changed-code rule looks the+ same):++ | Net code lines | 0 | 1-10 | 11-30 | 31-100 | 101-300 | >300 |+ | ---------------------------- | --- | ---- | ----- | ------ | ------- | ---- |+ | Runs that surfaced something | 6% | 3% | 12% | 23% | 35% | 56% |++ - An offline replay of 527 follow-ups on 243 PRs (review-eval `experiments/2026-10-15-gate-surfacing`): deferring at+ 10 net lines with two deferrals in a row at most saves about 16% of follow-up spend (9% of all Standard spend). It+ withholds 7 of 167 surfaced findings at the deferred push (3 of them on docs-only pushes) and 0 of 40 must-fix+ labels (95% upper bound 10%).+ - A 30-line threshold saves 25% but withholds 3 must-fix labels.+ - A fitted probability model did not beat the size buckets (Brier 0.145 vs 0.148). A cost-per-probability term+ changed 7 of 125 deferrals.+ - `own_code_lines` counts churn: a rebase counts every commit again, which made large pushes look small-yield in an+ earlier read. The rule uses net lines for that reason.++- **Not chosen.**+ - A 30-line threshold: it withholds must-fix findings.+ - A probability model: no better than the size buckets.+ - A per-repo cost term: it changes few deferrals.+ - System One: its below-threshold pushes carried must-fix labels at the same rate as the rest.+- **Before it goes live.**+ - A few days of shadow decisions. In shadow mode the review still runs and moves the baseline, so net lines are per+ push, not added up over deferred pushes as in live mode.+ - The final-push gap: in the replay 62 of 243 PRs ended on a deferred push, 33 of them merged. That needs a review+ started when stamphog asks for evidence on a deferred head, and a visible "latest push not reviewed yet" state on+ the PR.+ - One baseline for the gate and the posting filter.+### ✅ BUILT 2026-10-15 — automatic Standard follow-ups post only changed-code findings from run 2 on- **What.** `FLASH_WHOLE_PR_TURNS` goes from 2 to 1. Run 1 still reviews the whole pull request with the doubleddiff --git a/products/review_hog/backend/reviewer/push_gate.py b/products/review_hog/backend/reviewer/push_gate.pyindex ef4a684938a1..04b59548d039 100644--- a/products/review_hog/backend/reviewer/push_gate.py+++ b/products/review_hog/backend/reviewer/push_gate.py@@ -12,15 +12,24 @@ The rules, in order. The first rule that matches gives the reason:3. `merge_only`: the PR's full diff against its base is the same at both heads (a base merge or arebase). 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+5. `small_change`: the push changes at most `SMALL_CHANGE_MAX_NET_CODE_LINES` code lines net, read from+ the compare of the last reviewed head and the push head. The rule matches only when the push head+ descends from the last reviewed head: after a rebase or a force-push the compare does not show the+ push's own change. After `SMALL_CHANGE_MAX_DEFERRALS` deferrals in a row the next small push runs the+ review, so small pushes cannot pile up without a review. A push that every rule lets through to a review+ sets the count back to 0. A push that a rule skips keeps the count, because nothing was reviewed. The+ count is stored only after the last rule has decided, so a draft or throttle skip also keeps it. When+ the count cannot be stored, because another turn of the PR stored one after this turn read it or Redis+ refuses the write, a small push runs the review.+6. `system_one_below_threshold`: System One rates the new own commits below a threshold.+7. `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. `next_push_likely`: on a PR that is not a draft, when no rule above matched, another automatic+8. `next_push_likely`: on a PR that is not a draft, when no rule above matched, another automaticfollow-up is likely to come. Skipped changes add up and the next review covers them. The chancecomes from a table fitted offline on the follow-up number and the PR size. Every decision on aPR 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+9. `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@@ -60,6 +69,7 @@ SKIP_NO_NEW_COMMITS = TrueSKIP_REVIEWHOG_COMMITS_ONLY = TrueSKIP_MERGE_ONLY = TrueSKIP_DOCS_ONLY = False+SKIP_SMALL_CHANGE = FalseSKIP_SYSTEM_ONE = FalseSKIP_DRAFT = True# Before this goes on, `next_push_likely` must defer only once per reviewed head. A skip does not@@ -68,6 +78,19 @@ SKIP_NEXT_PUSH = FalseSKIP_THROTTLED = TrueNEXT_PUSH_SKIP_AT = 0.85+# Picked by the replay in `review-eval/experiments/2026-10-15-gate-surfacing`.+SMALL_CHANGE_MAX_NET_CODE_LINES = 10+SMALL_CHANGE_MAX_DEFERRALS = 2+# Long enough to span a PR's quiet days, short enough that an abandoned PR's counter goes away.+_SMALL_CHANGE_DEFERRALS_TTL_SECONDS = 3 * 24 * 3600+# Compare-and-set: two turns of one PR can overlap, and each counts from the value it read.+_STORE_STREAK_IF_UNCHANGED = """+if (redis.call('GET', KEYS[1]) or '') ~= ARGV[1] then+ return 0+end+redis.call('SET', KEYS[1], ARGV[2], 'EX', ARGV[3])+return 1+"""# 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.@@ -172,6 +195,7 @@ SkipReason = Literal["reviewhog_commits_only","merge_only","docs_only",+ "small_change","system_one_below_threshold","draft","next_push_likely",@@ -184,6 +208,7 @@ RunReason = Literal["interdiff_too_large","compare_unavailable","snapshot_unavailable",+ "small_change_not_stored",]@@ -199,6 +224,10 @@ class PushGateDecision:# 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 = Nonenext_push_probability: float | None = None+ # Lines the push changes in code files between the last reviewed head and this head.+ net_code_lines: int | None = None+ # Small-change deferrals in a row after this decision. None when the gate did not read the counter.+ small_change_deferrals: int | None = None@frozen@@ -240,6 +269,8 @@ def _rule_enabled(reason: SkipReason) -> bool:return SKIP_MERGE_ONLYif reason == "docs_only":return SKIP_DOCS_ONLY+ if reason == "small_change":+ return SKIP_SMALL_CHANGEif reason == "draft":return SKIP_DRAFTif reason == "next_push_likely":@@ -278,6 +309,8 @@ def _matched(probability: float | None = None,model: str | None = None,own_code_lines: int | None = None,+ net_code_lines: int | None = None,+ small_change_deferrals: int | None = None,) -> PushGateDecision:return PushGateDecision(skip=_rule_enabled(reason),@@ -287,6 +320,8 @@ def _matched(model=model,own_commits=own_commits,own_code_lines=own_code_lines,+ net_code_lines=net_code_lines,+ small_change_deferrals=small_change_deferrals,)@@ -352,6 +387,8 @@ class PushGate:self.repository = repositoryself._token = tokenself._installation_id = installation_id+ # The counter value the last read saw, so the store can tell whether another turn moved it.+ self._small_change_seen = ""def _get(self, path: str, *, endpoint: str, params: dict[str, str | int] | None = None) -> dict[str, Any] | None:try:@@ -400,6 +437,56 @@ class PushGate:files.extend(commit_files)return _CommitFiles(files=files, complete=complete)+ def _net_code_lines(self, previous_head_sha: str, head_sha: str) -> int | None:+ """Code lines the push changes between the two heads, or None when GitHub does not give every count."""+ comparison = self._get(+ f"/compare/{previous_head_sha}...{head_sha}",+ endpoint="/compare/{basehead}",+ params={"per_page": _COMPARE_COMMITS_PER_PAGE},+ )+ if comparison is None:+ return None+ # A three-dot compare starts at the merge base, so its files are the push's change only when+ # the push head descends from the last reviewed head.+ merge_base_sha = (comparison.get("merge_base_commit") or {}).get("sha")+ if comparison.get("status") != "ahead" or merge_base_sha != previous_head_sha:+ return None+ files: list[dict[str, Any]] = comparison.get("files") or []+ if len(files) >= GITHUB_COMPARE_FILES_CAP:+ return None+ lines = 0+ for file in files:+ if _NON_CODE_FILE.search(file["filename"]):+ continue+ additions = file.get("additions")+ deletions = file.get("deletions")+ if additions is None or deletions is None:+ return None+ lines += additions + deletions+ return lines++ def _small_change_key(self, pr_number: int) -> str:+ return f"reviewhog_small_change_deferrals:{self.repository}:{pr_number}"++ def _small_change_streak_after(self, *, pr_number: int, head_sha: str, small: bool) -> int | None:+ """The small-change deferrals in a row after this push, or None when Redis is unavailable.++ A small push below the limit adds one. Any other push sets the count to 0, which also makes the+ push after `SMALL_CHANGE_MAX_DEFERRALS` deferrals run the review. A retried turn at the same head+ gets the count of its first attempt, so a retry does not count the push again.+ """+ try:+ stored = get_client().get(self._small_change_key(pr_number))+ except RedisError:+ return None+ self._small_change_seen = stored.decode() if stored else ""+ stored_head, stored_count = self._small_change_seen.split(":") if stored else ("", "0")+ if stored_head == head_sha:+ return int(stored_count)+ if small and int(stored_count) < SMALL_CHANGE_MAX_DEFERRALS:+ return int(stored_count) + 1+ return 0+def _ask_system_one(self, code_files: list[_ChangedFile], own_commits: int, lines_known: bool) -> PushGateDecision:lines = sum(file.changes for file in code_files) if lines_known else Noneif any(file.patch is None for file in code_files):@@ -437,11 +524,7 @@ class PushGate:own_code_lines=lines,)- 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`.-- Rules 1 to 5 only: `apply_draft_rule` adds rule 6 on top of the result.- """+ def _judge(self, *, previous_head_sha: str, head_sha: str, base_branch: str, pr_number: int) -> PushGateDecision: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:@@ -471,11 +554,72 @@ class PushGate:code_files = [file for file in own_files.files if not _NON_CODE_FILE.search(file.filename)]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)+ net_code_lines = self._net_code_lines(previous_head_sha, head_sha)+ small = net_code_lines is not None and 1 <= net_code_lines <= SMALL_CHANGE_MAX_NET_CODE_LINES+ # The count moves in shadow mode too, so the logged would_skip sequence follows what live mode would+ # do. In shadow mode the review still runs and moves the baseline, so net lines count from the+ # previous push and do not add up over the deferred pushes as they would in live mode.+ deferrals = self._small_change_streak_after(pr_number=pr_number, head_sha=head_sha, small=small)+ if small and deferrals is not None and deferrals > 0:+ return _matched(+ "small_change",+ own_commits=len(own_shas),+ own_code_lines=sum(file.changes for file in code_files) if own_files.complete else None,+ net_code_lines=net_code_lines,+ small_change_deferrals=deferrals,+ )+ decision = self._ask_system_one(code_files, own_commits=len(own_shas), lines_known=own_files.complete)+ return replace(decision, net_code_lines=net_code_lines, small_change_deferrals=deferrals)++ def decide(self, *, previous_head_sha: str, head_sha: str, base_branch: str, pr_number: int) -> PushGateDecision:+ """Judge the push from `previous_head_sha`, the last automatically reviewed head, to `head_sha`.++ Rules 1 to 6 only: `apply_draft_rule` adds rule 7 on top of the result. The decision carries the+ small-change count, and `record_small_change_streak` stores it after the last rule has decided.+ """+ decision = self._judge(+ previous_head_sha=previous_head_sha, head_sha=head_sha, base_branch=base_branch, pr_number=pr_number+ )+ if decision.skip:+ return decision+ if decision.small_change_deferrals is not None:+ return decision+ deferrals = self._small_change_streak_after(pr_number=pr_number, head_sha=head_sha, small=False)+ return replace(decision, small_change_deferrals=deferrals)++ def record_small_change_streak(+ self, decision: PushGateDecision, *, pr_number: int, head_sha: str+ ) -> PushGateDecision:+ """Store the small-change count of the final decision, and return the decision that applies.++ The store succeeds only when the counter still holds the value `decide` read. When another turn+ moved it first, or the write fails, the next push would count from the old value, so a small-change+ match runs the review.+ """+ # Apart from `decide`, because the draft and throttle rules run later and can still skip the review.+ if decision.small_change_deferrals is None:+ return decision+ # A rule skipped the review, so the baseline did not move and the stored count stays.+ if decision.skip and decision.reason != "small_change":+ return decision+ try:+ stored = get_client().register_script(_STORE_STREAK_IF_UNCHANGED)(+ keys=[self._small_change_key(pr_number)],+ args=[+ self._small_change_seen,+ f"{head_sha}:{decision.small_change_deferrals}",+ _SMALL_CHANGE_DEFERRALS_TTL_SECONDS,+ ],+ )+ except RedisError:+ stored = 0+ if stored or decision.reason != "small_change":+ return decision+ return replace(decision, skip=False, would_skip=False, reason="small_change_not_stored")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."""+ """Rule 7, 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 decisionreturn _matched(@@ -484,13 +628,15 @@ def apply_draft_rule(decision: PushGateDecision, *, draft: bool) -> PushGateDeciprobability=decision.probability,model=decision.model,own_code_lines=decision.own_code_lines,+ net_code_lines=decision.net_code_lines,+ small_change_deferrals=decision.small_change_deferrals,)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.+ """Rule 8, 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'sadditions plus deletions. Both are None when they are unknown.@@ -505,12 +651,14 @@ def apply_next_push_rule(probability=decision.probability,model=decision.model,own_code_lines=decision.own_code_lines,+ net_code_lines=decision.net_code_lines,+ small_change_deferrals=decision.small_change_deferrals,)return replace(decision, next_push_probability=probability)def apply_throttle(decision: PushGateDecision, *, report_id: str, head_sha: str) -> PushGateDecision:- """Rule 8, last: a push that the rules before it skip takes no token. Without Redis the push runs.+ """Rule 9, 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.diff --git a/products/review_hog/backend/temporal/activities.py b/products/review_hog/backend/temporal/activities.pyindex 571d38d87fff..eea1da21db95 100644--- a/products/review_hog/backend/temporal/activities.py+++ b/products/review_hog/backend/temporal/activities.py@@ -2318,6 +2318,8 @@ def _track_push_gate_decided(input: GatePushInput, decision: PushGateDecision, d"system_one_skip_below": SYSTEM_ONE_SKIP_BELOW,"own_commits": decision.own_commits,"own_code_lines": decision.own_code_lines,+ "net_code_lines": decision.net_code_lines,+ "small_change_deferrals": decision.small_change_deferrals,"pr_draft": draft,"next_push_probability": decision.next_push_probability,},@@ -2344,6 +2346,7 @@ def _pr_is_draft_now(repository: str, pr_number: int, *, token: str, installatiodef _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)+ gate: PushGate | None = Noneif current is None:decision = PushGateDecision(skip=False, would_skip=False, reason="snapshot_unavailable")else:@@ -2355,6 +2358,7 @@ def _gate_push(input: GatePushInput) -> PushGateDecision:previous_head_sha=input.previous_head_sha,head_sha=input.head_sha,base_branch=current.pr_metadata.base_branch,+ pr_number=current.pr_metadata.number,)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@@ -2376,6 +2380,10 @@ def _gate_push(input: GatePushInput) -> PushGateDecision: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 gate is not None and current is not None:+ decision = gate.record_small_change_streak(+ decision, pr_number=current.pr_metadata.number, 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 ebd6a3976260..e09b95860d67 100644--- a/products/review_hog/backend/tests/test_push_gate.py+++ b/products/review_hog/backend/tests/test_push_gate.py@@ -7,9 +7,10 @@ import time_machinefrom unittest.mock import MagicMock, patchfrom parameterized import parameterized+from redis.exceptions import RedisErrorfrom posthog.llm.system_one import NoulAnswer, SystemOneNotConfigured, SystemOneRequestFailed, SystemOneResult-from posthog.redis import TEST_clear_clients+from posthog.redis import TEST_clear_clients, get_clientfrom posthog.token_bucket import BucketUnavailable, TEST_reset_scriptsfrom products.review_hog.backend.reviewer.push_gate import (@@ -58,6 +59,18 @@ def _own_commit(sha: str) -> dict[str, Any]:return _commit(sha, author=_REVIEWHOG_BOT, committer=_REVIEWHOG_BOT, verified=True)+def _net_file(filename: str, lines: int) -> dict[str, Any]:+ return {"filename": filename, "additions": lines, "deletions": 0}+++def _net_compare(files: list[dict[str, Any]], *, status: str = "ahead") -> dict[str, Any]:+ return {"status": status, "merge_base_commit": {"sha": "old"}, "files": files}+++# Large enough that the small-change rule leaves the push to the rules after it.+_LARGE_NET_FILES = [_net_file("posthog/billing.py", 40)]++def _pr(commits: list[dict[str, Any]], files: list[dict[str, Any]]) -> dict[str, Any]:return {"total_commits": len(commits), "commits": commits, "files": files}@@ -67,10 +80,13 @@ def _push(new_commits: list[dict[str, Any]],pr_files: list[dict[str, Any]],own_commit_files: list[dict[str, Any]] | None = None,+ net_files: list[dict[str, Any]] | None = None,+ head: str = "new",) -> 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),+ f"compare/master...{head}": _pr(new_commits, pr_files),+ f"compare/old...{head}": _net_compare(_LARGE_NET_FILES if net_files is None else net_files),"commits/c": {"files": own_commit_files or []},}@@ -92,18 +108,24 @@ def _decide(draft: bool = False,follow_up: int | None = None,pr_lines: int | None = None,+ head: str = "new",+ record: bool = False,+ gate: PushGate | None = None,) -> PushGateDecision:+ gate = gate or PushGate(team_id=1, repository="PostHog/posthog", token="t", installation_id="9")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]"),):- decision = PushGate(team_id=1, repository="PostHog/posthog", token="t", installation_id="9").decide(- previous_head_sha="old", head_sha="new", base_branch="master"- )+ decision = gate.decide(previous_head_sha="old", head_sha=head, base_branch="master", pr_number=1)if draft:- return apply_draft_rule(decision, draft=True)- return apply_next_push_rule(decision, follow_up=follow_up, pr_lines=pr_lines)+ decision = apply_draft_rule(decision, draft=True)+ else:+ decision = apply_next_push_rule(decision, follow_up=follow_up, pr_lines=pr_lines)+ if record:+ decision = gate.record_small_change_streak(decision, pr_number=1, head_sha=head)+ return decisiondef _system_one(probability: float) -> MagicMock:@@ -347,10 +369,13 @@ def test_push_gate_skips_a_draft_push_and_keeps_the_system_one_answer() == expected+# Autouse because every gate decision on a code push reads the small-change counter.[email protected](autouse=True)def empty_redis() -> Iterator[None]:TEST_clear_clients()TEST_reset_scripts()+ # The fake Redis server outlives its clients, so a counter from an earlier test would stay.+ get_client().flushdb()yieldTEST_clear_clients()TEST_reset_scripts()@@ -452,3 +477,185 @@ def test_push_gate_records_a_likely_next_push_without_skipping(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) == expected+++def _small_push(head: str, net_files: list[dict[str, Any]]) -> dict[str, dict[str, Any] | None]:+ return _push(+ new_commits=[_commit("a"), _commit("c")],+ pr_files=[_file("posthog/billing.py", _BILLING_FIX)],+ own_commit_files=[_file("posthog/billing.py", _BILLING_FIX)],+ net_files=net_files,+ head=head,+ )+++ [+ (+ "small_push_shadow",+ _small_push("new", [_net_file("posthog/billing.py", 4), _net_file("README.md", 50)]),+ (False, True, "small_change", 4, 1),+ ),+ (+ "eleven_lines_runs",+ _small_push("new", [_net_file("posthog/billing.py", 11)]),+ (False, False, "system_one_above_threshold", 11, 0),+ ),+ (+ "capped_compare_is_unknown",+ _small_push("new", [_net_file(f"posthog/module_{n}.py", 1) for n in range(300)]),+ (False, False, "system_one_above_threshold", None, 0),+ ),+ (+ "rebased_head_is_unknown",+ {+ **_small_push("new", []),+ "compare/old...new": _net_compare([_net_file("posthog/billing.py", 3)], status="diverged"),+ },+ (False, False, "system_one_above_threshold", None, 0),+ ),+ (+ "missing_count_is_unknown",+ _small_push("new", [{"filename": "posthog/billing.py"}]),+ (False, False, "system_one_above_threshold", None, 0),+ ),+ (+ "no_code_lines_stays_docs_only",+ {**_DOCS_PUSH, "compare/old...new": _net_compare([_net_file("posthog/billing.py", 3)])},+ (False, True, "docs_only", None, 0),+ ),+ ]+)+def test_push_gate_defers_a_push_with_few_net_code_lines(+ _name: str,+ responses: dict[str, dict[str, Any] | None],+ expected: tuple[bool, bool, str, int | None, int | None],+) -> None:+ decision = _decide(responses, _system_one(0.8))+ assert (+ decision.skip,+ decision.would_skip,+ decision.reason,+ decision.net_code_lines,+ decision.small_change_deferrals,+ ) == expected+++def test_push_gate_reviews_the_small_push_after_two_deferrals() -> None:+ small = [_net_file("posthog/billing.py", 3)]+ pushes = [+ ("n1", small),+ ("n2", small),+ ("n2", small),+ ("n3", small),+ ("n4", small),+ ("n5", [_net_file("posthog/billing.py", 30)]),+ ("n6", small),+ ]+ outcomes = []+ for head, net_files in pushes:+ decision = _decide(_small_push(head, net_files), _system_one(0.8), head=head, record=True)+ outcomes.append((decision.reason, decision.small_change_deferrals))++ assert outcomes == [+ ("small_change", 1),+ ("small_change", 2),+ ("small_change", 2),+ ("system_one_above_threshold", 0),+ ("small_change", 1),+ ("system_one_above_threshold", 0),+ ("small_change", 1),+ ]+++def test_push_gate_reviews_a_small_push_whose_count_another_turn_moved() -> None:+ small = [_net_file("posthog/billing.py", 3)]+ _decide(_small_push("n1", small), _system_one(0.8), head="n1", record=True)+ first = PushGate(team_id=1, repository="PostHog/posthog", token="t", installation_id="9")+ second = PushGate(team_id=1, repository="PostHog/posthog", token="t", installation_id="9")+ overlapping = [+ (first, "n2", _decide(_small_push("n2", small), _system_one(0.8), head="n2", gate=first)),+ (second, "n3", _decide(_small_push("n3", small), _system_one(0.8), head="n3", gate=second)),+ ]++ recorded = [+ gate.record_small_change_streak(decision, pr_number=1, head_sha=head) for gate, head, decision in overlapping+ ]++ assert [(decision.reason, decision.would_skip) for decision in recorded] == [+ ("small_change", True),+ ("small_change_not_stored", False),+ ]+ assert get_client().get("reviewhog_small_change_deferrals:PostHog/posthog:1") == b"n2:2"+++ [+ ("read_fails", True, ("system_one_above_threshold", 3, None)),+ ("write_fails", False, ("small_change_not_stored", 3, 1)),+ ]+)+def test_push_gate_reviews_a_small_push_when_redis_fails(+ _name: str, read_fails: bool, expected: tuple[str, int, int | None]+) -> None:+ redis = MagicMock()+ if read_fails:+ redis.get.side_effect = RedisError("down")+ else:+ redis.get.return_value = None+ redis.register_script.return_value.side_effect = RedisError("read only")+ with patch(f"{_MODULE}.get_client", return_value=redis):+ decision = _decide(_small_push("new", [_net_file("posthog/billing.py", 3)]), _system_one(0.8), record=True)+ assert (decision.reason, decision.net_code_lines, decision.small_change_deferrals) == expected+++ [+ (+ "reviewed_docs_push_resets",+ _push(+ new_commits=[_commit("a"), _commit("c")],+ pr_files=[_file("posthog/billing.py", _BILLING), _file("README.md")],+ own_commit_files=[_file("README.md")],+ head="n3",+ ),+ False,+ [("docs_only", 0), ("small_change", 1)],+ ),+ (+ "skipped_merge_keeps_streak",+ _push(+ new_commits=[_commit("a"), _commit("m", merge=True)],+ pr_files=[_file("posthog/billing.py", _BILLING_AFTER_MERGE)],+ head="n3",+ ),+ False,+ [("merge_only", None), ("system_one_above_threshold", 0)],+ ),+ (+ "draft_skip_of_the_forced_review_keeps_streak",+ _small_push("n3", [_net_file("posthog/billing.py", 3)]),+ True,+ [("draft", 0), ("system_one_above_threshold", 0)],+ ),+ ]+)+def test_push_gate_small_change_streak_after_a_push_another_rule_decides(+ _name: str,+ middle_push: dict[str, dict[str, Any] | None],+ middle_draft: bool,+ expected_tail: list[tuple[str, int | None]],+) -> None:+ small = [_net_file("posthog/billing.py", 3)]+ pushes = [+ ("n1", _small_push("n1", small), False),+ ("n2", _small_push("n2", small), False),+ ("n3", middle_push, middle_draft),+ ("n4", _small_push("n4", small), False),+ ]+ outcomes = []+ for head, responses, draft in pushes:+ decision = _decide(responses, _system_one(0.8), draft=draft, head=head, record=True)+ outcomes.append((decision.reason, decision.small_change_deferrals))++ assert outcomes == [("small_change", 1), ("small_change", 2), *expected_tail]diff --git a/products/review_hog/backend/tests/test_review_completed_tracking.py b/products/review_hog/backend/tests/test_review_completed_tracking.pyindex 2bb47dfa0973..6f7e066ff098 100644--- a/products/review_hog/backend/tests/test_review_completed_tracking.py+++ b/products/review_hog/backend/tests/test_review_completed_tracking.py@@ -350,6 +350,7 @@ class TestTrackReviewCompleted(BaseTest):patch("products.review_hog.backend.temporal.activities.posthoganalytics.capture") as capture,):gate.return_value.decide.return_value = decision+ gate.return_value.record_small_change_streak.side_effect = lambda decision, **_: decisionresults = [_gate_push(GatePushInput(@@ -367,6 +368,8 @@ class TestTrackReviewCompleted(BaseTest):assert ReviewReport.objects.for_team(self.team.id).get(id=report_id).status == ReviewReport.Status.IDLEassert [(result.skip, result.reason) for result in results] == [(True, "system_one_below_threshold")] * 2+ recorded = gate.return_value.record_small_change_streak.call_args_list+ assert [call.args[0] for call in recorded] == resultsfirst, second = capture.call_args_listassert first.kwargs["event"] == "reviewhog_push_gate_decided"props = first.kwargs["properties"]