You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Only optimize and print new utilities on rebuilds - #20680
The AST of each candidate is already cached by the design system, but when a single new candidate shows up, build() still re-sorts every rule and runs optimizeAst, handleNesting and toCss over the entire stylesheet. handleNesting also re-parses every selector, because its parse cache only lives for one call. So the cost of a rebuild grows with the size of the stylesheet instead of the size of the change.
Profile of a rebuild that adds one class, on the tailwindcss.com repo (13.6k scanned candidates, 716 KB of CSS):
Step
Time
Re-sort all rules (compileCandidates)
3.2 ms
optimizeAst on the whole stylesheet
3.7 ms
handleNesting on the whole stylesheet
4.8 ms
toCss on the whole stylesheet
1.0 ms
This PR adds an incremental path for the utilities (packages/tailwindcss/src/incremental.ts):
Only the new candidates are compiled and sorted. They're merged into the list of already sorted candidates. When new variants show up, the variant bits of existing candidates are updated: new variants can shift the bits, but never the relative order of candidates we already sorted.
The optimized and flattened output of each utility node is cached, keyed by the AST node the design system already caches. A build stitches the cached output together, merging adjacent at-rules (e.g. @media) and rules with the same selector, the same way handleNesting does. Cached nodes are copied before they're merged into, never mutated.
The rest of the stylesheet still goes through optimizeAst on every build, with a placeholder where the utilities go. The @at-root nodes (@property, @keyframes) and the animation values of the utilities are passed along, so @property deduplication, the @property polyfill and unused @keyframes removal work as before.
toCss caches the printed CSS of the cached nodes.
Rules that only contain declarations (most utilities) skip optimizeAst/handleNesting entirely, so the per-utility setup cost doesn't slow down the initial build.
The output should be byte-for-byte identical to the non-incremental build. We fall back to the non-incremental build when:
source maps are requested (from), because toCss needs the positions of every node in the current build
@tailwind utilities is somewhere we can't handle (e.g. inside a rule, or in a context like @theme)
something unexpected comes up during a build
Results
Same project, Node 24, Apple Silicon. Rebuild numbers are the median of 300 rebuilds:
Before
After
Rebuild that adds 1 class (tailwindcss.com)
12.6 ms
1.4 ms
Rebuild that adds 1 class (@import "tailwindcss")
9.2 ms
1.1 ms
Rebuild that adds a class with a new variant
15.0 ms
2.8–4.1 ms
Initial build, warm JIT
~37 ms
~38 ms
Initial build, fresh process
~68 ms
~75 ms
Open questions
Cold initial build is ~10% slower in a fresh process. It's the same once the JIT is warm, so it's likely from the extra code paths warming up. Worth looking at before merging.
PostCSS always passes from, so @tailwindcss/postcss doesn't benefit yet. The same goes for Vite with css.devSourcemap. The non-incremental build only needs from for toCss source map tracking, so a follow-up could make that check narrower.
Follow-up for Vite: the Vite plugin re-walks the whole project with scanner.scan() on every CSS request (7.7 ms on the same project). Scanning only the changed file with scanner.scanFiles() takes 0.3 ms. Together with this PR, that would take Tailwind's share of an HMR update from ~20 ms to ~2 ms.
Test plan
Added packages/tailwindcss/src/incremental.test.ts. It compares the incremental build with the non-incremental build (from set) across several inputs and orders of adding candidates, covering:
inputs: default, without layers, important + theme(static), custom @utility/@custom-variant/@keyframes with sibling rules in @layer utilities, and utilities nested in a rule (the fallback)
candidates: variants, stacked variants, at-rule merging, @property, @keyframes, color-mix(…) polyfills, arbitrary values/properties, important, invalid candidates, and CSS variables used outside of utilities
Checked that the tests fail when the at-rule merging or the copy-on-write of cached nodes is removed.
vitest run --hideSkippedTests from the root: 5722 passed, 1 skipped. Rust isn't installed on my machine, so I didn't run cargo test or build oxide. For the JS packages that need @tailwindcss/oxide, I used the published 4.3.5 binary; this PR doesn't touch Rust.
tsc --noEmit reports the same errors as on main (all from missing build artifacts locally), and prettier --check / pnpm changelog check pass.
Outside of the test suite, I compared the CSS of the incremental and non-incremental builds for 1281 incremental builds on the tailwindcss.com candidates, across 7 inputs (including prefix(tw)) and random orders and batch sizes: no differences.
Review was skipped as selected files did not have any reviewable changes.
Run configuration
Source mode: Auto
Repository: Unavailable
Branch: Unavailable
File: No configuration file from this repository applied
Commit: Unavailable
Layers: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: ce8ed25a-5523-4191-8d22-3292d1793533
Commits
Reviewing files that changed from the base of the PR and between 34f9d41 and 62dda3d.
You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.
Use the checkbox below for a quick retry:
Trigger review
No actionable comments were generated in the recent review.
Walkthrough
The compiler now supports incremental utility builds when the stylesheet meets the builder’s supported conditions. It caches eligible AST output, compiles queued candidates, and merges their utility nodes into the optimized stylesheet. If incremental building cannot handle the input, compilation falls back to the existing full path. New tests compare incremental output with reference output across multiple stylesheets, candidate orders, and batch sizes.
Merge Risk: Low · previous review 34f9d
The large compilation test may time out on slow runners. The change is otherwise suitable to merge with that risk understood.
Pre-merge checks: 4
Check name
Status
Explanation
Title check
The title clearly summarizes the main change: rebuilds optimize and print only new utilities.
Description check
The description explains the incremental build path, its fallbacks, performance results, and tests. It is directly related to the changeset.
Linked Issues check
Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check
Check skipped because no linked issues were found for this pull request.
Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
File: No configuration file from this repository applied
Commit: Unavailable
Layers: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: e2129248-ee7d-41a3-9dc9-32d831be6270
Commits
Reviewing files that changed from the base of the PR and between 884f10d and 34f9d41.
Files selected for processing: 1
packages/tailwindcss/src/index.ts
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 8 remain after this review.
Set an explicit timeout for the 150,000-candidate test.
This test parses and compiles 150,000 candidates. It then sorts the candidates and stitches 150,000 root-level nodes in one call. Vitest applies its default test timeout unless the config overrides it. A slow CI runner can exceed that limit and make the test flaky. The same test also covers the RangeError regression, so a spurious timeout would hide a real signal.
Pass an explicit timeout as the third argument of test(…). Alternatively, lower the candidate count. The count only needs to exceed the call-stack argument limit.
⏱️ Proposed change
-test('builds with a very large number of utilities', async () => {+test('builds with a very large number of utilities', { timeout: 30_000 }, async () => {
Review info
Run configuration
Source mode: Auto
Repository: Unavailable
Branch: Unavailable
File: No configuration file from this repository applied
Commit: Unavailable
Layers: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: 54aa853b-b124-43d9-aceb-59be5e0d1285
Commits
Reviewing files that changed from the base of the PR and between 9b2c925 and 884f10d.
Files selected for processing: 5
.changelog/incremental-utility-builds.md
packages/tailwindcss/src/ast.ts
packages/tailwindcss/src/incremental.test.ts
packages/tailwindcss/src/incremental.ts
packages/tailwindcss/src/index.ts
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.
The AST of each candidate is already cached by the design system, but
when a single new candidate showed up, `build()` re-sorted every rule and
ran `optimizeAst`, `handleNesting` and `toCss` over the entire stylesheet.
This caches the optimized and flattened output of each utility node, and
the printed CSS of those nodes. A rebuild now only compiles, sorts and
flattens the new candidates, and stitches the cached utilities together,
merging adjacent at-rules the same way `handleNesting` does. The rest of
the stylesheet still goes through `optimizeAst` on every build.
When source maps are requested, or when the `@tailwind utilities` node is
somewhere the incremental build can't handle (e.g. inside a rule), we use
the non-incremental build.
When no utility has output, for example when a build only has invalid
candidates, the placeholder kept the at-rules around `@tailwind
utilities` alive. Once the placeholder was removed, they printed
without a body, e.g. `@media print;`, where the non-incremental build
removes them.
In that case, optimize the utility nodes with the rest of the
stylesheet, the same way the non-incremental build does.
The incremental build replaced the nodes of the parent of the utilities
with `parent.splice(0, parent.length, ...nodes)`. Each node becomes an
argument of the call, so more than about 120k nodes (e.g. 130k
utilities at the root) overflowed the call stack. The non-incremental
build handles them.
Clear the array and push the nodes in a loop instead.
`unseenCandidates` is only read by the incremental build. Without it (e.g.
with `from`, or after a fallback), the list kept a reference to every new
candidate for the lifetime of the compiler.
This PR builds on
#20680, and targets its
branch. Merge that one first.
## Summary
The incremental build of
#20680 is turned off
when `from` is set. The CLI with `--output`, `@tailwindcss/postcss`,
`@tailwindcss/webpack`, `@tailwindcss/turbopack` and `@tailwindcss/vite`
with CSS source maps all set `from`, so they don't get the faster
rebuilds.
These integrations need `from` for source maps, and for the file, line
and column in CSS syntax errors
(#19282). So the fix is
in core, and the integrations don't change:
- The incremental build gives new utility nodes the source location of
`@tailwind utilities` before it caches them, the same way the
non-incremental build does.
- `build()` no longer tracks the positions in the output, so it can
reuse the printed CSS of the cached utilities. `buildSourceMap()` tracks
them instead, once for each build. The printed CSS is the same, and all
callers ask for the source map right after `build()`.
## Performance
Rebuilds on tailwindcss.com that add one class (median of 600 builds):
| Build | `main` |
#20680 | This PR |
| --- | --- | --- | --- |
| `compile()` with `from` (CLI with `--output`, webpack, Turbopack) |
11.8 ms | 11.8 ms | 1.2–1.5 ms |
| `compile()` with `from`, and a source map after each build (CLI with
`--map`, Vite) | 18.4 ms | 17.4 ms | 7.4–8.8 ms |
| `compileAst()` with `from` (PostCSS, without its conversion to a
PostCSS AST) | 11.4 ms | — | 1.7 ms |
With this PR, a build with `from` is as fast as a build without it
(about 1.1 ms). With source maps, `createSourceMap()` is now most of the
time.
## Test plan
- `incremental.test.ts` used `from` to get the non-incremental build to
compare against. It now loads a second copy of the modules where the
incremental build is mocked away. It runs with and without `from`, and
with `from` it also compares the source maps. Without the fix, 7 tests
fail.
- A new test in `source-map.test.ts` does several builds, and compares
each source map with the source map of a new compiler. It fails when the
positions are out of date.
- The `tailwindcss`, `@tailwindcss/postcss` and `@tailwindcss/node`
tests pass.
- Locally, the integration tests pass for Vite source maps, and for the
watch mode, source map and parse error tests of `@tailwindcss/cli` and
`@tailwindcss/postcss`.
<sub>Sent by an AI assistant on behalf of @RobinMalfait.</sub>
… act on (#20728)
This PR keeps `### Changed` in the changelog for changes that users may
have to act on, and documents which section to use.
`[Unreleased]` had a `### Changed` section with two performance entries
(#20680 and
#20688). A performance
improvement is not a change that users have to act on, and the repo
already lists them under `### Fixed` (e.g.
#20694,
#20678 and
#20663).
## Changes
- `CHANGELOG.md`: remove the `### Changed` section of `[Unreleased]`.
Combine the two entries into one entry in `### Fixed`, because
#20688 only extends
#20680 to the other
integrations. The entry goes in the merge order of
#20680.
- `CHANGELOG.md`: move the canonicalization entry of
#20697 from `### Added`
to `### Fixed`, in merge order, and drop the empty `### Added` heading.
A canonicalization improvement is not a new feature for users, and the
canonicalization entries of 4.3.4 and 4.3.5 are in `### Fixed` too.
- `.github/CONTRIBUTING.md`: add a guide on which section to pick. The
examples for `### Changed` come from earlier releases: changes to the
CSS of existing utilities, renamed or replaced utilities (also when the
upgrade tool migrates them), theme defaults, APIs, stricter parsing,
source detection defaults, and supported versions.
- `.changelog/README.md`: link to that guide.
This PR edits `CHANGELOG.md` directly instead of adding a fragment,
because it fixes entries that the "Compile changelog" workflow already
compiled. Released sections stay as they are. The PR changes only docs,
so it needs no changelog entry of its own.
## Test plan
- `pnpm changelog check` passes.
- `pnpm --silent changelog` shows `[Unreleased]` with only `### Fixed`.
- `pnpm prettier --check` passes for the three files.
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
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.
Summary
The AST of each candidate is already cached by the design system, but when a single new candidate shows up,
build()still re-sorts every rule and runsoptimizeAst,handleNestingandtoCssover the entire stylesheet.handleNestingalso re-parses every selector, because its parse cache only lives for one call. So the cost of a rebuild grows with the size of the stylesheet instead of the size of the change.Profile of a rebuild that adds one class, on the tailwindcss.com repo (13.6k scanned candidates, 716 KB of CSS):
compileCandidates)optimizeAston the whole stylesheethandleNestingon the whole stylesheettoCsson the whole stylesheetThis PR adds an incremental path for the utilities (
packages/tailwindcss/src/incremental.ts):@media) and rules with the same selector, the same wayhandleNestingdoes. Cached nodes are copied before they're merged into, never mutated.optimizeAston every build, with a placeholder where the utilities go. The@at-rootnodes (@property,@keyframes) and theanimationvalues of the utilities are passed along, so@propertydeduplication, the@propertypolyfill and unused@keyframesremoval work as before.toCsscaches the printed CSS of the cached nodes.Rules that only contain declarations (most utilities) skip
optimizeAst/handleNestingentirely, so the per-utility setup cost doesn't slow down the initial build.The output should be byte-for-byte identical to the non-incremental build. We fall back to the non-incremental build when:
from), becausetoCssneeds the positions of every node in the current build@tailwind utilitiesis somewhere we can't handle (e.g. inside a rule, or in a context like@theme)Results
Same project, Node 24, Apple Silicon. Rebuild numbers are the median of 300 rebuilds:
@import "tailwindcss")Open questions
from, so@tailwindcss/postcssdoesn't benefit yet. The same goes for Vite withcss.devSourcemap. The non-incremental build only needsfromfortoCsssource map tracking, so a follow-up could make that check narrower.scanner.scan()on every CSS request (7.7 ms on the same project). Scanning only the changed file withscanner.scanFiles()takes 0.3 ms. Together with this PR, that would take Tailwind's share of an HMR update from ~20 ms to ~2 ms.Test plan
packages/tailwindcss/src/incremental.test.ts. It compares the incremental build with the non-incremental build (fromset) across several inputs and orders of adding candidates, covering:important+theme(static), custom@utility/@custom-variant/@keyframeswith sibling rules in@layer utilities, and utilities nested in a rule (the fallback)@property,@keyframes,color-mix(…)polyfills, arbitrary values/properties, important, invalid candidates, and CSS variables used outside of utilitiesvitest run --hideSkippedTestsfrom the root: 5722 passed, 1 skipped. Rust isn't installed on my machine, so I didn't runcargo testor build oxide. For the JS packages that need@tailwindcss/oxide, I used the published 4.3.5 binary; this PR doesn't touch Rust.tsc --noEmitreports the same errors as onmain(all from missing build artifacts locally), andprettier --check/pnpm changelog checkpass.prefix(tw)) and random orders and batch sizes: no differences.