ci: label pull requests that conflict with main needs rebase (PR-CONFLICT-LABEL)

Every pull request is reviewed by hand, and with over a hundred open the
reviewer has no quick way to skip the ones that cannot merge as they
stand. tools/pr_conflict_label.py asks the GitHub API for each open pull
request's `mergeable` and labels the conflicting ones `needs rebase`,
removing the label once they merge cleanly again; an answer GitHub has
not computed yet is asked again a few times and otherwise left for the
next run. .github/workflows/conflict-label.yml runs it on a push to main
(all open pull requests), on a pull request being opened, reopened or
pushed to (that one), and hourly.

The job uses pull_request_target so a fork's pull request can be
labeled, and is safe with it: it checks out main, never the pull
request, and the tool reads only the API, so no pull request code runs.
Its token can read contents and write pull requests, nothing else;
tests/test_pr_conflict_label.py checks that, and the tool against a fake
API.

The pull request template also asks for `Fixes: #N` and `GPUs tested:`
lines and has checklist items for "based on current main" and "one
topic"; tests/test_docs_pr_template.py checks the new prompts, and
CONTRIBUTING.md gets a short Pull requests section. The process is
modelled on AnyPS5's (boykopovar/AnyPS5); the code is written here, not
copied.
This commit is contained in:
Mouad-Scriptz-0
2026-11-24 02:30:12 +00:00
parent da60a36159
commit 4f7a347775
6 changed files with 373 additions and 8 deletions

View File

@ -4,6 +4,8 @@ Claimed in the coordination issue as: <!-- the item ID from the open "Coordinati
Depends on: <!-- #N for every pull request this one builds on or conflicts with (the coordination issue's
Commands section, AGENTS.md); delete the line if it builds on none and conflicts with none -->
Fixes: <!-- #N for each issue this closes (GitHub closes it on merge); delete the line if it closes none -->
### What and why
<!-- What this changes and the problem it solves. -->
@ -13,9 +15,13 @@ Depends on: <!-- #N for every pull request this one builds on or conflicts with
<!-- What you ran and on which GPU and driver (CONTRIBUTING.md). For the shader translator: how many shaders
translate and pass spirv-val, before and after. -->
GPUs tested: <!-- vendor, model, driver and OS of each GPU the GPU tests ran on, or n/a -->
AI-assisted: <!-- yes or no (AGENTS.md asks a coding agent to say so) -->
### Checklist
- [ ] Based on current `main` and merges cleanly (a conflicting pull request is labeled `needs rebase`).
- [ ] One topic; follow-up work goes in a new pull request.
- [ ] No game data, keys or decryption (CONTRIBUTING.md), including in logs or reports quoted here.
- [ ] A new translator rule is in the contract table of `docs/design.md`, with how it was confirmed.

41
.github/workflows/conflict-label.yml vendored Normal file
View File

@ -0,0 +1,41 @@
name: Needs rebase label
# Labels the open pull requests that conflict with main `needs rebase` and unlabels them once they merge again
# (tools/pr_conflict_label.py). A push to main can make any open pull request conflict, so it checks all of them; a
# push to a pull request checks that one; the hourly run catches merges GitHub had not computed yet.
#
# pull_request_target gives a fork's pull request a token that can write labels. That is safe only because this job
# checks out main, never the pull request, and the tool reads nothing but the GitHub API: no pull request code runs.
on:
push:
branches: [main]
pull_request_target:
types: [opened, reopened, synchronize]
schedule:
- cron: '17 * * * *'
workflow_dispatch:
permissions: {}
concurrency:
group: conflict-label-${{ github.event.pull_request.number || 'all' }}
cancel-in-progress: false
jobs:
label:
runs-on: ubuntu-24.04
timeout-minutes: 15
permissions:
contents: read
pull-requests: write
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
ref: ${{ github.event.repository.default_branch }}
persist-credentials: false
fetch-depth: 1
- name: Label conflicting pull requests
env:
GITHUB_TOKEN: ${{ github.token }}
PR: ${{ github.event.pull_request.number }}
run: python3 -I tools/pr_conflict_label.py --repo "$GITHUB_REPOSITORY" ${PR:+--pr "$PR"}

View File

@ -60,3 +60,13 @@ methods are still open.
- Say what you tested and on which GPU in the pull request.
- Run the translator tests with `python -I scripts/run_semantic_tests.py tests/semantic` (see `tests/semantic/README.md`). A new
translator rule should come with a small hand-written `.asm` fixture and its expected output words.
## Pull requests
- One topic per pull request, based on current `main`. Follow-up work goes in a new pull request, not into an open
one.
- Fill in the [template](.github/pull_request_template.md): the claim, `Depends on:`, `Fixes: #N` for an issue it
closes, what you tested, `GPUs tested:` (vendor, model, driver and OS) and whether it was AI-assisted.
- A pull request that conflicts with `main` is labeled `needs rebase` (`tools/pr_conflict_label.py`, run on every
push to `main` and to the pull request, and hourly). Rebase it on `main` yourself; the label goes once it merges
cleanly. Reviews start with the pull requests that do.

View File

@ -1,10 +1,11 @@
"""The pull request template prompts for a `Depends on:` line and for whether the work was AI-assisted.
"""The pull request template prompts for `Depends on:`, `Fixes:`, `GPUs tested:` and whether it was AI-assisted.
python -I tests/test_docs_pr_template.py
The coordination issue builds its merge chains from `Depends on: #N` lines, and AGENTS.md asks a pull request to
say that it was AI-assisted; without a prompt in `.github/pull_request_template.md` those are the lines authors
leave out. This reads the template only, so rewording AGENTS.md or CONTRIBUTING.md cannot fail it. No game files.
The coordination issue builds its merge chains from `Depends on: #N` lines, AGENTS.md asks a pull request to say
that it was AI-assisted, `Fixes: #N` closes the issue on merge and `GPUs tested:` is what a reviewer checks a GPU
change against. Without a prompt in `.github/pull_request_template.md` those are the lines authors leave out. This
reads the template only, so rewording AGENTS.md or CONTRIBUTING.md cannot fail it. No game files.
"""
import os
import re
@ -13,7 +14,7 @@ import unittest
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATE = os.path.join(".github", "pull_request_template.md")
# A prompt is a line of its own that starts with the words an author fills in.
PROMPTS = ("Depends on:", "AI-assisted:")
PROMPTS = ("Depends on:", "Fixes:", "GPUs tested:", "AI-assisted:")
def missing_prompts(template):
@ -22,14 +23,15 @@ def missing_prompts(template):
class PullRequestTemplateTest(unittest.TestCase):
def test_template_has_both_prompts(self):
def test_template_has_every_prompt(self):
with open(os.path.join(ROOT, TEMPLATE), encoding="utf-8") as f:
self.assertEqual(missing_prompts(f.read()), [])
def test_a_template_without_a_prompt_is_reported(self):
self.assertEqual(missing_prompts("### Tested\n"), ["Depends on:", "AI-assisted:"])
self.assertEqual(missing_prompts("### Tested\n"), list(PROMPTS))
# A mention inside another sentence is not a prompt: the line has to start with it.
self.assertEqual(missing_prompts("no Depends on: here\nAI-assisted: no\n"), ["Depends on:"])
self.assertEqual(missing_prompts("no Depends on: here\nFixes: none\nGPUs tested: n/a\nAI-assisted: no\n"),
["Depends on:"])
if __name__ == "__main__":

View File

@ -0,0 +1,157 @@
"""tools/pr_conflict_label.py labels conflicting pull requests `needs rebase` and unlabels them once they merge.
python -I tests/test_pr_conflict_label.py
A fake GitHub API stands in for the network, so this checks the calls the tool makes: which pull requests get the
label, that one whose merge GitHub has not computed yet is asked again and otherwise left alone, that the label is
created only when it is first needed, that `--dry-run` writes nothing, and that the workflow runs the tool without
checking out pull request code. Standard library only; no network, no game files.
"""
import os
import re
import sys
import unittest
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, os.path.join(ROOT, "tools"))
import pr_conflict_label as pcl # noqa: E402
REPO = "owner/name"
class FakeApi:
"""Pull requests as {number: [mergeable answers in order, the last one repeating]} plus their labels."""
def __init__(self, prs, labeled=(), label_exists=False, closed=()):
self.answers = {n: list(a) for n, a in prs.items()}
self.labels = {n: ({pcl.LABEL} if n in labeled else set()) for n in prs}
self.closed = set(closed)
self.label_exists = label_exists
self.calls = []
def __call__(self, method, path, body=None):
self.calls.append((method, path, body))
m = re.fullmatch(rf"/repos/{REPO}/pulls/(\d+)", path)
if method == "GET" and m:
n = int(m.group(1))
answers = self.answers[n]
mergeable = answers.pop(0) if len(answers) > 1 else answers[0]
return {"number": n, "state": "closed" if n in self.closed else "open", "mergeable": mergeable,
"labels": [{"name": name} for name in sorted(self.labels[n])]}
if method == "GET" and path.startswith(f"/repos/{REPO}/pulls?"):
page = int(re.search(r"[?&]page=(\d+)", path).group(1))
numbers = sorted(self.answers)
return [{"number": n} for n in numbers[(page - 1) * 100:page * 100]]
if method == "POST" and path == f"/repos/{REPO}/labels":
if self.label_exists:
raise pcl.ApiError(422, "already_exists")
self.label_exists = True
return {}
m = re.fullmatch(rf"/repos/{REPO}/issues/(\d+)/labels", path)
if method == "POST" and m:
self.labels[int(m.group(1))] |= set(body["labels"])
return []
m = re.fullmatch(rf"/repos/{REPO}/issues/(\d+)/labels/needs%20rebase", path)
if method == "DELETE" and m:
n = int(m.group(1))
if pcl.LABEL not in self.labels[n]:
raise pcl.ApiError(404, "Label does not exist")
self.labels[n].discard(pcl.LABEL)
return None
raise AssertionError(f"unexpected call {method} {path}")
def writes(self):
return [c for c in self.calls if c[0] != "GET"]
def run(api, numbers, **kw):
return pcl.run(api, REPO, numbers, sleep=lambda s: None, out=lambda s: None, **kw)
class DecideTest(unittest.TestCase):
def test_every_case(self):
self.assertEqual(pcl.decide(False, False), "add")
self.assertEqual(pcl.decide(True, True), "remove")
self.assertIsNone(pcl.decide(False, True)) # already labeled
self.assertIsNone(pcl.decide(True, False)) # clean and unlabeled
self.assertIsNone(pcl.decide(None, False)) # not computed: never guess
self.assertIsNone(pcl.decide(None, True))
class RunTest(unittest.TestCase):
def test_labels_conflicts_and_unlabels_rebased_ones(self):
api = FakeApi({1: [False], 2: [True], 3: [True], 4: [False]}, labeled={3, 4})
done = run(api, [1, 2, 3, 4])
self.assertEqual(done, {"add": [1], "remove": [3], "unknown": []})
self.assertEqual(api.labels, {1: {pcl.LABEL}, 2: set(), 3: set(), 4: {pcl.LABEL}})
def test_an_uncomputed_merge_is_asked_again_then_left_alone(self):
api = FakeApi({1: [None, None, False], 2: [None]}, labeled={2})
done = run(api, [1, 2], attempts=4)
self.assertEqual(done, {"add": [1], "remove": [], "unknown": [2]})
self.assertEqual(api.labels[2], {pcl.LABEL}) # unknown keeps the label it had
self.assertEqual(sum(1 for c in api.calls if c[1] == f"/repos/{REPO}/pulls/2"), 4)
def test_the_label_is_created_once_and_only_when_needed(self):
api = FakeApi({1: [True], 2: [True]})
run(api, [1, 2])
self.assertEqual(api.writes(), [])
api = FakeApi({1: [False], 2: [False]})
run(api, [1, 2])
self.assertEqual(sum(1 for c in api.writes() if c[1] == f"/repos/{REPO}/labels"), 1)
def test_an_existing_label_is_not_an_error(self):
api = FakeApi({1: [False]}, label_exists=True)
self.assertEqual(run(api, [1])["add"], [1])
def test_a_label_removed_in_between_is_not_an_error(self):
api = FakeApi({1: [True]}, labeled={1})
api.labels[1].discard(pcl.LABEL)
orig = api.__call__
def stale(method, path, body=None): # the GET still reports the label someone just removed
result = orig(method, path, body)
if method == "GET" and path.endswith("/pulls/1"):
result["labels"] = [{"name": pcl.LABEL}]
return result
self.assertEqual(pcl.run(stale, REPO, [1], sleep=lambda s: None, out=lambda s: None)["remove"], [1])
def test_closed_pull_requests_are_skipped(self):
api = FakeApi({1: [False]}, closed={1})
self.assertEqual(run(api, [1]), {"add": [], "remove": [], "unknown": []})
self.assertEqual(api.writes(), [])
def test_dry_run_writes_nothing(self):
api = FakeApi({1: [False], 2: [True]}, labeled={2})
done = run(api, [1, 2], dry_run=True)
self.assertEqual((done["add"], done["remove"]), ([1], [2]))
self.assertEqual(api.writes(), [])
def test_open_pull_numbers_follows_pages(self):
api = FakeApi({n: [True] for n in range(1, 251)})
self.assertEqual(pcl.open_pull_numbers(api, REPO), list(range(1, 251)))
class WorkflowTest(unittest.TestCase):
def setUp(self):
with open(os.path.join(ROOT, ".github", "workflows", "conflict-label.yml"), encoding="utf-8") as f:
self.text = f.read()
def test_runs_this_tool(self):
self.assertIn("python3 -I tools/pr_conflict_label.py", self.text)
def test_never_checks_out_pull_request_code(self):
# pull_request_target runs with a write token; checking out the head would run untrusted code with it.
self.assertIn("pull_request_target", self.text)
self.assertNotRegex(self.text, r"github\.event\.pull_request\.head|github\.head_ref|refs/pull/")
self.assertRegex(self.text, r"ref:\s*\$\{\{\s*github\.event\.repository\.default_branch\s*\}\}")
self.assertIn("persist-credentials: false", self.text)
def test_token_is_limited_to_pull_requests(self):
self.assertRegex(self.text, r"(?m)^permissions:\s*\{\}\s*$")
job_perms = re.findall(r"(?m)^\s{6}(\w[\w-]*):\s*(read|write)\s*$", self.text)
self.assertEqual(dict(job_perms), {"contents": "read", "pull-requests": "write"})
if __name__ == "__main__":
unittest.main()

149
tools/pr_conflict_label.py Normal file
View File

@ -0,0 +1,149 @@
"""Label the open pull requests that conflict with their base branch `needs rebase`, and unlabel them once they merge.
python -I tools/pr_conflict_label.py --repo OWNER/NAME [--pr N] [--dry-run]
`.github/workflows/conflict-label.yml` runs this on every push to `main` (a merge can make other pull requests
conflict), on a pull request being opened, reopened or pushed to (a rebase can clear a conflict), and hourly in case
GitHub had not finished computing a merge. Every pull request gets reviewed by hand; the label lets a reviewer skip
the ones that cannot be merged as they stand and tells their authors to rebase.
GitHub computes `mergeable` in the background and answers `null` until it has, so a pull request whose answer is
still unknown is asked again a few times and otherwise left as it is for the next run. Only the GitHub REST API is
read and written: no pull request code is checked out or run, which is what makes the `pull_request_target` trigger
safe here. The token comes from `GITHUB_TOKEN` (or `GH_TOKEN`); `--dry-run` prints the changes and writes nothing.
Standard library only; no game files.
"""
import argparse
import json
import os
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
LABEL = "needs rebase"
LABEL_COLOR = "d93f0b"
LABEL_DESCRIPTION = "Conflicts with the base branch: rebase it on main"
API = "https://api.github.com"
class ApiError(Exception):
def __init__(self, status, message):
super().__init__(f"HTTP {status}: {message}")
self.status = status
def github_api(token):
"""A function (method, path, body=None) -> parsed JSON (or None) that calls the GitHub REST API with `token`."""
def call(method, path, body=None):
data = None if body is None else json.dumps(body).encode("utf-8")
req = urllib.request.Request(API + path, data=data, method=method, headers={
"Accept": "application/vnd.github+json",
"Authorization": f"Bearer {token}",
"User-Agent": "pr-conflict-label",
"X-GitHub-Api-Version": "2022-11-28",
})
try:
with urllib.request.urlopen(req, timeout=30) as resp:
raw = resp.read()
except urllib.error.HTTPError as e:
raise ApiError(e.code, e.read().decode("utf-8", "replace")[:300]) from None
return json.loads(raw) if raw else None
return call
def decide(mergeable, labeled):
"""'add', 'remove' or None for a pull request whose `mergeable` is True, False or None (not computed yet)."""
if mergeable is False and not labeled:
return "add"
if mergeable is True and labeled:
return "remove"
return None
def open_pull_numbers(api, repo):
numbers, page = [], 1
while True:
batch = api("GET", f"/repos/{repo}/pulls?state=open&per_page=100&page={page}")
numbers += [p["number"] for p in batch]
if len(batch) < 100:
return numbers
page += 1
def ensure_label(api, repo):
try:
api("POST", f"/repos/{repo}/labels",
{"name": LABEL, "color": LABEL_COLOR, "description": LABEL_DESCRIPTION})
except ApiError as e:
if e.status != 422: # 422: the label exists already
raise
def apply(api, repo, number, action):
if action == "add":
api("POST", f"/repos/{repo}/issues/{number}/labels", {"labels": [LABEL]})
else:
try:
api("DELETE", f"/repos/{repo}/issues/{number}/labels/{urllib.parse.quote(LABEL, safe='')}")
except ApiError as e:
if e.status != 404: # 404: someone removed it in between
raise
def run(api, repo, numbers, dry_run=False, attempts=4, wait=10.0, sleep=time.sleep, out=print):
"""Label or unlabel each pull request of `numbers`. Returns {'add': [...], 'remove': [...], 'unknown': [...]}."""
done = {"add": [], "remove": [], "unknown": []}
pending = list(numbers)
label_ready = dry_run
for attempt in range(attempts):
if attempt:
sleep(wait) # asking for a pull request starts GitHub's merge computation; give it time
unknown = []
for number in pending:
pr = api("GET", f"/repos/{repo}/pulls/{number}")
if pr.get("state") != "open":
continue
labeled = any(label.get("name") == LABEL for label in pr.get("labels", []))
if pr.get("mergeable") is None:
unknown.append(number)
continue
action = decide(pr["mergeable"], labeled)
if action is None:
continue
out(f"#{number}: {action} '{LABEL}'" + (" (dry run)" if dry_run else ""))
if not dry_run:
if action == "add" and not label_ready:
ensure_label(api, repo)
label_ready = True
apply(api, repo, number, action)
done[action].append(number)
pending = unknown
if not pending:
break
done["unknown"] = pending
if pending:
out("mergeable not computed yet, left for the next run: " + " ".join(f"#{n}" for n in pending))
return done
def main(argv=None):
ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
ap.add_argument("--repo", default=os.environ.get("GITHUB_REPOSITORY"), help="OWNER/NAME")
ap.add_argument("--pr", type=int, action="append", help="only this pull request (repeatable)")
ap.add_argument("--dry-run", action="store_true", help="print the changes, write nothing")
args = ap.parse_args(argv)
token = os.environ.get("GITHUB_TOKEN") or os.environ.get("GH_TOKEN")
if not args.repo or not token:
ap.error("needs --repo (or GITHUB_REPOSITORY) and GITHUB_TOKEN (or GH_TOKEN)")
api = github_api(token)
numbers = args.pr or open_pull_numbers(api, args.repo)
done = run(api, args.repo, numbers, dry_run=args.dry_run)
print(f"{len(numbers)} checked: {len(done['add'])} labeled, {len(done['remove'])} unlabeled, "
f"{len(done['unknown'])} not computed yet")
return 0
if __name__ == "__main__":
sys.exit(main())