Repository navigation
perf(binding): serialize a transform's CSS only when it is read - #968
Merged
Merged
Conversation
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 Report✅ All modified and coverable lines are covered by tests.
🚀 New features to boost your workflow:
|
12 of 14 tasks
#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>
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.
Summary
Output::newused to serialize the resultingcssimmediately 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:loader.ts)plugin.ts)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 globalWeak) is serialized against the sheet as it stands, before any of the following happens:SheetGuard::deref_mut)set_atom_hoist, file routes, canonical map, restoring the atom plan inimport_sheet,reset_build_stateSerialization runs in exactly the atom mode the transform committed with. This uses the new
AtomModeGuard::exactandis_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 passfalse. The coordinator reads it as before.cssonly whencssFile && !watch, the only case where it is actually used.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)
Real builds (1 run)
codeExtractdropped from about 1.9 s to 0.87 s. The serialization moved to the subsequentgetCss(null)(0.84 s). Rsbuild does notfreeoutputs, so they settle at the next commit; the gain is small and there is no loss.Byte identity: the sha256 of output built with the lazy binary matches before.
0000aba7…09928940…429cbc9e…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
SheetCell, and the settle hook work together.PENDING(lazy_css) and perf(binding): reuse a serialized sheet until it changes #967'sCSS_CACHEmust move intoEngineStateonce feat(binding): keep engine state per session and swap it into the globals #963 lands. A settle is needed before switching sessions (it happens automatically if the session swap is a mutable borrow of the sheet).takeExtractOutputsignature incoordinator.ts. Existing call sites keep working.loader.ts.Test plan
cargo test -p devup-ui-binding-core -p css --tests: 4 scenarios in the newtests/lazy_css.rs(serial) andAtomModeGuard::exactunit testscargo test -p devup-ui-wasm --tests(141 passed),cargo test -p devup-ui-binding --testscargo clippy -p css -p devup-ui-binding-core -p devup-ui-wasm -p devup-ui-binding --all-targets -- -D warnings,cargo fmt --allbun testcssgetter.bunx tsc --noEmit(next-plugin, webpack-plugin), prettier요약
transform이 스타일을 추가할 때마다
Output::new가 결과css를 즉시 직렬화하던 것을, 처음 읽힐 때 직렬화하도록 바꿨습니다. singleCss에서는 이 직렬화가 공유 base 시트 전체라서, 빌드 전체로 보면 시트 크기에 대해 이차 비용입니다. 그런데 다음 호스트는 이 값을 읽지 않습니다.loader.ts)plugin.ts)바이트 동일성 보장 방식
LazyCss(libs/binding/src/lazy_css.rs)는 "이 transform 직후의 시트"를 뜻합니다. 아직 읽히지 않은 최신 결과(전역Weak하나)는 다음 시점보다 먼저 그때의 시트로 직렬화됩니다.SheetGuard::deref_mut)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는 기존처럼 읽습니다.cssFile && !watch일 때만css를 읽습니다. 실제로 쓰는 경우가 이때뿐입니다.측정
fixture는 #967과 같습니다(파일 845개, 최종 CSS 약 196KB). native 엔진입니다.
Next/webpack loader 호출 패턴 시뮬레이션 (in-process, 843 파일 × 5회 median, 바이너리 교대 실행)
실제 빌드 (1회)
codeExtract누적이 약 1.9 s에서 0.87 s로 줄었습니다. 직렬화는 이어지는getCss(null)(0.84 s)로 옮겨 갔습니다. Rsbuild는 출력을free하지 않아 다음 commit에서 settle되므로, 이득은 작고 손해는 없습니다.바이트 동일성: lazy 바이너리로 빌드한 출력 sha256이 before와 같습니다.
0000aba7…09928940…429cbc9e…c1f27c64…Rsbuild는 settle 경로(해제 안 된 결과가 다음 commit에서 직렬화됨)를 가장 많이 거치는 호스트인데, 여기서도 출력이 같습니다.
겹치는 PR
SheetCell, settle 훅이 함께 동작합니다.PENDING(lazy_css)과 #967의CSS_CACHE는 #963이 들어오면EngineState로 옮겨야 합니다. 세션 전환 전에는 settle이 필요합니다(세션 swap이 시트 가변 borrow라면 자동으로 됩니다).coordinator.ts의takeExtractOutput시그니처에 기본값이 있는 인자 하나를 추가했습니다. 기존 호출부는 그대로 동작합니다.loader.tssnapshot 블록과 인접합니다.테스트 계획
cargo test -p devup-ui-binding-core -p css --tests: 새tests/lazy_css.rs(serial) 4개 시나리오와AtomModeGuard::exact단위 테스트cargo test -p devup-ui-wasm --tests(141개 통과),cargo test -p devup-ui-binding --testscargo clippy -p css -p devup-ui-binding-core -p devup-ui-wasm -p devup-ui-binding --all-targets -- -D warnings,cargo fmt --allbun testcssgetter를 호출하지 않는지 확인합니다.bunx tsc --noEmit(next-plugin, webpack-plugin), prettier🤖 Generated with Claude Code