Skip to content

Add /api/greenlight/pr_state route for the trymerge greenlight guard - #8630

Merged
jeanschmidt merged 2 commits into
mainfrom
jeanschmidt/pytorchbot-trymerge-greenlight-check
Aug 26, 2026
Merged

jeanschmidt merged 2 commits into
mainfrom
jeanschmidt/pytorchbot-trymerge-greenlight-check

Conversation

@jeanschmidt

Copy link
Copy Markdown
Contributor

Impact: new authenticated HUD API endpoint; consumed by pytorch/pytorch trymerge
Risk: low

What

Adds a read-only GET /api/greenlight/pr_state route that returns the authoritative greenlight verdict row per PR from misc.greenlight_pr_state, batched over up to 50 PR numbers. Also extracts the mockRes test helper into test/nextApiMocks.ts so the new tests and the existing crcr tests share one mock.

Why

trymerge needs to verify at land time that greenlight actually approved the exact commit being merged — the merge_rules.yaml "Greenlight Review Bot" rule otherwise lets a single bot approval authorize any head. trymerge runs outside the ClickHouse network boundary, so it needs an HTTP front for the ledger; this is that front. The client side lives in .github/scripts/greenlight_ledger.py on pytorch/pytorch.

Notes

Things worth a reviewer's attention, since they're load-bearing for merge correctness:

  • Row selection (ORDER BY pr_number, run_id DESC, version DESC LIMIT 1 BY pr_number) is a deliberate copy of greenlight's own reader in greenlight/src/greenlight/state.py. If one side changes, both must.
  • No head_sha filter, on purpose — the caller compares SHAs itself so it can distinguish "no verdict yet" from "verdict for an older commit".
  • Query cache is off and Cache-Control: no-store is set: a stale minute here is enough to land on a superseded verdict.
  • eval_hash is in the table but deliberately not selected or returned.
  • version is normalized to ISO-8601 UTC because ClickHouse's zone suffix depends on output format, and an unparsable value 500s rather than silently passing through.

Auth uses the existing x-hud-internal-bot / session path; trymerge passes HUD_API_TOKEN. The 50-PR cap is mirrored as a constant on the client, which batches to stay under it.

**Impact:** new authenticated HUD API endpoint; consumed by pytorch/pytorch trymerge (no existing HUD behavior changes)
**Risk:** low

## What
Adds a read-only `GET /api/greenlight/pr_state` route that returns the authoritative greenlight verdict row per PR from `misc.greenlight_pr_state`, batched over up to 50 PR numbers. Also extracts the `mockRes` test helper into `test/nextApiMocks.ts` so the new tests and the existing crcr tests share one mock.

## Why
trymerge needs to verify at land time that greenlight actually approved the exact commit being merged — the `merge_rules.yaml` "Greenlight Review Bot" rule otherwise lets a single bot approval authorize any head. trymerge runs outside the ClickHouse network boundary, so it needs an HTTP front for the ledger; this is that front. The client side lives in `.github/scripts/greenlight_ledger.py` on pytorch/pytorch.

## Notes
Things worth a reviewer's attention, since they're load-bearing for merge correctness:

- Row selection (`ORDER BY pr_number, run_id DESC, version DESC LIMIT 1 BY pr_number`) is a deliberate copy of greenlight's own reader in `greenlight/src/greenlight/state.py`. If one side changes, both must.
- No `head_sha` filter, on purpose — the caller compares SHAs itself so it can distinguish "no verdict yet" from "verdict for an older commit".
- Query cache is off and `Cache-Control: no-store` is set: a stale minute here is enough to land on a superseded verdict.
- `eval_hash` is in the table but deliberately not selected or returned.
- `version` is normalized to ISO-8601 UTC because ClickHouse's zone suffix depends on output format, and an unparsable value 500s rather than silently passing through.

Auth uses the existing `x-hud-internal-bot` / session path; trymerge passes `HUD_API_TOKEN`. The 50-PR cap is mirrored as a constant on the client, which batches to stay under it.

Signed-off-by: Jean Schmidt <[email protected]>
@vercel

vercel Bot commented Aug 25, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
torchci Ready Ready Preview Aug 26, 2026 1:19am

Request Review

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed. label Aug 25, 2026
FROM misc.greenlight_pr_state
WHERE repo = {repo: String}
AND pr_number IN {pr_numbers: Array(Int64)}
ORDER BY pr_number, run_id DESC, version DESC

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, not sure if we need version DESC here, using pr_number and run_id seems unique enough

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.

Good instinct, but for each pr_number it can be multiple run_id, and for each multiple entries, like LAND, FAILED, CANCELLED, etc. So the version DESC it to get the latest run status for that greenlight (pr_number, run_id) pair.

@huydhn

huydhn commented Aug 25, 2026

Copy link
Copy Markdown
Contributor

@claude Check if auth matches how pytorch/pytorch#194809 tries to use the API

@claude

claude Bot commented Aug 25, 2026 •

Copy link
Copy Markdown

Claude finished @huydhn's task in 1m 33s —— View job


Auth compatibility check vs pytorch/pytorch#194809


⚠️ I couldn't fetch pytorch/pytorch#194809. Both WebFetch and gh (needed to read the other repo) require permissions that aren't granted to this run, so I can't directly diff the client against the server. Below is the exact auth contract the endpoint enforces — please confirm the client matches it, or grant WebFetch/gh and re-trigger me and I'll verify directly.

What the HUD endpoint actually requires

pr_state.ts:77 calls checkAuthWithApiToken, which (torchci/lib/auth/auth.ts:6-22) accepts either:

  1. A custom header — x-hud-internal-bot: <token>, compared with == against process.env.INTERNAL_API_TOKEN:
    const API_TOKEN_HEADER = "x-hud-internal-bot";
    const headerToken = req.headers[API_TOKEN_HEADER];
    if (headerToken && headerToken == process.env.INTERNAL_API_TOKEN) {
      return { ok: true, type: "header" };
    }
  2. A NextAuth session (session.user + session.accessToken) — the browser path, not applicable to trymerge.

There is no Authorization: Bearer / token path. So for the bot the client must:

  • Send the token in the x-hud-internal-bot header (not Authorization, not a cookie).
  • Send a value equal to HUD's INTERNAL_API_TOKEN env var. The PR body says trymerge reads it from HUD_API_TOKEN on the client side — that's fine as long as the CI secret plumbed into HUD_API_TOKEN is the same secret as HUD's INTERNAL_API_TOKEN. If those are two different secrets, every call 401s.

Things to confirm in the client (greenlight_ledger.py in #194809)

  1. Header name is exactly x-hud-internal-bot. Header names are case-insensitive so casing is fine, but a wrong name (e.g. Authorization) → 401.
  2. Method + path: GET /api/greenlight/pr_state (non-GET → 405, pr_state.ts:73).
  3. Query params: repo=owner/name and prNumbers= a comma-separated list of positive ints, ≤ 50 entries (pr_state.ts:82-104). The client must URL-encode the / in repo and batch to stay under 50 — the PR body says it mirrors the 50 cap, good.
  4. Secret parity: the CI secret feeding the client's HUD_API_TOKEN must equal HUD's INTERNAL_API_TOKEN. This is the single most likely mismatch and is not visible in either diff — it lives in repo/deployment secrets. Worth an explicit check.

One server-side note while here

auth.ts:9 uses == (loose equality) for the token compare. Both sides are strings here so it behaves like ===, but it's a non-constant-time compare — acceptable for an internal bot token, just noting it isn't timing-safe.

--- · branch jeanschmidt/pytorchbot-trymerge-greenlight-check

@huydhn huydhn left a comment •

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.

LGTM!

@jeanschmidt
jeanschmidt merged commit 829026e into main Aug 26, 2026
4 checks passed
pytorchmergebot pushed a commit to pytorch/pytorch 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
…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
…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

This branch was successfully deployed

1 active deployment
Preview — ece6e520 Deployed Aug 26, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants