Skip to content

perf(binding): extract a batch on worker threads with in-order numbering - #1113

Open
owjs3901 wants to merge 6 commits into
mainfrom
perf/parallel-prewarm-core
Open

owjs3901 wants to merge 6 commits into
mainfrom
perf/parallel-prewarm-core

Conversation

@owjs3901

@owjs3901 owjs3901 commented Dec 5, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Stack: this PR (A, core) → B (binding extractBatch, #1114) → C (Next plugin prewarm, #1115, on #1112). Based on main.

Class names are numbered first come, first served per bucket, so extraction has always run one file at a time. This PR lets the core extract many files on worker threads while every class and file number comes out exactly as it does when the files are extracted one by one in order.

Ordered turns (css::numbering_order)

  • class_num_for_key and the file-number insert in get_file_num_by_filename are the only places numbers are handed out. Both now call a thread-local hook first.
  • A worker extracting file i holds a Turn. Its first numbering access blocks until files 0..i have passed their turns. The turn passes when the outermost extraction (depth 1) reaches code generation (numbering_done() in extract_source), or when the extraction ends.
  • Commit-time names. The stylesheet commit (Output::new → update_styles_in_bucket) can hand out the first number of a style too, for example a global style a page reaches through an import (resetCss() called from a layout). Before the turn passes, the extractor now walks the styles in the commit's order and naming scope (name_as_committed), so the later commit on the calling thread only looks names up. Outside a batch this hook does nothing.
  • Numbering after the turn passed, or reading a file number another file could still add, marks the file out of order. The batch then restores a Snapshot (class map, file map, reservation state) and extracts everything one by one. The result is never wrong, at worst sequential.
  • Outside a turn (every existing caller), the hooks do nothing. Single-file APIs are unchanged.

Prefix lock (css::with_prefix)

with_prefix held the global prefix mutex while it named a class. In a batch, naming can wait for a turn, so one worker could wait for its turn while holding the lock that the worker before it needed: apps/landing hung. The prefix is now an Arc<str> copied out under the lock, and no lock is held across a numbering call (test_with_prefix_holds_no_lock_while_naming).

Core batch (devup_ui_binding_core::extract_batch)

  • Scoped worker threads (std::thread::scope, 16 MiB stacks, at most 8 by default; no new dependencies). Sources are taken in index order.
  • The JS resolver must run on the calling thread, so workers send resolve requests over a channel. Each answer is shared per batch by (specifier, importer), so the large app makes 630 resolver calls instead of 2,400. Transport failures are not cached.
  • Outputs are committed in source order on the calling thread.
  • The batch stays sequential with one thread or under atom hoisting.

Determinism

  • libs/binding/tests/batch.rs builds a synthetic app: 48 components behind one barrel collapsed into one bucket, 6 routes, a broken file, a plain file, a @global file and an unnumbered file. It checks that outputs, sheet, class map, file map and CSS equal one-by-one code_extract at 1/2/3/4/8/16/64 threads, repeated, with and without source maps. It also covers every resolver answer kind, atom hoisting, the empty batch, and one resolver call per unique pair.
  • Regression test a_batch_commits_each_source_before_a_later_one_names: a globalCss inside an exported reset() called from a layout, plus 6 pages, compared with one by one at 2/4/8 threads × 4. It fails without the commit-time naming above.
  • numbering_order unit tests cover the wait/pass rules, nested extractions, out-of-order detection, snapshot restore and commit-time naming in the turn only.
  • Real JS resolver, B's binding: the 334-file large app gives outputs and exported state byte-identical to sequential at 2/4/8 threads × 7; apps/landing (194 files) gives the same state hash at 1/2/4/8/16 threads.

Performance (via B and C)

Large Turbopack app, prewarm extraction of 334 files, 7 runs each, median [min–max], this commit:

ms
one by one (today) 260 [228–292]
batch, 2 threads 151 [139–158]
batch, 4 threads 130 [125–137]
batch, 8 threads 125 [124–132]

End-to-end build numbers are in C (#1115).

Tests

  • cargo test --workspace: all pass, insta snapshots unchanged.
  • cargo clippy --all-targets --all-features -D warnings and cargo fmt: clean.

요약

스택: 이 PR (A, 코어) → B (바인딩 extractBatch, #1114) → C (Next 플러그인 prewarm, #1115, #1112 기반). main 기반입니다.

클래스 이름은 버킷별로 먼저 요청한 순서대로 번호가 매겨집니다. 그래서 추출은 지금까지 파일 하나씩만 실행됐습니다. 이 PR은 코어가 여러 파일을 워커 스레드에서 추출하게 합니다. 이때 모든 클래스 번호와 파일 번호는 파일을 순서대로 하나씩 추출할 때와 똑같이 나옵니다.

순서 있는 차례 (css::numbering_order)

  • 번호를 나눠 주는 곳은 class_num_for_key와 get_file_num_by_filename의 파일 번호 삽입, 두 곳뿐입니다. 두 곳 모두 이제 먼저 스레드 로컬 훅을 호출합니다.
  • 파일 i를 추출하는 워커는 Turn을 가집니다. 첫 번호 접근은 0..i 파일이 모두 차례를 넘길 때까지 기다립니다. 차례는 가장 바깥 추출(깊이 1)이 코드 생성에 이르거나(extract_source의 numbering_done()) 추출이 끝나면 넘어갑니다.
  • 확정 시점의 이름. 스타일시트 확정(Output::new → update_styles_in_bucket)도 스타일에 첫 번호를 줄 수 있습니다. 예를 들어 페이지가 import로 닿는 전역 스타일(레이아웃에서 부르는 resetCss())이 그렇습니다. 이제 추출기는 차례를 넘기기 전에 확정과 같은 순서와 이름 범위로 스타일을 훑습니다(name_as_committed). 그래서 나중에 호출 스레드에서 하는 확정은 이름을 찾아보기만 합니다. 배치 밖에서는 이 훅이 아무것도 하지 않습니다.
  • 차례가 넘어간 뒤 번호를 매기거나, 다른 파일이 아직 추가할 수 있는 파일 번호를 읽으면 그 파일은 순서 밖으로 표시됩니다. 그러면 배치는 Snapshot(class map, file map, 예약 상태)을 복원하고 전부 하나씩 다시 추출합니다. 결과가 틀리는 일은 없고, 최악의 경우 순차 실행이 될 뿐입니다.
  • 차례 밖에서는(기존 호출 전부) 훅이 아무것도 하지 않습니다. 단일 파일 API는 바뀌지 않습니다.

접두사 잠금 (css::with_prefix)

with_prefix는 클래스 이름을 붙이는 동안 전역 접두사 mutex를 쥐고 있었습니다. 배치에서는 이름 붙이기가 차례를 기다릴 수 있습니다. 그래서 한 워커가 앞 워커에게 필요한 잠금을 쥔 채 자기 차례를 기다릴 수 있었고, apps/landing이 멈췄습니다. 이제 접두사는 잠금 안에서 복사해 낸 Arc<str>이고, 번호 호출 동안 쥐는 잠금은 없습니다(test_with_prefix_holds_no_lock_while_naming).

코어 배치 (devup_ui_binding_core::extract_batch)

  • std::thread::scope 워커 스레드를 씁니다(스택 16 MiB, 기본 최대 8개, 새 의존성 없음). 소스는 인덱스 순서로 가져갑니다.
  • JS 리졸버는 호출 스레드에서만 실행해야 해서, 워커는 리졸브 요청을 채널로 보냅니다. 응답은 배치 안에서 (specifier, importer)별로 공유됩니다. 그래서 대형 앱의 리졸버 호출이 2,400번에서 630번으로 줄어듭니다. 전송 실패는 캐시하지 않습니다.
  • 출력은 호출 스레드에서 소스 순서대로 확정합니다.
  • 스레드가 하나이거나 atom hoisting을 쓰면 배치는 순차로 실행됩니다.

결정성

  • libs/binding/tests/batch.rs는 합성 앱을 만듭니다. 한 버킷으로 합쳐지는 barrel 뒤의 컴포넌트 48개, 라우트 6개, 깨진 파일, 일반 파일, @global 파일, 번호 없는 파일로 이뤄져 있습니다. 1/2/3/4/8/16/64 스레드에서 반복 실행하면서, 소스맵 유무와 관계없이 출력, sheet, class map, file map, CSS가 하나씩 code_extract한 결과와 같은지 확인합니다. 모든 리졸버 응답 종류, atom hoisting, 빈 배치, 고유 쌍당 리졸버 호출 1회도 확인합니다.
  • 회귀 테스트 a_batch_commits_each_source_before_a_later_one_names: 내보낸 reset() 안의 globalCss를 레이아웃에서 부르고 페이지 6개를 더해, 2/4/8 스레드 × 4회로 하나씩 추출한 결과와 비교합니다. 위의 확정 시점 이름 붙이기가 없으면 실패합니다.
  • numbering_order 단위 테스트는 대기/넘김 규칙, 중첩 추출, 순서 밖 감지, 스냅샷 복원, 차례 안에서만 하는 확정 시점 이름 붙이기를 다룹니다.
  • 실제 JS 리졸버와 B의 바인딩으로: 334개 파일의 대형 앱은 2/4/8 스레드 × 7회 모두 출력과 내보낸 상태가 순차 결과와 바이트 단위로 같았고, apps/landing(194개 파일)은 1/2/4/8/16 스레드에서 상태 해시가 같았습니다.

성능 (B, C 경유)

대형 Turbopack 앱의 334개 파일 prewarm 추출, 각 7회, 중앙값 [최소–최대], 이 커밋 기준:

ms
하나씩 (현재) 260 [228–292]
배치, 2 스레드 151 [139–158]
배치, 4 스레드 130 [125–137]
배치, 8 스레드 125 [124–132]

전체 빌드 수치는 C(#1115)에 있습니다.

테스트

  • cargo test --workspace: 모두 통과했고 insta 스냅샷은 바뀌지 않았습니다.
  • cargo clippy --all-targets --all-features -D warnings와 cargo fmt: 경고 없음.

Fix after review: one-by-one batches commit each source in order

A batch that runs one by one (one thread, atom hoisting, or after a source numbered out of turn) extracted every source and committed them all afterwards. A commit can hand out a style's first number (a globalCss a layout reaches through an import), so later sources took those numbers first: with threads: 1, a_batch_commits_each_source_before_a_later_one_names got display:flex as .a instead of .d. The sequential path now commits each source right after extracting it; the regression test runs at 1/2/4/8 threads. Also: Batch::parallel is false when the batch fell back, the worker channel lives inside the thread scope so a resolver panic fails the batch instead of hanging it (a_resolver_that_panics_fails_the_batch_without_hanging), and into_styles has its doc and #[must_use] back.

Stress check on the stack tip (native release build, real next build): the large app (334 files) gave identical prewarm outputs, class map, file map, sheet, base CSS, emitted CSS and HTML classes in 3 per-file builds and at 1/2/4/8/16 threads × 4. apps/landing did the same at 1/2/4/8/16 threads × 3. The only difference was MDX file numbering, which also changes between per-file builds.


리뷰 후 수정: 하나씩 도는 배치가 소스마다 순서대로 확정

하나씩 도는 배치(스레드 1개, atom hoisting, 또는 어떤 소스가 차례 밖에서 번호를 매긴 뒤)는 모든 소스를 추출한 다음에야 한꺼번에 확정했습니다. 확정이 스타일의 첫 번호를 줄 수 있어서(레이아웃이 import로 닿는 globalCss), 뒤 소스가 그 번호를 먼저 가져갔습니다. threads: 1에서 a_batch_commits_each_source_before_a_later_one_names는 display:flex를 .d가 아니라 .a로 받았습니다. 이제 순차 경로는 소스를 추출한 직후 바로 확정하고, 회귀 테스트는 1/2/4/8 스레드에서 돕니다. 그 밖에 배치가 순차로 되돌아가면 Batch::parallel이 false이고, 워커 채널을 스레드 scope 안에 두어 리졸버가 panic하면 배치가 멈추지 않고 실패하며(a_resolver_that_panics_fails_the_batch_without_hanging), into_styles의 문서와 #[must_use]를 되돌렸습니다.

스택 끝에서 한 스트레스 검사(네이티브 release 빌드, 실제 next build): 대형 앱(334개 파일)은 파일별 빌드 3회와 1/2/4/8/16 스레드 × 4회 모두 prewarm 출력, class map, file map, sheet, 기본 CSS, 내보낸 CSS, HTML 클래스가 같았습니다. apps/landing도 1/2/4/8/16 스레드 × 3회에서 같았습니다. 다른 것은 MDX 파일 번호뿐이었고, 이것은 파일별 빌드끼리도 바뀝니다.

🤖 Generated with Claude Code

Class names are numbered first come, first served, so extraction had to run
one file at a time. A file now takes an ordered turn: its first class or file
number waits until every earlier file has finished naming, and the turn passes
as soon as the outermost extraction reaches code generation. A file that names
anything after its turn passed (or reads a file number another file may still
add) is marked out of order; the batch then restores a snapshot of the class,
file and reservation state and extracts one by one.

The new core `extract_batch` runs sources on scoped worker threads, asks the
host resolver on the calling thread once per (specifier, importer), commits
the outputs in source order and stays sequential under atom hoisting or with
one thread. Existing single-file extraction is unchanged: outside a turn the
hooks do nothing.

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

codecov Bot commented Dec 5, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

Files with missing lines Coverage Δ
libs/binding/src/batch.rs 100.00% <100.00%> (ø)
libs/binding/src/lib.rs 100.00% <ø> (ø)
libs/css/src/file_map.rs 100.00% <100.00%> (ø)
libs/css/src/lib.rs 100.00% <100.00%> (ø)
libs/css/src/numbering_order.rs 100.00% <100.00%> (ø)
libs/css/src/slot_reservation.rs 100.00% <100.00%> (ø)
libs/extractor/src/lib.rs 100.00% <100.00%> (ø)
libs/extractor/src/style_collector.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 and others added 5 commits December 5, 2026 16:47
with_prefix held the global prefix mutex while its closure named classes.
In a batch, a worker naming its file's first class waits there for an
earlier file's turn; with the lock held, the earlier file could not name its
own classes, and the batch deadlocked (seen on apps/landing under a Next
production build). The prefix is now an Arc<str> copied out under the lock,
so no lock is held while a name waits for its turn.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Committing an output to the stylesheet names classes too (a style's class
in the global bucket is named when it is added). The batch committed every
output only after all sources were extracted, so a later source's
extraction could name a class before an earlier source's commit did; on
apps/landing that moved classes in the global bucket.

A worker now commits its source itself, after waiting for its turn, and the
turn passes only once the commit is done, so numbering and the stylesheet
change in source order exactly as one by one. Parsing and resolving imports
before a source's first number still run at once. With the turn held to the
end, nothing can number after its turn passed, so the out-of-order check,
the snapshot fallback and the extractor's turn hooks go; a worker that
panics fails the batch with its panic, as one by one would.

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

A source that imports global styles names them when it is committed. The
test fails on the batch that committed only after extracting every source.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…odegen again

Holding each source's turn until its output was committed (acb9501)
was correct but serialized code generation and the stylesheet commit: the
large app's prewarm only went from 289 ms to about 200-230 ms.

The turn passes at code generation again, and the batch commits on the
calling thread in source order. What the commit would name first
(global-bucket names of styles a source reaches through an import, for
instance) is now named before the turn passes: the extractor walks the
styles in the commit's order and scope (`name_as_committed`), so the
commit only looks names up. Outside a batch the hook does nothing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…e by one

A batch on one thread, under atom hoisting, or after a source numbered out
of turn extracted every source first and committed them all afterwards.
Committing a source can hand out the first number of a style, such as a
global style a layout reaches through an import, so later sources took
those numbers first and class names differed from extracting one by one.
The one-by-one path now commits each source right after extracting it.

`Batch::parallel` now tells whether the outputs come from worker threads,
so a batch that fell back no longer reports itself parallel. The workers'
channel is created inside the thread scope, so a resolver that panics on
the calling thread fails the batch instead of leaving workers waiting for
an answer. The doc and `#[must_use]` of `StyleCollector::into_styles` are
back on it.

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