Unverified Commit 47f99170 authored by Tobias Koppers's avatar Tobias Koppers Committed by GitHub

Turbopack: chunk each layout segment once in production (#99100)

### What?

Stops Turbopack from re-chunking every App Router layout segment once
per page in production builds. The manually constructed server-utilities
chunk group is now only created in development.

### Why?

A production build should chunk each shared layout segment exactly once.
Instead, a layout segment was chunked again for every endpoint below it.
On a small app with four endpoints, the root layout was chunked 4 times
and a nested `dashboard` layout 2 times. The emitted output was still
shared, so this was wasted build work rather than bigger bundles, which
is why output-based tests never caught it.

Production already builds a single module graph for the whole app, so
the module graph is not what differs between endpoints. The difference
comes from the server-utilities chunk group that seeds the
layout-segment chain:

- It is a `SharedMerged` group whose parent is the current endpoint's
entry chunk group.
- A merged group's parent is part of its identity, so every endpoint
gets a different group (5 chunkings on the same app).
- Its result seeds the availability info passed to each layout segment
after it. Availability info is part of the chunking task key, so each
shared segment ended up with a different key per endpoint and was
chunked again.

The code comment already said this manual shared chunk exists mainly to
help development. That makes sense there: each endpoint has its own
module graph in development, and without the group layout segments would
share very little across pages.

This is PR 0 of the chunk-group stack. The PRs above it are:

1. #98733 — canonical chunk-group identity
2. #98734 — graph-derived output groups
3. #98823 — Pages Router dev client graph chaining
4. #98685 — chunk-group availability bitmaps
5. #99050 — keyed chunk-group index lookups

### How?

The manual server-utilities group is now created only in
per-page-module-graph mode, which is development. In production the
layout-segment chain starts from an endpoint-independent state, so
sibling endpoints produce the same chunking task key for a shared
segment. The server utilities are then chunked with the entry through
the whole-app graph. Development behaves exactly as before.

On the same four-endpoint app, a production build now chunks the root
layout and the nested layout **once each**, and the manual
server-utilities group is gone. Development still creates the group and
chunks segments per page, which is expected for on-demand compilation.

Adds `test/e2e/app-dir/layout-segment-chunk-sharing`, a root layout and
a nested layout that share one module across two sibling pages. It
asserts two things:

- **Output sharing (Turbopack dev and production):** the shared module
is emitted into exactly one server chunk. Webpack builds a
self-contained server bundle per route, so this assertion is gated on
the bundler, not the mode.
- **Work sharing (Turbopack production only):** output sharing alone
does not prove the chunking *task* was reused, since a segment could be
re-chunked per page with an identical result. The test builds with
tracing enabled and uses `next internal query-trace` to count executions
of the nested layout's chunking task, which must be exactly one. A cache
hit produces no execution span, so the count equals the number of real
executions. Development compiles pages on demand with a module graph per
page, so repeated chunking is expected there and the assertion is
skipped.

With the fix reverted, the work-sharing assertion fails with 2
executions, while the output-sharing assertion still passes.

### Performance

Measured on a synthetic App Router app: a root layout and a nested
`section/layout.tsx`, each importing M modules (~20% `'use client'`),
with N trivial sibling pages under `section/`. Cold `next build` with
release native builds of both commits (`192fcaf7` vs this PR, one shared
JS build); paired runs in ABBA order on an 8 vCPU / 16 GB Vercel Sandbox
VM; 95% Student-t intervals on the paired differences.

At **800 pages × 1,000 modules per layout**, a dedicated 12-pair run:

| metric | Δ | 95% CI | pairs improved |
|---|---|---|---|
| Turbopack compile time | **−6.3%** (−767 ms) | [−968, −565] ms | 12/12
|
| total `next build` time | **−2.2%** (−764 ms) | [−1241, −287] ms |
9/12 |
| Turbopack process peak RSS | **−4.2%** (−104 MB) | [−141, −68] MB |
12/12 |

In traces of that build, the nested layout goes from 800 chunking
executions to 1, the root layout from 802 to 1, and the server-utilities
group from 803 to 0 (Node.js chunking spans overall: 7,223 → 1,617).
Smaller configurations (50–800 pages × 200 modules, 200 pages × 1,000
modules; 8 pairs each) showed no detected difference in time or
Turbopack memory, so the gain matters mainly for large apps.

**Trade-off:** without the manual shared group, a few server utilities
(the `*-async-storage.external` and `runtime-reacts.external` wrappers,
the vendored `react-rsc` getter and a small `bytes` helper) are now
inlined into each page's SSR entry chunk instead of being emitted once.
That adds about **2.3 KB of server output per App Router endpoint**
(+0.9% to +4.4% of server JS in these fixtures). Client JS is
byte-identical. Keeping these modules shared in production without
per-endpoint identity would be a possible follow-up.

### Verification

- Trace measurement on the fixture (production): root layout 4 → 1,
nested layout 2 → 1, server-utilities group 5 → 0; dev unchanged
- Production build renders and serves every route with the shared
module; the shared module is still emitted into exactly one server chunk
- `layout-segment-chunk-sharing` — Turbopack production (3 passed),
Turbopack dev (output assertion passed, trace assertion skipped),
webpack production (Turbopack-only assertions skipped)
- `cargo clippy --workspace --all-targets -- -D warnings -A deprecated`,
`cargo fmt --all -- --check`
- `turbopack-core` + `next-core` unit tests (252 passed);
`turbopack-tests` snapshots (126 passed, no changes)

<!-- NEXT_JS_LLM -->


<!-- fleet 4f67c6f7-bbe2-454b-9a17-822a60ef8f7e -->
Co-authored-by: 's avatarvercel-fleet-prod[bot] <318278635+vercel-fleet-prod[bot]@users.noreply.github.com>
Co-authored-by: 's avatarTobias Koppers <1365881+sokra@users.noreply.github.com>
parent 42f155f4
......@@ -1913,48 +1913,61 @@ impl AppEndpoint {
let entry_chunk_group = ChunkGroup::Entry(vec![app_entry.rsc_entry]);
let chunk_group_info = module_graph.chunk_group_info();
let client_references = client_references.await?;
let span = tracing::trace_span!("server utils");
async {
let parent_chunk_group = *chunk_group_info
.get_index_of(entry_chunk_group.clone())
.await?;
// This is basically a manual shared chunk. But it's particularly helpful
// for development, so that we share more layout segment chunks across
// pages.
let server_utils = client_references
.server_utils
.iter()
.map(async |m| Ok(ResolvedVc::upcast(m.await?.module)))
.try_join()
.await?;
let chunk_group = chunking_context
.chunk_group(
AssetIdent::from_path(
this.app_project.project().project_path().owned().await?,
// A manual shared chunk for the server utilities, created for development
// only.
//
// In development every endpoint gets its own module graph (see
// `per_page_module_graph`), so without this the layout segments would share
// very little across pages.
//
// It must not be created in production. Its `parent` is *this* endpoint's
// entry chunk group, and `parent` is part of a merged group's identity, so
// the group -- and hence the availability info it seeds into the layout
// segment chain below -- would differ for every endpoint. That makes each
// shared layout segment re-chunk once per descendant endpoint. In production
// a single whole-app module graph already shares these modules, so they are
// chunked as part of the entry instead.
if *project.per_page_module_graph().await? {
let chunk_group_info = module_graph.chunk_group_info();
let span = tracing::trace_span!("server utils");
async {
let parent_chunk_group = *chunk_group_info
.get_index_of(entry_chunk_group.clone())
.await?;
let server_utils = client_references
.server_utils
.iter()
.map(async |m| Ok(ResolvedVc::upcast(m.await?.module)))
.try_join()
.await?;
let chunk_group = chunking_context
.chunk_group(
AssetIdent::from_path(
this.app_project.project().project_path().owned().await?,
)
.with_modifier(rcstr!("server-utils"))
.into_vc(),
ChunkGroup::SharedMerged {
merge_tag: NEXT_SERVER_UTILITY_MERGE_TAG.clone(),
entries: server_utils,
parent: parent_chunk_group,
},
module_graph,
AvailabilityInfo::root(),
)
.with_modifier(rcstr!("server-utils"))
.into_vc(),
ChunkGroup::SharedMerged {
merge_tag: NEXT_SERVER_UTILITY_MERGE_TAG.clone(),
entries: server_utils,
parent: parent_chunk_group,
},
module_graph,
AvailabilityInfo::root(),
)
.to_resolved()
.await?;
.to_resolved()
.await?;
current_chunk_group = chunk_group;
current_chunk_group = chunk_group;
anyhow::Ok(())
anyhow::Ok(())
}
.instrument(span)
.await?;
}
.instrument(span)
.await?;
for server_component in client_references
.server_component_entries
.iter()
......
import type { ReactNode } from 'react'
import { sharedLayoutValue } from '../shared-layout-module'
export default function DashboardLayout({ children }: { children: ReactNode }) {
return (
<section>
<p id="dashboard-layout">{sharedLayoutValue('dashboard')}</p>
{children}
</section>
)
}
import { sharedLayoutValue } from '../../shared-layout-module'
export default function PageOne() {
return <p id="page-one">{sharedLayoutValue('one')}</p>
}
import { sharedLayoutValue } from '../../shared-layout-module'
export default function PageTwo() {
return <p id="page-two">{sharedLayoutValue('two')}</p>
}
import type { ReactNode } from 'react'
import { sharedLayoutValue } from './shared-layout-module'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>
<p id="root-layout">{sharedLayoutValue('root')}</p>
{children}
</body>
</html>
)
}
import { sharedLayoutValue } from './shared-layout-module'
export default function Page() {
return <p id="index">{sharedLayoutValue('index')}</p>
}
// This module is imported by the root layout, the nested layout and both
// sibling pages. The layout segment chunking optimization gives each nested
// segment the availability info of its parent, so a module already present in
// an ancestor segment's chunks must not be emitted again into the chunks of a
// descendant segment.
//
// The marker below is therefore expected to appear in exactly one emitted
// server chunk. If chunk sharing across layout segments regresses, the module
// is duplicated into each segment's chunks and the marker shows up in several.
export const LAYOUT_SEGMENT_SHARED_MARKER =
'layout-segment-shared-marker-3f9a1c7e'
export function sharedLayoutValue(prefix: string): string {
return `${prefix}:${LAYOUT_SEGMENT_SHARED_MARKER}`
}
import { existsSync } from 'fs'
import { readFile, readdir } from 'fs/promises'
import path, { join } from 'path'
import type { ChildProcess } from 'child_process'
import spawn from 'cross-spawn'
import treeKill from 'tree-kill'
import { nextTestSetup } from 'e2e-utils'
import { findPort, retry } from 'next-test-utils'
import { LAYOUT_SEGMENT_SHARED_MARKER } from './app/shared-layout-module'
const nextBin = path.join(
path.dirname(require.resolve('next/package')),
'dist/bin/next'
)
/** Run `next internal query-trace` and return its stdout. */
function runQueryTraceCli(args: string[]): Promise<string> {
return new Promise((resolve, reject) => {
const proc = spawn(
'node',
['--no-deprecation', nextBin, 'internal', 'query-trace', ...args],
{ stdio: 'pipe' }
)
let stdout = ''
let stderr = ''
proc.stdout?.on('data', (chunk: Buffer) => (stdout += chunk.toString()))
proc.stderr?.on('data', (chunk: Buffer) => (stderr += chunk.toString()))
proc.on('close', (code) => {
if (code === 0) resolve(stdout)
else reject(new Error(`query-trace exited with ${code}:\n${stderr}`))
})
})
}
type QuerySpansResult = {
spans: Array<{ id: string; name: string }>
page: number
totalPages: number
totalCount: number
}
describe('layout-segment-chunk-sharing', () => {
const { next, isNextDev, isTurbopack, skipped } = nextTestSetup({
files: __dirname,
// Write a Turbopack trace so the chunking tasks can be counted below.
env: { NEXT_TURBOPACK_TRACING: '1' },
// This suite inspects the on-disk build output and a local build trace to
// assert how modules were chunked, neither of which is reachable on a
// deployment.
skipDeployment: true,
})
if (skipped) return
it('renders the shared module from every segment', async () => {
const $ = await next.render$('/dashboard/one')
expect($('#root-layout').text()).toBe(
`root:${LAYOUT_SEGMENT_SHARED_MARKER}`
)
expect($('#dashboard-layout').text()).toBe(
`dashboard:${LAYOUT_SEGMENT_SHARED_MARKER}`
)
expect($('#page-one').text()).toBe(`one:${LAYOUT_SEGMENT_SHARED_MARKER}`)
})
// The layout segment chunking optimization hands each nested segment the
// availability info of its parent, so a module already emitted into an
// ancestor segment's chunks must not be emitted again for a descendant.
//
// `app/shared-layout-module.ts` is imported by the root layout, the nested
// `dashboard` layout and both sibling pages under it. If the optimization
// holds it is emitted exactly once; if chunk sharing regresses it is
// duplicated into the chunks of each segment that imports it.
//
// This holds for Turbopack in both dev and production. It does not hold for
// webpack, which builds a self-contained server bundle per route, so the
// module is legitimately present in each of them -- hence the gate is on the
// bundler, not on the mode.
;(!isTurbopack ? describe.skip : describe)('chunk sharing', () => {
it('emits the shared layout module into exactly one server chunk', async () => {
// `next dev` and `next build` write their output to different trees.
const serverDir = isNextDev
? join(next.testDir, '.next', 'dev', 'server')
: join(next.testDir, '.next', 'server')
const entries = await readdir(serverDir, {
recursive: true,
withFileTypes: true,
})
const chunkFiles = entries
.filter((entry) => entry.isFile() && entry.name.endsWith('.js'))
.map((entry) => join(entry.parentPath ?? entry.path, entry.name))
// Guard against the assertion silently passing because the glob found
// nothing (e.g. if the output layout changes).
expect(chunkFiles.length).toBeGreaterThan(0)
const matching: string[] = []
for (const file of chunkFiles) {
const contents = await readFile(file, 'utf8')
if (contents.includes(LAYOUT_SEGMENT_SHARED_MARKER)) {
matching.push(file.slice(serverDir.length + 1))
}
}
expect(matching).toHaveLength(1)
})
})
// Emitting the shared module once (above) only shows that the chunk
// *outputs* are shared. It does not show that the chunking *work* is: the
// `dashboard` layout segment could still be re-chunked once per page under
// it, each time producing an identical result.
//
// So count the chunking task executions in the build trace. A turbo-tasks
// cache hit produces no execution span, so the number of chunking spans for a
// segment is the number of times it was actually chunked. A production build
// uses a single module graph for the whole app, so the segment shared by
// `/dashboard/one` and `/dashboard/two` must be chunked exactly once.
//
// Production only: in development every page gets its own module graph and
// compiles on demand, so chunking a segment once per page is expected there.
;(!isTurbopack || isNextDev ? describe.skip : describe)(
'layout segment chunking in the build trace',
() => {
let traceServerProcess: ChildProcess | undefined
let mcpPort: number
beforeAll(async () => {
const traceFile = join(
next.testDir,
'.next-profiles',
'trace-turbopack.bin'
)
await retry(
async () => {
if (!existsSync(traceFile)) {
throw new Error(`Trace file not found yet: ${traceFile}`)
}
},
15_000,
500
)
mcpPort = await findPort()
traceServerProcess = spawn(
'node',
[
'--no-deprecation',
nextBin,
'internal',
'trace',
traceFile,
'--mcp-port',
String(mcpPort),
],
{ stdio: 'inherit' }
)
// Wait for the MCP HTTP server to be ready.
await retry(
async () => {
const res = await fetch(`http://127.0.0.1:${mcpPort}/mcp`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json, text/event-stream',
},
body: JSON.stringify({
jsonrpc: '2.0',
method: 'tools/list',
id: 0,
}),
})
if (res.status >= 500) {
throw new Error(`MCP server not ready (HTTP ${res.status})`)
}
},
30_000,
500
)
}, 120_000)
afterAll(async () => {
if (traceServerProcess?.pid) {
await new Promise<void>((resolve) => {
treeKill(traceServerProcess!.pid!, 'SIGKILL', () => resolve())
})
traceServerProcess = undefined
}
})
/** Every span, on every page, whose name contains `search`. */
async function findSpans(search: string) {
const names: string[] = []
for (let page = 1; ; page++) {
const result: QuerySpansResult = JSON.parse(
await runQueryTraceCli([
'--port',
String(mcpPort),
// Aggregated mode (the default) only searches the root level and
// silently finds nothing for spans nested below it.
'--no-aggregated',
'--json',
'--search',
search,
'--page',
String(page),
])
)
names.push(...result.spans.map((span) => span.name))
if (page >= result.totalPages) return names
}
}
it('chunks the shared dashboard layout segment exactly once', async () => {
// The chunking span name embeds the module ident, e.g.
// turbopack_nodejs::chunking_context chunking
// [project]/app/dashboard/layout.tsx [app-rsc] (ecmascript, Next.js Server Component)
const ident =
'app/dashboard/layout.tsx [app-rsc] (ecmascript, Next.js Server Component)'
// `--search` is a plain substring filter, so it also matches spans that
// merely *mention* this ident (e.g. analysis of the pages importing it).
// Keep only the chunking of the segment itself: anchored on the
// operation, and ending at the ident so the `client modules` and
// `ssr modules` chunk groups of the same segment are not counted.
const segmentChunking =
/^turbopack_nodejs::chunking_context chunking \[project\]\/(?:.*\/)?app\/dashboard\/layout\.tsx \[app-rsc\] \(ecmascript, Next\.js Server Component\)$/
const spans = await findSpans(ident)
expect(spans.filter((name) => segmentChunking.test(name))).toHaveLength(
1
)
})
}
)
})
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {}
export default nextConfig
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment