diff --git a/.github/scripts/review-deferrals.py b/.github/scripts/review-deferrals.py new file mode 100644 index 0000000000..92e4168a09 --- /dev/null +++ b/.github/scripts/review-deferrals.py @@ -0,0 +1,200 @@ +"""Fails a pull request that leaves a defect for the release quality pass. + +A review point may wait for the release quality pass when the reply to it ends with +``, but only a quality point may (AGENTS.md, "Review comments"). The Claude +review (claude-code-review.yml, posting as github-actions) ends each inline finding with its +category, a last line `Category: bug` and so on, so the reviewer classifies a finding and the +author doesn't. This check refuses a deferral reply in a thread that the reviewer opened with a +`bug`, `security` or `agents-md` finding, or whose opening comment someone else has since edited. + +Threads opened by anyone else (CodeRabbit, people) or by a review from before categories carry no +category and are let through: a reviewer there can answer the reply. They are listed in a notice. +An edited review finding is refused whatever category it now shows, since the edit may have +removed or changed it; the override below settles a harmless edit. + +`performance` is left out on purpose: a faster path may wait. A performance finding that is also a +crash path or breaks "Size for real data" carries `bug` or `agents-md`, the more serious category. + +Both markers err towards refusing. The deferral marker counts wherever it sits in a reply, as the +release quality pass collects it, so a reply that only mentions it is refused too: reword it. The +override counts only when it ends its reply, so a mention doesn't approve. + +A maintainer overrides the check for a finding, misclassified or accepted as it is, by replying in +its thread with ``. A maintainer here is the repository's owner, a member +of its organization or a collaborator, as GitHub labels the reply. The author may be that maintainer: the +override is a deliberate, recorded decision, not a second opinion. + +CI runs this on each push and again in the merge queue, which sees replies posted after the last +push. It needs GH_TOKEN (read access to pull requests), GITHUB_REPOSITORY, and PR_NUMBER or, in the +merge queue, MERGE_GROUP_REF. +""" + +import json +import os +import re +import subprocess +import sys + +DEFER = "" +APPROVE = "" +# Visible text on a line of its own: the review's inline-comment tool strips hidden comments. +# Markdown emphasis and code marks around the label or the value, and capitals, are let through. +CATEGORY = re.compile(r"^[*_`]*Category[*_`]*:[*_` \t]*([A-Za-z-]+)[*_`]*\.?[ \t\r]*$", re.M) +MUST_FIX = {"bug", "security", "agents-md"} +MAY_WAIT = {"performance", "quality"} +REVIEWER = "github-actions" +MAINTAINERS = {"OWNER", "MEMBER", "COLLABORATOR"} +QUEUE_REF = re.compile(r"/pr-(\d+)-[0-9a-f]{40}$") + +THREADS = """ +query($owner: String!, $name: String!, $number: Int!, $endCursor: String) { + repository(owner: $owner, name: $name) { + pullRequest(number: $number) { + reviewThreads(first: 50, after: $endCursor) { + pageInfo { hasNextPage endCursor } + nodes { id path line originalLine comments(first: 100) { %s } } + } + } + } +} +""" +COMMENTS = """pageInfo { hasNextPage endCursor } + nodes { url body authorAssociation lastEditedAt author { login __typename } editor { login } }""" +MORE_COMMENTS = """ +query($id: ID!, $endCursor: String) { + node(id: $id) { ... on PullRequestReviewThread { comments(first: 100, after: $endCursor) { %s } } } +} +""" + + +def is_reviewer(comment): + """Whether a comment was posted by the Claude review workflow's bot account.""" + author = comment.get("author") or {} + return author.get("login") == REVIEWER and author.get("__typename") == "Bot" + + +def category(opening): + """The category a reviewer finding gives itself: the most serious of its markers, or None.""" + if not is_reviewer(opening): + return None + found = [c.lower() for c in CATEGORY.findall(opening.get("body") or "")] + found = [c for c in found if c in MUST_FIX | MAY_WAIT] # an unknown word is no category + serious = [c for c in found if c in MUST_FIX] + return (serious or found or [None])[0] + + +def edited_by_someone_else(opening): + """Whether a human or other account edited the reviewer's comment, which may have changed its category.""" + if not opening.get("lastEditedAt"): + return False + return ((opening.get("editor") or {}).get("login")) != REVIEWER + + +def approved(replies): + """Whether a maintainer overrode the check for the thread's deferral.""" + for reply in replies: + author = reply.get("author") or {} + if ( + (reply.get("body") or "").rstrip().endswith(APPROVE) + and author.get("__typename") != "Bot" + and reply.get("authorAssociation") in MAINTAINERS + ): + return True + return False + + +def check(threads): + """Sorts the threads that hold a deferral reply into (refused, unclassified) lists of messages.""" + refused, unclassified = [], [] + for thread in threads: + comments = thread.get("comments") or [] + if not comments: + continue + opening, replies = comments[0], comments[1:] + deferral = next((r for r in replies if DEFER in (r.get("body") or "")), None) + if deferral is None: + continue + where = f"{thread.get('path')}:{thread.get('line') or thread.get('originalLine') or '?'}" + if not is_reviewer(opening): + unclassified.append(f"{where} ({(opening.get('author') or {}).get('login', 'ghost')}): {deferral.get('url')}") + continue + kind = category(opening) + if edited_by_someone_else(opening): + reason = "its finding was edited after the review posted it" + elif kind in MUST_FIX: + reason = f"the reviewer classed it as {kind}" + else: + if kind is None: + unclassified.append(f"{where} (review without a category): {deferral.get('url')}") + continue + if not approved(replies): + refused.append(f"{where}: left for the release quality pass, but {reason}. {deferral.get('url')}") + return refused, unclassified + + +def graphql(query, **variables): + """Runs one GraphQL query through the gh CLI and returns its data.""" + args = ["gh", "api", "graphql", "-f", f"query={query}"] + for key, value in variables.items(): + args += ["-F" if isinstance(value, int) else "-f", f"{key}={value}"] + out = subprocess.run(args, check=True, stdout=subprocess.PIPE, text=True, timeout=120).stdout + return json.loads(out)["data"] + + +def fetch(repo, number): + """The pull request's review threads, every comment of each in order.""" + owner, name = repo.split("/", 1) + threads, cursor = [], None + while True: + extra = {"endCursor": cursor} if cursor else {} + pr = graphql(THREADS % COMMENTS, owner=owner, name=name, number=number, **extra)["repository"]["pullRequest"] + page = pr["reviewThreads"] + for node in page["nodes"]: + comments, more = node["comments"]["nodes"], node["comments"]["pageInfo"] + while more["hasNextPage"]: + rest = graphql(MORE_COMMENTS % COMMENTS, id=node["id"], endCursor=more["endCursor"])["node"]["comments"] + comments, more = comments + rest["nodes"], rest["pageInfo"] + threads.append({**node, "comments": comments}) + if not page["pageInfo"]["hasNextPage"]: + return threads + cursor = page["pageInfo"]["endCursor"] + + +def pr_number(): + """The pull request to check, from PR_NUMBER or the merge queue's branch name.""" + if os.environ.get("PR_NUMBER"): + return int(os.environ["PR_NUMBER"]) + match = QUEUE_REF.search(os.environ.get("MERGE_GROUP_REF", "")) + if match is None: + raise SystemExit("::error::No PR_NUMBER, and MERGE_GROUP_REF names no pull request.") + return int(match.group(1)) + + +def escape(text): + """Text for a workflow command line: a path with a newline must not start a command of its own.""" + return text.replace("%", "%25").replace("\r", "%0D").replace("\n", "%0A") + + +def main(): + """Checks the pull request and exits 1 if it defers a finding that must be fixed.""" + number = pr_number() + refused, unclassified = check(fetch(os.environ["GITHUB_REPOSITORY"], number)) + for line in unclassified: + print(f"::notice::Deferred without a review category, not checked: {escape(line)}") + for line in refused: + print(f"::error::{escape(line)}") + if refused: + print( + f"#{number} leaves {len(refused)} finding(s) that must be fixed for the release quality pass. " + "Fix each in the pull request and take the marker out of the reply; for a defect too large " + "for it, link a filed issue in the reply instead of the marker. To let one wait all the same, " + "a maintainer replies in its thread with . " + "Then run the checks again (re-run the job, or queue the pull request again)." + ) + return 1 + print(f"#{number}: no deferral to the release quality pass is on a finding that must be fixed.") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/.github/scripts/test_review_deferrals.py b/.github/scripts/test_review_deferrals.py new file mode 100644 index 0000000000..53d16125ef --- /dev/null +++ b/.github/scripts/test_review_deferrals.py @@ -0,0 +1,138 @@ +"""Checks for review-deferrals.py on review threads recorded from pull requests, cut down to the fields it reads.""" + +import importlib.util +from pathlib import Path +import unittest +import unittest.mock + +SPEC = importlib.util.spec_from_file_location("review_deferrals", Path(__file__).with_name("review-deferrals.py")) +MODULE = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(MODULE) + +AUTHOR = "contributor" +REVIEWER = {"login": "github-actions", "__typename": "Bot"} +CODERABBIT = {"login": "coderabbitai", "__typename": "Bot"} + + +def comment(author, body, association="CONTRIBUTOR", editor=None): + return { + "url": f"https://github.com/o/r/pull/1#discussion_r{abs(hash(body)) % 10**9}", + "body": body, + "authorAssociation": association, + "lastEditedAt": "2026-11-16T03:39:59Z" if editor else None, + "author": author, + "editor": {"login": editor} if editor else None, + } + + +def thread(*comments, path="crates/data/src/dbf.rs"): + return {"path": path, "line": 120, "comments": list(comments)} + + +def finding(text, kind=None, editor=None): + marker = f"\n\nCategory: {kind}" if kind else "" + return comment(REVIEWER, text + marker, editor=editor) + + +def reply(text, author=AUTHOR, association="MEMBER"): + return comment({"login": author, "__typename": "User"}, text, association) + + +DEFER = reply("The reader skipping deleted records predates this PR; left for the release quality pass. ") +BUG = "**Bug:** a deleted record shifts every later row's attributes by one." + + +class ReviewDeferrals(unittest.TestCase): + def check(self, *threads): + return MODULE.check(list(threads)) + + def test_a_deferred_bug_is_refused(self): + refused, unclassified = self.check(thread(finding(BUG, "bug"), DEFER)) + self.assertEqual(len(refused), 1) + self.assertIn("classed it as bug", refused[0]) + self.assertEqual(unclassified, []) + + def test_a_deferred_quality_point_passes(self): + quality = finding("**Quality:** appending `dbf` keeps the fuzz corpus's extension indexes.", "quality") + self.assertEqual(self.check(thread(quality, DEFER)), ([], [])) + + def test_an_undeferred_bug_is_not_this_checks_business(self): + answer = reply("Fixed in d3eda9c78.") + self.assertEqual(self.check(thread(finding(BUG, "bug"), answer)), ([], [])) + + def test_a_grouped_comment_takes_its_most_serious_category(self): + both = finding(BUG + "\nCategory: quality", "agents-md") + refused, _ = self.check(thread(both, DEFER)) + self.assertIn("classed it as agents-md", refused[0]) + + def test_only_a_maintainer_overrides_the_check(self): + rule = finding("**Never silent:** the deleted-record notice has no test.", "agents-md") + by_contributor = reply("Misclassified. ", association="CONTRIBUTOR") + by_bot = comment(CODERABBIT, "", "MEMBER") + by_maintainer_author = reply("An extra test for working code. ") + mention = reply("I won't reply `` to this one.") + self.assertEqual(len(self.check(thread(rule, DEFER, by_contributor, by_bot, mention))[0]), 1) + self.assertEqual(self.check(thread(rule, DEFER, by_maintainer_author)), ([], [])) + + def test_an_edited_finding_counts_as_must_fix(self): + edited = finding(BUG, "quality", editor=AUTHOR) + refused, _ = self.check(thread(edited, DEFER)) + self.assertIn("edited after the review posted it", refused[0]) + + def test_threads_without_a_category_pass_with_a_notice(self): + rabbit = thread(comment(CODERABBIT, "_Potential issue_ | **Major** Record the uppercase DBF sidecar."), DEFER) + person = thread(reply("Should this clamp?", author="maintainer"), DEFER) + old_review = thread(finding("**Bug risk (low):** every non-I/O record error is counted."), DEFER) + unknown = thread(finding(BUG, "bugs"), DEFER) + refused, unclassified = self.check(rabbit, person, old_review, unknown) + self.assertEqual(refused, []) + self.assertEqual(len(unclassified), 4) + + def test_the_marker_counts_wherever_it_sits_as_the_sweep_collects_it(self): + trailing = reply("Left for the release quality pass. Will do after the merge.") + tracked = reply("Left for the release quality pass. \n\n") + for deferral in (trailing, tracked): + self.assertEqual(len(self.check(thread(finding(BUG, "bug"), deferral))[0]), 1) + + def test_a_category_line_may_be_emphasised_or_capitalised(self): + for line in ("**Category:** bug", "Category: `bug`", "Category: Bug", "_Category_: BUG", "Category: bug.", "Category: bug\r"): + refused, _ = self.check(thread(comment(REVIEWER, BUG + "\n\n" + line), DEFER)) + self.assertEqual(len(refused), 1, line) + + def test_an_edited_finding_without_a_category_is_refused_too(self): + refused, unclassified = self.check(thread(finding(BUG, editor=AUTHOR), DEFER)) + self.assertEqual((len(refused), unclassified), (1, [])) + + def test_a_category_is_a_line_of_its_own(self): + prose = finding("The Category: bug label in the legend is cut short.\n\nCategory: quality") + self.assertEqual(self.check(thread(prose, DEFER)), ([], [])) + + def test_a_marker_in_the_opening_comment_is_not_a_deferral(self): + self.assertEqual(self.check(thread(finding(BUG + " ", "bug"))), ([], [])) + + def test_the_merge_queue_branch_names_the_pull_request(self): + ref = "refs/heads/gh-readonly-queue/main/pr-2655-76a6cd2823b4431c363e30a8023c7f69bccae938" + with unittest.mock.patch.dict(MODULE.os.environ, {"PR_NUMBER": "", "MERGE_GROUP_REF": ref}): + self.assertEqual(MODULE.pr_number(), 2655) + + def test_fetch_reads_every_page_of_threads_and_comments(self): + def page(nodes, cursor=None): + return {"pageInfo": {"hasNextPage": cursor is not None, "endCursor": cursor}, "nodes": nodes} + + first, second, third = finding(BUG, "bug"), reply("a"), DEFER + answers = iter([ + {"repository": {"pullRequest": {"reviewThreads": page( + [{"id": "T1", "path": "a.rs", "line": 1, "comments": page([first], "c1")}], "t1")}}}, + {"node": {"comments": page([second], "c2")}}, + {"node": {"comments": page([third])}}, + {"repository": {"pullRequest": {"reviewThreads": page( + [{"id": "T2", "path": "b.rs", "line": 2, "comments": page([])}])}}}, + ]) + with unittest.mock.patch.object(MODULE, "graphql", lambda *a, **k: next(answers)): + threads = MODULE.fetch("o/r", 1) + self.assertEqual([t["id"] for t in threads], ["T1", "T2"]) + self.assertEqual(threads[0]["comments"], [first, second, third]) + + +if __name__ == "__main__": + unittest.main() diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index fec00ec253..902ecf4082 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -177,7 +177,7 @@ jobs: echo "run=true" >> "$GITHUB_OUTPUT" exit 0 fi - if grep -qE '^(Cargo\.lock|(.*/)?Cargo\.toml|deny\.toml|about\.toml|xtask/src/(main|notices)\.rs|(.*/)?THIRD-PARTY-LICENSES\.txt|\.github/scripts/(check-cargo-sources|test_[^/]+)\.py|\.github/workflows/ci\.yml|crates/map/src/color/(scientific|matplotlib)\.rs|crates/tiles/src/(symbols|style)\.rs|crates/data/src/(raster/crs|esripbf)\.rs)$|^(third-party/|\.cargo/)' <<<"$changed"; then + if grep -qE '^(Cargo\.lock|(.*/)?Cargo\.toml|deny\.toml|about\.toml|xtask/src/(main|notices)\.rs|(.*/)?THIRD-PARTY-LICENSES\.txt|\.github/scripts/(check-cargo-sources|review-deferrals|test_[^/]+)\.py|\.github/workflows/ci\.yml|crates/map/src/color/(scientific|matplotlib)\.rs|crates/tiles/src/(symbols|style)\.rs|crates/data/src/(raster/crs|esripbf)\.rs)$|^(third-party/|\.cargo/)' <<<"$changed"; then echo "run=true" >> "$GITHUB_OUTPUT" else echo "No dependency, licence or notice files changed; skipping." @@ -292,6 +292,27 @@ jobs: - name: Count direct row uses run: cargo run --locked -q -p xtask -- rows + # A review point left for the release quality pass must be a quality point + # (.github/scripts/review-deferrals.py). The merge queue's run sees replies posted after the last + # push. It runs the checkout with a read-only token and no secrets, like every job here. + deferrals: + name: Review deferrals + runs-on: ubuntu-latest + permissions: + contents: read + pull-requests: read + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + persist-credentials: false + - name: No defect left for the release quality pass + if: github.event_name == 'pull_request' || github.event_name == 'merge_group' + env: + GH_TOKEN: ${{ github.token }} + PR_NUMBER: ${{ github.event.pull_request.number }} + MERGE_GROUP_REF: ${{ github.event.merge_group.head_ref }} + run: python3 .github/scripts/review-deferrals.py + # The packages whose tests this run needs, for `test` (.github/scripts/test-selection.sh). Only # tests are narrowed: lint, the wasm build, licences and the schema check run whole every time. select: @@ -395,7 +416,7 @@ jobs: # unless their conditions below hold (the same as on the jobs), and every other job always runs. tests_pass: name: Tests pass - needs: [lint, wasm, ios, android, licenses, schema, rows, plan, select, test] + needs: [lint, wasm, ios, android, licenses, schema, rows, deferrals, plan, select, test] if: ${{ always() }} runs-on: ubuntu-latest steps: diff --git a/.github/workflows/claude-code-review.yml b/.github/workflows/claude-code-review.yml index a231820ab5..a0e53ea832 100644 --- a/.github/workflows/claude-code-review.yml +++ b/.github/workflows/claude-code-review.yml @@ -499,6 +499,8 @@ jobs: Post specific findings as inline review comments on the relevant lines using the create_inline_comment tool. For each comment, briefly explain the issue and, when the fix is small and self-contained, include a committable suggestion block. Group minor nits together rather than posting many separate inline comments. + End every inline comment with its category as the last line, on a line of its own, as one of `Category: bug`, `Category: security`, `Category: performance`, `Category: quality` or `Category: agents-md`, the same groups as the summary. Write it as plain visible text: the comment tool removes hidden HTML comments. `bug` is wrong results, crashes and lost or corrupted data; `agents-md` is a break of a rule in `pr-context/AGENTS.md`; `quality` is style, naming, wording, a refactor or an extra test for code that works. Give a comment one category line, the most serious of what it holds (bug, security, agents-md, performance, quality), and post a bug on its own rather than among nits. The category decides what may wait: CI refuses a reply that leaves a bug, security or agents-md finding for the release quality pass, so classify by what the finding is, neither softening a defect into quality nor raising a quality point to a bug. + After posting inline comments, end your run by writing the summary as your FINAL MESSAGE. Do not try to post it yourself — you have no tool that can, and a workflow step publishes your final message as the PR comment verbatim. So your final message must be the comment body and nothing else: no preamble, no "I've completed the review", no meta-commentary about the tools you used. That final message must start with the heading "## Code review" and list the findings grouped by category (Bugs, Security, Performance, Quality, AGENTS.md), each with a one-line description and confidence. If you genuinely find nothing worth raising, say so and note what you checked. diff --git a/AGENTS.md b/AGENTS.md index 76a5649243..e88446c6f3 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -174,6 +174,10 @@ immediately; label-gated build jobs in `ci.yml` start from the next push. wait for the **release quality pass**, where maintainers handle them together before each release. Reply that it's left for the release quality pass, end the reply with ``, and leave it out of the next push. +- The Claude review ends each inline finding with its category (a last line such as `Category: bug`). + CI's `Review deferrals` job fails, on each push and in the merge queue, when the marker answers + a `bug`, `security` or `agents-md` finding, or one edited since it was posted. A maintainer + overrides it for one finding by ending a reply in its thread with ``. ## Looking at the app - `cargo run --release -p rustgis` (opens the World Atlas sample). diff --git a/docs/contributing.md b/docs/contributing.md index 658278366d..755fe0030e 100644 --- a/docs/contributing.md +++ b/docs/contributing.md @@ -34,7 +34,20 @@ naming, wording, a refactor, an extra test for code that works) can be left for quality pass**: before each release, maintainers gather these from the merged pull requests and fix them together. Reply on the comment that it's left for the release quality pass (agents end the reply with ``), so it can be found. Bugs, crashes, silent data loss and -breaks of the rules in AGENTS.md are fixed in the pull request. +breaks of the rules in AGENTS.md are fixed in the pull request, even when the problem predates it, +the input that triggers it is rare, the fix needs a wider change or earlier code does the same. A +defect too large for the pull request gets an issue, filed and linked from the reply, instead of +the marker. + +The Claude review ends each inline comment with its category (`Category: bug`, security, +performance, quality or agents-md). CI's **Review deferrals** check, which runs on each push and again in the +merge queue, fails when a reply leaves a bug, security or AGENTS.md finding for the release quality +pass. A maintainer can override it for one finding by ending a reply in its thread with +`` and running the check again. The override isn't a reason: it records +that a maintainer accepts the finding for the release quality pass, or judges it misclassified. A maintainer here is the repository's owner, a member of its organization or a +collaborator, and the pull request's author may be that maintainer. Comments from +other reviewers carry no category, so the check lets them through: those reviewers answer the +reply themselves. Changes to saved or generated output must classify each new owning field: address, executable parameters, generated text or user data. Use the shared durable-output transaction and keep