Skip to content

[trymerge] Add greenlight ledger client and login normalization - #194838

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

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

Conversation

@jeanschmidt

@jeanschmidt jeanschmidt commented Aug 26, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Greenlight records one row per review run in misc.greenlight_pr_state, naming the
head SHA that run evaluated. greenlight_ledger.py reads the latest row per PR through
the HUD /api/greenlight/pr_state route that fronts that table: it batches at the
route's 50-PR limit, retries with backoff, normalizes the route's timestamps to aware
UTC, and classifies the statuses into terminal and in-flight sets. Row selection stays
server-side so writer and reader agree on which row is authoritative.

greenlight_identity.py holds the one login-normalization rule every comparison in the
guard goes through. GraphQL renders a GitHub App's login bare while REST appends
[bot], so a comparison that skips normalization silently fails to match — which means
either the guard switches itself off or it refuses a merge it should allow.

These two modules are the leaves of the guard's import graph: identity imports nothing,
and the ledger only needs github_utils. Landing them first keeps each piece of the
land-time guard reviewable on its own and each change under the 2000 LOC infra limit.

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/194838

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

⏳ No Failures, 11 Pending

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

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

Both new files (.github/scripts/greenlight_identity.py, greenlight_ledger.py)
are currently unreferenced — grep finds no importer — yet they add non-trivial,
easily unit-testable logic to the land-time merge guard's trust plumbing
(parse_utc_timestamp's Z-suffix/naive-tzinfo handling, the 3-attempt backoff
loop in _fetch_batch, _MAX_PRS_PER_REQUEST chunking in fetch_ledger_states, and
normalize_login) with no test file, in a directory that tests its helpers by
convention (test_trymerge.py, test_gitutils.py, test_label_utils.py) and which
mypy.ini does not cover. Mechanics I could verify are sound: gh_fetch_url's
signature matches and it only attaches GITHUB_TOKEN for api.github.com URLs so
no GitHub token leaks to hud.pytorch.org, the retry loop fails closed by raising
GreenlightLedgerError, and the Python-3.10 assumptions behind
removesuffix/fromisoformat match trymerge.yml:28. What I cannot verify is intent
at a trust boundary: is_known_bot omits pytorchgreenlight from BOT_LOGINS, so
greenlight's bare GraphQL login would not register as a bot under the
docstring's own "whose review counts as a human's" framing — plausibly
intentional given the separate is_greenlight helper, but unresolvable without
the consumer code arriving in later stack PRs, so a human should confirm before
this guard machinery lands.

reason: insufficient_tests
Reviewed commit: 75384d4 (NOT the current head 0e5bc7a)

Inference job

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

jeanschmidt added a commit that referenced this pull request Aug 27, 2026
Greenlight records one row per review run in `misc.greenlight_pr_state`, naming the
head SHA that run evaluated. `greenlight_ledger.py` reads the latest row per PR through
the HUD `/api/greenlight/pr_state` route that fronts that table: it batches at the
route's 50-PR limit, retries with backoff, normalizes the route's timestamps to aware
UTC, and classifies the statuses into terminal and in-flight sets. Row selection stays
server-side so writer and reader agree on which row is authoritative.

`greenlight_identity.py` holds the one login-normalization rule every comparison in the
guard goes through. GraphQL renders a GitHub App's login bare while REST appends
`[bot]`, so a comparison that skips normalization silently fails to match — which means
either the guard switches itself off or it refuses a merge it should allow.

These two modules are the leaves of the guard's import graph: identity imports nothing,
and the ledger only needs `github_utils`. Landing them first keeps each piece of the
land-time guard reviewable on its own and each change under the 2000 LOC infra limit.

Signed-off-by: Jean Schmidt <[email protected]>
ghstack-source-id: 7e75d15
Pull-Request: #194838
[ghstack-poisoned]
[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
…4839)

`greenlight_preflight.py` detects PRs greenlight will never produce a verdict for, so a
merge can refuse immediately instead of waiting out the full budget for an answer that
is not coming. It mirrors the upstream filters that drop a PR before it is ever
fingerprinted — `review._recency_filter` (excluded labels and the review window, each
with an escape for a PR whose recorded status is non-terminal) and both arms of
`review_gate.human_review_skip_reason` (changes requested by a non-bot, and an approval
from the merge-authorized set). Each mirrored constant is commented with its upstream
source in pytorch/test-infra under `greenlight/src/greenlight/`, because drift in either
direction either costs a merge an hour of waiting or refuses a PR greenlight would in
fact have reviewed.

`greenlight_messages.py` is the single place that renders guard outcomes as text. Three
surfaces share one set of outcomes: the refusal that ends a merge, the line the retry
loop logs while it waits, and the comment posted to the PR the first time a merge waits.

Split out from the guard so the mirrored upstream filters can be reviewed against
greenlight's own source on their own, and to keep each change under the 2000 LOC infra
limit. Both modules sit above the ledger and identity leaves and below the guard itself:
preflight reads the ledger's status sets and identity's normalization, messages reads
the ledger's route URL and preflight's excluded-labels phrase. The references each makes
back to `greenlight_guard` are annotations only, under `TYPE_CHECKING`, so nothing here
imports the guard at runtime.

Signed-off-by: Jean Schmidt <[email protected]>
Pull Request resolved: #194839
Approved by: https://github.com/huydhn
ghstack dependencies: #194838
pytorchmergebot pushed a commit that referenced this pull request Aug 28, 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]>
Pull Request resolved: #194840
Approved by: https://github.com/huydhn
ghstack dependencies: #194838, #194839
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
…rch#194838)

Greenlight records one row per review run in `misc.greenlight_pr_state`, naming the
head SHA that run evaluated. `greenlight_ledger.py` reads the latest row per PR through
the HUD `/api/greenlight/pr_state` route that fronts that table: it batches at the
route's 50-PR limit, retries with backoff, normalizes the route's timestamps to aware
UTC, and classifies the statuses into terminal and in-flight sets. Row selection stays
server-side so writer and reader agree on which row is authoritative.

`greenlight_identity.py` holds the one login-normalization rule every comparison in the
guard goes through. GraphQL renders a GitHub App's login bare while REST appends
`[bot]`, so a comparison that skips normalization silently fails to match — which means
either the guard switches itself off or it refuses a merge it should allow.

These two modules are the leaves of the guard's import graph: identity imports nothing,
and the ledger only needs `github_utils`. Landing them first keeps each piece of the
land-time guard reviewable on its own and each change under the 2000 LOC infra limit.

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

`greenlight_preflight.py` detects PRs greenlight will never produce a verdict for, so a
merge can refuse immediately instead of waiting out the full budget for an answer that
is not coming. It mirrors the upstream filters that drop a PR before it is ever
fingerprinted — `review._recency_filter` (excluded labels and the review window, each
with an escape for a PR whose recorded status is non-terminal) and both arms of
`review_gate.human_review_skip_reason` (changes requested by a non-bot, and an approval
from the merge-authorized set). Each mirrored constant is commented with its upstream
source in pytorch/test-infra under `greenlight/src/greenlight/`, because drift in either
direction either costs a merge an hour of waiting or refuses a PR greenlight would in
fact have reviewed.

`greenlight_messages.py` is the single place that renders guard outcomes as text. Three
surfaces share one set of outcomes: the refusal that ends a merge, the line the retry
loop logs while it waits, and the comment posted to the PR the first time a merge waits.

Split out from the guard so the mirrored upstream filters can be reviewed against
greenlight's own source on their own, and to keep each change under the 2000 LOC infra
limit. Both modules sit above the ledger and identity leaves and below the guard itself:
preflight reads the ledger's status sets and identity's normalization, messages reads
the ledger's route URL and preflight's excluded-labels phrase. The references each makes
back to `greenlight_guard` are annotations only, under `TYPE_CHECKING`, so nothing here
imports the guard at runtime.

Signed-off-by: Jean Schmidt <[email protected]>
Pull Request resolved: pytorch#194839
Approved by: https://github.com/huydhn
ghstack dependencies: pytorch#194838
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
…rch#194838)

Greenlight records one row per review run in `misc.greenlight_pr_state`, naming the
head SHA that run evaluated. `greenlight_ledger.py` reads the latest row per PR through
the HUD `/api/greenlight/pr_state` route that fronts that table: it batches at the
route's 50-PR limit, retries with backoff, normalizes the route's timestamps to aware
UTC, and classifies the statuses into terminal and in-flight sets. Row selection stays
server-side so writer and reader agree on which row is authoritative.

`greenlight_identity.py` holds the one login-normalization rule every comparison in the
guard goes through. GraphQL renders a GitHub App's login bare while REST appends
`[bot]`, so a comparison that skips normalization silently fails to match — which means
either the guard switches itself off or it refuses a merge it should allow.

These two modules are the leaves of the guard's import graph: identity imports nothing,
and the ledger only needs `github_utils`. Landing them first keeps each piece of the
land-time guard reviewable on its own and each change under the 2000 LOC infra limit.

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

`greenlight_preflight.py` detects PRs greenlight will never produce a verdict for, so a
merge can refuse immediately instead of waiting out the full budget for an answer that
is not coming. It mirrors the upstream filters that drop a PR before it is ever
fingerprinted — `review._recency_filter` (excluded labels and the review window, each
with an escape for a PR whose recorded status is non-terminal) and both arms of
`review_gate.human_review_skip_reason` (changes requested by a non-bot, and an approval
from the merge-authorized set). Each mirrored constant is commented with its upstream
source in pytorch/test-infra under `greenlight/src/greenlight/`, because drift in either
direction either costs a merge an hour of waiting or refuses a PR greenlight would in
fact have reviewed.

`greenlight_messages.py` is the single place that renders guard outcomes as text. Three
surfaces share one set of outcomes: the refusal that ends a merge, the line the retry
loop logs while it waits, and the comment posted to the PR the first time a merge waits.

Split out from the guard so the mirrored upstream filters can be reviewed against
greenlight's own source on their own, and to keep each change under the 2000 LOC infra
limit. Both modules sit above the ledger and identity leaves and below the guard itself:
preflight reads the ledger's status sets and identity's normalization, messages reads
the ledger's route URL and preflight's excluded-labels phrase. The references each makes
back to `greenlight_guard` are annotations only, under `TYPE_CHECKING`, so nothing here
imports the guard at runtime.

Signed-off-by: Jean Schmidt <[email protected]>
Pull Request resolved: pytorch#194839
Approved by: https://github.com/huydhn
ghstack dependencies: pytorch#194838
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/1/head branch November 10, 2026 01:43
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