Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .github/pull_request_template.md
Original file line number Diff line number Diff line change
Expand Up @@ -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. -->
Expand All @@ -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 changes: 41 additions & 0 deletions .github/workflows/conflict-label.yml
Original file line number Diff line number Diff line change
@@ -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"}
10 changes: 10 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
18 changes: 10 additions & 8 deletions tests/test_docs_pr_template.py
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -13,7 +14,7 @@
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):
Expand All @@ -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__":
Expand Down
157 changes: 157 additions & 0 deletions tests/test_pr_conflict_label.py
Original file line number Diff line number Diff line change
@@ -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()
Loading