Repository navigation
[trymerge] Verify greenlight approved the exact commit being landed - #194809
jeanschmidt wants to merge 2 commits into
Conversation
**Impact:** mergebot only — PRs whose sole merge authorization is the `pytorchgreenlight` approval **Risk:** medium ## What Adds a land-time gate to `merge_into`: when the only approval that satisfies a merge rule is greenlight's, trymerge reads greenlight's verdict ledger over the new HUD `/api/greenlight/pr_state` route and refuses to land unless greenlight recorded `LAND` for the head commit that is actually being merged. The gate logic lives in new `greenlight_*.py` modules next to trymerge; `trymerge.py` only wires the PR facts in and turns the verdict into the exception the merge loop already understands. Three smaller changes in `trymerge.py` that are worth reading on their own: - `find_matching_merge_rule` gains an `approved_by_override` kwarg, so the guard can ask "would any rule still match if greenlight had not approved?" without duplicating rule evaluation. Default behaviour is unchanged. - The inline approver expansion is extracted to `rule_approvers`, and a malformed team ref (`org/team/extra`) now raises instead of expanding to nobody. Previously `gh_get_team_members` warned, returned `[]`, and the rule then matched *any* approver. - Two REST accessors (`get_updated_at`, `get_bot_reviewers`) added on `GitHubPR`. They are REST rather than fields on `GH_GET_PR_INFO_QUERY` because that query text is the cache key for the recorded GraphQL fixtures — extending it invalidates all of them. ## Why `merge_rules.yaml`'s "Greenlight Review Bot" rule lets a single `pytorchgreenlight` approval authorize a merge of any path, and pytorch/pytorch has no GitHub-native required reviews, so that approval is never dismissed when the author pushes more commits. Today an author can get greenlight's approval on a benign commit, push anything on top, and `@pytorchbot merge` lands unreviewed content. This closes that window by comparing the head SHA greenlight actually evaluated against the head being landed. # Notes Behaviour reviewers should sanity-check: - **Scope.** The guard is skipped entirely when greenlight did not approve, and when any other merge rule still matches after dropping greenlight's approval. A drive-by approval from a random GitHub user does *not* switch it off. - **Waiting.** "greenlight hasn't answered yet" raises `MandatoryChecksMissingError`, so the existing 5-minute retry loop handles it. The 60-minute budget is owned by `merge()` and shared across re-entries, and opens at the first wait (not at command time, since `merge_into` is only reached once CI is green). One comment is posted to the PR the first time it waits. - **Force merge.** `-f` gets no wait window and therefore never waits; it refuses instead if greenlight is the only authority and hasn't verified the head. - **ghstack.** Checked against each open PR's GitHub head, which is what greenlight records, not the `/orig` revision git cherry-picks. - **Failure modes.** A HUD outage is a wait, not a refusal, until the budget runs out; an unreadable `merge_rules.yaml` or an unclassifiable reviewer leaves the guard on rather than inventing an authorization. Depends on the `/api/greenlight/pr_state` route in pytorch/test-infra; `HUD_API_TOKEN` is already plumbed into `trymerge.yml`. Several preflight constants here mirror greenlight's own (review window, excluded labels, review timeout, the authorized-login set). Drift on either side makes this wait for a verdict that is never coming — the mirrored values are commented with their upstream source, and one test asserts `merge_rules.yaml` still grants `pytorchgreenlight` merge authority so a rename there can't silently disable the guard. Signed-off-by: Jean Schmidt <[email protected]>
🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/194809
Note: Links to docs will display an error until the docs builds have been completed. ❌ 3 New Failures, 2 PendingAs of commit 2b12927 with merge base e812f6f ( GREEN LIGHT - PR requires human review:
reason: NEW FAILURES - The following jobs have failed:
This comment was automatically generated by Dr. CI and updates every 15 minutes. |
|
PR requires human review Whyreason: |
- `greenlight_ledger.py`: reads the latest verdict row per PR from greenlight's
ClickHouse ledger through the HUD `/api/greenlight/pr_state` route, batching at
the route's 50-PR limit, retrying with backoff, and normalizing the route's
timestamps to aware UTC.
- `greenlight_guard.py`: the decision itself. Compares the head SHA greenlight
recorded against the head being landed and returns ALLOW / WAIT / DENY, plus the
wait budget (`GreenlightWaitWindow`) that `merge()` carries across re-entries.
- `greenlight_preflight.py`: mirrors greenlight's own skip filters (excluded
labels, review window, unresolved requested changes, approval by a login listed
in merge_rules.yaml) so a PR greenlight will never review is refused immediately
instead of after an hour of waiting.
- `greenlight_identity.py` / `greenlight_messages.py`: one login-normalization
rule shared by every comparison, and one place rendering the refusal, the wait
log line, and the PR comment.
- Tests for all three behavioural modules: the decision table, stack handling,
laziness of the per-PR GitHub lookups, transport failure modes, and the
preflight mirror.
Notes
`trymerge.py` at HEAD already imports these; this commit supplies the modules it
wires in. They are deliberately import-free of `trymerge` — `trymerge` imports
them, so the reverse would cycle. Everything the guard needs about a PR arrives
as plain data or as a callable on `PRUnderMerge`, and the callables stay callables
because each one costs a GitHub request that only the minority of PRs greenlight
alone authorizes ever needs.
Two failure directions were weighed and split deliberately: anything that is only
unknown (no ledger row, a verdict for an older commit, a review still running, an
unreadable HUD, a reviewer GitHub would not classify) waits and is refused only
once the budget is spent, while anything settled against the head being landed
(NO_LAND/CANCELLED/FAILED, an unrecognized status, a review that has outlived
greenlight's own timeout) refuses at once. The alternative — refusing on first
uncertainty — turns a HUD blip into a dead merge; the alternative in the other
direction — waiting on a settled negative — burns an hour and lands nothing.
The preflight constants (review window, excluded labels, review timeout, the
authorized-login set) are copies of greenlight's, cited in comments at each
definition. Drift on either side costs a merge an hour of waiting for a verdict
that was never coming, or refuses a PR greenlight would in fact have reviewed.
Test Plan
```
cd .github/scripts
python -m pytest test_greenlight_guard.py test_greenlight_ledger.py \
test_greenlight_preflight.py -q
```
104 passed. The ledger tests exercise the transport against a mocked
`gh_fetch_url` (every documented route error code, malformed payloads, batch
capping, backoff, recovery on retry), so no test touches the network.
Signed-off-by: Jean Schmidt <[email protected]>
|
@claude Confirm if this could be merged safely without the need to rebase other PRs |
|
Claude finished @huydhn's task in 10m 49s —— View job Yes — this should land safely without rebasing other PRsShort answer: nothing in this PR changes the shape of a merge commit, a branch, or a file that other in-flight PRs depend on, so no open PR needs a rebase. The risks are elsewhere (deployment ordering and one behavior change to AnalysisWhy no rebase is neededRebases become necessary when a landed change either (a) conflicts textually with in-flight branches, (b) changes generated/checked-in artifacts other PRs also regenerate, or (c) makes CI on stale bases fail. None of those apply:
What I'd actually double-check before landingThese are ordering/blast-radius items, not rebase items:
CI statusThe only failing check on this PR is Verdict: no rebase of other PRs required. The gate is the |
|
A forward-looking questions: How tight is the connection between merge bot and Greenlight bot at the moment? Focusing on Greenlight bot, I want to avoid a situation when we try to onboard Greenlight bot to, ExecuTorch for example, and things are tangled because we build it in a way that only works with merge bot. Could Greenlight bot work with regular GitHub repos that don't use merge bot? |
Not currently, given github does not consider its stamp as binding (still haven't give it this permission) so the stamp it gives does not allow you to click on "Squash and merge" buttom. But, there is a drawback of not using pytorchbot, race condition. It will behave exactly like a human approval will: you can submit any change after the approval, so, unless there is sufficient time between a submitting changes, greenlight review and revoke the approval, the PR can still be merged. This can only be enforced with either requiring every merge be approved for the exact ref (a repo change that affects all approvals) or pytorchbot. |
|
I'll resubmit this one, most of LOC are tests, but I want to keep under the limits that our saniy-checks require. |
|
exploded this one in a gstack: #194841 |
I see. That makes sense. Let's chat more about this (after 27th). I want to clarify that I mean merge bot here, specifically, the trymerge.py script, and not pytorchbot in general. IMO, coupling greenlight bot and merge bot means limiting the usefulness of greenlight bot in the long run because bringing merge bot to other repos is tough and also out of scope. And then, telling other repos that they couldn't use greenlight bot because they don't have merge bot doesn't sound good neither. |
Impact: try-merge and mergebot
Risk: medium
What
Adds a land-time gate to
merge_into: when greenlight's approval is the only one thatsatisfies a merge rule, trymerge reads greenlight's verdict ledger over the HUD
/api/greenlight/pr_stateroute and refuses to land unless greenlight recordedLANDfor the head commit actually being merged. The decision logic lives in new
greenlight_*.pymodules next to trymerge (guard, ledger client, preflight mirror,login normalization, message rendering);
trymerge.pyonly feeds PR facts in and turnsthe verdict into an exception the existing merge loop already understands.
Three smaller
trymerge.pychanges worth reading on their own:find_matching_merge_rulegains anapproved_by_overridekwarg so the guard can ask"would any rule still match if greenlight had not approved?" without duplicating rule
evaluation. Default behaviour is unchanged.
rule_approvers, and a malformed teamref (
org/team/extra) now raises instead of expanding to nobody. Previouslygh_get_team_memberswarned, returned[], and the rule then matched any approver.GitHubPR(get_updated_at,get_bot_reviewers). REST ratherthan new fields on
GH_GET_PR_INFO_QUERY, because that query text is the cache key forthe recorded GraphQL fixtures and extending it invalidates all of them.
Why
The "Greenlight Review Bot" rule in
merge_rules.yamllets a singlepytorchgreenlightapproval authorize a merge of any path, and pytorch/pytorch has no GitHub-native required
reviews, so that approval is never dismissed when the author pushes more commits. Today an
author can get greenlight's approval on a benign commit, push anything on top, and
@pytorchbot mergelands unreviewed content.Notes
Review the modules commit first, then the wiring commit — the second is mostly call-site
plumbing once the guard's contract is clear.
Behaviour worth sanity-checking:
other merge rule still matches after dropping greenlight's approval. A drive-by approval
from a random GitHub user does not switch it off.
commit, a review still in flight, an unreadable HUD) waits; anything settled against the
head being landed (
NO_LAND/CANCELLED/FAILED, unknown status, a review pastgreenlight's own timeout) refuses immediately. Waits raise
MandatoryChecksMissingError, so the existing 5-minute retry loop handles them. The60-minute budget is owned by
merge(), shared across re-entries, and opens at the firstwait rather than at command time (
merge_intois only reached once CI is green). Onecomment is posted to the PR the first time it waits.
-fgets no wait window and so never waits; it refuses instead ifgreenlight is the only authority and hasn't verified the head.
records, not the
/origrevision git cherry-picks.merge_rules.yamlor an unclassifiable reviewerleaves the guard on rather than inventing an authorization.
Depends on the
/api/greenlight/pr_stateroute in pytorch/test-infra;HUD_API_TOKENisalready plumbed into
trymerge.yml.Several preflight constants mirror greenlight's own (review window, excluded labels,
review timeout, the authorized-login set). Drift on either side makes this wait for a
verdict that is never coming, or refuse a PR greenlight would have reviewed — each
mirrored value is commented with its upstream source, and one test asserts
merge_rules.yamlstill grantspytorchgreenlightmerge authority so a rename therecan't silently disable the guard.