From 991aed312ff2bddfa44921751b0ac903227ff698 Mon Sep 17 00:00:00 2001 From: mavrick Date: Sun, 22 Nov 2026 12:09:31 -0600 Subject: [PATCH 1/6] ci: fail a pull request that raises a limit which only goes down xtask/row-uses.txt and xtask/memory-limits.txt only come down, but nothing stopped a pull request from editing a limit up to make `cargo xtask rows` or `cargo xtask memory` pass. A new job compares both files with the commit the change was made on and fails when a limit rose or was removed. A new memory scenario is fine. A maintainer overrides it by commenting on the pull request with a message ending in . --- .github/scripts/ratchet-limits.py | 177 +++++++++++++++++++++++++ .github/scripts/test_ratchet_limits.py | 125 +++++++++++++++++ .github/workflows/ci.yml | 27 +++- AGENTS.md | 3 + docs/contributing.md | 7 + 5 files changed, 337 insertions(+), 2 deletions(-) create mode 100644 .github/scripts/ratchet-limits.py create mode 100644 .github/scripts/test_ratchet_limits.py diff --git a/.github/scripts/ratchet-limits.py b/.github/scripts/ratchet-limits.py new file mode 100644 index 0000000000..e79697cad4 --- /dev/null +++ b/.github/scripts/ratchet-limits.py @@ -0,0 +1,177 @@ +"""Fails a pull request that raises a limit which only goes down. + +`xtask/row-uses.txt` (`cargo xtask rows`) and `xtask/memory-limits.txt` (`cargo xtask memory`) are +committed limits that AGENTS.md says only come down: the xtask checks fail when the code is over +its limit, but nothing stopped a pull request from editing the limit up to make them pass. This +check compares each limit with the one in the commit the change was made on and fails when one +is higher or has been removed. A new line (a new memory scenario) is fine. Lowering a limit is what +the files are for. + +A limit may need to rise for a reason a maintainer accepts. A maintainer overrides the check by +commenting on the pull request, or reviewing it, with a message that ends with +``, then running the check again. The marker counts only at the end +of the message, so a message that mentions it does not approve. A maintainer here is the +repository's owner, a member of its organization or a collaborator, as GitHub labels the message; +the pull request's author may be that maintainer: the override is a deliberate, recorded decision. +One approval covers every raise in the pull request as it stands when the check runs. + +Only these two files are checked. The other hand-kept lists (the commands the hostile tests skip, +the known-silent reader cases, the cancellation exemptions) grow for good reasons, and AGENTS.md +doesn't say they only go down. + +CI runs this on pull requests and in the merge queue. It needs BASE_SHA (the commit the change was +made on, or the queue entry's parent), GH_TOKEN (read access to pull requests, used only when a +limit has risen), GITHUB_REPOSITORY, and PR_NUMBER or, in the merge queue, MERGE_GROUP_REF. +""" + +import json +import math +import os +import re +import subprocess +import sys + +LIMIT_FILES = ["xtask/row-uses.txt", "xtask/memory-limits.txt"] +APPROVE = "" +MAINTAINERS = {"OWNER", "MEMBER", "COLLABORATOR"} +QUEUE_REF = re.compile(r"/pr-(\d+)-[0-9a-f]{40}$") + + +def parse(text): + """The `name = number` lines of a limits file, a `#` starting a comment; the first line of a name counts. + + The xtask readers take the first line of a name too, so a later one can't move the limit. + """ + limits = {} + for n, line in enumerate(text.splitlines(), 1): + line = line.split("#", 1)[0].strip() + if not line: + continue + name, sep, value = line.partition("=") + if not sep: + raise ValueError(f"line {n}: expected `name = number`") + try: + number = float(value.strip()) + except ValueError: + raise ValueError(f"line {n}: `{value.strip()}` is not a number") from None + if not math.isfinite(number): + raise ValueError(f"line {n}: `{value.strip()}` is not a finite number") + limits.setdefault(name.strip(), (number, value.strip())) + return limits + + +def compare(path, base_text, head_text): + """The raised or removed limits of one file, as messages; ([], notices) when nothing is wrong. + + `base_text` is None when the file didn't exist on the base (nothing to compare), `head_text` None + when the change deletes it. + """ + if base_text is None: + return [], [] + try: + base = parse(base_text) + except ValueError as error: + return [], [f"{path} on the base can't be read ({error}), so its limits aren't compared"] + if head_text is None: + return [f"{path}: deleted, but it holds {len(base)} limit(s) that only go down"], [] + try: + head = parse(head_text) + except ValueError as error: + return [f"{path}: {error}"], [] + problems = [] + for name, (old, old_text) in base.items(): + if name not in head: + problems.append(f"{path}: the limit `{name}` ({old_text}) was removed") + elif head[name][0] > old: + problems.append(f"{path}: `{name}` rose from {old_text} to {head[name][1]}") + return problems, [] + + +def run(args): + """Runs a command and returns its standard output, raising if it fails.""" + return subprocess.run(args, check=True, stdout=subprocess.PIPE, text=True, timeout=120).stdout + + +def base_file(base_sha, path): + """The file's text on the base commit, or None when the base has no such file.""" + if not run(["git", "ls-tree", "--name-only", base_sha, "--", path]).strip(): + return None + return run(["git", "show", f"{base_sha}:{path}"]) + + +def head_file(path): + """The file's text in the checkout, or None when it isn't there.""" + try: + with open(path, encoding="utf-8") as f: + return f.read() + except FileNotFoundError: + return None + + +def messages(repo, number): + """Every comment and review on the pull request, as (body, author association, is a bot).""" + found = [] + for endpoint in (f"repos/{repo}/issues/{number}/comments", f"repos/{repo}/pulls/{number}/reviews"): + out = run( + ["gh", "api", "--paginate", endpoint, "--jq", + ".[] | {body, association: .author_association, bot: (.user.type == \"Bot\")}"] + ) + found += [json.loads(line) for line in out.splitlines() if line.strip()] + return found + + +def approved(found): + """Whether a maintainer's message ends with the override.""" + return any( + (m.get("body") or "").rstrip().endswith(APPROVE) and not m.get("bot") and m.get("association") in MAINTAINERS + for m in found + ) + + +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 newline must not start a command of its own.""" + return text.replace("%", "%25").replace("\r", "%0D").replace("\n", "%0A") + + +def main(): + """Checks the limits against the base and exits 1 if one rose or was removed without a maintainer's say.""" + base_sha = os.environ.get("BASE_SHA", "") + if not re.fullmatch(r"[0-9a-f]{40}", base_sha): + raise SystemExit("::error::BASE_SHA is not a commit hash, so there is nothing to compare the limits with.") + run(["git", "fetch", "--no-tags", "--depth=1", "origin", base_sha]) + problems = [] + for path in LIMIT_FILES: + found, notices = compare(path, base_file(base_sha, path), head_file(path)) + problems += found + for notice in notices: + print(f"::notice::{escape(notice)}") + if not problems: + print("No limit that only goes down has risen.") + return 0 + number = pr_number() + if approved(messages(os.environ["GITHUB_REPOSITORY"], number)): + for problem in problems: + print(f"::notice::{escape(problem)}: approved by a maintainer on #{number}") + return 0 + for problem in problems: + print(f"::error::{escape(problem)}") + print( + f"#{number} raises {len(problems)} limit(s) that only go down. Fix the code so the old limit holds, " + "or, if the rise is deliberate, a maintainer comments on the pull request with a message ending " + f"in {APPROVE} and the check is run again (re-run the job, or queue the pull request again)." + ) + return 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/.github/scripts/test_ratchet_limits.py b/.github/scripts/test_ratchet_limits.py new file mode 100644 index 0000000000..02100e5148 --- /dev/null +++ b/.github/scripts/test_ratchet_limits.py @@ -0,0 +1,125 @@ +"""Checks for ratchet-limits.py on limits files cut down from xtask/row-uses.txt and xtask/memory-limits.txt.""" + +import importlib.util +from pathlib import Path +import unittest +import unittest.mock + +SPEC = importlib.util.spec_from_file_location("ratchet_limits", Path(__file__).with_name("ratchet-limits.py")) +MODULE = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(MODULE) + +ROWS = "# Direct uses = rows outside the data crate.\ncount = 782\n" +MEMORY = "# ratios\nload_mib = 200.00\njoin = 2.10 # a note\nedits_growth = 0.10\n" +SHA = "a" * 40 + + +def person(body, association="MEMBER", bot=False): + return {"body": body, "association": association, "bot": bot} + + +class RatchetLimits(unittest.TestCase): + def problems(self, base, head): + found, notices = MODULE.compare("xtask/x.txt", base, head) + self.assertEqual(notices, []) + return found + + def test_a_raised_row_count_is_refused(self): + found = self.problems(ROWS, ROWS.replace("782", "783")) + self.assertEqual(len(found), 1) + self.assertIn("`count` rose from 782 to 783", found[0]) + + def test_an_unchanged_or_lowered_limit_passes(self): + self.assertEqual(self.problems(ROWS, ROWS), []) + self.assertEqual(self.problems(ROWS, ROWS.replace("782", "700")), []) + self.assertEqual(self.problems(MEMORY, MEMORY.replace("2.10", "1.9")), []) + + def test_each_memory_limit_is_held_to_its_own_value(self): + head = MEMORY.replace("join = 2.10", "join = 2.11").replace("200.00", "150") + found = self.problems(MEMORY, head) + self.assertEqual(len(found), 1) + self.assertIn("`join` rose from 2.10 to 2.11", found[0]) + + def test_a_decimal_that_reads_the_same_is_not_a_raise(self): + self.assertEqual(self.problems(MEMORY, MEMORY.replace("200.00", "200.0")), []) + + def test_a_removed_limit_is_refused_but_a_new_one_is_fine(self): + found = self.problems(MEMORY, MEMORY.replace("edits_growth = 0.10\n", "")) + self.assertEqual(len(found), 1) + self.assertIn("`edits_growth` (0.10) was removed", found[0]) + self.assertEqual(self.problems(MEMORY, MEMORY + "pdf = 3.0\n"), []) + + def test_commenting_a_limit_out_removes_it(self): + found = self.problems(MEMORY, MEMORY.replace("join = 2.10", "# join = 2.10")) + self.assertEqual(len(found), 1) + + def test_a_deleted_file_is_refused_and_a_new_one_is_fine(self): + self.assertEqual(len(self.problems(ROWS, None)), 1) + self.assertEqual(self.problems(None, ROWS), []) + + def test_the_first_line_of_a_name_is_the_limit_as_xtask_reads_it(self): + self.assertEqual(MODULE.parse("count = 5\ncount = 9\n")["count"][0], 5) + self.assertEqual(len(self.problems(ROWS, "count = 782\ncount = 999\n")), 0) + self.assertEqual(len(self.problems(ROWS, "count = 999\ncount = 782\n")), 1) + + def test_a_file_that_cannot_be_read_fails_on_the_head_and_is_skipped_on_the_base(self): + found = self.problems(ROWS, "count = many\n") + self.assertEqual(len(found), 1) + self.assertIn("not a number", found[0]) + self.assertEqual(len(self.problems(ROWS, "count\n")), 1) + self.assertEqual(len(self.problems(ROWS, "count = nan\n")), 1) + found, notices = MODULE.compare("xtask/x.txt", "count = many\n", ROWS) + self.assertEqual((found, len(notices)), ([], 1)) + + def test_only_a_maintainers_message_ending_in_the_marker_approves(self): + marker = MODULE.APPROVE + self.assertTrue(MODULE.approved([person(f"Needed for the new loader. {marker}\n")])) + self.assertTrue(MODULE.approved([person(marker, "OWNER"), person("x")])) + self.assertFalse(MODULE.approved([person(marker, "CONTRIBUTOR")])) + self.assertFalse(MODULE.approved([person(marker, "NONE")])) + self.assertFalse(MODULE.approved([person(marker, bot=True)])) + self.assertFalse(MODULE.approved([person(f"I won't reply `{marker}` to this.")])) + self.assertFalse(MODULE.approved([person(f"{marker} but not yet")])) + self.assertFalse(MODULE.approved([person(None)])) + self.assertFalse(MODULE.approved([])) + + 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 main(self, base, head, messages): + env = {"BASE_SHA": SHA, "GITHUB_REPOSITORY": "o/r", "PR_NUMBER": "7"} + files = dict(zip(MODULE.LIMIT_FILES, head)) + asked = [] + + def messages_of(repo, number): + asked.append((repo, number)) + return messages + + with ( + unittest.mock.patch.dict(MODULE.os.environ, env), + unittest.mock.patch.object(MODULE, "run", lambda args: ""), + unittest.mock.patch.object(MODULE, "base_file", lambda sha, path: dict(zip(MODULE.LIMIT_FILES, base))[path]), + unittest.mock.patch.object(MODULE, "head_file", lambda path: files[path]), + unittest.mock.patch.object(MODULE, "messages", messages_of), + unittest.mock.patch("builtins.print"), + ): + return MODULE.main(), asked + + def test_main_fails_on_a_raise_and_passes_with_an_approval(self): + raised = (ROWS.replace("782", "900"), MEMORY) + self.assertEqual(self.main((ROWS, MEMORY), raised, []), (1, [("o/r", 7)])) + self.assertEqual(self.main((ROWS, MEMORY), raised, [person(f"Fine. {MODULE.APPROVE}")])[0], 0) + + def test_main_asks_nobody_when_no_limit_rose(self): + self.assertEqual(self.main((ROWS, MEMORY), (ROWS.replace("782", "1"), MEMORY), []), (0, [])) + + def test_main_refuses_a_base_that_is_not_a_commit(self): + with unittest.mock.patch.dict(MODULE.os.environ, {"BASE_SHA": ""}): + with self.assertRaises(SystemExit): + MODULE.main() + + +if __name__ == "__main__": + unittest.main() diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 902ecf4082..df4bb546bd 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|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 + 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|ratchet-limits|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." @@ -313,6 +313,29 @@ jobs: MERGE_GROUP_REF: ${{ github.event.merge_group.head_ref }} run: python3 .github/scripts/review-deferrals.py + # xtask/row-uses.txt and xtask/memory-limits.txt only go down (AGENTS.md): the check against the + # commit the change was made on (.github/scripts/ratchet-limits.py) fails when one rose or went. + # The merge queue's run sees a maintainer's approval posted after the last push. Read-only token, + # no secrets, like every job here. + ratchets: + name: Limits only go down + runs-on: ubuntu-latest + permissions: + contents: read + pull-requests: read + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + persist-credentials: false + - name: No limit raised + if: github.event_name == 'pull_request' || github.event_name == 'merge_group' + env: + GH_TOKEN: ${{ github.token }} + BASE_SHA: ${{ github.event.pull_request.base.sha || github.event.merge_group.base_sha }} + PR_NUMBER: ${{ github.event.pull_request.number }} + MERGE_GROUP_REF: ${{ github.event.merge_group.head_ref }} + run: python3 .github/scripts/ratchet-limits.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: @@ -416,7 +439,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, deferrals, plan, select, test] + needs: [lint, wasm, ios, android, licenses, schema, rows, deferrals, ratchets, plan, select, test] if: ${{ always() }} runs-on: ubuntu-latest steps: diff --git a/AGENTS.md b/AGENTS.md index cad3c3bddc..008e362103 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -160,6 +160,9 @@ its limit in `xtask/memory-limits.txt`; a change that lowers one commits the low It counts only the libraries and programs built for the host, not tests, examples, benches or code built only for other targets, nor a row indexed without reading a field (`features[i]` alone); use the accessors there too. +Both limit files only go down: CI's `Limits only go down` job fails a pull request that raises or +removes a limit against its base (a new memory scenario is fine). A maintainer approves a deliberate +raise by commenting on the pull request with a message ending in ``. While you work, `cargo xtask changed` runs the same checks on only the packages your branch changes and those that depend on them (and `test-hygiene` on the whole workspace, and formatting, `layers` and `rows` when packages are checked), or everything when a diff --git a/docs/contributing.md b/docs/contributing.md index 63de3b8195..dfb8e0c973 100644 --- a/docs/contributing.md +++ b/docs/contributing.md @@ -49,6 +49,13 @@ collaborator, and the pull request's author may be that maintainer. Comments fro other reviewers carry no category, so the check lets them through: those reviewers answer the reply themselves. +The limits in `xtask/row-uses.txt` and `xtask/memory-limits.txt` only go down. CI's **Limits only go +down** check, which runs on each push and again in the merge queue, fails when a pull request raises +or removes one against the commit it was made on; a new memory scenario is fine. A maintainer approves +a deliberate raise by commenting on the pull request, or reviewing it, with a message that ends in +`` (a maintainer as for the deferral override above), and the check +is run again. + 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 credential removal separate from execution and approval identity. Review every writer that From 008540d9888e02b5409d8a7447b8495cdaeae7e6 Mon Sep 17 00:00:00 2001 From: mavrick Date: Sun, 22 Nov 2026 12:45:58 -0600 Subject: [PATCH 2/6] ci: tie a limit approval to the limit and value it names An approval line now names the file, the limit and the value, so a later push that raises a limit further needs its own approval, and the failure prints each line to copy. Lines end at LF or CRLF only, as in the xtask readers, and a symbolic link at a limit path fails the check. --- .github/scripts/ratchet-limits.py | 99 ++++++++++++++++++-------- .github/scripts/test_ratchet_limits.py | 81 +++++++++++++++++---- AGENTS.md | 3 +- docs/contributing.md | 10 +-- 4 files changed, 143 insertions(+), 50 deletions(-) diff --git a/.github/scripts/ratchet-limits.py b/.github/scripts/ratchet-limits.py index e79697cad4..2a10516ee7 100644 --- a/.github/scripts/ratchet-limits.py +++ b/.github/scripts/ratchet-limits.py @@ -7,13 +7,18 @@ is higher or has been removed. A new line (a new memory scenario) is fine. Lowering a limit is what the files are for. -A limit may need to rise for a reason a maintainer accepts. A maintainer overrides the check by -commenting on the pull request, or reviewing it, with a message that ends with -``, then running the check again. The marker counts only at the end -of the message, so a message that mentions it does not approve. A maintainer here is the +A limit may need to rise for a reason a maintainer accepts. A maintainer overrides the check for +one change by commenting on the pull request, or reviewing it, with a line of its own that the +failure prints for that change, such as ``. +The line names the file, the limit and the value it was approved at, so a later push that raises +the limit further, or another limit, needs its own approval. A removed limit is approved the same +way (`... memory-limits.txt save removed -->`), as is a deleted file. A maintainer here is the repository's owner, a member of its organization or a collaborator, as GitHub labels the message; the pull request's author may be that maintainer: the override is a deliberate, recorded decision. -One approval covers every raise in the pull request as it stands when the check runs. + +The check compares the two data files with their base. It does not look at the code that reads +them (`xtask/src/rows.rs`, `xtask/src/memory.rs`), and it runs from the pull request's own +checkout, like the other checks here, so a pull request that loosens those is for review to catch. Only these two files are checked. The other hand-kept lists (the commands the hostile tests skip, the known-silent reader cases, the cancellation exemptions) grow for good reasons, and AGENTS.md @@ -32,7 +37,7 @@ import sys LIMIT_FILES = ["xtask/row-uses.txt", "xtask/memory-limits.txt"] -APPROVE = "" +APPROVE = "ratchet-raise-approved" MAINTAINERS = {"OWNER", "MEMBER", "COLLABORATOR"} QUEUE_REF = re.compile(r"/pr-(\d+)-[0-9a-f]{40}$") @@ -43,8 +48,10 @@ def parse(text): The xtask readers take the first line of a name too, so a later one can't move the limit. """ limits = {} - for n, line in enumerate(text.splitlines(), 1): - line = line.split("#", 1)[0].strip() + # Lines end at LF or CRLF only, as in Rust's `str::lines`: `splitlines` would also split at a + # vertical tab, form feed or bare CR, which the xtask readers keep inside the line. + for n, line in enumerate(text.split("\n"), 1): + line = line.removesuffix("\r").split("#", 1)[0].strip() if not line: continue name, sep, value = line.partition("=") @@ -60,11 +67,16 @@ def parse(text): return limits +def marker(token): + """The line a maintainer's message carries to approve the change named by `token`.""" + return f"" + + def compare(path, base_text, head_text): - """The raised or removed limits of one file, as messages; ([], notices) when nothing is wrong. + """The raised or removed limits of one file, as (message, approval token) pairs, and notices. `base_text` is None when the file didn't exist on the base (nothing to compare), `head_text` None - when the change deletes it. + when the change deletes it. A token of None means nothing can approve the problem: fix the file. """ if base_text is None: return [], [] @@ -73,36 +85,47 @@ def compare(path, base_text, head_text): except ValueError as error: return [], [f"{path} on the base can't be read ({error}), so its limits aren't compared"] if head_text is None: - return [f"{path}: deleted, but it holds {len(base)} limit(s) that only go down"], [] + return [(f"{path}: deleted, but it holds {len(base)} limit(s) that only go down", f"{path} deleted")], [] try: head = parse(head_text) except ValueError as error: - return [f"{path}: {error}"], [] + return [(f"{path}: {error}", None)], [] problems = [] for name, (old, old_text) in base.items(): if name not in head: - problems.append(f"{path}: the limit `{name}` ({old_text}) was removed") + problems.append((f"{path}: the limit `{name}` ({old_text}) was removed", f"{path} {name} removed")) elif head[name][0] > old: - problems.append(f"{path}: `{name}` rose from {old_text} to {head[name][1]}") + problems.append((f"{path}: `{name}` rose from {old_text} to {head[name][1]}", f"{path} {name}={head[name][1]}")) return problems, [] def run(args): - """Runs a command and returns its standard output, raising if it fails.""" - return subprocess.run(args, check=True, stdout=subprocess.PIPE, text=True, timeout=120).stdout + """Runs a command and returns its standard output as it is, line endings included; raises if it fails.""" + return subprocess.run(args, check=True, stdout=subprocess.PIPE, timeout=120).stdout.decode("utf-8", "replace") + + +def base_mode(base_sha, path): + """The file's git mode on the base commit (`120000` is a symbolic link), or None when it has no such file.""" + listing = run(["git", "ls-tree", base_sha, "--", path]).split() + return listing[0] if listing else None def base_file(base_sha, path): """The file's text on the base commit, or None when the base has no such file.""" - if not run(["git", "ls-tree", "--name-only", base_sha, "--", path]).strip(): + if base_mode(base_sha, path) is None: return None return run(["git", "show", f"{base_sha}:{path}"]) +def is_link(path): + """Whether the checkout has a symbolic link at the path.""" + return os.path.islink(path) + + def head_file(path): - """The file's text in the checkout, or None when it isn't there.""" + """The file's text in the checkout, with its line endings, or None when it isn't there.""" try: - with open(path, encoding="utf-8") as f: + with open(path, encoding="utf-8", newline="") as f: return f.read() except FileNotFoundError: return None @@ -120,10 +143,13 @@ def messages(repo, number): return found -def approved(found): - """Whether a maintainer's message ends with the override.""" +def approved(found, token): + """Whether a maintainer's message has the approval line for `token` on a line of its own.""" + line = marker(token) return any( - (m.get("body") or "").rstrip().endswith(APPROVE) and not m.get("bot") and m.get("association") in MAINTAINERS + not m.get("bot") + and m.get("association") in MAINTAINERS + and any(row.strip() == line for row in (m.get("body") or "").splitlines()) for m in found ) @@ -151,6 +177,11 @@ def main(): run(["git", "fetch", "--no-tags", "--depth=1", "origin", base_sha]) problems = [] for path in LIMIT_FILES: + # A link reads as its target here and as its own text in git, so the two sides would not + # be the same file: neither is accepted. + if is_link(path) or base_mode(base_sha, path) == "120000": + problems.append((f"{path}: is a symbolic link, but the limits must be in a regular file", None)) + continue found, notices = compare(path, base_file(base_sha, path), head_file(path)) problems += found for notice in notices: @@ -159,17 +190,25 @@ def main(): print("No limit that only goes down has risen.") return 0 number = pr_number() - if approved(messages(os.environ["GITHUB_REPOSITORY"], number)): - for problem in problems: - print(f"::notice::{escape(problem)}: approved by a maintainer on #{number}") + found = messages(os.environ["GITHUB_REPOSITORY"], number) + refused = [] + for message, token in problems: + if token is not None and approved(found, token): + print(f"::notice::{escape(message)}: approved by a maintainer on #{number}") + else: + refused.append((message, token)) + print(f"::error::{escape(message)}") + if not refused: return 0 - for problem in problems: - print(f"::error::{escape(problem)}") print( - f"#{number} raises {len(problems)} limit(s) that only go down. Fix the code so the old limit holds, " - "or, if the rise is deliberate, a maintainer comments on the pull request with a message ending " - f"in {APPROVE} and the check is run again (re-run the job, or queue the pull request again)." + f"#{number} raises {len(refused)} limit(s) that only go down. Fix the code so the old limit holds, " + "or, if the change is deliberate, a maintainer comments on the pull request with each of these " + "lines on a line of its own, and the check is run again (re-run the job, or queue the pull request " + "again). A removed memory scenario needs its line too." ) + for _, token in refused: + if token is not None: + print(marker(token)) return 1 diff --git a/.github/scripts/test_ratchet_limits.py b/.github/scripts/test_ratchet_limits.py index 02100e5148..560740484d 100644 --- a/.github/scripts/test_ratchet_limits.py +++ b/.github/scripts/test_ratchet_limits.py @@ -22,7 +22,10 @@ class RatchetLimits(unittest.TestCase): def problems(self, base, head): found, notices = MODULE.compare("xtask/x.txt", base, head) self.assertEqual(notices, []) - return found + return [message for message, _ in found] + + def tokens(self, base, head): + return [token for _, token in MODULE.compare("xtask/x.txt", base, head)[0]] def test_a_raised_row_count_is_refused(self): found = self.problems(ROWS, ROWS.replace("782", "783")) @@ -71,24 +74,39 @@ def test_a_file_that_cannot_be_read_fails_on_the_head_and_is_skipped_on_the_base found, notices = MODULE.compare("xtask/x.txt", "count = many\n", ROWS) self.assertEqual((found, len(notices)), ([], 1)) - def test_only_a_maintainers_message_ending_in_the_marker_approves(self): - marker = MODULE.APPROVE - self.assertTrue(MODULE.approved([person(f"Needed for the new loader. {marker}\n")])) - self.assertTrue(MODULE.approved([person(marker, "OWNER"), person("x")])) - self.assertFalse(MODULE.approved([person(marker, "CONTRIBUTOR")])) - self.assertFalse(MODULE.approved([person(marker, "NONE")])) - self.assertFalse(MODULE.approved([person(marker, bot=True)])) - self.assertFalse(MODULE.approved([person(f"I won't reply `{marker}` to this.")])) - self.assertFalse(MODULE.approved([person(f"{marker} but not yet")])) - self.assertFalse(MODULE.approved([person(None)])) - self.assertFalse(MODULE.approved([])) + def test_each_problem_has_its_own_approval_token(self): + self.assertEqual(self.tokens(ROWS, ROWS.replace("782", "783")), ["xtask/x.txt count=783"]) + self.assertEqual(self.tokens(MEMORY, MEMORY.replace("join = 2.10", "join = 2.2")), ["xtask/x.txt join=2.2"]) + self.assertEqual(self.tokens(MEMORY, MEMORY.replace("edits_growth = 0.10\n", "")), ["xtask/x.txt edits_growth removed"]) + self.assertEqual(self.tokens(ROWS, None), ["xtask/x.txt deleted"]) + self.assertEqual(self.tokens(ROWS, "count = many\n"), [None]) + + def test_only_a_maintainers_line_for_that_change_approves(self): + line = MODULE.marker("xtask/x.txt count=790") + self.assertEqual(line, "") + self.assertTrue(MODULE.approved([person(f"Needed for the new loader.\n{line}\n")], "xtask/x.txt count=790")) + self.assertTrue(MODULE.approved([person(f"x\n {line} \nthanks", "OWNER")], "xtask/x.txt count=790")) + self.assertFalse(MODULE.approved([person(line, "CONTRIBUTOR")], "xtask/x.txt count=790")) + self.assertFalse(MODULE.approved([person(line, "NONE")], "xtask/x.txt count=790")) + self.assertFalse(MODULE.approved([person(line, bot=True)], "xtask/x.txt count=790")) + self.assertFalse(MODULE.approved([person(f"I won't reply `{line}` to this.")], "xtask/x.txt count=790")) + self.assertFalse(MODULE.approved([person(f"> {line}")], "xtask/x.txt count=790")) + self.assertFalse(MODULE.approved([person(None)], "xtask/x.txt count=790")) + self.assertFalse(MODULE.approved([], "xtask/x.txt count=790")) + + def test_an_approval_is_for_the_value_and_the_limit_it_names(self): + line = person(MODULE.marker("xtask/x.txt count=790")) + self.assertFalse(MODULE.approved([line], "xtask/x.txt count=900")) + self.assertFalse(MODULE.approved([line], "xtask/y.txt count=790")) + self.assertFalse(MODULE.approved([line], "xtask/x.txt join=790")) + self.assertFalse(MODULE.approved([line], "xtask/x.txt count removed")) 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 main(self, base, head, messages): + def main(self, base, head, messages, link_in_head=False, link_on_base=False): env = {"BASE_SHA": SHA, "GITHUB_REPOSITORY": "o/r", "PR_NUMBER": "7"} files = dict(zip(MODULE.LIMIT_FILES, head)) asked = [] @@ -100,6 +118,8 @@ def messages_of(repo, number): with ( unittest.mock.patch.dict(MODULE.os.environ, env), unittest.mock.patch.object(MODULE, "run", lambda args: ""), + unittest.mock.patch.object(MODULE, "base_mode", lambda sha, path: link_on_base and "120000" or "100644"), + unittest.mock.patch.object(MODULE, "is_link", lambda path: link_in_head), unittest.mock.patch.object(MODULE, "base_file", lambda sha, path: dict(zip(MODULE.LIMIT_FILES, base))[path]), unittest.mock.patch.object(MODULE, "head_file", lambda path: files[path]), unittest.mock.patch.object(MODULE, "messages", messages_of), @@ -107,10 +127,41 @@ def messages_of(repo, number): ): return MODULE.main(), asked - def test_main_fails_on_a_raise_and_passes_with_an_approval(self): + def test_main_fails_on_a_raise_and_passes_with_an_approval_of_that_value(self): raised = (ROWS.replace("782", "900"), MEMORY) self.assertEqual(self.main((ROWS, MEMORY), raised, []), (1, [("o/r", 7)])) - self.assertEqual(self.main((ROWS, MEMORY), raised, [person(f"Fine. {MODULE.APPROVE}")])[0], 0) + row_path = MODULE.LIMIT_FILES[0] + ok = person(MODULE.marker(f"{row_path} count=900")) + self.assertEqual(self.main((ROWS, MEMORY), raised, [ok])[0], 0) + stale = person(MODULE.marker(f"{row_path} count=790")) + self.assertEqual(self.main((ROWS, MEMORY), raised, [stale])[0], 1) + + def test_main_needs_an_approval_for_every_change(self): + row_path, memory_path = MODULE.LIMIT_FILES + raised = (ROWS.replace("782", "900"), MEMORY.replace("join = 2.10", "join = 3").replace("edits_growth = 0.10\n", "")) + one = person(MODULE.marker(f"{row_path} count=900")) + both = person(f"{MODULE.marker(f'{memory_path} join=3')}\n{MODULE.marker(f'{memory_path} edits_growth removed')}") + self.assertEqual(self.main((ROWS, MEMORY), raised, [one])[0], 1) + self.assertEqual(self.main((ROWS, MEMORY), raised, [one, both])[0], 0) + + def test_a_symbolic_link_at_a_limit_path_is_never_accepted(self): + approving = [person(MODULE.marker(f"{path} {name}")) for path in MODULE.LIMIT_FILES for name in ("None", "count=782")] + self.assertEqual(self.main((ROWS, MEMORY), (ROWS, MEMORY), approving, link_in_head=True)[0], 1) + self.assertEqual(self.main((ROWS, MEMORY), (ROWS, MEMORY), approving, link_on_base=True)[0], 1) + self.assertEqual(self.main((ROWS, MEMORY), (ROWS, MEMORY), [])[0], 0) + + def test_lines_end_at_lf_or_crlf_only_as_the_xtask_readers_have_them(self): + # Rust keeps a vertical tab, form feed or bare CR inside a line: here the comment hides the first count. + for separator in ("\v", "\f", "\r", "\x1c", "\u2028"): + head = f"# note{separator}count = 782\ncount = 999\n" + self.assertEqual(len(self.problems(ROWS, head)), 1, repr(separator)) + self.assertEqual(MODULE.parse("count = 5\r\ncount = 9\r\n")["count"][0], 5) + self.assertEqual(self.problems(ROWS, ROWS.replace("\n", "\r\n")), []) + + def test_main_never_lets_an_unreadable_file_through(self): + row_path = MODULE.LIMIT_FILES[0] + approving = [person(MODULE.marker(f"{row_path} None")), person(MODULE.marker(f"{row_path} count=many"))] + self.assertEqual(self.main((ROWS, MEMORY), ("count = many\n", MEMORY), approving)[0], 1) def test_main_asks_nobody_when_no_limit_rose(self): self.assertEqual(self.main((ROWS, MEMORY), (ROWS.replace("782", "1"), MEMORY), []), (0, [])) diff --git a/AGENTS.md b/AGENTS.md index 008e362103..b379a04bcb 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -162,7 +162,8 @@ built only for other targets, nor a row indexed without reading a field (`featur the accessors there too. Both limit files only go down: CI's `Limits only go down` job fails a pull request that raises or removes a limit against its base (a new memory scenario is fine). A maintainer approves a deliberate -raise by commenting on the pull request with a message ending in ``. +raise by commenting on the pull request with the line the failure prints for it +(``). While you work, `cargo xtask changed` runs the same checks on only the packages your branch changes and those that depend on them (and `test-hygiene` on the whole workspace, and formatting, `layers` and `rows` when packages are checked), or everything when a diff --git a/docs/contributing.md b/docs/contributing.md index dfb8e0c973..1d4903f549 100644 --- a/docs/contributing.md +++ b/docs/contributing.md @@ -51,10 +51,12 @@ reply themselves. The limits in `xtask/row-uses.txt` and `xtask/memory-limits.txt` only go down. CI's **Limits only go down** check, which runs on each push and again in the merge queue, fails when a pull request raises -or removes one against the commit it was made on; a new memory scenario is fine. A maintainer approves -a deliberate raise by commenting on the pull request, or reviewing it, with a message that ends in -`` (a maintainer as for the deferral override above), and the check -is run again. +or removes one against the commit it was made on; a new memory scenario is fine. A maintainer +approves a deliberate raise (or a removed scenario) by commenting on the pull request, or reviewing +it, with the line the failure prints for it, such as +`` (a maintainer as for the deferral +override above), and the check is run again. The line names the limit and its value, so a later +push that raises it further needs a new approval. 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 From da169c7722e58f4d6a8acf0db66f79426c6610c7 Mon Sep 17 00:00:00 2001 From: mavrick Date: Sun, 22 Nov 2026 13:22:43 -0600 Subject: [PATCH 3/6] ci: read the limit files with Rust's whitespace, and name the base commit A line starting with U+001C to U+001F was read as a different key here than by the xtask readers, because Python's strip removes them and Rust's trim does not. The docs, docstring and CI comment say the comparison is with the base commit, which for a pull request is the base branch's tip. --- .github/scripts/ratchet-limits.py | 24 ++++++++++++++---------- .github/scripts/test_ratchet_limits.py | 7 +++++++ .github/workflows/ci.yml | 2 +- AGENTS.md | 4 ++-- docs/contributing.md | 4 ++-- 5 files changed, 26 insertions(+), 15 deletions(-) diff --git a/.github/scripts/ratchet-limits.py b/.github/scripts/ratchet-limits.py index 2a10516ee7..5147b46af0 100644 --- a/.github/scripts/ratchet-limits.py +++ b/.github/scripts/ratchet-limits.py @@ -3,8 +3,8 @@ `xtask/row-uses.txt` (`cargo xtask rows`) and `xtask/memory-limits.txt` (`cargo xtask memory`) are committed limits that AGENTS.md says only come down: the xtask checks fail when the code is over its limit, but nothing stopped a pull request from editing the limit up to make them pass. This -check compares each limit with the one in the commit the change was made on and fails when one -is higher or has been removed. A new line (a new memory scenario) is fine. Lowering a limit is what +check compares each limit with the one on the base commit (the pull request's base branch, or the +merge queue entry's parent) and fails when one is higher or has been removed. A new line (a new memory scenario) is fine. Lowering a limit is what the files are for. A limit may need to rise for a reason a maintainer accepts. A maintainer overrides the check for @@ -24,8 +24,8 @@ the known-silent reader cases, the cancellation exemptions) grow for good reasons, and AGENTS.md doesn't say they only go down. -CI runs this on pull requests and in the merge queue. It needs BASE_SHA (the commit the change was -made on, or the queue entry's parent), GH_TOKEN (read access to pull requests, used only when a +CI runs this on pull requests and in the merge queue. It needs BASE_SHA (the pull request's base +commit, or the queue entry's parent), GH_TOKEN (read access to pull requests, used only when a limit has risen), GITHUB_REPOSITORY, and PR_NUMBER or, in the merge queue, MERGE_GROUP_REF. """ @@ -39,6 +39,9 @@ LIMIT_FILES = ["xtask/row-uses.txt", "xtask/memory-limits.txt"] APPROVE = "ratchet-raise-approved" MAINTAINERS = {"OWNER", "MEMBER", "COLLABORATOR"} +# What Rust's `str::trim` removes (Unicode White_Space). Python's `strip` also removes U+001C to +# U+001F, so a line that starts with one would read as a different key here than in the xtask readers. +RUST_WHITESPACE = "\t\n\x0b\x0c\r \x85\xa0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000" QUEUE_REF = re.compile(r"/pr-(\d+)-[0-9a-f]{40}$") @@ -50,20 +53,21 @@ def parse(text): limits = {} # Lines end at LF or CRLF only, as in Rust's `str::lines`: `splitlines` would also split at a # vertical tab, form feed or bare CR, which the xtask readers keep inside the line. - for n, line in enumerate(text.split("\n"), 1): - line = line.removesuffix("\r").split("#", 1)[0].strip() + for n, raw in enumerate(text.split("\n"), 1): + line = raw.removesuffix("\r").split("#", 1)[0].strip(RUST_WHITESPACE) if not line: continue name, sep, value = line.partition("=") if not sep: raise ValueError(f"line {n}: expected `name = number`") + value = value.strip(RUST_WHITESPACE) try: - number = float(value.strip()) + number = float(value) except ValueError: - raise ValueError(f"line {n}: `{value.strip()}` is not a number") from None + raise ValueError(f"line {n}: `{value}` is not a number") from None if not math.isfinite(number): - raise ValueError(f"line {n}: `{value.strip()}` is not a finite number") - limits.setdefault(name.strip(), (number, value.strip())) + raise ValueError(f"line {n}: `{value}` is not a finite number") + limits.setdefault(name.strip(RUST_WHITESPACE), (number, value)) return limits diff --git a/.github/scripts/test_ratchet_limits.py b/.github/scripts/test_ratchet_limits.py index 560740484d..34da9bd9c7 100644 --- a/.github/scripts/test_ratchet_limits.py +++ b/.github/scripts/test_ratchet_limits.py @@ -156,6 +156,13 @@ def test_lines_end_at_lf_or_crlf_only_as_the_xtask_readers_have_them(self): head = f"# note{separator}count = 782\ncount = 999\n" self.assertEqual(len(self.problems(ROWS, head)), 1, repr(separator)) self.assertEqual(MODULE.parse("count = 5\r\ncount = 9\r\n")["count"][0], 5) + # Python's `strip` removes U+001C to U+001F; Rust's `trim` doesn't, so the xtask readers + # take the second line's 999 as the limit. + for control in ("\x1c", "\x1d", "\x1e", "\x1f"): + found = self.problems(ROWS, f"{control}count = 782\ncount = 999\n") + self.assertEqual(len(found), 1, repr(control)) + self.assertIn("rose from 782 to 999", found[0]) + self.assertEqual(MODULE.parse("\u3000count\u00a0=\u2003 5 \n")["count"][0], 5) self.assertEqual(self.problems(ROWS, ROWS.replace("\n", "\r\n")), []) def test_main_never_lets_an_unreadable_file_through(self): diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index df4bb546bd..2a55b933a0 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -314,7 +314,7 @@ jobs: run: python3 .github/scripts/review-deferrals.py # xtask/row-uses.txt and xtask/memory-limits.txt only go down (AGENTS.md): the check against the - # commit the change was made on (.github/scripts/ratchet-limits.py) fails when one rose or went. + # base commit (.github/scripts/ratchet-limits.py) fails when one rose or went. # The merge queue's run sees a maintainer's approval posted after the last push. Read-only token, # no secrets, like every job here. ratchets: diff --git a/AGENTS.md b/AGENTS.md index b379a04bcb..090f2601ec 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -162,8 +162,8 @@ built only for other targets, nor a row indexed without reading a field (`featur the accessors there too. Both limit files only go down: CI's `Limits only go down` job fails a pull request that raises or removes a limit against its base (a new memory scenario is fine). A maintainer approves a deliberate -raise by commenting on the pull request with the line the failure prints for it -(``). +raise by commenting on the pull request with the line the failure prints for it, on a line of its +own (``). While you work, `cargo xtask changed` runs the same checks on only the packages your branch changes and those that depend on them (and `test-hygiene` on the whole workspace, and formatting, `layers` and `rows` when packages are checked), or everything when a diff --git a/docs/contributing.md b/docs/contributing.md index 1d4903f549..ae0419958a 100644 --- a/docs/contributing.md +++ b/docs/contributing.md @@ -51,9 +51,9 @@ reply themselves. The limits in `xtask/row-uses.txt` and `xtask/memory-limits.txt` only go down. CI's **Limits only go down** check, which runs on each push and again in the merge queue, fails when a pull request raises -or removes one against the commit it was made on; a new memory scenario is fine. A maintainer +or removes one against the base commit; a new memory scenario is fine. A maintainer approves a deliberate raise (or a removed scenario) by commenting on the pull request, or reviewing -it, with the line the failure prints for it, such as +it, with the line the failure prints for it on a line of its own, such as `` (a maintainer as for the deferral override above), and the check is run again. The line names the limit and its value, so a later push that raises it further needs a new approval. From 7137508a119376e5f47c7c355d14ca911cf58b81 Mon Sep 17 00:00:00 2001 From: mavrick Date: Sun, 22 Nov 2026 13:54:04 -0600 Subject: [PATCH 4/6] ci: read row-uses.txt as `cargo xtask rows` does, and fail on an unreadable base A line without an `=`, or a key other than `count`, is ignored by the row reader, so the check ignores it too. A limits file that can't be read on the base now needs an approval instead of being skipped, so a raise can't hide behind it. A message's lines are split at LF only, as the file's are. --- .github/scripts/ratchet-limits.py | 32 ++++++++++++++--------- .github/scripts/test_ratchet_limits.py | 36 +++++++++++++++++++++++++- AGENTS.md | 2 +- 3 files changed, 56 insertions(+), 14 deletions(-) diff --git a/.github/scripts/ratchet-limits.py b/.github/scripts/ratchet-limits.py index 5147b46af0..f0d8b9733f 100644 --- a/.github/scripts/ratchet-limits.py +++ b/.github/scripts/ratchet-limits.py @@ -4,14 +4,15 @@ committed limits that AGENTS.md says only come down: the xtask checks fail when the code is over its limit, but nothing stopped a pull request from editing the limit up to make them pass. This check compares each limit with the one on the base commit (the pull request's base branch, or the -merge queue entry's parent) and fails when one is higher or has been removed. A new line (a new memory scenario) is fine. Lowering a limit is what -the files are for. +merge queue entry's parent) and fails when one is higher or has been removed. A new line (a new +memory scenario) is fine. Lowering a limit is what the files are for. A limit may need to rise for a reason a maintainer accepts. A maintainer overrides the check for one change by commenting on the pull request, or reviewing it, with a line of its own that the -failure prints for that change, such as ``. -The line names the file, the limit and the value it was approved at, so a later push that raises -the limit further, or another limit, needs its own approval. A removed limit is approved the same +failure prints for that change, such as +``. The line names the file, the +limit and the value it was approved at, so a later push that raises the limit further, or another +limit, needs its own approval. A removed limit is approved the same way (`... memory-limits.txt save removed -->`), as is a deleted file. A maintainer here is the repository's owner, a member of its organization or a collaborator, as GitHub labels the message; the pull request's author may be that maintainer: the override is a deliberate, recorded decision. @@ -36,7 +37,8 @@ import subprocess import sys -LIMIT_FILES = ["xtask/row-uses.txt", "xtask/memory-limits.txt"] +ROWS_FILE = "xtask/row-uses.txt" +LIMIT_FILES = [ROWS_FILE, "xtask/memory-limits.txt"] APPROVE = "ratchet-raise-approved" MAINTAINERS = {"OWNER", "MEMBER", "COLLABORATOR"} # What Rust's `str::trim` removes (Unicode White_Space). Python's `strip` also removes U+001C to @@ -45,10 +47,12 @@ QUEUE_REF = re.compile(r"/pr-(\d+)-[0-9a-f]{40}$") -def parse(text): +def parse(text, rows_file=False): """The `name = number` lines of a limits file, a `#` starting a comment; the first line of a name counts. The xtask readers take the first line of a name too, so a later one can't move the limit. + `rows_file` reads `xtask/row-uses.txt` as `cargo xtask rows` does: only `count` matters, and a + line without an `=` is ignored. `cargo xtask memory` rejects a line without one. """ limits = {} # Lines end at LF or CRLF only, as in Rust's `str::lines`: `splitlines` would also split at a @@ -58,6 +62,9 @@ def parse(text): if not line: continue name, sep, value = line.partition("=") + name = name.strip(RUST_WHITESPACE) + if rows_file and (not sep or name != "count"): + continue if not sep: raise ValueError(f"line {n}: expected `name = number`") value = value.strip(RUST_WHITESPACE) @@ -67,7 +74,7 @@ def parse(text): raise ValueError(f"line {n}: `{value}` is not a number") from None if not math.isfinite(number): raise ValueError(f"line {n}: `{value}` is not a finite number") - limits.setdefault(name.strip(RUST_WHITESPACE), (number, value)) + limits.setdefault(name, (number, value)) return limits @@ -85,13 +92,14 @@ def compare(path, base_text, head_text): if base_text is None: return [], [] try: - base = parse(base_text) + base = parse(base_text, path == ROWS_FILE) except ValueError as error: - return [], [f"{path} on the base can't be read ({error}), so its limits aren't compared"] + # The limits can't be compared, so a raise could hide behind this: it needs a maintainer's say. + return [(f"{path}: can't be read on the base ({error}), so its limits can't be compared", f"{path} unreadable on base")], [] if head_text is None: return [(f"{path}: deleted, but it holds {len(base)} limit(s) that only go down", f"{path} deleted")], [] try: - head = parse(head_text) + head = parse(head_text, path == ROWS_FILE) except ValueError as error: return [(f"{path}: {error}", None)], [] problems = [] @@ -153,7 +161,7 @@ def approved(found, token): return any( not m.get("bot") and m.get("association") in MAINTAINERS - and any(row.strip() == line for row in (m.get("body") or "").splitlines()) + and any(row.strip() == line for row in (m.get("body") or "").split("\n")) for m in found ) diff --git a/.github/scripts/test_ratchet_limits.py b/.github/scripts/test_ratchet_limits.py index 34da9bd9c7..26c5b1518f 100644 --- a/.github/scripts/test_ratchet_limits.py +++ b/.github/scripts/test_ratchet_limits.py @@ -71,8 +71,42 @@ def test_a_file_that_cannot_be_read_fails_on_the_head_and_is_skipped_on_the_base self.assertIn("not a number", found[0]) self.assertEqual(len(self.problems(ROWS, "count\n")), 1) self.assertEqual(len(self.problems(ROWS, "count = nan\n")), 1) + # An unreadable base can't be compared, so it needs a maintainer's say, not a pass. found, notices = MODULE.compare("xtask/x.txt", "count = many\n", ROWS) - self.assertEqual((found, len(notices)), ([], 1)) + self.assertEqual(([token for _, token in found], notices), (["xtask/x.txt unreadable on base"], [])) + + def test_the_row_count_is_read_as_cargo_xtask_rows_reads_it(self): + path = MODULE.ROWS_FILE + note = "see AGENTS.md\nsome = thing\n" + ROWS + # A line without an `=`, and a key other than `count`, are ignored there, so they are here. + self.assertEqual(MODULE.compare(path, note, note), ([], [])) + self.assertEqual(MODULE.compare(path, note, ROWS), ([], [])) + found, _ = MODULE.compare(path, note, ROWS.replace("782", "900")) + self.assertEqual([message for message, _ in found], [f"{path}: `count` rose from 782 to 900"]) + # `cargo xtask memory` rejects such a line, and so does the check on that file. + found, _ = MODULE.compare(MODULE.LIMIT_FILES[1], "see AGENTS.md\n" + MEMORY, MEMORY) + self.assertEqual(len(found), 1) + self.assertIn("unreadable on base", found[0][1]) + + def test_messages_reads_comments_and_reviews_one_object_per_line(self): + asked = [] + + def run(args): + asked.append(args[3]) + return '{"body": "a", "association": "MEMBER", "bot": false}\n\n{"body": "b", "association": "NONE", "bot": true}\n' + + with unittest.mock.patch.object(MODULE, "run", run): + found = MODULE.messages("o/r", 7) + self.assertEqual(asked, ["repos/o/r/issues/7/comments", "repos/o/r/pulls/7/reviews"]) + self.assertEqual([m["body"] for m in found], ["a", "b", "a", "b"]) + + def test_the_pull_request_number_comes_from_the_environment_first(self): + ref = "refs/heads/gh-readonly-queue/main/pr-2655-76a6cd2823b4431c363e30a8023c7f69bccae938" + with unittest.mock.patch.dict(MODULE.os.environ, {"PR_NUMBER": "12", "MERGE_GROUP_REF": ref}): + self.assertEqual(MODULE.pr_number(), 12) + with unittest.mock.patch.dict(MODULE.os.environ, {"PR_NUMBER": "", "MERGE_GROUP_REF": "refs/heads/main"}): + with self.assertRaises(SystemExit): + MODULE.pr_number() def test_each_problem_has_its_own_approval_token(self): self.assertEqual(self.tokens(ROWS, ROWS.replace("782", "783")), ["xtask/x.txt count=783"]) diff --git a/AGENTS.md b/AGENTS.md index 090f2601ec..1944842510 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -163,7 +163,7 @@ the accessors there too. Both limit files only go down: CI's `Limits only go down` job fails a pull request that raises or removes a limit against its base (a new memory scenario is fine). A maintainer approves a deliberate raise by commenting on the pull request with the line the failure prints for it, on a line of its -own (``). +own (``), then re-runs the job. While you work, `cargo xtask changed` runs the same checks on only the packages your branch changes and those that depend on them (and `test-hygiene` on the whole workspace, and formatting, `layers` and `rows` when packages are checked), or everything when a From 3935c6cb3e4937cee951ada804b0482158d7c273 Mon Sep 17 00:00:00 2001 From: mavrick Date: Sun, 22 Nov 2026 14:28:08 -0600 Subject: [PATCH 5/6] ci: check the head before an unreadable-base approval, and read gh output of any layout A head file that doesn't parse can no longer be waved through by approving an unreadable base: the head is parsed first and has no approval. The comments and reviews are read as a stream of JSON values, so either layout of gh's output works. The notices return value that nothing used is gone. --- .github/scripts/ratchet-limits.py | 41 ++++++++++++++++---------- .github/scripts/test_ratchet_limits.py | 28 +++++++++++------- 2 files changed, 44 insertions(+), 25 deletions(-) diff --git a/.github/scripts/ratchet-limits.py b/.github/scripts/ratchet-limits.py index f0d8b9733f..8bd28afffe 100644 --- a/.github/scripts/ratchet-limits.py +++ b/.github/scripts/ratchet-limits.py @@ -84,31 +84,33 @@ def marker(token): def compare(path, base_text, head_text): - """The raised or removed limits of one file, as (message, approval token) pairs, and notices. + """The raised or removed limits of one file, as (message, approval token) pairs. `base_text` is None when the file didn't exist on the base (nothing to compare), `head_text` None when the change deletes it. A token of None means nothing can approve the problem: fix the file. """ if base_text is None: - return [], [] + return [] + head = None + if head_text is not None: + try: + head = parse(head_text, path == ROWS_FILE) + except ValueError as error: + return [(f"{path}: {error}", None)] try: base = parse(base_text, path == ROWS_FILE) except ValueError as error: # The limits can't be compared, so a raise could hide behind this: it needs a maintainer's say. - return [(f"{path}: can't be read on the base ({error}), so its limits can't be compared", f"{path} unreadable on base")], [] - if head_text is None: - return [(f"{path}: deleted, but it holds {len(base)} limit(s) that only go down", f"{path} deleted")], [] - try: - head = parse(head_text, path == ROWS_FILE) - except ValueError as error: - return [(f"{path}: {error}", None)], [] + return [(f"{path}: can't be read on the base ({error}), so its limits can't be compared", f"{path} unreadable on base")] + if head is None: + return [(f"{path}: deleted, but it holds {len(base)} limit(s) that only go down", f"{path} deleted")] problems = [] for name, (old, old_text) in base.items(): if name not in head: problems.append((f"{path}: the limit `{name}` ({old_text}) was removed", f"{path} {name} removed")) elif head[name][0] > old: problems.append((f"{path}: `{name}` rose from {old_text} to {head[name][1]}", f"{path} {name}={head[name][1]}")) - return problems, [] + return problems def run(args): @@ -143,6 +145,18 @@ def head_file(path): return None +def objects(text): + """Every JSON value in `text`, whether `gh` prints them one to a line or indented.""" + decoder, at, found = json.JSONDecoder(), 0, [] + while True: + while at < len(text) and text[at].isspace(): + at += 1 + if at >= len(text): + return found + value, at = decoder.raw_decode(text, at) + found.append(value) + + def messages(repo, number): """Every comment and review on the pull request, as (body, author association, is a bot).""" found = [] @@ -151,7 +165,7 @@ def messages(repo, number): ["gh", "api", "--paginate", endpoint, "--jq", ".[] | {body, association: .author_association, bot: (.user.type == \"Bot\")}"] ) - found += [json.loads(line) for line in out.splitlines() if line.strip()] + found += objects(out) return found @@ -194,10 +208,7 @@ def main(): if is_link(path) or base_mode(base_sha, path) == "120000": problems.append((f"{path}: is a symbolic link, but the limits must be in a regular file", None)) continue - found, notices = compare(path, base_file(base_sha, path), head_file(path)) - problems += found - for notice in notices: - print(f"::notice::{escape(notice)}") + problems += compare(path, base_file(base_sha, path), head_file(path)) if not problems: print("No limit that only goes down has risen.") return 0 diff --git a/.github/scripts/test_ratchet_limits.py b/.github/scripts/test_ratchet_limits.py index 26c5b1518f..183a95c7f1 100644 --- a/.github/scripts/test_ratchet_limits.py +++ b/.github/scripts/test_ratchet_limits.py @@ -1,6 +1,7 @@ """Checks for ratchet-limits.py on limits files cut down from xtask/row-uses.txt and xtask/memory-limits.txt.""" import importlib.util +import json from pathlib import Path import unittest import unittest.mock @@ -20,12 +21,10 @@ def person(body, association="MEMBER", bot=False): class RatchetLimits(unittest.TestCase): def problems(self, base, head): - found, notices = MODULE.compare("xtask/x.txt", base, head) - self.assertEqual(notices, []) - return [message for message, _ in found] + return [message for message, _ in MODULE.compare("xtask/x.txt", base, head)] def tokens(self, base, head): - return [token for _, token in MODULE.compare("xtask/x.txt", base, head)[0]] + return [token for _, token in MODULE.compare("xtask/x.txt", base, head)] def test_a_raised_row_count_is_refused(self): found = self.problems(ROWS, ROWS.replace("782", "783")) @@ -72,19 +71,20 @@ def test_a_file_that_cannot_be_read_fails_on_the_head_and_is_skipped_on_the_base self.assertEqual(len(self.problems(ROWS, "count\n")), 1) self.assertEqual(len(self.problems(ROWS, "count = nan\n")), 1) # An unreadable base can't be compared, so it needs a maintainer's say, not a pass. - found, notices = MODULE.compare("xtask/x.txt", "count = many\n", ROWS) - self.assertEqual(([token for _, token in found], notices), (["xtask/x.txt unreadable on base"], [])) + self.assertEqual(self.tokens("count = many\n", ROWS), ["xtask/x.txt unreadable on base"]) + # Nothing approves a head that doesn't parse, whatever the base is. + self.assertEqual(self.tokens("count = many\n", "count = oops\n"), [None]) def test_the_row_count_is_read_as_cargo_xtask_rows_reads_it(self): path = MODULE.ROWS_FILE note = "see AGENTS.md\nsome = thing\n" + ROWS # A line without an `=`, and a key other than `count`, are ignored there, so they are here. - self.assertEqual(MODULE.compare(path, note, note), ([], [])) - self.assertEqual(MODULE.compare(path, note, ROWS), ([], [])) - found, _ = MODULE.compare(path, note, ROWS.replace("782", "900")) + self.assertEqual(MODULE.compare(path, note, note), []) + self.assertEqual(MODULE.compare(path, note, ROWS), []) + found = MODULE.compare(path, note, ROWS.replace("782", "900")) self.assertEqual([message for message, _ in found], [f"{path}: `count` rose from 782 to 900"]) # `cargo xtask memory` rejects such a line, and so does the check on that file. - found, _ = MODULE.compare(MODULE.LIMIT_FILES[1], "see AGENTS.md\n" + MEMORY, MEMORY) + found = MODULE.compare(MODULE.LIMIT_FILES[1], "see AGENTS.md\n" + MEMORY, MEMORY) self.assertEqual(len(found), 1) self.assertIn("unreadable on base", found[0][1]) @@ -100,6 +100,14 @@ def run(args): self.assertEqual(asked, ["repos/o/r/issues/7/comments", "repos/o/r/pulls/7/reviews"]) self.assertEqual([m["body"] for m in found], ["a", "b", "a", "b"]) + def test_gh_output_may_be_compact_or_indented(self): + compact = '{"body": "a", "association": "MEMBER", "bot": false}\n{"body": "b", "association": "NONE", "bot": true}\n' + indented = json.dumps(MODULE.objects(compact), indent=2)[1:-1].replace("},", "}\n") + self.assertEqual(MODULE.objects(compact), MODULE.objects(indented)) + self.assertEqual(len(MODULE.objects(indented)), 2) + self.assertEqual(MODULE.objects(""), []) + self.assertEqual(MODULE.objects(" \n"), []) + def test_the_pull_request_number_comes_from_the_environment_first(self): ref = "refs/heads/gh-readonly-queue/main/pr-2655-76a6cd2823b4431c363e30a8023c7f69bccae938" with unittest.mock.patch.dict(MODULE.os.environ, {"PR_NUMBER": "12", "MERGE_GROUP_REF": ref}): From df7138cae81f9886d675e093ba46bc4e5d8f1aa0 Mon Sep 17 00:00:00 2001 From: mavrick Date: Sun, 22 Nov 2026 15:07:18 -0600 Subject: [PATCH 6/6] ci: bind an unreadable-base approval to the head it was given on The approval line for a base that can't be read carries a digest of the head file, so a later push to the same file needs its own approval. --- .github/scripts/ratchet-limits.py | 7 +++++-- .github/scripts/test_ratchet_limits.py | 7 ++++++- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/.github/scripts/ratchet-limits.py b/.github/scripts/ratchet-limits.py index 8bd28afffe..b17f43a755 100644 --- a/.github/scripts/ratchet-limits.py +++ b/.github/scripts/ratchet-limits.py @@ -30,6 +30,7 @@ limit has risen), GITHUB_REPOSITORY, and PR_NUMBER or, in the merge queue, MERGE_GROUP_REF. """ +import hashlib import json import math import os @@ -100,8 +101,10 @@ def compare(path, base_text, head_text): try: base = parse(base_text, path == ROWS_FILE) except ValueError as error: - # The limits can't be compared, so a raise could hide behind this: it needs a maintainer's say. - return [(f"{path}: can't be read on the base ({error}), so its limits can't be compared", f"{path} unreadable on base")] + # The limits can't be compared, so a raise could hide behind this: it needs a maintainer's say, + # for the head as it is (its digest is in the token), not for whatever is pushed next. + digest = hashlib.sha256((head_text or "").encode("utf-8")).hexdigest()[:12] + return [(f"{path}: can't be read on the base ({error}), so its limits can't be compared", f"{path} unreadable on base, head {digest}")] if head is None: return [(f"{path}: deleted, but it holds {len(base)} limit(s) that only go down", f"{path} deleted")] problems = [] diff --git a/.github/scripts/test_ratchet_limits.py b/.github/scripts/test_ratchet_limits.py index 183a95c7f1..73ee370789 100644 --- a/.github/scripts/test_ratchet_limits.py +++ b/.github/scripts/test_ratchet_limits.py @@ -71,7 +71,12 @@ def test_a_file_that_cannot_be_read_fails_on_the_head_and_is_skipped_on_the_base self.assertEqual(len(self.problems(ROWS, "count\n")), 1) self.assertEqual(len(self.problems(ROWS, "count = nan\n")), 1) # An unreadable base can't be compared, so it needs a maintainer's say, not a pass. - self.assertEqual(self.tokens("count = many\n", ROWS), ["xtask/x.txt unreadable on base"]) + self.assertEqual(len(self.tokens("count = many\n", ROWS)), 1) + # The approval is for the head it was given on: another head needs another line. + [first] = self.tokens("count = many\n", ROWS) + [second] = self.tokens("count = many\n", ROWS.replace("782", "900")) + self.assertTrue(first.startswith("xtask/x.txt unreadable on base, head ") and first != second) + self.assertEqual(self.tokens("count = many\n", ROWS), [first]) # Nothing approves a head that doesn't parse, whatever the base is. self.assertEqual(self.tokens("count = many\n", "count = oops\n"), [None])