Repository navigation
pre-commit: cut the kwarg formatter's CPU 6.5x and stop the ruff fork bomb (#14174) - #14249
Merged
Merged
Conversation
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
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes the compute half of #14174: pre-commit.ci reported that the
ruff-format-with-kwargshook makes this repo its most expensive user, and that it fork-bombs ruff.What was wrong
pre-commit.ci runs every hook with
--all-fileson 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.pyre-tokenized, re-parsed and re-dumped the same text up to seven times per file (4 fulltokenizecalls, 7ast.parsecalls, 2 or more whole-fileast.dumpcalls, severalast.walkcalls), and the cyclic GC swept the resulting objects for nothing.ruff formatitself is about 9 CPU-s of the total.require_serial, so pre-commit started one partition per CPU, and each partition started its own multithreadedruff format, plus tworuff --versionprobes and two Python processes. On a 192-core box that was 168 concurrentruff formatprocesses and about 32,000 threads.What this changes
.pre-commit-config.yaml:require_serial: trueon the hook.scripts/run_ruff_format.py: oneruff formatper hook call. The Python passes either side run in at most 8 size-balanced chunks (bounded by usable CPUs,UNSLOTH_RUFF_FORMAT_JOBSoverrides), 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 separatorssplitlinesand 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 auprefix.tests/test_run_ruff_format_jobs.py(job count, chunking, interrupts, chunked vs serial on real files);tests/test_formatter_fixed_point.pypins 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:ruff formatThe 53k-line
studio/backend/routes/inference.pygoes 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_fileon real files, and the full pre, ruff 0.6.9, post pipeline, checking output bytes, the changed flag and the exception type.transformers/src, each also with six kinds of unformatted variants (kwarg spaces stripped, def commas toggled, asserts exploded, blank lines after imports, split strings, redundantpass): about 80k texts, 0 differences.uprefix 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.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:
f"{x=}"tof"{x = }", which changes the printed text.remove_redundant_passescan turn the next string into a docstring, leave an empty suite, or cut the wrong characters after non-ASCII text on the same line.def f[T: g(1)](a, b, c=0)).Not covered
subprocess,tempfileandos.stat.