Skip to content

perf(binding): reuse a serialized sheet until it changes - #967

Merged
owjs3901 merged 1 commit into
mainfrom
perf/css-serialization-cache
Nov 17, 2026
Merged

owjs3901 merged 1 commit into
mainfrom
perf/css-serialization-cache

Conversation

@owjs3901

@owjs3901 owjs3901 commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

Summary

getCss and a transform result's css used to serialize the whole sheet on every call; they now reuse the result until the sheet, or a setting its serialization reads, changes.

  • libs/binding/src/css_cache.rs: stores create_css results keyed by (bucket, whether file CSS imports base, actual atom-hoist mode). A hit returns exactly the string create_css returned in the same state, so the output is byte-for-byte identical ([전수조사/G] 결정성: 같은 소스는 항상 같은 출력 (파일·class 번호) #694 determinism preserved).
  • Invalidation points
    • Wrapped GLOBAL_STYLE_SHEET in SheetCell. Every mutable borrow (DerefMut) clears the cache. So with_style_sheet_mut, the reservation's sheet replacement, and even tests that take the lock and modify it directly all invalidate. Existing GLOBAL_STYLE_SHEET.lock() call sites compile unchanged.
    • Output::new (transform commit) invalidates only when something actually changed. The criteria are the values returned by collected, updatedBaseStyle, and rm_global_css, plus pinning the atom plan on the first commit. When the same source is extracted again (transform after prewarm, two environments) the sheet doesn't change, so the cache is kept. Hosts already use this flag to decide whether to rewrite the base CSS.
    • Setters for globals that create_css reads outside the sheet (atom-hoist threshold, file routes, canonical map, test state reset) also clear the cache. set_atom_hoist and import_file_routes_internal changed from re-exports to wrapper functions with the same signatures.

Measurements

Environment: Windows, native engine (profile.native), a fixture adapted from benchmark/large-app.mjs to produce lots of CSS (800 components, 40 routes, 845 files, about 196KB of final CSS). The fixture was fed as-is into Vite/Rsbuild builds, and a preload wrapping the @devup-ui/binding exports counted calls and time. Machine load varied a lot, so cumulative per-call time is more reliable than wall-clock.

Rsbuild singleCss: true (3 runs each)

getCss(null) calls getCss(null) cumulative codeExtract cumulative wall
before 1612 2402–2689 ms 1955–2077 ms 7.2–8.1 s
after 1612 100–140 ms 1784–2563 ms 5.2–6.6 s

The part where the same source was extracted twice, in prewarm and transform, and the base was re-read with getCss(null) on every transform almost disappeared (about −95%). For the whole build it's about −20%.

Rsbuild singleCss: false: 4806 getCss(file) calls went from 35–44 ms to 19–31 ms. Its share of the total is small, so there is no noticeable difference.
Vite (both modes): a Vite build calls getCss only 4 times, so there is neither gain nor loss. An in-process simulation repeating only the extraction path (843 files × 5 runs median) was also within noise: before 1803–1891 ms, after 1823–2001 ms.

Byte identity: the sha256 of output CSS is the same before and after.

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

Overlapping PRs

Test plan

  • cargo test -p devup-ui-binding-core --tests: the new tests/css_cache.rs runs serially and checks 5 scenarios.
    • Reuse
    • Kept on re-extraction
    • Invalidated by direct lock modification
    • Results per atom-hoist setting equal a fresh serialization
    • Invalidated when the plan is pinned
  • cargo test -p devup-ui-binding-core: unit tests (poison recovery, key normalization)
  • cargo test -p devup-ui-wasm --tests (141 passed), cargo test -p devup-ui-binding --tests
  • cargo clippy -p devup-ui-binding-core -p devup-ui-wasm -p devup-ui-binding --all-targets -- -D warnings, cargo fmt --all
  • After a native build, Rsbuild/Vite large-fixture output hashes match before

요약

getCss와 transform 결과의 css가 호출마다 시트 전체를 직렬화하던 것을, 시트나 그 직렬화가 읽는 설정이 바뀔 때까지 재사용하도록 바꿨습니다.

  • libs/binding/src/css_cache.rs: (bucket, 파일 CSS의 base import 여부, 실제 atom-hoist 모드) 키로 create_css 결과를 보관합니다. 적중하면 같은 상태에서 create_css가 돌려준 문자열 그대로이므로 출력은 바이트 단위로 같습니다([전수조사/G] 결정성: 같은 소스는 항상 같은 출력 (파일·class 번호) #694 결정성 유지).
  • 무효화 지점
    • GLOBAL_STYLE_SHEET를 SheetCell로 감쌌습니다. 가변 borrow(DerefMut)마다 캐시를 비웁니다. 그래서 with_style_sheet_mut, reservation의 시트 교체, 테스트가 lock을 직접 잡고 고치는 경우까지 모두 무효화됩니다. 기존 GLOBAL_STYLE_SHEET.lock() 호출부는 그대로 컴파일됩니다.
    • Output::new(transform commit)은 실제로 바뀐 경우에만 무효화합니다. 판단 기준은 collected, updatedBaseStyle, rm_global_css가 돌려주는 값과 첫 commit의 atom plan 고정입니다. 같은 소스를 다시 추출할 때(prewarm 후 transform, 두 environment)는 시트가 바뀌지 않으므로 캐시가 유지됩니다. 호스트도 이미 이 플래그로 base CSS를 다시 쓸지 정합니다.
    • create_css가 시트 밖에서 읽는 전역(atom-hoist threshold, file routes, canonical map, test state reset)의 setter도 캐시를 비웁니다. set_atom_hoist와 import_file_routes_internal은 re-export에서 wrapper 함수로 바꿨고 시그니처는 같습니다.

측정

환경: Windows, native 엔진(profile.native), benchmark/large-app.mjs를 CSS가 많도록 변형한 fixture(컴포넌트 800개, 라우트 40개, 파일 845개, 최종 CSS 약 196KB). 이 fixture를 Vite/Rsbuild 빌드에 그대로 넣고, @devup-ui/binding export를 감싼 preload로 호출 횟수와 시간을 셌습니다. 머신 부하 편차가 커서 wall-clock보다 호출별 누적 시간이 더 믿을 만합니다.

Rsbuild singleCss: true (각 3회)

getCss(null) 호출 getCss(null) 누적 codeExtract 누적 wall
before 1612 2402–2689 ms 1955–2077 ms 7.2–8.1 s
after 1612 100–140 ms 1784–2563 ms 5.2–6.6 s

같은 소스를 prewarm과 transform에서 두 번 추출하고, transform마다 base를 getCss(null)로 다시 읽던 부분이 거의 사라졌습니다(약 −95%). 빌드 전체로는 약 −20%입니다.

Rsbuild singleCss: false: getCss(file) 4806회 35–44 ms에서 19–31 ms로 줄었습니다. 전체에서 차지하는 비중이 작아 체감 차이는 없습니다.
Vite(두 모드): Vite build에서 getCss는 4회뿐이라 이득도 손해도 없습니다. 추출 경로만 반복하는 in-process 시뮬레이션(843 파일 × 5회 median)도 before 1803–1891 ms, after 1823–2001 ms로 노이즈 범위 안입니다.

바이트 동일성: 출력 CSS의 sha256이 before와 after에서 같습니다.

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

겹치는 PR

테스트 계획

  • cargo test -p devup-ui-binding-core --tests: 새 tests/css_cache.rs는 serial로 돌며 5개 시나리오를 확인합니다.
    • 재사용
    • 재추출 시 유지
    • 직접 lock 수정 시 무효화
    • atom-hoist 설정별 결과가 fresh 직렬화와 같은지
    • plan 고정 시 무효화
  • cargo test -p devup-ui-binding-core: 단위 테스트(poison 복구, key 정규화)
  • cargo test -p devup-ui-wasm --tests (141개 통과), cargo test -p devup-ui-binding --tests
  • cargo clippy -p devup-ui-binding-core -p devup-ui-wasm -p devup-ui-binding --all-targets -- -D warnings, cargo fmt --all
  • native 빌드 후 Rsbuild/Vite 대형 fixture 출력 해시가 before와 같음

🤖 Generated with Claude Code

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>
@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 Δ
libs/binding/src/css_cache.rs 100.00% <100.00%> (ø)
libs/binding/src/lib.rs 100.00% <100.00%> (ø)
libs/binding/src/output.rs 100.00% <100.00%> (ø)
🚀 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
owjs3901 merged commit fe4d65b into main Nov 17, 2026
27 checks passed
@owjs3901
owjs3901 deleted the perf/css-serialization-cache branch November 17, 2026 02:48
owjs3901 added a commit that referenced this pull request Nov 17, 2026
#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>
owjs3901 added a commit that referenced this pull request Nov 17, 2026
extractor/lib.rs keeps both this branch's ExtractorCaches export and
main's vanilla_extract_theme_import_tests module. Main added no binding
exports since the last merge, so the counts stay: 33 ABI names, 21
validated functions with 48 positions and 288 cases, and 28 parity
scenarios. #967's serialization cache needs no session state: a session
switch swaps the sheet through a tracked mutable borrow, which forgets
the cached serializations.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
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