Skip to content

perf(hooks): gate route-qa-runners behind a shell prefilter - #570

Merged
sumithr merged 17 commits into
mainfrom
perf/route-qa-hook-prefilter
Aug 1, 2026
Merged

sumithr merged 17 commits into
mainfrom
perf/route-qa-hook-prefilter

Conversation

@sumithr

@sumithr sumithr commented Jul 22, 2026 •

Copy link
Copy Markdown
Owner

Summary

The PostToolUse Bash hook (route-qa-runners.py) paid a Python interpreter start-up on every Bash call, while only mutmut/promptfoo/eval-shaped commands can ever route. The Bash entry now goes through route-qa-runners-prefilter.cmd, a cmd.exe/sh polyglot. On POSIX its shell branch greps the hook payload for those tokens and only then invokes the Python hook, so an unrelated Bash call finishes with no interpreter spawn at all. On Windows the batch branch takes no shortcut and pipes every payload straight into route-qa-runners.py, which is exactly what settings.json did before this PR, so Windows contributors keep the routing they already had.

Routing behaviour is unchanged on both platforms: the Python command-shape gate still makes every routing decision.

Related issue

None: latency finding from a workflow-config audit.

Changes

  • New .claude/hooks/route-qa-runners-prefilter.cmd. Line 1 opens a quoted heredoc that hides the batch block from sh; cmd.exe reads that same line as a label. The POSIX branch matches the token set mutmut / promptfoo / eval, documented as a required superset of the Python hook's command shapes (eval is what covers npm run eval, which contains no "promptfoo"). The batch branch probes python, then py -3, then python3, making each one prove it is Python 3 before using it, so a Windows Store alias stub or a Python 2 falls through instead of consuming the branch and dropping the payload. No usable interpreter is a silent exit 0, never an error: the hook is advisory and must not disturb the Bash result it observes.
  • The .cmd extension is load-bearing twice over: cmd.exe only executes batch files by that extension, and Claude Code's Windows handling prepends bash to any command containing .sh, which would defeat the batch block.
  • .claude/settings.json: the Bash PostToolUse entry now invokes the prefilter instead of the Python hook directly.
  • .gitattributes: *.cmd text eol=lf. The rename out of *.sh dropped the wrapper's line-ending pin, and a CRLF checkout kills the POSIX branch on case "$payload" in\r.
  • .pre-commit-config.yaml and .github/workflows/lint.yml: the file has no shebang, so shellcheck's auto-detection skips it. Both now point shellcheck at it explicitly with --shell=sh; the batch block sits inside a quoted heredoc, which shellcheck reads as data.
  • .claude/hooks/route-qa-runners.py: docstring pointing at the prefilter, the superset requirement, and the Windows branch's different behaviour.
  • .claude/README.md: prefilter row and the full polyglot rationale.
  • tests/test_route_qa_runners.py: 12 new tests.

Also fixed here: the required ruff check + format job was red on main

Not caused by this PR, but found by it and fixed in it rather than left live on main.

pyproject.toml had ruff>=0.5,<1 while .pre-commit-config.yaml pinned rev: v0.13.0. An open range cannot agree with a fixed rev, so the three gates that run ruff were running three different versions: CI resolved whatever was newest, git commit used 0.13.0, and a synced venv had something else again. ruff 0.16.0 then began formatting Python inside Markdown fences, taking ruff format . on clean main from 252 files to 335 (252 .py + 83 .md), and the required job went red on a main nobody had touched: 426c4ac reproduces it exactly, reporting 3 files would be reformatted, 332 files already formatted.

  • pyproject.toml: ruff==0.16.0, an exact pin unlike the ranges around it, with the reason recorded at the pin.
  • .pre-commit-config.yaml: rev: v0.16.0, comment rewritten to say the two must match exactly.
  • Reformatted the 3 drifting files: tests/scenarios/CONFORMANCE.md and two worked examples. Cosmetic only (an import split, blank lines, a parametrize wrap) inside illustrative code blocks; nothing reads these byte-for-byte.

Pinning the version turned out not to be enough, because the gates also have to look at the same files. The upstream ruff-pre-commit hooks declare types_or as python/pyi/jupyter, and CI's two steps do not walk the same tree:

ruff check --show-files .    253 .py + pyproject.toml and ruff.toml
ruff format --check .        253 .py + 83 .md

Only ruff-format needs an override. Reverting a formatted fence shows the gap it closes:

ruff format --check <file>                   ->  1 file would be reformatted
pre-commit run ruff-format --files <file>    ->  ruff format...(no files to check)Skipped

so a contributor could commit drifting Markdown, pass every local gate, and turn the required CI job red. With types_or: [python, pyi, jupyter, markdown] the same hook reports 1 file reformatted.

ruff-check deliberately keeps the upstream list. It ignores Markdown entirely, and its only non-Python inputs are the two config TOMLs, which it special-cases by name, so a toml tag would hand the hook every tracked .toml, including tests/fixtures/repo_map/rust_context_crate/Cargo.toml, which ruff check --show-files . does not list. Those two files carry no lint risk either: ruff.toml selects E/F/I/B/UP and every TOML rule lives in the RUF family, so ruff check on them can raise no findings. They still need covering for a different reason, below.

Ruff also rejects an invalid config outright, independent of any lint rule, and nothing local caught that. A typo'd selector is valid TOML, so check-toml passes it while CI dies:

check-toml                       ->  Passed
ruff check .                     ->  ruff failed
                                     Cause: Unknown rule selector `NOT-A-RULE` in `select` from ruff.toml
pre-commit ruff-check ruff.toml  ->  (no files to check)Skipped

origin/main carries the same bare hook, so that gap predates this PR. It is closed by a files:-scoped aliased entry (the pattern this config already uses for the shellcheck polyglot) matching only pyproject.toml, ruff.toml and .ruff.toml. With it, the injected config fails at commit time instead of in CI.

What is and is not test-enforced

tests/test_toolchain_pins.py asserts the version agreement and nothing else: the pyproject constraint is an exact == pin, and the pre-commit rev: equals v<that version>. Three injections fail distinctly (open range, stale rev, deleted rev).

That scope is deliberate. The ruff check + format job installs ruff from pyproject.toml and never opens .pre-commit-config.yaml, so a stale rev: is invisible to it and nothing else can catch it. Every other property of the hooks (types_or, args, files, exclude, stages) only decides whether the local convenience hook mirrors CI; weaken any of them and the required job still fails on the next push. An earlier revision of this PR did try to pin the hook shapes, and successive review passes kept finding holes in it (keys, then values, then pre-commit semantics) without ever finding one in the config itself. The hooks' intended shape and the measurements behind it are recorded in .pre-commit-config.yaml beside the hooks instead.

One constraint that did survive into the module: it anchors the repo root on .git, matching tests/test_check_no_em_dashes.py. A naive parents[1] lands in mutmut's mutants/ copy, which carries pyproject.toml but none of the repo's dotfiles, and the resulting FileNotFoundError tripped mutmut's -x so all six modules reported 0 killed, i.e. one broken test rendered as six catastrophic regressions.

How it was verified

Routing, through the real wiring. Four payloads piped into the prefilter exactly as settings.json invokes it:

payload result
git status, exit 0 exit 0, 0 bytes stdout, 0 bytes stderr
uv run mutmut run + real survivor fixture additionalContext naming mutation-survivor-triage
npm run eval + real promptfoo FAIL fixture, exit 100 additionalContext naming eval-failure-diagnoser
cat mutmut.log + same survivor fixture exit 0, 0 bytes stdout, 0 bytes stderr (token present, command shape wrong)

The perf contract itself. A sandboxed copy of the prefilter next to a recording stand-in for route-qa-runners.py, counting real invocations:

git status               python spawns: 0
ls -la                   python spawns: 0
npm test                 python spawns: 0
uv run mutmut run        python spawns: 1

100 non-routing calls: 8.3 ms/call through the prefilter vs 27.9 ms/call invoking the Python hook directly.

Tests. uv run pytest tests/test_route_qa_runners.py: 50 passed, 2 skipped on macOS. The 2 skips are the cmd.exe batch-branch tests, which run for real on the five windows-latest jobs; the POSIX-only tests skip there in turn. Both branches are therefore executed by the matrix rather than inferred.

Three of the new tests were added because an earlier revision passed without them, each confirmed by re-injecting the defect:

  • test_eval_token_alone_still_routes: deleting *eval* from the token list left the old test green, because the promptfoo fixture contains the word "promptfoo" three times. The new case uses a payload whose only token is eval.
  • test_token_free_payload_does_not_invoke_the_python_hook: widening the case to *) passed every test, so the PR's central claim was unpinned. Now counted directly.
  • test_the_two_hooks_only_name_sibling_files_that_exist: the rename left the Python hook's docstring pointing at the dead .sh spelling. Every route-qa-runners* filename either hook names must now resolve on disk, and each must still name the other.

Other gates. python -m mypy: clean, 74 source files. shellcheck --shell=sh on the prefilter: clean, and verified load-bearing by injecting a shell bug and watching it fail. ruff check . clean and ruff format --check . reports 336 files already formatted, on the now-pinned 0.16.0. Mutation gate on this branch: 1621/1621 mutants executed, 1621 killed, 0 survivors, all 6 modules at or above baseline.

Checklist

  • PR title follows Conventional Commits
  • Tests pass locally (pytest) and lint/type checks are green (pre-commit run --all-files, python -m mypy)
  • Added or updated tests covering the change
  • Updated the relevant docs in this same PR
  • No breaking changes (or they are called out above)

sumithr and others added 17 commits July 22, 2026 18:14
The PostToolUse Bash hook paid a Python interpreter start-up on every
Bash call, while only mutmut/promptfoo/eval-shaped commands can ever
route. A /bin/sh prefilter now greps the payload for those tokens and
only invokes the Python hook on a match; unrelated commands complete in
~10ms with no interpreter spawn. Routing behaviour is unchanged: the
Python command-shape gate still makes every routing decision.

The token list must stay a superset of the Python hook's command shapes
("eval" covers "npm run eval", which contains no "promptfoo"). New
tests pin the superset, the wrapper's transparency on routing payloads,
and the settings.json wiring.
The five prefilter tests exec route-qa-runners-prefilter.sh via its shebang,
which Windows cannot do (OSError [WinError 193]), failing all five
windows-latest pytest jobs. The prefilter is a /bin/sh script for the
macOS/Linux dev machines .claude/settings.json targets, so those tests now
carry the same skipif the session-start Bash hook tests use. The two contracts
that are meaningful on Windows (shebang present, settings.json wiring) stay
unconditional. Hoists the function-local os import and documents the platform
constraint in .claude/README.md.
Codex review found test_npm_run_eval_fail_routes_through_wrapper could not
detect the regression its docstring claimed to pin: real promptfoo stdout
contains the word promptfoo, so the payload still matched via the promptfoo
token with *eval* deleted from the prefilter. Verified by mutation, the test
passed against that mutant.

Adds test_eval_token_alone_still_routes, using a payload whose only token is
the eval in the command: promptfoo exits 100 on a failing case and the Python
hook routes on that exit code alone, so no stdout marker is needed. Deleting
*eval* from the prefilter now fails this test, and deleting *mutmut* fails the
mutmut test. Both token mutants are killed.

Also narrows the skip condition to sys.platform alone, dropping the
shutil.which(sh) probe that could have silently skipped these tests on a POSIX
host with no PATH-visible sh, and records the prefilter's raw-text matching
limitation against the Python hook's shlex parsing.
Second codex pass found no defects but four wording nits, all in prose added
by the previous two commits: the test-module comment still described the hook
as macOS/Linux-only after the README explained the Windows path, the script
header overstated the cost and rarity of the shlex gap, and the README both
asserted an unqualified token superset and presented the Windows behaviour as
proven when nothing in this repo exercises it. Wording only, no behaviour
change.
The per-file merge review found the PR's central contract untested. Widening
the case statement to a catch-all would send every Bash call to the Python
hook, reverting the whole latency saving, yet every existing test still
passed: the silence assertions cannot tell 'the prefilter skipped Python'
from 'Python ran and declined to route'.

Adds test_token_free_payload_does_not_invoke_the_python_hook, which runs the
real prefilter in a sandbox against a stand-in for the Python hook that
records each invocation, then requires zero invocations for 'git status' and
'npm test' and exactly one for 'uv run mutmut run'. Verified by mutation: the
catch-all case fails this test and no other.
The prefilter shipped as a POSIX /bin/sh script, which replaced a
settings.json entry that had pointed at route-qa-runners.py. Windows runs a
.py by association, so the swap silently took the routing reminder away from
Windows contributors, and Git Bash would not reliably restore it: the hook's
shebang asks for python3, which Git Bash on Windows frequently lacks.

Makes the prefilter a cmd.exe/sh polyglot instead, the same trick already used
by hooks/run-hook.cmd. cmd.exe runs the batch block; sh skips it as a quoted
heredoc and runs the POSIX branch. Windows deliberately takes no shortcut and
pipes straight to route-qa-runners.py, restoring exactly the pre-prefilter
behaviour, and exits 0 in silence when it finds no interpreter. POSIX keeps
the token prefilter and the full saving, measured at 10.1 vs 33.7 ms/call.

The .cmd extension is required twice over: cmd.exe only executes batch files
by it, and Claude Code prepends bash to any command containing .sh, which
would defeat the batch block. test_wrapper_is_a_runnable_polyglot fails on a
rename back.

Both branches are now proven by CI rather than inferred: the POSIX branch runs
on ubuntu and macOS, and two new windows-only tests drive the batch branch
through cmd.exe on windows-latest. The test harness now invokes the hook as a
shell command string, which is how Claude Code invokes it, because a
shebang-less polyglot cannot be exec'd directly.

Having no shebang also hid the file from shellcheck's auto-detection, so it is
pointed at explicitly in .pre-commit-config.yaml and the lint.yml mirror,
verified to still fail on an injected quoting bug.
Two defects codex found in the polyglot, both of which would have silently
undone the Windows fix.

The interpreter selection tested only whether python.exe was on PATH. The
Windows Store ships a stub by that name which opens the Store and runs
nothing, and a Python 2 would also satisfy the check; either one consumed the
branch and then exited, skipping the py -3 fallback and dropping the payload.
Each candidate is now probed by running it and making it prove it is Python 3,
so an unusable one falls through instead of swallowing the route.

Renaming the wrapper from .sh to .cmd also dropped it out of the
"*.sh text eol=lf" rule in .gitattributes. On a checkout with
core.autocrlf=true the POSIX branch would then receive CRLF and die on a
carriage return at the end of the case statement, which is the exact failure
the existing .gitattributes comment describes. Adds "*.cmd text eol=lf"
(cmd.exe reads LF batch files fine, and hooks/run-hook.cmd is already LF in
this repo) and a test asserting the file contains no CRLF, verified to fail on
an injected one.
Renaming the prefilter from .sh to .cmd left route-qa-runners.py telling the
reader it is "deployed behind route-qa-runners-prefilter.sh", a file that is no
longer in the tree. That sends a contributor looking for something that is not
there, and the sentence was wrong a second way: it described the token grep as
the whole of the wrapper's behaviour, which is true only of the POSIX branch.
The Windows branch takes no shortcut and pipes every payload straight in.

Adds a guard, because this is now the second rename this file has survived:
every route-qa-runners*.{py,cmd,sh} filename either hook mentions has to resolve
on disk, and each hook has to still name the other. Verified load-bearing twice
by re-injecting the defect - the dead .sh spelling fails on the existence check,
and dropping the cross-reference for a self-mention fails on the sibling check.
The required "ruff check + format" job was red, and not because of anything on
this branch: clean main at 426c4ac reproduces it exactly. pyproject.toml asked
for ruff>=0.5,<1 while .pre-commit-config.yaml pinned rev: v0.13.0, and an open
range cannot agree with a fixed rev. Three gates were running three different
ruff versions at once - CI resolved whatever was newest, git commit used 0.13.0,
a synced venv had 0.15.22 - so the comment claiming the two pins matched was
describing something structurally impossible.

ruff 0.16.0 then began formatting Python inside Markdown fences, taking
`ruff format .` from 252 files to 332. Three pre-existing files drifted and the
required check went red on a main nobody had touched, while every contributor's
git commit stayed green.

Pins ruff==0.16.0 and rev: v0.16.0, exact and identical, with the reason
recorded at both. Reformats the three files: cosmetic only (an import split,
blank lines, a parametrize wrap) inside illustrative code blocks, and nothing
reads them byte-for-byte.

Adds tests/test_toolchain_pins.py so the next divergence is a test failure
rather than a surprise on an unrelated PR: the pyproject constraint has to be an
exact == pin, and the pre-commit rev has to be v<that version>. Both verified
load-bearing by re-injecting the original defects.
Pinning ruff to one version was not enough: the two gates also have to look at
the same FILES. The upstream ruff-pre-commit hooks declare types_or as
python/pyi/jupyter, while CI runs a bare `ruff check .` / `ruff format --check .`
that walks Markdown too. So a drifting fence produced

    ruff format..............................(no files to check)Skipped

at `git commit` and a red required job in CI - the exact divergence the pin was
meant to close, just moved from "different versions" to "different file sets".
Reproduced by reverting a formatted fence and watching the hook skip a file the
CLI reformats; with types_or set the same hook now reports "1 file reformatted".
Both ids get it, since `ruff check` and `ruff format` are separate CI steps.

Also fixes two defects in the guards added alongside the pin:

The module resolved the repo root as parents[1] of its own file. mutmut runs the
suite from a `mutants/` copy that carries pyproject.toml but none of the repo's
dotfiles, so .pre-commit-config.yaml was missing there, the module raised
FileNotFoundError, and mutmut's -x aborted the run - every module reported 0
killed and the gate read as six catastrophic regressions rather than one broken
test. It now walks up for a directory holding BOTH files, which the mutants copy
never does.

The rev regex spanned the whole file, so deleting ruff's own rev would have
matched the NEXT repo's rev and reported a mismatch instead of a missing pin.
The search is now bounded to the ruff repo block, and deleting the rev reports
exactly that.

Adds test_pre_commit_ruff_hooks_cover_markdown. All three guards verified
load-bearing by injection: open range, stale rev, types_or removed, types_or
without markdown, and rev deleted each fail with their own message.
The previous commit gave both ruff hooks the same types_or on the claim that
ruff 0.16 formats AND lints Markdown. Only half of that is true. Measured:

    ruff check --show-files .   253 .py + 2 .toml (pyproject.toml, ruff.toml)
    ruff format --check .       253 .py + 83 .md

`ruff check` ignores Markdown entirely, so listing it there was noise, and the
hook was still skipping the two TOML files CI lints. The lists are now per-hook
and each mirrors what its own CI step discovers. Confirmed through pre-commit:
ruff-check on pyproject.toml/ruff.toml now Passed instead of Skipped, and
ruff-check on a Markdown file correctly reports Skipped.

Also repairs two things in the guard module.

It anchored the repo root on the first ancestor holding both pyproject.toml and
.pre-commit-config.yaml. That fixed the mutants/ copy but could still walk out
into an enclosing project when either marker was missing. Now anchored on .git,
matching tests/test_check_no_em_dashes.py - never copied into mutants/, and a
file rather than a directory in a worktree, which is why it tests exists().
Verified by loading the module from mutants/tests/: it resolves to the real repo
root and all three guards pass there.

The helpers parsed the YAML with regexes, which tied the tests to one spelling.
They now go through yaml.safe_load, the same way pre-commit reads the file, so
YAML semantics decide. Verified by rewriting the entry with quoted scalars,
reordered keys and a block-style list: the tests still pass where the regex
version would have failed all three.

Six injections still fail distinctly: open range, stale rev, types_or removed,
markdown dropped from ruff-format, toml dropped from ruff-check, rev deleted.
Two holes in the guards added earlier in this branch.

The hook lookup built its dict straight from the YAML entries, so duplicate ids
collapsed silently. pre-commit runs EVERY entry, meaning a second
`- id: ruff-check` is an extra hook rather than a redefinition: a malformed
duplicate sitting next to a correct entry passed all three tests while
pre-commit ran both. Duplicates are now rejected before the dict is built.

The coverage test asserted a hard-coded types_or per hook, which only relocated
the drift - the list and reality could disagree with the list wrong and the test
still green. It now probes ruff itself with one real file per tracked extension
and requires the hook's selection to agree on every one.

Getting that probe right needed one non-obvious correction. Naming a file
explicitly bypasses ruff's discovery rules: `ruff format --check
marketplace.json` reports "1 file would be reformatted", happily parsing JSON as
Python, while the same file inside a directory yields "No Python files found
under the given path(s)". The first version of the probe passed paths directly
and duly reported that ruff formats .json and py.typed. CI runs `ruff check .`
and `ruff format --check .`, both directories, so the probe now copies each
representative into a scratch directory inside the repo - inside, so ruff
resolves the same ruff.toml it would in CI - and probes that.

The measured version catches over-selection as well as under-selection: adding a
bogus `json` to ruff-format's types_or now fails, which an exact-match against a
hard-coded list only did by coincidence.

Eight injections fail distinctly: open range, stale rev, types_or removed,
markdown dropped from ruff-format, toml dropped from ruff-check, rev deleted,
duplicate hook id, and a bogus extra type.
Reverts two mistakes made earlier in this branch.

`types_or: [..., toml]` on ruff-check was wrong. `ruff check` does not lint
arbitrary TOML - it special-cases pyproject.toml and ruff.toml by NAME, and
`ruff check --show-files .` lists exactly those two while ignoring the tracked
tests/fixtures/repo_map/rust_context_crate/Cargo.toml. The tag therefore handed
the hook a file CI never lints. It also closed nothing: ruff.toml selects
E/F/I/B/UP and every TOML rule lives in the RUF family, so `ruff check` on those
two config files cannot raise anything. ruff-check goes back to the upstream
list; only ruff-format keeps an override, for Markdown, which is the one real
gap and is verified by reverting a fence and watching the hook skip it.

The measured-coverage test cannot run where it matters. The pre-push pytest and
mutmut hooks execute in isolated environments whose additional_dependencies list
PyYAML but neither identify nor ruff, so importing identify raised
ModuleNotFoundError there and would have taken the pre-push suite and the
mutation gate down - the same failure mode as the mutants/ path bug two commits
ago, from the same habit of assuming the test runs where I run it. Its probe was
also unsound: picking the first tracked file per suffix chose pyproject.toml to
represent .toml, which is precisely the special-cased name, so it measured 253
+2 as agreement and hid the Cargo.toml over-selection it existed to catch.

The guards are now pure YAML/TOML reads, which run in every environment. Seven
injections fail distinctly: open range, stale rev, types_or removed, markdown
dropped, toml re-added to ruff-check, rev deleted, duplicate hook id. Confirmed
through pre-commit: ruff-format Passed on a Markdown file, ruff-check Skipped on
Cargo.toml exactly as CI ignores it, ruff-check Passed on a .py.
ruff rejects an invalid config outright, independent of any lint rule, and
nothing local caught that. A typo'd selector is valid TOML so check-toml passes
it, while CI dies with

    ruff failed
      Cause: Unknown rule selector `NOT-A-RULE` in `select` from ruff.toml

The source hook cannot cover this: ruff finds pyproject.toml and ruff.toml by
NAME, so a `toml` type tag would drag in every other tracked .toml that CI
ignores. They get their own files-scoped entry instead, the same aliased-hook
pattern already used for the shellcheck polyglot below. The gap predates this
branch - origin/main carries the same bare ruff-check hook - but it surfaced
here, so it is fixed here.

The first attempt at that hook silently did nothing. pre-commit ANDs every
filter together, and upstream ruff-check sets types_or to python/pyi/jupyter, so
inheriting it and adding only `files:` intersects to the empty set: the hook
reported "(no files to check)Skipped" while looking correct in the config. It
overrides types_or now. Caught because the injected bad config still reached CI
in the probe, not because the config read well.

That is the same mistake as the earlier one my own test masked, so the guard now
asserts the override rather than the regex, and fails on the broken spelling.

Also tightens two things codex raised. The ruff-check assertion checks "no toml
tag" instead of "no types_or at all", since re-stating the upstream list
explicitly is legal and behaviour-preserving, and policing spelling is not the
point. And ruff-format must carry neither `exclude:` nor `files:`, either of
which silently negates the markdown coverage the types_or override buys.

Nine injections now fail distinctly: open range, stale rev, format types_or
removed, markdown dropped, toml added to the source hook, rev deleted, alias
removed (duplicate identity), files pattern widened to all TOML, and an exclude
that negates markdown. Confirmed through pre-commit: the bad config fails the
new hook, a valid config passes, Cargo.toml is skipped, and .py still lints.
Three separate rounds of review found the same shape of hole: the guard denied
whichever narrowing key had just been noticed, and pre-commit has more of them
than I kept enumerating. types, types_or, exclude_types, files and exclude are
all ANDed together, and stages can move a hook off `git commit` entirely, so
`types_or` being right proves very little on its own. Injecting
`types: [python]`, `exclude_types: [markdown]` or `stages: [pre-push]` each left
Markdown unselected at commit time while every assertion passed.

A blocklist is only ever as complete as the last review, so each ruff hook is
now pinned to an exact set of permitted keys. Any other key - including ones
pre-commit has not shipped yet - fails until someone reasons about what it does
to coverage and adds it deliberately with a test. All six injections that got
through before now fail, naming the offending key.

Also widens the config hook to `.ruff.toml`, which ruff reads under that name
too, and corrects the note about alias semantics: alias ADDS a selector rather
than replacing the id, so `pre-commit run ruff-check` targets both entries
carrying that id while `ruff-check-config` targets only the aliased one. Keying
on alias-or-id here is about telling two same-id entries apart, not about
mirroring the CLI lookup.

A nested `**/pyproject.toml` still falls outside the hook regex. None is
tracked, and matching them would need a pattern that cannot distinguish a real
nested config from a fixture, so it is recorded next to the constant rather
than half-closed.
Seven rounds of review found seven holes, every one of them in this guard rather
than in the config it guards. The last was decisive: allowlisting the hook keys
still left their VALUES unchecked, so `args: [--exit-zero]` or
`args: [--exclude '*.py']` passed every assertion while ruff reported success on
real violations or discovered no files at all. Keys, then values, then
pre-commit semantics - the space is unbounded, and each round of chasing it
introduced a defect of its own.

The reframe that settles it: the pre-commit hook is a convenience, not the gate.
`ruff check + format` is a required status check that runs `python -m ruff check
.` and `python -m ruff format --check .` over the real tree. Weaken a hook here
and the required job still fails on the next push, so asserting the hook's shape
guards a layer that cannot be authoritative.

Exactly one property escapes that. CI installs ruff from pyproject.toml and
never reads .pre-commit-config.yaml, so a stale `rev:` is invisible to it: a
version bump on one side alone silently puts contributors on a different
formatter than the required job, which is the original PR #570 failure. Nothing
but this module can catch that, so this module keeps that and drops the rest.

Two tests remain, from five. The hooks' intended shape and the measurements
behind it move into .pre-commit-config.yaml, next to the hooks, labelled as
reasoning to preserve rather than a contract something will catch you breaking.

Also narrows the config-file pattern to ^(pyproject|ruff|\.ruff)\.toml$. The
previous ^\.?(pyproject|ruff)\.toml$ also matched .pyproject.toml, which is not
a name ruff reads; the optional dot belongs only on the ruff alternative.

Three injections fail distinctly: open range, stale rev, rev deleted. Hook
behaviour re-verified by hand though no longer asserted: ruff-format Passed on a
Markdown file, ruff-check-config Passed on the two configs and Skipped on
Cargo.toml.
"CI never reads .pre-commit-config.yaml" was literally false: CI runs pytest,
which runs this very parser. The accurate statement, and the one the scope
decision actually rests on, is narrower - the `ruff check + format` job installs
ruff from pyproject.toml and never opens the file, so a stale rev is invisible
to the gate that would otherwise catch a version mismatch.
@sumithr
sumithr merged commit 096e231 into main Aug 1, 2026
47 of 48 checks passed
@sumithr
sumithr deleted the perf/route-qa-hook-prefilter branch August 1, 2026 23:48
sumithr added a commit that referenced this pull request Aug 1, 2026
🤖 I have created a release *beep* *boop*
---


##
[0.60.2](v0.60.1...v0.60.2)
(2026-08-01)


### Performance Improvements

* **hooks:** gate route-qa-runners behind a shell prefilter
([#570](#570))
([096e231](096e231))

---
This PR was generated with [Release
Please](https://github.com/googleapis/release-please). See
[documentation](https://github.com/googleapis/release-please#release-please).

---------

Co-authored-by: release-please[bot] <release-please[bot]@users.noreply.github.com>
sumithr pushed a commit that referenced this pull request Aug 3, 2026
The guard added in #570 cost more defects than it caught. Successive review
passes found a hole in it every round - a repo-root that resolved into mutmut's
mutants/ copy and aborted the mutation run, imports absent from the isolated
pre-push hook environments, a probe that picked the one special-cased filename
and so could not detect the over-selection it existed to catch, an allowlist
that still left permitted VALUES unchecked - while never once finding a hole in
the config it guarded.

What it protected is a stale `rev:`, which the `ruff check + format` job cannot
see because it installs ruff from pyproject.toml and never opens
.pre-commit-config.yaml. That risk is real but narrow, and it is now carried by
a comment at the pin itself rather than by a test module that has to be right
about pre-commit's filter semantics to be worth anything.

Everything the guard actually fixed stays: the exact ruff==0.16.0 pin, the
matching rev, the markdown types_or on ruff-format, and the files-scoped
ruff-check-config entry that catches an invalid ruff config at commit time.
Those are enforced by CI running the real commands over the real tree.
sumithr added a commit that referenced this pull request Aug 3, 2026
Supersedes Dependabot #575, which bumped `pyproject.toml` only.

The comment sitting directly above the pin says to move it and the
`ruff-pre-commit` `rev:` together in one commit. CI installs ruff via
`pip install -e ".[dev,vertex]"` and never opens
`.pre-commit-config.yaml`, so a one-sided bump leaves `git commit` and
the required CI job running different ruff versions, which is exactly
the drift #570 fixed.

## Changes

| File | From | To |
|---|---|---|
| `pyproject.toml:128` | `ruff==0.16.0` | `ruff==0.16.1` |
| `.pre-commit-config.yaml:39` | `rev: v0.16.0` | `rev: v0.16.1` |

## Verification

0.16.1 introduces no formatting change against this tree, so no fixture
churn:

```
ruff --version                 ruff 0.16.1
ruff check .                   All checks passed!
ruff format --check .          336 files already formatted
git diff -- tests/scenarios/   (empty)
```

The graded conformance fixtures are untouched, which is the property
that matters after the 0.16.0 markdown-formatting change.
sumithr pushed a commit that referenced this pull request Aug 3, 2026
The guard added in #570 cost more defects than it caught. Successive review
passes found a hole in it every round - a repo-root that resolved into mutmut's
mutants/ copy and aborted the mutation run, imports absent from the isolated
pre-push hook environments, a probe that picked the one special-cased filename
and so could not detect the over-selection it existed to catch, an allowlist
that still left permitted VALUES unchecked - while never once finding a hole in
the config it guarded.

What it protected is a stale `rev:`, which the `ruff check + format` job cannot
see because it installs ruff from pyproject.toml and never opens
.pre-commit-config.yaml. That risk is real but narrow, and it is now carried by
a comment at the pin itself rather than by a test module that has to be right
about pre-commit's filter semantics to be worth anything.

Everything the guard actually fixed stays: the exact ruff==0.16.0 pin, the
matching rev, the markdown types_or on ruff-format, and the files-scoped
ruff-check-config entry that catches an invalid ruff config at commit time.
Those are enforced by CI running the real commands over the real tree.
sumithr added a commit that referenced this pull request Aug 3, 2026
## Summary

Removes `tests/test_toolchain_pins.py`, the guard added in #570, and the
block of prose in `.pre-commit-config.yaml` that was standing in for it.
The ruff hooks are executable: the way to know they are right is to run
them, not to read an essay about them or a test asserting their shape.

The guard cost more defects than it caught. Successive review passes
found a hole in it every round, and never once found a hole in the
config it guarded:

| Round | Hole in the guard |
|---|---|
| 1 | repo root resolved into mutmut's `mutants/` copy, raising
`FileNotFoundError`, tripping `-x` and reporting all six modules as 0
killed |
| 2 | imported `identify` and shelled out to `ruff`, neither of which
exists in the isolated pre-push hook environments |
| 3 | probed the first tracked `.toml`, which is `pyproject.toml`, the
one name ruff special-cases, so it could not detect the over-selection
it existed to catch |
| 4 | allowlisted hook keys but left permitted VALUES unchecked, so
`args: [--exit-zero]` passed every assertion |

One comment line survives, on `rev:`, because nothing executable covers
it: the required `ruff check + format` job installs ruff from
`pyproject.toml` and never opens `.pre-commit-config.yaml`, so a rev
that drifts from the pin puts contributors on a different formatter and
stays quiet until an unrelated PR goes red.

## What stays

Nothing that fixed a real problem is removed. The config is untouched
apart from the comments:

- `ruff==0.16.1` in `pyproject.toml` and the matching `rev: v0.16.1`,
which is what turned the required check green on `main`
- `types_or: [python, pyi, jupyter, markdown]` on `ruff-format`, so a
drifting Markdown fence is caught at commit time
- the files-scoped `ruff-check-config` entry, so an invalid ruff config
fails at commit time instead of in CI

## How it was verified

Each behaviour the deleted prose described, confirmed by running the
hook against a real file rather than asserting it:

```
pre-commit run ruff-check-config --files pyproject.toml ruff.toml
  ->  ruff check (ruff config files)...Passed

pre-commit run ruff-check-config --files tests/fixtures/repo_map/rust_context_crate/Cargo.toml
  ->  ruff check (ruff config files)...(no files to check)Skipped

pre-commit run ruff-format --files tests/scenarios/CONFORMANCE.md
  ->  ruff format...Passed
```

and each one failing on an injected defect, so the passes above are not
vacuous:

```
# `select = [..., "NOT-A-RULE"]` in ruff.toml
pre-commit run ruff-check-config --files ruff.toml
  ->  Failed, exit code 2
      Cause: Unknown rule selector `NOT-A-RULE` in `select` from ruff.toml

# `x   =    1` added to a Python fence in CONFORMANCE.md
pre-commit run ruff-format --files tests/scenarios/CONFORMANCE.md
  ->  Failed, files were modified by this hook
      1 file reformatted
```

That second one is the whole reason `ruff-format` overrides `types_or`:
with the upstream python/pyi/jupyter list the same file reports `(no
files to check)Skipped`.

Both injections were reverted, confirmed by `git status`.

Full gates, on the pinned ruff 0.16.1 (rebased onto #582, which bumped
the pin from 0.16.0; the conflict was in the comment this PR deletes,
resolved by keeping the new rev):

- `uv run ruff check .`: All checks passed
- `uv run ruff format --check .`: 335 files already formatted (252 `.py`
+ 83 `.md`, one fewer `.py` after the deletion)
- `uv run mypy`: no issues in 74 source files
- `uv run pytest -q`: 100% coverage held; only
`test_built_wheel_contains_py_typed_marker` fails, the known `No module
named pip` in a uv venv, which the CI `pip install` jobs cover
- `pre-commit validate-config`: exit 0
- No dangling references to the deleted module remain (`grep -rn
toolchain_pins` is empty)

Mutation gate, dispatched on this branch because the diff touches
`tests/**/*.py` (run 30819133472, Linux, 4m27s):

```
| Module            | Baseline killed | Current killed | Survivors | Verdict |
| knowledge_loaders | 472             | 472            | 0         | OK      |
| rules             | 41              | 41             | 0         | OK      |
| standards         | 25              | 25             | 0         | OK      |
| tdm_validation    | 203             | 203            | 0         | OK      |
| coverage_models   | 87              | 87             | 0         | OK      |
| report_builder    | 793             | 793            | 0         | OK      |
All modules: kill counts >= baseline and 0 survivors. Strict gate passed.
```

## Residual risk, accepted deliberately

Stated plainly rather than buried, because it is the whole trade this PR
makes.

**Nothing now compares `pyproject.toml`'s `ruff==` pin with
`.pre-commit-config.yaml`'s `rev:`.** Verified by injecting `rev:
v0.15.0` and running every gate: the full suite passes, `pre-commit
validate-config` exits 0, no test reads `rev:` at all, and the required
lint job runs `python -m ruff` installed from `pyproject.toml` without
ever opening the config. A one-sided bump reaches `main` silently and
surfaces later as a red required check on somebody's unrelated PR. That
is the #570 failure, and it is now guarded by a comment instead of a
test.

The trade is accepted because the guard cost four rounds of its own
defects and caught none in the config, and because the real bump path
already does the right thing: #582 bumped `ruff` to 0.16.1 and synced
the `rev:` in one commit, touching exactly `pyproject.toml` and
`.pre-commit-config.yaml`.

Two related notes from the adversarial pass, neither a defect in this
PR:

- Weakening a *different* hook property (`types_or: [python]` on
`ruff-format`, or `stages: [manual]`) is not caught by CI *at the moment
of weakening* either. CI catches the drifting file it lets through, on
the next push. The deleted test never asserted hook shapes, so this is
unchanged by this PR.
- `tests/test_mutmut_subprocess_exclusions.py:274` globs every
`tests/test_*.py`, so deleting one changes its parametrize set. Inert
here: the deleted module was never in the mutmut `--ignore` list, all
six ignore paths still resolve, and the module runs 148 passed / 0
failed on this branch.

## Checklist

- [x] PR title follows [Conventional
Commits](https://www.conventionalcommits.org/)
- [x] Tests pass locally (`pytest`) and lint/type checks are green
(`pre-commit run --all-files`, `python -m mypy`)
- [ ] Added or updated tests covering the change (n/a: this PR REMOVES a
test; the hook behaviours are verified by executing the hooks, above,
and enforced by the required `ruff check + format` job)
- [x] Updated the relevant docs in this same PR
- [x] No breaking changes (or they are called out above)

---------

Co-authored-by: sumithr <sumith.ramsookbhai@johnlewis.co.uk>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants