Skip to content

pre-commit: cut the kwarg formatter's CPU 6.5x and stop the ruff fork bomb (#14174) - #14249

Merged
danielhanchen merged 6 commits into
mainfrom
fix/precommit-ci-perf-14174
Oct 19, 2026
Merged

danielhanchen merged 6 commits into
mainfrom
fix/precommit-ci-perf-14174

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Fixes the compute half of #14174: pre-commit.ci reported that the ruff-format-with-kwargs hook makes this repo its most expensive user, and that it fork-bombs ruff.

What was wrong

pre-commit.ci runs every hook with --all-files on every PR, so the cost that matters is one whole-repo run. On main that was 458 CPU-s for 4314 files:

  • scripts/enforce_kwargs_spacing.py re-tokenized, re-parsed and re-dumped the same text up to seven times per file (4 full tokenize calls, 7 ast.parse calls, 2 or more whole-file ast.dump calls, several ast.walk calls), and the cyclic GC swept the resulting objects for nothing. ruff format itself is about 9 CPU-s of the total.
  • The hook had no require_serial, so pre-commit started one partition per CPU, and each partition started its own multithreaded ruff format, plus two ruff --version probes and two Python processes. On a 192-core box that was 168 concurrent ruff format processes and about 32,000 threads.

What this changes

  • .pre-commit-config.yaml: require_serial: true on the hook.
  • scripts/run_ruff_format.py: one ruff format per hook call. The Python passes either side run in at most 8 size-balanced chunks (bounded by usable CPUs, UNSLOTH_RUFF_FORMAT_JOBS overrides), with a barrier between stages. Every name that reaches one file stays in one chunk, in order, and chunks are killed if the wrapper is interrupted.
  • scripts/enforce_kwargs_spacing.py: each stage parses the file once. A sparse scan finds kwarg = operators and string literals instead of a full tokenize (f-strings still go through the interpreter's tokenizer, so the 3.11 vs 3.12+ difference is kept), only def headers and short asserts are tokenized, and edits are checked on the edited fragment instead of dumping the whole file. Anything unusual takes the previous implementation, kept verbatim as _reference_*: syntax errors, line separators splitlines and tokenize disagree on, PEP 695 headers, possible 3.14 t-strings, shared or continued assert rows, f-folds glued to a keyword or next to a u prefix.
  • Tests: tests/test_run_ruff_format_jobs.py (job count, chunking, interrupts, chunked vs serial on real files); tests/test_formatter_fixed_point.py pins its own parallel batches to one job each.

Results

pre-commit run ruff-format-with-kwargs --all-files, base and head alternated in the same window, median of 3:

main this PR
user CPU 402.8 s 62.7 s
sys CPU 55.7 s 7.2 s
total CPU 458 s 70 s (6.5x less)
concurrent ruff format 168 1
wall (192 cores, shared host) 20 to 25 s 13 to 31 s
tree after the run clean clean

The 53k-line studio/backend/routes/inference.py goes from about 12 s to about 1.7 s per run. In-process over the repo the Python passes go from roughly 400 CPU-s to 46 CPU-s.

Output is unchanged

The formatter has to stay byte-identical, so the new script was compared against the previous one with a differential harness: every public pass, both stages, process_file on real files, and the full pre, ruff 0.6.9, post pipeline, checking output bytes, the changed flag and the exception type.

  • All 4314 repo files, the CPython stdlib and transformers/src, each also with six kinds of unformatted variants (kwarg spaces stripped, def commas toggled, asserts exploded, blank lines after imports, split strings, redundant pass): about 80k texts, 0 differences.
  • CPython 3.9, 3.10, 3.11, 3.12, 3.13 and 3.14, including hand-written 3.14 t-string cases.
  • About 1.6M generated programs aimed at the fast paths. Those runs and the review found four inputs where a fast path diverged: an f-fold next to a u prefix on another line, an f-fold glued to a keyword, and two asserts on a continued or shared row. The last two commits fix them, and each repro now matches on every version. The final script then passed the 415-file sample with variants on all six versions, the repo, and 150k fresh programs, with 0 differences.
  • The only known difference is on input that does not parse: on Python 3.10 a file with a NUL byte returns unchanged where the previous script raised ValueError. ruff then rejects that file, so the hook fails on it either way.

Existing behaviour that this PR keeps on purpose, to be fixed separately:

  • On 3.12+ the spacing pass rewrites f"{x=}" to f"{x = }", which changes the printed text.
  • remove_redundant_passes can turn the next string into a docstring, leave an empty suite, or cut the wrong characters after non-ASCII text on the same line.
  • With PEP 695 type parameters the trailing comma can land inside the bound (def f[T: g(1)](a, b, c=0)).

Not covered

  • Windows and macOS were not run; the chunked wrapper only uses subprocess, tempfile and os.stat.
  • The CI move that keeps this hook off pre-commit.ci entirely is a separate PR.

The pre and post passes re-tokenized, re-parsed and re-dumped the same text up
to seven times per file, and pre-commit.ci runs them over every file on every
PR. Each stage now parses once, finds kwarg '=' and string literals with a
sparse scan instead of a full tokenize, tokenizes only def headers and short
asserts, and checks edits on the edited fragment instead of dumping the whole
file. Unusual input (syntax errors, splitlines-only line breaks, PEP 695
headers, possible 3.14 t-strings) takes the previous code, kept verbatim.

Output is byte-identical to the previous script on the repo, the stdlib and
transformers, including unformatted variants, on CPython 3.10 to 3.14.
Share the def-signature rule and the one-line length estimate between the
fast and fallback paths, hoist the imports, count usable CPUs (affinity)
rather than host CPUs, replay chunk output as bytes, describe what
require_serial really does, and test the chunked path against the serial
one on real files.
…ent (#14174)

The constants an f-fold produces take their kind from the first u-prefixed piece
of the whole concatenation, which can sit on the next line, outside the run the
local check sees. Found by fuzzing against the previous implementation.
)

- f-folds glued to a name or keyword (return"a" f"{x}") and asserts whose
  first row is shared or continued now defer to the whole-file check
- Python 3.9 has no ast.match_case
- unroll the string-literal regex: one backtracking frame per character made a
  10 MB literal cost 1.2 GB
- every name for one file goes to the same chunk in order instead of being
  dropped, chunks are killed on an interrupt, replay works without a byte buffer
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 19, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ⚠️ Failed 2026-10-19T12:33:30.633798Z 4e3ac06 PR opened
🔒 Security Review ⚠️ Failed 2026-10-19T12:33:31.531804Z 4e3ac06 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@danielhanchen
danielhanchen merged commit d122ab5 into main Oct 19, 2026
@danielhanchen
danielhanchen deleted the fix/precommit-ci-perf-14174 branch October 19, 2026 13:01
danielhanchen added a commit that referenced this pull request Oct 19, 2026
## Summary

Main is over the startup bundle budget again, so `Frontend build +
bundle sanity` fails on every PR based on it:

```
over the startup budget: transfer 2012.0 KB > 2011.9 KB, raw 6681.8 KB > 6680.6 KB      (main at 26e246d)
```

#14247 (Developer mode opt-in for experimental CPU video generation)
added 1,777 B raw / 654 B transfer to the startup chunks. It merged
without raising the limits.

## Cause

`#14247` touches eager startup code. Its new strings land in
`i18n/locales/en.ts` (the English catalog ships in the startup chunks),
and the developer-mode flag is read from `__root.tsx`,
`app-sidebar.tsx`, `config/env.ts` and `config/hardware-verdict.ts`. The
settings section itself is lazy. This is small real growth with no lazy
home. The other commits since the last measurement (#14204, #14239,
#14249) change no frontend code.

## Change

- **`check-bundle-budget.ts`:** a BUDGET comment entry for #14247, and
both limits moved to the measured build plus a 160 B raw / 189 B
transfer margin:
  - `rawBytes`: 6,840,888 -> 6,842,343.
  - `transferBytes`: 2,060,219 -> 2,060,510.

## Testing

One machine and build, Node 24, exact byte totals from the budget
script. CI has matched this machine to the byte on earlier budget
changes.

| tree | raw B | transfer B |
|---|---|---|
| `88afa84b87` (before #14247) | 6,840,406 | 2,059,667 |
| main `26e246d407` | 6,842,183 | 2,060,321 |

- **Main against the old limits:** `over the startup budget: transfer
2012.0 KB > 2011.9 KB, raw 6681.8 KB > 6680.6 KB`.
- **With this change:** `within budget (0.2 KB transfer, 0.2 KB raw to
spare)`, 96 chunks.
danielhanchen added a commit that referenced this pull request Oct 24, 2026
…tock ruff (#14993)

The `ruff-format-with-kwargs` hook now formats with ruff-unsloth, a ruff
0.6.9 build that writes this repo's style itself, instead of running
Python passes before and after stock ruff. Output is unchanged; a full
run costs about a quarter of the CPU.

Follows up #14174 and #14249.

## Why

The old hook parsed every file with Python's `ast` twice: once before
ruff to normalize magic commas, and once after it to put back the kwarg
spacing and import blank lines that ruff had just removed. `ast.parse`
was about 42 of the hook's CPU seconds; `ruff format` itself was about
7. pre-commit.ci runs the hook with `--all-files` on every PR, so that
cost is paid in full each time.

Upstream ruff will not add a kwarg spacing option
(astral-sh/ruff#13344), and the formatter is compiled code, so there is
nothing to patch at runtime.

## ruff-unsloth

Source: https://github.com/unslothai/ruff, branch `unsloth-0.6.9`
(`UNSLOTH.md` lists the rules). Release:
https://github.com/unslothai/ruff/releases/tag/v0.6.9-unsloth.1, wheels
for Linux x86_64/aarch64/musl, macOS arm64/x86_64 and Windows x86_64,
plus `SHA256SUMS`. It installs as the `ruff-unsloth` binary and the
`ruff_unsloth` module, so it sits next to a stock ruff install.

Against ruff 0.6.9 it changes four things:

- Keyword arguments, unannotated defaults (lambdas included) and class
pattern keywords are written `name = value`. The spaced `=` is measured
as one column, so lines break exactly where stock 0.6.9 breaks them,
which is what the old post-pass produced.
- A def with 3 or more parameters and a default is always one parameter
per line; every other def ignores its magic trailing comma.
- A multi-line assert with no comment and no one-element tuple ignores
its magic trailing commas when its rows, joined by single spaces, fit.
- No blank line after the imports of a nested block of at most 3
statements, when only blank lines separate them from the next statement.

## What changes

- `.pre-commit-config.yaml`: `additional_dependencies` lists one
ruff-unsloth wheel per platform, picked by an environment marker and
pinned by `#sha256=`. Musl cannot be told apart from glibc by a marker,
so Alpine needs the musllinux wheel installed by hand; platforms with no
wheel install nothing and the script refuses with an install hint.
- `scripts/run_ruff_format.py`: runs `python -m ruff_unsloth format`
once, then `enforce_kwargs_spacing.py --residual` in the same bounded
chunks as before. The pin is read from the wheel URLs (`0.6.9.post1`)
and compared with the installed distribution's version. Both checks
still run before anything is rewritten.
- `scripts/enforce_kwargs_spacing.py`: new `--residual` mode, the two
rules ruff-unsloth leaves to Python (merging adjacent same-line literals
and dropping redundant `pass`). A cheap scan decides whether a file
could need either; only those files reach the AST, and they get exactly
what the full post-pass would write. The default and `--pre` modes are
unchanged for running the script on its own.
- `studio-backend-ci.yml`: the fixed-point guard installs ruff-unsloth
from the same config lines (`pip install -r`), so pip picks the runner's
wheel and checks its hash.
- Formatted for the first time: `scripts/enforce_kwargs_spacing.py`,
which the old hook skipped because the pass refused to rewrite itself,
and `tests/studio/test_update_release_notes.py`, which contains U+2028
and went down a path that left it unspaced. The second is AST-identical
to main; the first differs only in the new residual code.
- Tests: `tests/test_enforce_kwargs_spacing_residual.py` checks that
every case the full post-pass changes gets the same change, that files
nothing applies to never reach the AST, and that every script under
`scripts/` agrees with the full pass.
`tests/test_run_ruff_format_pin.py` reads the new pin spellings.

## Results

`pre-commit run ruff-format-with-kwargs --all-files`, ruff cache cleared
before each run, 3 runs per arm on the same host, base and head one
after the other:

| | main | this PR |
|---|---|---|
| user + sys CPU | 82 to 93 s | 21 s |
| result on its own tree | Passed | Passed |

Wall time on this shared 192-core host was noisy (6 to 70 s on head, 16
to 245 s on main), so CPU is the comparable number.

## Equivalence

Before switching, the old hook and ruff-unsloth plus the residual pass
were run on three rewrites of the whole repo, so that both had real work
to do: stock ruff at line length 80 (4,506 files changed), at 140 with
magic trailing commas ignored (4,497), and at 100, which strips the
kwarg spacing (4,391). The two pipelines produced byte-identical output
in all three: 0 files differed. On main itself the only differences are
the two files above.

One intended difference: on Python 3.12+ the old pass rewrote f-string
debug specifiers, `f"{x=}"` to `f"{x = }"`, which changes the printed
text. ruff-unsloth leaves f-strings alone. Existing ones in the tree
stay as they are.

## Testing

- `pre-commit run ruff-format-with-kwargs --all-files` on this branch:
Passed, so the tree is a fixed point.
- Formatter tests, including `tests/test_formatter_fixed_point.py` with
ruff-unsloth installed: all pass.
- The workflow guard suites from `workflow-trigger-lint.yml` plus
`tests/security`: 3033 passed, 3 failed, and all three fail the same way
on unmodified main here (`test_lint_exec_literals.py`,
`test_lint_risky_loaders.py` and
`test_version_compat_bundle.py::test_the_daily_sweep_skips_what_it_cannot_import`).
- `tests/studio/test_update_release_notes.py` could not be run here
(`structlog` is not installed, same on main); its diff is whitespace
only.

## Not verified

- That pre-commit.ci installs direct wheel URLs from
`additional_dependencies`. This PR's own pre-commit.ci run answers it.
- The Linux aarch64, musl and macOS x86_64 wheels were built and
smoke-tested only where a native runner exists (Linux x86_64, macOS
arm64, Windows); the other three were not run.
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.

1 participant