Skip to content

Only optimize and print new utilities on rebuilds - #20680

Merged
RobinMalfait merged 4 commits into
mainfrom
incremental-utility-builds
Nov 10, 2026
Merged

RobinMalfait merged 4 commits into
mainfrom
incremental-utility-builds

Conversation

@adamwathan

Copy link
Copy Markdown
Contributor

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 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):

  1. 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.
  2. 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.
  3. 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.
  4. 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.

@RobinMalfait
RobinMalfait marked this pull request as ready for review November 10, 2026 14:38
@RobinMalfait
RobinMalfait requested a review from a team as a code owner November 10, 2026 14:38
@greptile-apps

greptile-apps Bot commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 5/5

[Medium impact] This PR appears safe to merge.

Reviews (4) · Last reviewed commit: "Only queue unseen candidates for the inc..." · Reviewed by Greptile

Comment thread packages/tailwindcss/src/index.ts Resolved
@coderabbitai

coderabbitai Bot commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

Important

Review skipped

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: Passed 4

Check name Status Explanation
Title check Passed The title clearly summarizes the main change: rebuilds optimize and print only new utilities.
Description check Passed The description explains the incremental build path, its fallbacks, performance results, and tests. It is directly related to the changeset.
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed 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.

Share

Recent 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: 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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nitpick comments: 1

packages/tailwindcss/src/incremental.test.ts: 1

263-272: Trivial · Maintainability & Code Quality · Quick win

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.

adamwathan and others added 4 commits November 10, 2026 18:33
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.
@RobinMalfait
RobinMalfait force-pushed the incremental-utility-builds branch from 34f9d41 to 62dda3d Compare November 10, 2026 17:35

@RobinMalfait RobinMalfait left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the PR! The incremental path for the utilities makes rebuilds a lot faster.

Sent by an AI assistant on behalf of @RobinMalfait.

@RobinMalfait
RobinMalfait merged commit e7b27c8 into main Nov 10, 2026
13 checks passed
@RobinMalfait
RobinMalfait deleted the incremental-utility-builds branch November 10, 2026 18:03
RobinMalfait added a commit that referenced this pull request Nov 10, 2026
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>
RobinMalfait added a commit that referenced this pull request Nov 16, 2026
… 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.
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