Skip to content

perf(binding): serialize a transform's CSS only when it is read - #968

Merged
owjs3901 merged 4 commits into
mainfrom
perf/lazy-transform-css
Nov 17, 2026
Merged

owjs3901 merged 4 commits into
mainfrom
perf/lazy-transform-css

Conversation

@owjs3901

@owjs3901 owjs3901 commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

Summary

This PR is stacked on #967. The first commit (perf(binding): reuse a serialized sheet until it changes) is the same as #967. Once #967 is merged, this PR's diff will contain only the second commit.

Output::new used to serialize the resulting css immediately every time a transform added styles; it now serializes on first read. Under singleCss this serialization covers the whole shared base sheet, so across a whole build the cost is quadratic in the sheet size. Yet the following hosts never read this value:

  • Next.js webpack loader (loader.ts)
  • Next Turbopack prewarm (plugin.ts)
  • Webpack loader in watch mode
  • Bun bundling

How byte-identical output is guaranteed

LazyCss (libs/binding/src/lazy_css.rs) means "the sheet right after this transform". The latest result not yet read (a single global Weak) is serialized against the sheet as it stands, before any of the following happens:

  1. A mutable borrow of the sheet (perf(binding): reuse a serialized sheet until it changes #967's SheetGuard::deref_mut)
  2. The start of the next transform commit
  3. A change to settings the serialization reads: set_atom_hoist, file routes, canonical map, restoring the atom plan in import_sheet, reset_build_state

Serialization runs in exactly the atom mode the transform committed with. This uses the new AtomModeGuard::exact and is_suppressed. So even a late read, after other extractions or setting changes, equals the old eager value. A result released without being read costs nothing.

Host changes:

  • takeExtractOutput(output, withCss = true): the Next loader and prewarm pass false. The coordinator reads it as before.
  • The Webpack loader reads css only when cssFile && !watch, the only case where it is actually used.
  • Vite, Rsbuild, Bun, and the NAPI/WASM getter signatures are unchanged.

Measurements

Same fixture as #967 (845 files, about 196KB of final CSS). Native engine.

Simulation of the Next/webpack loader call pattern (in-process, 843 files × 5 runs median, alternating binaries)

Mode #967 only This PR Change
singleCss, css not read (Next loader·prewarm, webpack watch) 1302–1413 ms 494–544 ms about −62%
singleCss, css read (Vite·webpack build) 1285–1353 ms 1331–1370 ms within noise
per-file, css not read 513–556 ms 507–516 ms about −3%

Real builds (1 run)

  • Rsbuild singleCss: cumulative codeExtract dropped from about 1.9 s to 0.87 s. The serialization moved to the subsequent getCss(null) (0.84 s). Rsbuild does not free outputs, so they settle at the next commit; the gain is small and there is no loss.
  • Vite: it reads the CSS right away, so only where the cost lands changes.

Byte identity: the sha256 of output built with the lazy binary matches before.

  • Rsbuild single: 0000aba7…
  • Rsbuild per-file: 09928940…
  • Vite single: 429cbc9e…
  • Vite per-file: c1f27c64…

Rsbuild is the host that goes through the settle path the most (unreleased results are serialized at the next commit), and the output is identical there too.

Overlapping PRs

Test plan

  • cargo test -p devup-ui-binding-core -p css --tests: 4 scenarios in the new tests/lazy_css.rs (serial) and AtomModeGuard::exact unit tests
    • Immediate read, double read
    • Late read after another transform
    • Released result
    • Read after atom setting change: each transform's mode preserved
  • cargo test -p devup-ui-wasm --tests (141 passed), cargo test -p devup-ui-binding --tests
  • cargo clippy -p css -p devup-ui-binding-core -p devup-ui-wasm -p devup-ui-binding --all-targets -- -D warnings, cargo fmt --all
  • bun test
    • Scope: next-plugin loader·coordinator·plugin·source-map.wasm tests, all of webpack-plugin
    • Result: 3701 pass. Used the lazy native binary and a freshly built WASM.
    • New test: checks that the Next loader does not call the css getter.
  • bunx tsc --noEmit (next-plugin, webpack-plugin), prettier
  • After a native build, Rsbuild/Vite large-fixture output hashes match before

요약

#967 위에 쌓인 PR입니다. 첫 커밋(perf(binding): reuse a serialized sheet until it changes)은 #967과 같습니다. #967이 머지되면 이 PR의 diff는 두 번째 커밋만 남습니다.

transform이 스타일을 추가할 때마다 Output::new가 결과 css를 즉시 직렬화하던 것을, 처음 읽힐 때 직렬화하도록 바꿨습니다. singleCss에서는 이 직렬화가 공유 base 시트 전체라서, 빌드 전체로 보면 시트 크기에 대해 이차 비용입니다. 그런데 다음 호스트는 이 값을 읽지 않습니다.

  • Next.js webpack loader (loader.ts)
  • Next Turbopack prewarm (plugin.ts)
  • Webpack loader watch 모드
  • Bun bundling

바이트 동일성 보장 방식

LazyCss(libs/binding/src/lazy_css.rs)는 "이 transform 직후의 시트"를 뜻합니다. 아직 읽히지 않은 최신 결과(전역 Weak 하나)는 다음 시점보다 먼저 그때의 시트로 직렬화됩니다.

  1. 시트 가변 borrow (#967의 SheetGuard::deref_mut)
  2. 다음 transform commit 시작
  3. 직렬화가 읽는 설정 변경: set_atom_hoist, file routes, canonical map, import_sheet의 atom plan 복원, reset_build_state

직렬화는 transform이 commit하던 atom mode 그대로 수행합니다. 이를 위해 새 AtomModeGuard::exact와 is_suppressed를 씁니다. 그래서 다른 추출이나 설정 변경 뒤에 늦게 읽어도 예전 eager 값과 같습니다. 읽지 않고 해제한 결과는 비용이 0입니다.

호스트 변경:

  • takeExtractOutput(output, withCss = true): Next loader와 prewarm은 false를 넘깁니다. coordinator는 기존처럼 읽습니다.
  • Webpack loader는 cssFile && !watch일 때만 css를 읽습니다. 실제로 쓰는 경우가 이때뿐입니다.
  • Vite, Rsbuild, Bun과 NAPI/WASM getter 시그니처는 그대로입니다.

측정

fixture는 #967과 같습니다(파일 845개, 최종 CSS 약 196KB). native 엔진입니다.

Next/webpack loader 호출 패턴 시뮬레이션 (in-process, 843 파일 × 5회 median, 바이너리 교대 실행)

모드 #967만 이 PR 변화
singleCss, css 안 읽음 (Next loader·prewarm, webpack watch) 1302–1413 ms 494–544 ms 약 −62%
singleCss, css 읽음 (Vite·webpack build) 1285–1353 ms 1331–1370 ms 노이즈 범위
per-file, css 안 읽음 513–556 ms 507–516 ms 약 −3%

실제 빌드 (1회)

  • Rsbuild singleCss: codeExtract 누적이 약 1.9 s에서 0.87 s로 줄었습니다. 직렬화는 이어지는 getCss(null)(0.84 s)로 옮겨 갔습니다. Rsbuild는 출력을 free하지 않아 다음 commit에서 settle되므로, 이득은 작고 손해는 없습니다.
  • Vite: CSS를 바로 읽으므로 비용 위치만 바뀝니다.

바이트 동일성: lazy 바이너리로 빌드한 출력 sha256이 before와 같습니다.

  • Rsbuild single: 0000aba7…
  • Rsbuild per-file: 09928940…
  • Vite single: 429cbc9e…
  • Vite per-file: c1f27c64…

Rsbuild는 settle 경로(해제 안 된 결과가 다음 commit에서 직렬화됨)를 가장 많이 거치는 호스트인데, 여기서도 출력이 같습니다.

겹치는 PR

테스트 계획

  • cargo test -p devup-ui-binding-core -p css --tests: 새 tests/lazy_css.rs(serial) 4개 시나리오와 AtomModeGuard::exact 단위 테스트
    • 즉시 읽기, 두 번 읽기
    • 다른 transform 뒤에 늦게 읽기
    • 해제된 결과
    • atom 설정 변경 뒤 읽기: 각 transform의 mode 유지
  • cargo test -p devup-ui-wasm --tests (141개 통과), cargo test -p devup-ui-binding --tests
  • cargo clippy -p css -p devup-ui-binding-core -p devup-ui-wasm -p devup-ui-binding --all-targets -- -D warnings, cargo fmt --all
  • bun test
    • 대상: next-plugin의 loader·coordinator·plugin·source-map.wasm 테스트, webpack-plugin 전체
    • 결과: 3701 pass. lazy native와 새로 빌드한 WASM을 썼습니다.
    • 새 테스트: Next loader가 css getter를 호출하지 않는지 확인합니다.
  • bunx tsc --noEmit (next-plugin, webpack-plugin), prettier
  • native 빌드 후 Rsbuild/Vite 대형 fixture 출력 해시가 before와 같음

🤖 Generated with Claude Code

owjs3901 and others added 2 commits November 15, 2026 20:49
getCss and the CSS a transform returns serialized the whole sheet on
every call. Between two extractions a build reads the same sheet several
times (the transform's CSS, the shared base it writes next, each
stylesheet module), and a source extracted again, as a prewarm and its
transform do, changes nothing. Keep each serialization keyed by bucket,
the base import and the effective atom mode, and forget them when the
sheet is borrowed mutably, when a commit reports a change or freezes the
atom plan, and when an atom-hoisting setting changes. A hit is exactly
what create_css returned for the same state, so the output is
byte-identical.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Every transform that added a style serialized its bucket, the whole
shared base in single-CSS mode, even though the Next.js loader and
prewarm never read it and the Webpack loader reads it only when it
writes it. Over a single-CSS build that is quadratic in the sheet.

The output now holds the request and serializes on the first read. It
still describes the sheet as its transform left it: the latest unread
result is serialized before the sheet is borrowed mutably, before the
next commit, and before an atom-hoisting setting changes, under the
atom mode its transform committed in (AtomModeGuard::exact). A result
released unread costs nothing. The Next.js loader and prewarm stop
reading it, and the Webpack loader reads it only outside watch mode
when it writes the file.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@codecov

codecov Bot commented Nov 15, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

Files with missing lines Coverage Δ
bindings/devup-ui-binding/src/output.rs 100.00% <ø> (ø)
bindings/devup-ui-wasm/src/lib.rs 100.00% <100.00%> (ø)
libs/binding/src/css_cache.rs 100.00% <ø> (ø)
libs/binding/src/lazy_css.rs 100.00% <100.00%> (ø)
libs/binding/src/lib.rs 100.00% <100.00%> (ø)
libs/binding/src/output.rs 100.00% <100.00%> (ø)
libs/css/src/atom_hoist.rs 100.00% <100.00%> (ø)
packages/next-plugin/src/coordinator.ts 100.00% <100.00%> (ø)
packages/next-plugin/src/loader.ts 100.00% <100.00%> (ø)
packages/next-plugin/src/plugin.ts 100.00% <100.00%> (ø)
... and 1 more
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

owjs3901 and others added 2 commits November 17, 2026 13:06
#967 landed on main as a squash identical to this branch's first
commit, so the conflicts were that commit against itself. The
conflicted files take main and re-apply only the lazy-serialization
commit on top, keeping main's resolver_state exports (#936) and the
var(--size)/var(--card) token assertions (#961), now read through
LazyCss::get(). The diff against main equals that commit exactly;
the ABI and export count are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Picks up #983's snapshot fix so CI runs against the current main.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@owjs3901
owjs3901 merged commit 0b94d3b into main Nov 17, 2026
27 checks passed
@owjs3901
owjs3901 deleted the perf/lazy-transform-css branch November 17, 2026 07:32
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