Skip to content

Do not retain the finished build's plugin context in @tailwindcss/vite - #20503

Closed
lazerg wants to merge 6 commits into
tailwindlabs:mainfrom
lazerg:fix/issue-20501-vite-plugin-context-leak
Closed

lazerg wants to merge 6 commits into
tailwindlabs:mainfrom
lazerg:fix/issue-20501-vite-plugin-context-leak

Conversation

@lazerg

@lazerg lazerg commented Sep 21, 2026

Copy link
Copy Markdown
Contributor

Summary

The build plugin's Root caches a compiler for as long as the plugin instance lives, but that compiler holds onto the PluginContext from the transform call that first created it, through the onDependency callback passed to compile(). Nothing ever released that captured context. In a plain vite build this never shows up because the process exits right after, but if the same plugin instance is reused afterward (Astro's static build runs the SSR/prerender build and then generates every page in the same process) the finished build's context, and the native Rolldown arena behind it, stay alive while the next phase starts allocating on top of it.

This clears the cached roots for an environment as soon as its bundle closes, so the reference is dropped before anything else gets a chance to run.

Fixes #20501

Test plan

Added a test that wraps the build plugin's transform handler to grab a WeakRef on the PluginContext from the first call, runs a Vite 8 (Rolldown) build, forces a few GCs, and checks the context was collected. It fails on the old code and passes with the fix (only reproduces under Rolldown, not Rollup). Ran the full integrations/vite suite locally and it passes.

@lazerg
lazerg requested a review from a team as a code owner September 21, 2026 03:42
@coderabbitai

coderabbitai Bot commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

Walkthrough

The Vite build plugin preserves cached roots during watch builds. For non-watch builds, closeBundle removes the current environment’s roots. closeWatcher also removes the current environment’s roots when the watcher closes. Vite 8 integration tests use WeakRef and forced garbage collection to check that the build transform’s PluginContext can be collected. The changelog records the memory-retention fix.

Priority: ➖ Normal

Severity of issue fixed: Medium

Merge Risk: 🔵 Low · up to bd7cf

The change appears mergeable, but add a watch-rebuild cache assertion to protect against future full recompilation on each change.

🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly describes the main change: releasing the finished build’s plugin context by not retaining it.
Description check ✅ Passed The description explains the context-retention issue, the cache-clearing fix, and the regression test. It directly relates to the changeset.
Linked Issues check ✅ Passed Issue #20501 requires releasing cached roots after a build so the cached compiler no longer retains its transform PluginContext. closeBundle() deletes the closing environment’s roots outside watch…
Out of Scope Changes check ✅ Passed The cache cleanup and both lifecycle tests address the context retention in Issue #20501. The changelog entry documents that fix. No unrelated changes are shown.

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

Comment @coderabbitai help to get the list of available commands.

@greptile-apps

greptile-apps Bot commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 5/5

[Medium risk] Fixes memory leak in the Vite plugin build process.

The PR appears safe to merge, with no outstanding correctness, security, or repository-rule violations.

Reviews (6) · Last reviewed commit: "Surface watch build errors in the leak t..." · Reviewed by Greptile

@navin-rio

Copy link
Copy Markdown

I independently found this same callback/cache retention path in a multi-environment production build using Vite 7/Rollup and @tailwindcss/vite 4.1.18. Deleting just the finished environment's roots after non-watch builds released a synthetic object attached to the transform context while the plugin instance remained alive. Dev transforms and a real Rollup watch CSS rebuild continued working. This supports the fix here; I won't open a duplicate PR.

Two suggestions for the regression coverage:

  • Keep the tailwindcss() plugin array strongly reachable through the GC check (and use it afterward). The current probe creates the plugins inside the build() argument, so collection could also mean the whole plugin/cache became unreachable. Yield before GC to avoid WeakRef's current-job keep-alive rule.
  • Consider checking this.meta.watchMode rather than the top-level resolved config.build.watch. Watch configuration can be environment-specific. Cover closing one environment while another's root remains usable, as well as the legacy default key.

Clearing the environment's inner map releases the same compiler references as deleting its outer cache entry; the latter also removes the empty map. This is one retention path, not a claim that every plugin holding a completed build graph is fixed. I haven't run this PR's integration suite locally.

@lazerg
lazerg force-pushed the fix/issue-20501-vite-plugin-context-leak branch from ff8a6f6 to 880aca0 Compare October 6, 2026 01:57
@lazerg

lazerg commented Oct 6, 2026

Copy link
Copy Markdown
Contributor Author

Thanks, both made sense. The test now keeps the plugin array alive across the GC check and yields before each gc(), and closeBundle checks this.meta.watchMode and deletes the environment's entry. Still fails without the fix.

@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.

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration
  • Configuration used: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 6922462f-c464-452e-a3ec-53f40136e7b6
📥 Commits

Reviewing files that changed from the base of the PR and between ff8a6f6 and 880aca0.

📒 Files selected for processing (3)
  • CHANGELOG.md
  • integrations/vite/plugin-context-leak.test.ts
  • packages/@tailwindcss-vite/src/index.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • CHANGELOG.md

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.

Comment thread packages/@tailwindcss-vite/src/index.ts Resolved

@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)
integrations/vite/plugin-context-leak.test.ts (1)

138-174: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Assert root-cache reuse across a watch rebuild.

The added watcher test closes the first BUNDLE_END result and then closes the watcher. It does not exercise an intermediate rebuild. integrations/vite/index.test.ts does rebuild in watch mode, but its assertions check emitted CSS only. If closeBundle deletes rootsByEnv during a rebuild, the CSS can remain correct while each change triggers a full recompile. Keep a watcher open through a second CSS rebuild and assert that the active root cache is reused.


ℹ️ Review info
⚙️ Run configuration
  • Configuration used: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 106f6f89-794f-4fdd-a3a8-920e0fa2145d
📥 Commits

Reviewing files that changed from the base of the PR and between 880aca0 and bd7cf84.

📒 Files selected for processing (2)
  • integrations/vite/plugin-context-leak.test.ts
  • packages/@tailwindcss-vite/src/index.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/@tailwindcss-vite/src/index.ts
  • integrations/vite/plugin-context-leak.test.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.

@lazerg

lazerg commented Oct 23, 2026

Copy link
Copy Markdown
Contributor Author

Hey @RobinMalfait, please take a look when you have time.

@lazerg

lazerg commented Nov 15, 2026

Copy link
Copy Markdown
Contributor Author

Closing due to inactivity.

@lazerg lazerg closed this Nov 15, 2026
RobinMalfait added a commit that referenced this pull request Nov 23, 2026
The build plugin kept a `Root` for each CSS file of each environment for
as long as the plugin lived. Each root keeps its compiler, its scanner
and the resolvers of the environment that built it. A process that keeps
the plugin after a build (e.g. Astro, which renders its pages after the
build) kept all of them in memory.

Delete the roots of an environment in `closeBundle`, except in watch
mode, where rebuilds use them again. In watch mode, delete them in
`closeWatcher`, once the watcher closes.

A reused builder now starts each build of an environment with new
roots. It no longer generates CSS for classes that were removed since
an earlier build, like a build in a new process.

This takes the `closeBundle` and `closeWatcher` hooks of
#20503 by lazerg.

#20501

Co-authored-by: lazerg <[email protected]>
RobinMalfait added a commit that referenced this pull request Nov 23, 2026
This PR makes `@tailwindcss/vite` release the compilers and scanners of
a build once the build finishes.

On `main`, a finished build no longer keeps its plugin context or its
module graph, thanks to
#20531 and
#20678. A probe like the
one in the issue reports both as freed.

But the build plugin still keeps a `Root` for each CSS file of each
environment, for as long as the plugin lives. Each root keeps its
compiler, its scanner, and the resolvers of the environment that built
it. So a process that keeps working after the build keeps all of them in
memory. Examples are Astro, which renders its pages after the build, and
Nuxt, which bundles the server with Nitro after the Vite builds. On Vite
8, Vite itself keeps the plugin alive after `build()`, so this happens
even when the process drops the plugin.

This PR deletes the roots of an environment in `closeBundle`, except in
watch mode, where rebuilds use them again. In watch mode, it deletes
them in `closeWatcher`, once the watcher closes. Unlike the
`rootsByEnv.clear()` that the issue suggests, it only deletes the roots
of the environment that finished, so it doesn't touch environments that
are still building. Dev mode doesn't change, because the hooks are on
the build plugin only (`apply: 'build'`).

The hooks come from
#20503 by lazerg, who is
a co-author of the commit.

## Behavior change

A reused builder (`builder.build(environment)` more than once) now
starts each build of an environment with new roots. So it no longer
generates CSS for classes that were removed since an earlier build, like
a build in a new process.
#20678 already starts
the scans over in this case, but the roots kept their earlier
candidates. The cost is that the second build sets up its compilers and
scanners again.

## Memory

Heap after GC, while the process keeps the plugin, for a fixture with
2,000 modules and one Tailwind CSS root, on Node 24.22:

| | `main` | This PR |
| --- | --- | --- |
| Vite 7, `build()` | 34.8 MiB | 23.4 MiB |
| Vite 7, builder with client and SSR | 46.6 MiB | 23.7 MiB |
| Vite 7, watch build after `close()` | 35.8 MiB | 23.0 MiB |
| Vite 8, `build()` | 33.8 MiB | 21.4 MiB |
| Vite 8, builder with client and SSR | 46.3 MiB | 22.5 MiB |

Before the build, the heap is 13.6 MiB with Vite 7 and 14.5 MiB with
Vite 8. Each root keeps about 11 MiB here, so projects with more roots
gain more. In a Nuxt project,
#20501 (comment)
measured about 130 MiB of live heap for the state of the plugin on
`main`.

The fix also doesn't depend on how the runtime captures closures. On Bun
1.4, the heap of the builder goes from 59.3 MiB to 22.9 MiB.

What stays belongs to Vite. The plugin keeps the resolved `config` for
its next build. On Vite 7, the config keeps the environment of the
latest build, because `vite:prepare-out-dir` keeps a `Set` of the
environments that it prepared. Vite 8 keeps its environments alive by
itself.

## Test plan

- A new integration test checks that a finished build releases its
compiler while the process keeps the plugin, and that a watch build
keeps it until the watcher closes. A `@plugin` tracks an object that
only the compiler keeps, with a `WeakRef`, and the scripts run with
`node --expose-gc`.
- A new integration test checks that a reused builder doesn't keep a
removed class.
- Both tests fail without the fix: the compiler stays alive, and
`.font-bold` stays in the second build.
- Watch rebuilds still reuse their roots: with `DEBUG=tailwindcss`, the
number of compiler setups doesn't change.
- `pnpm run build` and the Vite integration tests pass locally, except
the tests whose `pnpm install` fails in my local setup
(`?commonjs-proxy` and Nuxt).

Fixes #20501

<sub>Sent by an AI assistant on behalf of @RobinMalfait.</sub>

---------

Co-authored-by: lazerg <[email protected]>
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.

@tailwindcss/vite: cached Root.compiler pins the build's plugin context, keeping the finished bundle alive (multi-GB RSS in Astro SSG)

2 participants