Skip to content

perf(next-plugin): prewarm Turbopack production sources as one batch - #1115

Open
owjs3901 wants to merge 26 commits into
perf/turbo-setup-read-oncefrom
perf/parallel-prewarm-next
Open

owjs3901 wants to merge 26 commits into
perf/turbo-setup-read-oncefrom
perf/parallel-prewarm-next

Conversation

@owjs3901

@owjs3901 owjs3901 commented Dec 5, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Stack: #1113 (A, core) → #1114 (B, binding extractBatch) → this PR (C). Based on #1112's branch (perf/turbo-setup-read-once). #1114 is merged in with a merge commit.

The Next plugin's Turbopack production setup extracts every source file up front (the prewarm) so Turbopack's loaders only look results up. Until now it called codeExtract once per file on the main thread. It now hands all files to extractBatch in one call (extractPrewarmSources in prewarm.ts):

  • Native engine: perf(binding): extract a batch on worker threads with in-order numbering #1113's ordered batch on worker threads (at most 8). Class and file numbers come out exactly as one by one in the same order.
  • Engine without extractBatch (older bindings): the same per-file loop as before, so behavior is unchanged.
  • A source that fails still only skips that file with the same warning as before. Dev mode (next dev) does not prewarm and is unchanged.

Results

Cold next build, large Turbopack app (334 files)

8 rounds, alternating base (#1112) / this PR / Tailwind each round, one build at a time with at least 3 GB free memory before each. Windows 11, 2026-12-05. Median [min–max], ms.

base #1112 this PR Δ median Tailwind
setup (config done → "Creating an optimized production build") 334 [242–370] 250 [248–281] −84 (−25%) 54 [38–64]
create-dist-dir span 278 [206–309] 194 [191–218] −84 (−30%) 0.7
prewarm (collect + read + extract) 176 [145–189] 95 [89–110] −81 —
prewarm extract only 161 [133–173] 86 [79–99] −75 —
wall time 6,259 [5,406–6,399] 6,196 [4,506–6,383] −63 5,474 [4,981–5,743]
  • Setup and create-dist-dir drop by about 84 ms, and the spread of this PR's runs (248–281) sits entirely below base's median. One base run (242) overlapped, so the gain is clear but not every pair.
  • Wall time: the 63 ms gain is within run-to-run noise. Both arms span about 1 s. The setup is about 4% of a 6 s build, so this PR cannot close the wall-time gap to Tailwind (about 0.7 s) on its own. That gap is mostly in Turbopack's compile phase.
  • Micro benchmark of the extraction alone (334 files, real JS resolver, 7 runs, median): one by one 260 ms → batch 151 ms at 2 threads, 130 ms at 4, 125 ms at 8.

Output identity (base #1112 vs this PR)

Each app was built cold in both trees, then compared: df/ CSS and JSON, every emitted stylesheet, and every class attribute in the prerendered HTML.

  • Byte-identical: next-devup-ui-turbo, next-devup-ui-single-turbo, next-devup-ui-large-turbo, next-devup-ui-large-styled-turbo, next-devup-ui-large (webpack). An earlier run of the same check, on an earlier commit of this stack, also covered next-devup-ui, next-devup-ui-single, next-devup-ui-collapse and next-devup-ui-large-turbo-wasm.
  • apps/landing (194 files, 146 pages): classMap.json, the sheet, devup-ui.css, every emitted stylesheet and every HTML class are identical. fileMap.json, stateManifest.json and four numbered devup-ui-N.css files differ. Two base builds of landing also differ in those same three kinds of files, so this is existing build-to-build noise.
  • Determinism: apps/landing's whole extracted state hashes the same at 1/2/4/8/16 threads. The large app is byte-identical to sequential at 2/4/8 threads × 7 runs.

Checks

  • next dev --turbopack HMR on the large app: after adding bg="#a1b2c3" to a page, the served HTML got a new class and the dev stylesheet its rule.
  • @devup-ui/next-plugin: 338 tests, 100% coverage. Lint clean.

Bugs found on the way (fixed in #1113)

  • Deadlock: with_prefix held a mutex while naming a class, which can wait for a turn. apps/landing hung.
  • Commit-time naming: global styles reached through an import got their first number at the stylesheet commit, outside the turns. The class numbers in apps/landing differed. They are now named in the turn, and a regression test covers it.
  • One-by-one batches (one thread, atom hoisting, or a fallback) committed every source only after extracting all of them, so commit-time names came out in the wrong order there too. Each source is now committed before the next is extracted.

요약

스택: #1113 (A, 코어) → #1114 (B, 바인딩 extractBatch) → 이 PR (C). #1112 브랜치(perf/turbo-setup-read-once) 기반이며, #1114를 merge commit으로 합쳤습니다.

Next 플러그인의 Turbopack 프로덕션 설정은 모든 소스 파일을 미리 추출합니다(prewarm). 그래서 Turbopack 로더는 결과를 찾아보기만 합니다. 지금까지는 메인 스레드에서 파일마다 codeExtract를 한 번씩 불렀습니다. 이제는 모든 파일을 extractBatch 한 번에 넘깁니다(prewarm.ts의 extractPrewarmSources).

  • 네이티브 엔진: #1113의 순서 있는 배치를 워커 스레드(최대 8개)에서 실행합니다. 클래스 번호와 파일 번호는 같은 순서로 하나씩 추출할 때와 똑같이 나옵니다.
  • extractBatch가 없는 엔진(이전 바인딩): 예전과 같은 파일별 루프를 돌기 때문에 동작이 바뀌지 않습니다.
  • 실패한 소스는 여전히 그 파일만 건너뛰고, 경고도 예전과 같습니다. 개발 모드(next dev)는 prewarm을 하지 않으므로 바뀌지 않습니다.

결과

대형 Turbopack 앱(334개 파일)의 cold next build

8라운드입니다. 라운드마다 base(#1112) / 이 PR / Tailwind 순서를 돌려 가며 실행했고, 빌드는 한 번에 하나씩, 매번 여유 메모리 3 GB 이상에서 시작했습니다. Windows 11, 2026-12-05. 중앙값 [최소–최대], ms.

base #1112 이 PR 중앙값 차이 Tailwind
설정 (config 완료 → "Creating an optimized production build") 334 [242–370] 250 [248–281] −84 (−25%) 54 [38–64]
create-dist-dir 구간 278 [206–309] 194 [191–218] −84 (−30%) 0.7
prewarm (수집 + 읽기 + 추출) 176 [145–189] 95 [89–110] −81 —
prewarm 추출만 161 [133–173] 86 [79–99] −75 —
전체 시간 6,259 [5,406–6,399] 6,196 [4,506–6,383] −63 5,474 [4,981–5,743]
  • 설정과 create-dist-dir이 약 84 ms 줄었습니다. 이 PR의 실행 범위(248–281)는 모두 base의 중앙값보다 낮습니다. base 실행 하나(242)만 겹쳤으므로, 이득은 분명하지만 모든 쌍에서 나타나지는 않습니다.
  • 전체 시간: 63 ms 이득은 실행 간 노이즈 범위 안입니다. 양쪽 모두 약 1초 폭으로 흔들립니다. 설정은 6초 빌드의 약 4%뿐이라서, 이 PR만으로는 Tailwind와의 전체 시간 차이(약 0.7초)를 좁힐 수 없습니다. 그 차이는 대부분 Turbopack의 컴파일 단계에 있습니다.
  • 추출만 잰 마이크로 벤치마크(334개 파일, 실제 JS 리졸버, 7회 중앙값): 하나씩 260 ms → 배치 2 스레드 151 ms, 4 스레드 130 ms, 8 스레드 125 ms.

출력 동일성 (base #1112 vs 이 PR)

각 앱을 두 트리에서 cold 빌드한 뒤 비교했습니다. 대상은 df/의 CSS와 JSON, 내보낸 모든 스타일시트, 프리렌더된 HTML의 모든 class 속성입니다.

  • 바이트 단위로 같음: next-devup-ui-turbo, next-devup-ui-single-turbo, next-devup-ui-large-turbo, next-devup-ui-large-styled-turbo, next-devup-ui-large(webpack). 이 스택의 이전 커밋에서 같은 검사를 돌렸을 때는 next-devup-ui, next-devup-ui-single, next-devup-ui-collapse, next-devup-ui-large-turbo-wasm도 확인했습니다.
  • apps/landing(194개 파일, 146개 페이지): classMap.json, sheet, devup-ui.css, 내보낸 모든 스타일시트, 모든 HTML 클래스가 같습니다. fileMap.json, stateManifest.json, 번호 붙은 devup-ui-N.css 파일 4개는 다릅니다. landing을 base로 두 번 빌드해도 같은 세 종류의 파일이 다르므로, 원래 있던 빌드 간 노이즈입니다.
  • 결정성: apps/landing의 추출 상태 전체가 1/2/4/8/16 스레드에서 같은 해시를 냅니다. 대형 앱은 2/4/8 스레드 × 7회 모두 순차 결과와 바이트 단위로 같습니다.

확인

  • 대형 앱에서 next dev --turbopack HMR을 확인했습니다. 페이지에 bg="#a1b2c3"를 추가하자, 서빙된 HTML에 새 클래스가 생기고 개발 스타일시트에 그 규칙이 들어갔습니다.
  • @devup-ui/next-plugin: 테스트 338개, 커버리지 100%. lint 경고 없음.

도중에 찾은 버그 (#1113에서 수정)

  • 교착 상태: with_prefix가 클래스 이름을 붙이는 동안 mutex를 쥐고 있었고, 이름 붙이기는 차례를 기다릴 수 있습니다. 그래서 apps/landing이 멈췄습니다.
  • 확정 시점의 이름 붙이기: import로 닿는 전역 스타일이 차례 밖인 스타일시트 확정 때 첫 번호를 받았습니다. 그래서 apps/landing의 클래스 번호가 달라졌습니다. 이제는 차례 안에서 이름을 붙이고, 회귀 테스트로 확인합니다.
  • 하나씩 도는 배치(스레드 1개, atom hoisting, 또는 되돌아간 경우)는 모든 소스를 추출한 뒤에야 확정해서, 여기서도 확정 시점 이름의 순서가 틀렸습니다. 이제는 다음 소스를 추출하기 전에 소스마다 확정합니다.

🤖 Generated with Claude Code

owjs3901 and others added 8 commits December 5, 2026 12:11
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>
`extractBatch(rows, package, singleCss, importMainCssInCode,
importMainCssInCss, aliases, sourceMap, threads?)` extracts [filename, code,
cssDir] rows and returns, for each, the output codeExtract would give without
CSS or the Error its source failed with. The native engine runs the core batch
on worker threads (by default the cores, at most eight; more only queue on
the resolver), calling the module resolver on the JS thread. The WASM engine
extracts the rows one by one, so both engines keep one ABI.

The argument validator, ABI name lists and the native/WASM parity corpus learn
the new export; a corpus scenario compares the batch on both engines with
every resolver answer, and a private native check covers a resolver that
throws past the adapter.

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The coordinator prewarm extracted every source one by one on Next's main
thread before Turbopack could start compiling. It now reads the sources and
hands them to the engine's extractBatch, which the native engine runs on
worker threads with in-order numbering; outputs, warnings for sources that
fail and the stylesheet are those of extracting one by one. Engines without
extractBatch keep the previous loop.

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

Name the WASM threads parameter like the native one, so the ABI coverage
pairs it with its validation case.

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The native consumer check and the compiler structural types test pin the
number of engine exports; extractBatch adds one to each.

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

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 Δ
bindings/devup-ui-binding/index.mjs 100.00% <100.00%> (ø)
bindings/devup-ui-binding/src/host.rs 100.00% <ø> (ø)
bindings/devup-ui-binding/src/lib.rs 100.00% <ø> (ø)
bindings/devup-ui-wasm/src/lib.rs 100.00% <ø> (ø)
bindings/devup-ui-wasm/src/reservation.rs 100.00% <ø> (ø)
bindings/devup-ui-wasm/src/reservation/rows.rs 100.00% <100.00%> (ø)
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%> (ø)
... and 14 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 13 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>
…binding

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

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>
…binding

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>
…binding

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

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>
…rm-next

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>
…binding

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
owjs3901 and others added 5 commits December 5, 2026 18:55
…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>
…ler passes

The native adapter turned `threads` into a u32 with `>>> 0`, so -1 asked
for 4,294,967,295 workers (one per source in practice), 2.5 for 2 and NaN
for 0, and an explicit count was never capped at the default's eight.

`threads` now reaches the core as a number, and `batch_threads` keeps a
whole count from 1, capped at 8, and gives the default (the cores, at most
8) for none, 0, a negative, a fraction, NaN or an infinity. This follows
the `n` argument convention: any number or null is accepted, and a count
that makes no sense falls back like an `atomHoist` that does. The WASM
engine reads `threads` as a number too and still extracts one by one.

Covered by an rstest table in core, by the binding corpus that both
engines run and compare, by the native private host calling the raw
binding with those counts, and by a bun test through both engines.

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

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