Unverified Commit e2be0379 authored by Tobias Koppers's avatar Tobias Koppers Committed by GitHub

export: only send each static generation batch its own resume data cache seeds (#100048)

### What?

During the final static generation phase (fallback shells with Cache
Components), each export worker batch now receives only the resume data
cache (RDC) seeds for its own pages. It no longer receives the seed map
for the whole build.

### Why?

`exportPagesInBatches` sent the complete `renderResumeDataCachesByPage`
map to every batch. Each seed is a serialized resume data cache, so with
large `'use cache'` values and many fallback shells this message grows
with the whole build rather than with the batch. Messages to
child-process workers are JSON-encoded into a single string. Once that
string exceeds V8's maximum string length (about 512 MiB), `next build`
fails with a bare `RangeError: Invalid string length`. That happens in
both child-process and `experimental.workerThreads` mode. This is one of
the two failure directions behind #99850.

Example: 12 locales under `/[lang]/[slug]` (13 fallback shells), with
about 40 MiB of cached data per shell and
`staticGenerationMinPagesPerWorker: 1`. Every batch received a seed map
of about 686M characters and the build failed, even though no single
batch needed more than a fraction of it.

### How?

- **Filtering:** an inline loop in `exportPagesInBatches` picks out the
seeds whose page key matches a path in the batch. The initial phase,
which has no seed map, is unchanged. How seeds are chosen
(`buildRDCCacheByPage`) is unchanged.
- **Shared page key:** the `page: path` key that seeds are stored and
looked up under is now a shared helper in `export/utils.ts`. The
parent's seed selection, the batch filter and the worker can no longer
drift apart.
- **What this doesn't cover:** a single batch can still be too large to
send, and the hang in the worker→parent direction remains. A follow-up
PR stacked on this one adds pre-flight size checks with an actionable
error and fixes that hang.

### Verification

- **Existing unit tests:** 30 RDC/postponed-state tests pass. The
dedicated filtering unit suite was dropped per review; the packed-build
fixtures verify the filtering integration end to end.
- **Build and static checks:** full JS/native bootstrap, package/root
TypeScript, prettier and eslint pass.
- **Local `next build` with a packed tarball from this branch:**
- the 13-shell fixture above now succeeds and prerenders all 13 shells.
On `canary` it fails with the bare `RangeError`;
- small-payload builds and a 25-page × 50 MiB build with smaller batches
still succeed.
- **Existing tests:**
`test/production/app-dir/action-only-fallback-resume-data-cache` and
`test/production/app-dir/adapter-dynamic-routes/dynamic-routes-shell-prefixes.test.ts`
pass (`pnpm test-start-turbo`).

Part of #99850

<!-- NEXT_JS_LLM -->


<!-- fleet 647a1430-f874-478f-b678-12678ee4765d -->
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 cbf49db3
......@@ -76,7 +76,7 @@ import { isDynamicRoute } from '../shared/lib/router/utils/is-dynamic'
import { normalizeAppPath } from '../shared/lib/router/utils/app-paths'
import type { Params } from '../server/request/params'
import { Bundler } from '../lib/bundler'
import { getBuildDistDir } from './utils'
import { getBuildDistDir, getExportPathPageKey } from './utils'
export class ExportError extends Error {
code = 'NEXT_EXPORT_ERROR'
......@@ -147,7 +147,7 @@ function buildRDCCacheByPage(
// Normalize app pages before param matching.
const normalizedPage = normalizeAppPath(page)
const pageKey = page !== path ? `${page}: ${path}` : path
const pageKey = getExportPathPageKey({ page, path })
const fallbackParamNames = new Set(
_fallbackRouteParams.map((param) => param.paramName)
)
......@@ -723,8 +723,22 @@ async function exportAppImpl(
return (
await Promise.all(
batches.map(async (batch) =>
worker.exportPages({
batches.map(async (batch) => {
// Only send the seeds this batch needs. Sending the whole map to
// every worker can exceed the maximum IPC message size.
let batchRenderResumeDataCaches: Record<string, string> | undefined
if (renderResumeDataCachesByPage) {
batchRenderResumeDataCaches = {}
for (const exportPath of batch) {
const pageKey = getExportPathPageKey(exportPath)
if (Object.hasOwn(renderResumeDataCachesByPage, pageKey)) {
batchRenderResumeDataCaches[pageKey] =
renderResumeDataCachesByPage[pageKey]
}
}
}
return worker.exportPages({
buildId,
deploymentId: nextConfig.deploymentId,
clientAssetToken: nextConfig.supportsImmutableAssets
......@@ -745,9 +759,9 @@ async function exportAppImpl(
cacheMaxMemorySize: nextConfig.cacheMaxMemorySize,
fetchCache: true,
fetchCacheKeyPrefix: nextConfig.experimental.fetchCacheKeyPrefix,
renderResumeDataCachesByPage,
renderResumeDataCachesByPage: batchRenderResumeDataCaches,
})
)
})
)
).flat()
}
......
import type { NextConfigComplete } from '../server/config-shared'
import type { ExportPathEntry } from './types'
export function hasCustomExportOutput(config: NextConfigComplete) {
// In the past, a user had to run "next build" to generate
......@@ -14,3 +15,10 @@ export function getBuildDistDir(config: NextConfigComplete): string {
// and manifests still live in .next until they are exported.
return hasCustomExportOutput(config) ? '.next' : config.distDir
}
export function getExportPathPageKey({
page,
path,
}: Pick<ExportPathEntry, 'page' | 'path'>): string {
return page !== path ? `${page}: ${path}` : path
}
......@@ -59,6 +59,7 @@ import type { PagesRenderContext, PagesSharedContext } from '../server/render'
import type { AppSharedContext } from '../server/app-render/app-render'
import { MultiFileWriter } from '../lib/multi-file-writer'
import { createRenderResumeDataCache } from '../server/resume-data-cache/resume-data-cache'
import { getExportPathPageKey } from './utils'
import { installGlobalBehaviors } from '../server/node-environment-extensions/global-behaviors'
;(globalThis as any).__NEXT_DATA__ = {
nextExport: true,
......@@ -443,7 +444,7 @@ export async function exportPages(
maxAttempts: number
) => {
const { page, path } = exportPath
const pageKey = page !== path ? `${page}: ${path}` : path
const pageKey = getExportPathPageKey(exportPath)
let attempt = 0
let result
......
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