Skip to content

[trymerge] Add the greenlight land-time guard and its tests - #194840

Closed
jeanschmidt wants to merge 3 commits into
gh/jeanschmidt/3/basefrom
gh/jeanschmidt/3/head
Closed

jeanschmidt wants to merge 3 commits into
gh/jeanschmidt/3/basefrom
gh/jeanschmidt/3/head

Conversation

@jeanschmidt

@jeanschmidt jeanschmidt commented Aug 26, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

greenlight_guard.py is the decision itself. It compares the head SHA greenlight
recorded in its ledger against the head actually being landed and returns ALLOW, WAIT or
DENY, along with the wait budget (GreenlightWaitWindow) a merge carries across
re-entries. Everything it needs about a PR arrives as plain data or as a callable on
PRUnderMerge — the callables stay callables because each one costs a GitHub request
that only the minority of PRs greenlight alone authorizes ever needs. It must not import
trymerge: trymerge imports it, and the cycle would break both.

Two failure directions are 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. 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. Refusing on first
uncertainty would turn a HUD blip into a dead merge; waiting on a settled negative would
burn an hour and land nothing.

The tests cover the decision table, stack handling, the laziness of the per-PR GitHub
lookups, the ledger's transport failure modes against a mocked gh_fetch_url (every
documented route error code, malformed payloads, batch capping, backoff, recovery on
retry), and the preflight mirror. No test touches the network. They land together with
the guard because test_greenlight_guard.py owns the shared PR fixtures that the ledger
and preflight tests build on.

Split out from the trymerge.py wiring so the verdict logic can be reviewed against
greenlight's behaviour independently of the merge path, and to keep each change under the
2000 LOC infra limit. Nothing calls into this yet.

Signed-off-by: Jean Schmidt [email protected]

[ghstack-poisoned]
@jeanschmidt
jeanschmidt requested a review from a team as a code owner August 26, 2026 01:03
@pytorch-bot

pytorch-bot Bot commented Aug 26, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

🧪 See artifacts and rendered test results at hud.pytorch.org/pr/194840

Note: Links to docs will display an error until the docs builds have been completed.

⏳ No Failures, 19 Pending

As of commit aa8b8b6 with merge base e812f6f (image):
💚 Looks good so far! There are no failures yet. 💚

GREEN LIGHT - OUTDATED (earlier commit) - PR requires human review:

This change is too large for the automated reviewer to read in full, so it is
being declined automatically; a human reviewer should assess it.

reason: scope_too_large
Reviewed commit: 93de5ef (NOT the current head aa8b8b6)

Inference job

This comment was automatically generated by Dr. CI and updates every 15 minutes.

pytorchgreenlight[bot]
pytorchgreenlight Bot previously approved these changes Aug 26, 2026
Comment thread .github/scripts/greenlight_guard.py Outdated
else:
outcomes = [_evaluate_pr(pr, states.get(pr.pr_num), moment) for pr in guarded]

unresolved = [o for o in outcomes if o.verdict is not GuardVerdict.ALLOW]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: double negative is a bit hard to read, why not just say if all verdict are GuardVerdict.ALLOW, then GuardVerdict.ALLOW

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

claude came up with an even better code, let me submit it :)

return GuardResult(GuardVerdict.ALLOW)

try:
states = fetch(repo_full_name, [pr.pr_num for pr in guarded])

@huydhn huydhn Aug 27, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How does this fetch handle missing or invalid HUD_API_TOKEN? My read here is that when it happens, for example, we rotate the token, greenlight guard would continue to wait. I'm trying to debate with myself if this is a good or bad behaviour. I'm leaning more on the latter because HUD_API_TOKEN has already been set in the ongoing merge job and can't be updated.

Wdyt about?

  • Receiving client side 400/401/405 -> fail fast, and surface the error
  • Receiving flaky 5xx -> retry again up to MAX_WAIT_MINUTES

@jeanschmidt jeanschmidt Aug 27, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

you are right, in this case failing fast is better, given that there is no possible recover except from cancel the job and try again. Albeit this would be a very exotic occurrence...

jeanschmidt added a commit that referenced this pull request Aug 27, 2026
`greenlight_guard.py` is the decision itself. It compares the head SHA greenlight
recorded in its ledger against the head actually being landed and returns ALLOW, WAIT or
DENY, along with the wait budget (`GreenlightWaitWindow`) a merge carries across
re-entries. Everything it needs about a PR arrives as plain data or as a callable on
`PRUnderMerge` — the callables stay callables because each one costs a GitHub request
that only the minority of PRs greenlight alone authorizes ever needs. It must not import
`trymerge`: `trymerge` imports it, and the cycle would break both.

Two failure directions are 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. 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. Refusing on first
uncertainty would turn a HUD blip into a dead merge; waiting on a settled negative would
burn an hour and land nothing.

The tests cover the decision table, stack handling, the laziness of the per-PR GitHub
lookups, the ledger's transport failure modes against a mocked `gh_fetch_url` (every
documented route error code, malformed payloads, batch capping, backoff, recovery on
retry), and the preflight mirror. No test touches the network. They land together with
the guard because `test_greenlight_guard.py` owns the shared PR fixtures that the ledger
and preflight tests build on.

Split out from the `trymerge.py` wiring so the verdict logic can be reviewed against
greenlight's behaviour independently of the merge path, and to keep each change under the
2000 LOC infra limit. Nothing calls into this yet.

Signed-off-by: Jean Schmidt <[email protected]>
ghstack-source-id: 3865cf8
Pull-Request: #194840
@jeanschmidt

Copy link
Copy Markdown
Contributor Author

@huydhn

Implemented the changes, from claude:

You were right about the token: a rotated secret meant an hour of retries that
could never succeed, since a job's credentials are frozen at start.

I didn't take the status-code split, though. Most codes we'd actually see don't
come from the greenlight service itself — they come from the layer in front of
it, or from it being mid-deploy. A 401 during rotation is the clearest case: the
server only picks up a new token when it redeploys, while our secret flips
instantly, so those 401s are real but temporary. Failing fast would kill every
in-flight merge over something that clears itself in minutes.

Instead: a missing or malformed token is detectable locally, so that refuses
immediately and says re-running won't help. Everything else still retries, but on
a short budget rather than the full hour. Either way the wasted hour is gone.

Nit: done.

I also fixed two ways the guard could have allowed a merge it shouldn't have,
plus a path where a malformed secret could reach a public comment — those are
worth the closest look.

Left alone, flagging rather than burying: the same secret is read elsewhere in
trymerge where a failure is silently ignored, and force merge is also blocked
while the service is unreachable. Both pre-existing.

[ghstack-poisoned]
@pytorchgreenlight
pytorchgreenlight Bot dismissed their stale review August 27, 2026 23:38

Superseded by a newer greenlight verdict.

[ghstack-poisoned]
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Starting merge as part of PR stack under #194841

pytorchmergebot pushed a commit that referenced this pull request Aug 28, 2026
…194841)

**Impact:** mergebot only — PRs whose sole merge authorization is the `pytorchgreenlight`
approval
**Risk:** medium

Depends on pytorch/test-infra#8630 to be merged before merging this one

## What
Wires the greenlight land-time guard into `merge_into`: when the only approval that
satisfies a merge rule is greenlight's, trymerge reads greenlight's verdict ledger and
refuses to land unless greenlight recorded `LAND` for the head commit that is actually
being merged. The verdict logic already lives in the `greenlight_*.py` modules next to
trymerge; this change only feeds 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`.

This is the last change of the guard and the only one that alters existing behaviour;
the modules it calls landed ahead of it so that the merge-path wiring could be reviewed
on its own and each change stay under the 2000 LOC infra limit. One test here asserts
`merge_rules.yaml` still grants `pytorchgreenlight` merge authority, so a rename there
cannot silently disable the guard.

Signed-off-by: Jean Schmidt <[email protected]>
Pull Request resolved: #194841
Approved by: https://github.com/huydhn
ghstack dependencies: #194838, #194839, #194840
orrangetabby17 pushed a commit to orrangetabby17/pytorch that referenced this pull request Sep 2, 2026
…194840)

`greenlight_guard.py` is the decision itself. It compares the head SHA greenlight
recorded in its ledger against the head actually being landed and returns ALLOW, WAIT or
DENY, along with the wait budget (`GreenlightWaitWindow`) a merge carries across
re-entries. Everything it needs about a PR arrives as plain data or as a callable on
`PRUnderMerge` — the callables stay callables because each one costs a GitHub request
that only the minority of PRs greenlight alone authorizes ever needs. It must not import
`trymerge`: `trymerge` imports it, and the cycle would break both.

Two failure directions are 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. 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. Refusing on first
uncertainty would turn a HUD blip into a dead merge; waiting on a settled negative would
burn an hour and land nothing.

The tests cover the decision table, stack handling, the laziness of the per-PR GitHub
lookups, the ledger's transport failure modes against a mocked `gh_fetch_url` (every
documented route error code, malformed payloads, batch capping, backoff, recovery on
retry), and the preflight mirror. No test touches the network. They land together with
the guard because `test_greenlight_guard.py` owns the shared PR fixtures that the ledger
and preflight tests build on.

Split out from the `trymerge.py` wiring so the verdict logic can be reviewed against
greenlight's behaviour independently of the merge path, and to keep each change under the
2000 LOC infra limit. Nothing calls into this yet.

Signed-off-by: Jean Schmidt <[email protected]>
Pull Request resolved: pytorch#194840
Approved by: https://github.com/huydhn
ghstack dependencies: pytorch#194838, pytorch#194839
orrangetabby17 pushed a commit to orrangetabby17/pytorch that referenced this pull request Sep 2, 2026
…ytorch#194841)

**Impact:** mergebot only — PRs whose sole merge authorization is the `pytorchgreenlight`
approval
**Risk:** medium

Depends on pytorch/test-infra#8630 to be merged before merging this one

## What
Wires the greenlight land-time guard into `merge_into`: when the only approval that
satisfies a merge rule is greenlight's, trymerge reads greenlight's verdict ledger and
refuses to land unless greenlight recorded `LAND` for the head commit that is actually
being merged. The verdict logic already lives in the `greenlight_*.py` modules next to
trymerge; this change only feeds 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`.

This is the last change of the guard and the only one that alters existing behaviour;
the modules it calls landed ahead of it so that the merge-path wiring could be reviewed
on its own and each change stay under the 2000 LOC infra limit. One test here asserts
`merge_rules.yaml` still grants `pytorchgreenlight` merge authority, so a rename there
cannot silently disable the guard.

Signed-off-by: Jean Schmidt <[email protected]>
Pull Request resolved: pytorch#194841
Approved by: https://github.com/huydhn
ghstack dependencies: pytorch#194838, pytorch#194839, pytorch#194840
Sanskaaar1 pushed a commit to Sanskaaar1/pytorch that referenced this pull request Sep 8, 2026
…194840)

`greenlight_guard.py` is the decision itself. It compares the head SHA greenlight
recorded in its ledger against the head actually being landed and returns ALLOW, WAIT or
DENY, along with the wait budget (`GreenlightWaitWindow`) a merge carries across
re-entries. Everything it needs about a PR arrives as plain data or as a callable on
`PRUnderMerge` — the callables stay callables because each one costs a GitHub request
that only the minority of PRs greenlight alone authorizes ever needs. It must not import
`trymerge`: `trymerge` imports it, and the cycle would break both.

Two failure directions are 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. 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. Refusing on first
uncertainty would turn a HUD blip into a dead merge; waiting on a settled negative would
burn an hour and land nothing.

The tests cover the decision table, stack handling, the laziness of the per-PR GitHub
lookups, the ledger's transport failure modes against a mocked `gh_fetch_url` (every
documented route error code, malformed payloads, batch capping, backoff, recovery on
retry), and the preflight mirror. No test touches the network. They land together with
the guard because `test_greenlight_guard.py` owns the shared PR fixtures that the ledger
and preflight tests build on.

Split out from the `trymerge.py` wiring so the verdict logic can be reviewed against
greenlight's behaviour independently of the merge path, and to keep each change under the
2000 LOC infra limit. Nothing calls into this yet.

Signed-off-by: Jean Schmidt <[email protected]>
Pull Request resolved: pytorch#194840
Approved by: https://github.com/huydhn
ghstack dependencies: pytorch#194838, pytorch#194839
Sanskaaar1 pushed a commit to Sanskaaar1/pytorch that referenced this pull request Sep 8, 2026
…ytorch#194841)

**Impact:** mergebot only — PRs whose sole merge authorization is the `pytorchgreenlight`
approval
**Risk:** medium

Depends on pytorch/test-infra#8630 to be merged before merging this one

## What
Wires the greenlight land-time guard into `merge_into`: when the only approval that
satisfies a merge rule is greenlight's, trymerge reads greenlight's verdict ledger and
refuses to land unless greenlight recorded `LAND` for the head commit that is actually
being merged. The verdict logic already lives in the `greenlight_*.py` modules next to
trymerge; this change only feeds 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`.

This is the last change of the guard and the only one that alters existing behaviour;
the modules it calls landed ahead of it so that the merge-path wiring could be reviewed
on its own and each change stay under the 2000 LOC infra limit. One test here asserts
`merge_rules.yaml` still grants `pytorchgreenlight` merge authority, so a rename there
cannot silently disable the guard.

Signed-off-by: Jean Schmidt <[email protected]>
Pull Request resolved: pytorch#194841
Approved by: https://github.com/huydhn
ghstack dependencies: pytorch#194838, pytorch#194839, pytorch#194840
@github-actions
github-actions Bot deleted the gh/jeanschmidt/3/head branch November 10, 2026 01:49
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/trunk Trigger trunk jobs on your pull request Merged topic: not user facing topic category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants