Skip to content

perf(next-plugin): read each source once in the Turbopack setup - #1112

Open
owjs3901 wants to merge 1 commit into
perf/next-config-overlapfrom
perf/turbo-setup-read-once
Open

owjs3901 wants to merge 1 commit into
perf/next-config-overlapfrom
perf/turbo-setup-read-once

Conversation

@owjs3901

@owjs3901 owjs3901 commented Dec 4, 2026

Copy link
Copy Markdown
Contributor

Summary

Stacked on #1104. Under Turbopack, Next.js cannot start compiling until the coordinator setup ends. The setup runs on Next's main thread between next.config returning and "Creating an optimized production build". This PR makes that setup cheaper by reading each source file once.

The setup used to read the project's sources from disk several times: the import graph, file numbering (usesAny), the shared slot reservation, the production prewarm, and the module resolver that extraction calls back into. #1033 had routed these reads through plugin-utils' stamp-checked source cache (readSource inside withSourceCache). The squash merge of #1037 dropped that wiring and left source-cache.ts unused (only its tests imported it).

  • setupCoordinator now runs inside one withSourceCache run. The graph, numbering, reservation, prewarm and resolver read through readSource. Outside a run, readSource is still a plain readFileSync, so webpack, Vite and the other plugins are unchanged.
  • Inside a run, createModuleResolver looks each project file (relative, absolute or tsconfig-alias specifier) up once per importing directory and specifier. Before, it repeated the lookup for every importer and every pass of an extraction: the large app made 2,400 resolver calls for 334 files. File contents are still stamp-checked, so a file that changes is read again. Packages keep their existing stamp-checked resolution.

Results

Large Turbopack benchmark app (benchmark/large-app.mjs, 334 files), Next 16.4.6, Windows. Cold builds alternating base/change(/Tailwind), run one at a time, 2 × 8 rounds. Base is #1104's head with the same native binding.

metric (ms) base (n=16) median [min–max] this PR (n=16) median [min–max] Tailwind (n=8)
setup: config done → "Creating" 564 [386–691] 412 [314–513] 72 [42–89]
trace create-dist-dir 498 [342–599] 342 [265–425] 1 [0–1]
start → "Creating" 1368 [930–1635] 1158 [902–1583] 763 [524–1016]
compile (Creating → Compiled) 3459 [2551–4131] 3663 [2286–4739] 2967 [2332–7209]
wall 7282 [6473–8952] 7385 [5190–10390] 6170 [4645–11523]

On this machine the compile phase swings by about ±1s, so wall time cannot show a ~150ms change at this n. The setup phase is the steady metric, and it drops by about 150ms (−27%).

Setup breakdown (DEVUP_UI_PROFILE=1, 8 rounds each):

setup phase (ms) base median [min–max] this PR median [min–max]
whole setup 478 [339–559] 345 [262–378]
import graph 83 [68–97] 92 [64–111]
prewarm 337 [241–421] 215 [172–227]
↳ prewarm reads 37 [28–43] 10 [9–12]
↳ prewarm extraction (incl. resolver callbacks) 292 [208–368] 195 [157–208]
other (restore, MDX scan, numbering, CSS) 47 [30–59] 40 [27–49]

Most of the gain is in the prewarm. Its extraction calls the JS module resolver about 7 times per file, and each call used to re-stat and re-read the resolved module.

Output

Built with base and this PR's dists in the same worktree (same paths, same binding). I compared SHA-1s of .next/static, .next/server (build ID normalized) and df/:

  • next-devup-ui-large-turbo: identical (677 + 5 files)
  • next-devup-ui (--webpack): identical
  • next-devup-ui-turbo, next-devup-ui-single-turbo: identical except _not-found.html / 404.html. Those two flip between two hashes from run to run on base alone too, because Next orders their <title> tags nondeterministically.
  • apps/landing (LANDING_BUILD_MODE=next): the multiset of CSS contents, devup-ui.css and every static chunk are identical. Its file numbers (and so fileMap.json) already vary between two base builds, so a byte compare is not meaningful there.
  • next dev (turbo app): editing bg on the page shows up in the served CSS (HMR works).

Tests

  • bun test --coverage packages/plugin-utils packages/next-plugin: 1085 pass. Every changed file is at 100% lines/functions.
  • New test: inside a run, the resolver finds each project file once and still reads changed contents. A new run, or a call outside any run, sees newly created files.

Not in this PR

  • The rest of the prewarm is about 150ms of native extraction plus about 45ms of resolver callbacks. Parallelizing the native extraction (idea 1 of the investigation) is not feasible as a self-contained change. Extraction calls the JS resolver synchronously (a JS function only the main thread can run), and class names are assigned through the global class map in the middle of the visitor. A parallel analysis phase would need the extractor split into resolve/parse vs naming passes.
  • A per-extraction resolver memo in Rust saves about 15–20ms more in a JS simulation. I'm keeping it out of this PR.

요약

#1104 위에 쌓인 PR입니다. Turbopack에서 Next.js는 코디네이터 설정이 끝나야 컴파일을 시작할 수 있습니다. 이 설정은 next.config 반환과 "Creating an optimized production build" 사이에 Next 메인 스레드에서 실행됩니다. 이 PR은 각 소스 파일을 한 번만 읽게 해서 이 설정을 가볍게 합니다.

지금까지는 import 그래프, 파일 번호 매기기(usesAny), 공유 슬롯 예약, 프로덕션 prewarm, 추출 중 호출되는 모듈 리졸버가 같은 소스를 디스크에서 각각 다시 읽었습니다. #1033이 이 읽기들을 plugin-utils의 stamp 검사 소스 캐시(withSourceCache 안의 readSource)로 연결했지만, #1037의 squash merge에서 그 연결이 빠졌습니다. 그 뒤로 source-cache.ts는 테스트에서만 쓰이고 있었습니다.

  • setupCoordinator가 이제 하나의 withSourceCache 실행 안에서 돌고, 그래프·번호 매기기·예약·prewarm·리졸버가 readSource로 읽습니다. 실행 밖의 readSource는 그대로 readFileSync라서 webpack, Vite 등 다른 플러그인은 바뀌지 않습니다.
  • 실행 안에서 createModuleResolver는 프로젝트 파일(상대·절대·tsconfig alias 지정자)을 import하는 디렉터리와 지정자 조합마다 한 번만 찾습니다. 이전에는 import하는 파일마다, 추출 패스마다 다시 찾았습니다(대형 앱에서 334개 파일에 리졸버 호출 2,400번). 파일 내용은 계속 stamp로 검사하므로 바뀐 파일은 다시 읽고, 패키지는 기존 stamp 검사 방식으로 해석합니다.

결과

대형 Turbopack 벤치마크 앱(334개 파일), Next 16.4.6, Windows입니다. base/변경(/Tailwind)을 번갈아 하나씩 콜드 빌드했고(2 × 8라운드), base는 같은 네이티브 바인딩을 쓴 #1104 head입니다.

  • 설정 구간(config 완료 → "Creating") 중앙값: 564ms → 412ms(−27%). Tailwind는 72ms입니다.
  • trace create-dist-dir: 498 → 342ms.
  • 이 머신에서는 컴파일 구간이 ±1s씩 흔들려 이 표본 수로는 wall time에 약 150ms 차이가 드러나지 않습니다. 안정적인 지표는 설정 구간입니다.
  • 프로파일 기준 설정 전체는 478 → 345ms입니다. prewarm 읽기는 37 → 10ms, prewarm 추출(리졸버 콜백 포함)은 292 → 195ms로 줄었습니다.

출력

같은 worktree에서 base와 이 PR의 dist로 각각 빌드해 비교했습니다.

  • large-turbo와 webpack 빌드: 바이트 단위로 동일합니다.
  • turbo, single-turbo: _not-found.html/404.html만 다릅니다. 이 두 파일은 Next가 <title> 순서를 비결정적으로 정해서 base끼리 빌드해도 두 해시 사이를 오갑니다.
  • landing: CSS 내용 집합, devup-ui.css, 모든 static chunk가 동일합니다. 파일 번호는 base끼리 빌드해도 달라서 바이트 비교는 의미가 없습니다.
  • next dev HMR이 동작함을 확인했습니다.

테스트

  • bun test --coverage packages/plugin-utils packages/next-plugin: 1085개 통과, 변경된 파일은 모두 100% 커버리지입니다.
  • 새 테스트: 실행 안에서 리졸버가 프로젝트 파일을 한 번만 찾되 바뀐 내용은 다시 읽는지, 새 실행이나 실행 밖 호출에서는 새로 만든 파일을 찾는지 확인합니다.

이 PR에 포함하지 않은 것

  • 남은 prewarm 비용은 네이티브 추출 약 150ms와 리졸버 콜백 약 45ms입니다. 네이티브 추출 병렬화는 독립적인 변경으로는 할 수 없습니다. 추출이 메인 스레드에서만 실행되는 JS 리졸버를 동기로 호출하고, 클래스 이름이 visitor 도중에 전역 class map으로 정해지기 때문입니다. 병렬 분석 단계를 넣으려면 추출기를 해석/파싱 패스와 이름 부여 패스로 나눠야 합니다.
  • Rust 쪽 추출 단위 리졸버 메모는 JS 시뮬레이션 기준으로 15–20ms를 더 줄이지만 이 PR에는 넣지 않았습니다.

🤖 Generated with Claude Code

The coordinator setup that Turbopack waits for read the project's sources
from disk several times over: the import graph, file numbering, the shared
slot reservation, the production prewarm and the module resolver each read
them again. #1033 had routed these reads through plugin-utils' stamp-checked
source cache, but a later squash merge (#1037) disconnected it, leaving
source-cache.ts unused.

The setup now runs inside one withSourceCache run, and the graph, numbering,
reservation, prewarm and resolver read through readSource. Inside such a run
the module resolver also looks each project file up once per importing
directory and specifier, instead of again for every importer and every pass
of an extraction; it still reads a file again once its stamp changes.
Packages keep their existing stamp-checked resolution.

Large Turbopack benchmark app, 16 cold builds each: config done -> Creating
552-564ms -> 410-422ms median; the profiled setup 478 -> 345ms (prewarm
reads 37 -> 10ms, prewarm extraction 292 -> 195ms). Output is unchanged.

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

codecov Bot commented Dec 4, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

Files with missing lines Coverage Δ
packages/next-plugin/src/plugin.ts 100.00% <100.00%> (ø)
packages/next-plugin/src/prewarm.ts 100.00% <100.00%> (ø)
packages/plugin-utils/src/import-graph.ts 100.00% <100.00%> (ø)
packages/plugin-utils/src/index.ts 100.00% <100.00%> (ø)
packages/plugin-utils/src/numbering.ts 100.00% <100.00%> (ø)
packages/plugin-utils/src/reservation-discovery.ts 100.00% <100.00%> (ø)
packages/plugin-utils/src/source-cache.ts 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.

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