++}
+diff --git a/test/production/app-dir/output-export-async-route-module/fixtures/valid/next.config.js b/test/production/app-dir/output-export-async-route-module/fixtures/valid/next.config.js
+new file mode 100644
+index 00000000..fecf9218
+--- /dev/null
++++ b/test/production/app-dir/output-export-async-route-module/fixtures/valid/next.config.js
+@@ -0,0 +1,8 @@
++/**
++ * @type {import('next').NextConfig}
++ */
++const nextConfig = {
++ output: 'export',
++}
++
++module.exports = nextConfig
+diff --git a/test/production/app-dir/output-export-async-route-module/output-export-async-route-module.test.ts b/test/production/app-dir/output-export-async-route-module/output-export-async-route-module.test.ts
+new file mode 100644
+index 00000000..0c8ac29a
+--- /dev/null
++++ b/test/production/app-dir/output-export-async-route-module/output-export-async-route-module.test.ts
+@@ -0,0 +1,36 @@
++import { join } from 'path'
++import { nextTestSetup } from 'e2e-utils'
++
++describe('output-export-async-route-module', () => {
++ describe('invalid route', () => {
++ const { next } = nextTestSetup({
++ files: join(__dirname, 'fixtures', 'invalid'),
++ skipStart: true,
++ })
++
++ // The route module uses top-level await, so its `output: 'export'`
++ // validation runs after the module settles instead of throwing during
++ // require(). The resulting error must still fail the build.
++ it('fails the build when an async route module is not statically exportable', async () => {
++ const { exitCode, cliOutput } = await next.build()
++ expect(cliOutput).toContain(
++ 'not configured on route "/api/data" with "output: export"'
++ )
++ expect(exitCode).toEqual(expect.any(Number))
++ expect(exitCode).not.toBe(0)
++ })
++ })
++
++ describe('valid route', () => {
++ const { next } = nextTestSetup({
++ files: join(__dirname, 'fixtures', 'valid'),
++ skipStart: true,
++ })
++
++ it('exports an async route module that is statically exportable', async () => {
++ const { exitCode } = await next.build()
++ expect(exitCode).toBe(0)
++ expect(await next.readFile('out/api/data')).toBe('{"ok":true}')
++ })
++ })
++})
diff --git a/nextjs-95799-async-route-init-errors/tests/test.sh b/nextjs-95799-async-route-init-errors/tests/test.sh
new file mode 100644
index 0000000000000000000000000000000000000000..3098673d5213f11f0d90116d52209d729bc3c3fa
--- /dev/null
+++ b/nextjs-95799-async-route-init-errors/tests/test.sh
@@ -0,0 +1,98 @@
+#!/bin/bash
+set -uo pipefail
+mkdir -p /logs/verifier
+patch_applied=1
+fail_to_pass=0
+pass_to_pass=0
+deterministic=0
+setup_completed=0
+fail_to_pass_exit_code=-1
+fail_to_pass_repeat_exit_code=-1
+pass_to_pass_exit_code=-1
+verifier_cache=""
+
+kill_verifier_processes() { pkill -KILL -u "$(id -u verifier)" 2>/dev/null || true; }
+# Some toolchains fetch dependencies at test runtime (e.g. Next.js e2e installs),
+# so a single registry connection reset must not be misread as a dead test. Retry
+# only infrastructure-style failures with backoff; real assertion failures fail fast.
+run_verifier_command() {
+ local logfile
+ logfile="$(mktemp /tmp/selfbench-verifier-command-XXXXXX.log)"
+ local attempt=1
+ local status=1
+ while [ "$attempt" -le 3 ]; do
+ : > "$logfile"
+ runuser -u verifier -- env PATH="/usr/local/go/bin:/usr/local/cargo/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin" UV_CACHE_DIR="$verifier_cache" UV_NO_BUILD_ISOLATION=1 bash -lc "$1" >"$logfile" 2>&1
+ status=$?
+ if [ "$status" -eq 0 ]; then
+ break
+ fi
+ if [ "$attempt" -lt 3 ] && grep -qE 'ECONNRESET|ETIMEDOUT|ESOCKETTIMEDOUT|ENOTFOUND|EAI_AGAIN|META_FETCH_FAIL|FetchError|EPIPE|EPERM|registry\.npmjs' "$logfile"; then
+ sleep "$((10 * attempt))"
+ attempt=$((attempt + 1))
+ continue
+ fi
+ break
+ done
+ cat "$logfile"
+ rm -f "$logfile"
+ kill_verifier_processes
+ return "$status"
+}
+protect_held_out_path() {
+ local path="$1"
+ chown -R root:root -- "$path"
+ chmod -R a-w,go+rX -- "$path"
+}
+
+if [ ! -f /opt/selfbench/agent.patch ]; then
+ patch_applied=0
+elif [ -s /opt/selfbench/agent.patch ]; then
+ git -C /app apply --binary --whitespace=nowarn --exclude='test/production/app-dir/output-export-async-route-module/fixtures/invalid/app/api/data/route.ts' --exclude='test/production/app-dir/output-export-async-route-module/fixtures/invalid/app/api/data/route.ts/*' --exclude='test/production/app-dir/output-export-async-route-module/fixtures/invalid/app/layout.tsx' --exclude='test/production/app-dir/output-export-async-route-module/fixtures/invalid/app/layout.tsx/*' --exclude='test/production/app-dir/output-export-async-route-module/fixtures/invalid/app/page.tsx' --exclude='test/production/app-dir/output-export-async-route-module/fixtures/invalid/app/page.tsx/*' --exclude='test/production/app-dir/output-export-async-route-module/fixtures/invalid/next.config.js' --exclude='test/production/app-dir/output-export-async-route-module/fixtures/invalid/next.config.js/*' --exclude='test/production/app-dir/output-export-async-route-module/fixtures/valid/app/api/data/route.ts' --exclude='test/production/app-dir/output-export-async-route-module/fixtures/valid/app/api/data/route.ts/*' --exclude='test/production/app-dir/output-export-async-route-module/fixtures/valid/app/layout.tsx' --exclude='test/production/app-dir/output-export-async-route-module/fixtures/valid/app/layout.tsx/*' --exclude='test/production/app-dir/output-export-async-route-module/fixtures/valid/app/page.tsx' --exclude='test/production/app-dir/output-export-async-route-module/fixtures/valid/app/page.tsx/*' --exclude='test/production/app-dir/output-export-async-route-module/fixtures/valid/next.config.js' --exclude='test/production/app-dir/output-export-async-route-module/fixtures/valid/next.config.js/*' --exclude='test/production/app-dir/output-export-async-route-module/output-export-async-route-module.test.ts' --exclude='test/production/app-dir/output-export-async-route-module/output-export-async-route-module.test.ts/*' /opt/selfbench/agent.patch || patch_applied=0
+fi
+
+if [ "$patch_applied" -eq 1 ]; then setup_completed=1; fi
+
+if [ "$patch_applied" -eq 1 ] && [ "$setup_completed" -eq 1 ]; then
+ kill_verifier_processes
+ git -C /app restore --source=HEAD --staged --worktree -- 'test/production/app-dir/output-export-async-route-module/fixtures/invalid/app/api/data/route.ts' 'test/production/app-dir/output-export-async-route-module/fixtures/invalid/app/layout.tsx' 'test/production/app-dir/output-export-async-route-module/fixtures/invalid/app/page.tsx' 'test/production/app-dir/output-export-async-route-module/fixtures/invalid/next.config.js' 'test/production/app-dir/output-export-async-route-module/fixtures/valid/app/api/data/route.ts' 'test/production/app-dir/output-export-async-route-module/fixtures/valid/app/layout.tsx' 'test/production/app-dir/output-export-async-route-module/fixtures/valid/app/page.tsx' 'test/production/app-dir/output-export-async-route-module/fixtures/valid/next.config.js' 'test/production/app-dir/output-export-async-route-module/output-export-async-route-module.test.ts' 2>/dev/null || true
+ git -C /app clean -fd -- 'test/production/app-dir/output-export-async-route-module/fixtures/invalid/app/api/data/route.ts' 'test/production/app-dir/output-export-async-route-module/fixtures/invalid/app/layout.tsx' 'test/production/app-dir/output-export-async-route-module/fixtures/invalid/app/page.tsx' 'test/production/app-dir/output-export-async-route-module/fixtures/invalid/next.config.js' 'test/production/app-dir/output-export-async-route-module/fixtures/valid/app/api/data/route.ts' 'test/production/app-dir/output-export-async-route-module/fixtures/valid/app/layout.tsx' 'test/production/app-dir/output-export-async-route-module/fixtures/valid/app/page.tsx' 'test/production/app-dir/output-export-async-route-module/fixtures/valid/next.config.js' 'test/production/app-dir/output-export-async-route-module/output-export-async-route-module.test.ts' >/dev/null 2>&1 || true
+ git -C /app apply --binary --whitespace=nowarn /tests/test.patch || patch_applied=0
+ if [ "$patch_applied" -eq 1 ]; then
+ for protected_path in '/app/test/production/app-dir/output-export-async-route-module/fixtures/invalid/app/api/data/route.ts' '/app/test/production/app-dir/output-export-async-route-module/fixtures/invalid/app/layout.tsx' '/app/test/production/app-dir/output-export-async-route-module/fixtures/invalid/app/page.tsx' '/app/test/production/app-dir/output-export-async-route-module/fixtures/invalid/next.config.js' '/app/test/production/app-dir/output-export-async-route-module/fixtures/valid/app/api/data/route.ts' '/app/test/production/app-dir/output-export-async-route-module/fixtures/valid/app/layout.tsx' '/app/test/production/app-dir/output-export-async-route-module/fixtures/valid/app/page.tsx' '/app/test/production/app-dir/output-export-async-route-module/fixtures/valid/next.config.js' '/app/test/production/app-dir/output-export-async-route-module/output-export-async-route-module.test.ts'; do protect_held_out_path "$protected_path"; done
+ fi
+ rm -f /tests/test.patch
+fi
+
+if [ "$patch_applied" -eq 1 ] && [ "$setup_completed" -eq 1 ]; then
+ cd '/app/.'
+ verifier_cache="$(mktemp -d /tmp/selfbench-verifier-uv-XXXXXX)"
+ cp -a /opt/uv-cache/. "$verifier_cache"/
+ chown -R verifier:verifier "$verifier_cache"
+ if run_verifier_command 'NEXT_TELEMETRY_DISABLED=1 pnpm --filter next build && pnpm test-start-webpack '"'"'test/production/app-dir/output-export-async-route-module/output-export-async-route-module.test.ts'"'"''; then
+ fail_to_pass_exit_code=0
+ fail_to_pass=1
+ if run_verifier_command 'NEXT_TELEMETRY_DISABLED=1 pnpm --filter next build && pnpm test-start-webpack '"'"'test/production/app-dir/output-export-async-route-module/output-export-async-route-module.test.ts'"'"''; then
+ fail_to_pass_repeat_exit_code=0
+ deterministic=1
+ else
+ fail_to_pass_repeat_exit_code=$?
+ fi
+ else
+ fail_to_pass_exit_code=$?
+ fi
+ if run_verifier_command 'true'; then
+ pass_to_pass_exit_code=0
+ pass_to_pass=1
+ else
+ pass_to_pass_exit_code=$?
+ fi
+ rm -rf "$verifier_cache"
+fi
+
+reward=0
+if [ "$patch_applied" -eq 1 ] && [ "$fail_to_pass" -eq 1 ] && [ "$pass_to_pass" -eq 1 ] && [ "$deterministic" -eq 1 ]; then reward=1; fi
+cat > /logs/verifier/reward.json <`,
++ // ...) is not something we have an emitted source map for.
++ let scriptPath = scriptNameOrSourceURL
++ if (scriptNameOrSourceURL.startsWith('file://')) {
++ if (scriptNameOrSourceURL.includes('?')) {
++ return null
++ }
++ try {
++ scriptPath = fileURLToPath(scriptNameOrSourceURL)
++ } catch {
++ return null
++ }
++ }
++ if (!isAbsolute(scriptPath)) {
++ return null
++ }
++
++ // Only chunks emitted into `distDir` have an on-disk source map to point at.
++ const relativePath = relative(distDir, scriptPath)
++ if (
++ relativePath.startsWith('..') ||
++ // On Windows an absolute path on a different drive is returned unchanged
++ // rather than as a `..`-prefixed relative path.
++ isAbsolute(relativePath)
++ ) {
++ return null
++ }
++
++ // The emitted source map lives next to its chunk with a `.map` suffix (see
++ // `SourceMapAsset::path`). Encode through `pathToFileURL` so any special
++ // characters in the path are escaped into a well-formed `file:` URL.
++ return pathToFileURL(scriptPath + '.map').href
++}
++
+ export async function createHotReloaderTurbopack(
+ opts: SetupOpts & { isSrcDir: boolean },
+ serverFields: ServerFields,
+@@ -410,6 +454,14 @@ export async function createHotReloaderTurbopack(
+ getSourceMapFromTurbopack.bind(null, project)
+ )
+
++ let canonicalDistDir = distDir
++ try {
++ canonicalDistDir = realpathSync(distDir)
++ } catch {}
++ setBundlerFindSourceMapURLImplementation(
++ getSourceMapURLFromTurbopack.bind(null, canonicalDistDir)
++ )
++
+ // Set up code frame renderer using native bindings
+ const { installCodeFrameSupport } =
+ require('../lib/install-code-frame') as typeof import('../lib/install-code-frame')
+@@ -417,6 +469,7 @@ export async function createHotReloaderTurbopack(
+
+ opts.onDevServerCleanup?.(async () => {
+ setBundlerFindSourceMapImplementation(() => undefined)
++ setBundlerFindSourceMapURLImplementation(() => null)
+ await project.onExit()
+ await lockfile?.unlock()
+ })
+diff --git a/packages/next/src/server/lib/source-maps.ts b/packages/next/src/server/lib/source-maps.ts
+index 40b3a2204c..10f8a4880b 100644
+--- a/packages/next/src/server/lib/source-maps.ts
++++ b/packages/next/src/server/lib/source-maps.ts
+@@ -158,6 +158,36 @@ export function filterStackFrameDEV(
+ }
+ }
+
++// `scriptNameOrSourceURL` is what React forwards from the stack frame: the
++// script's `getScriptNameOrSourceURL()`, which for the server chunks we can
++// map is an absolute filesystem path, not a URL. The returned value is the
++// source map's URL (`file:` or `data:`).
++type FindSourceMapURL = (scriptNameOrSourceURL: string) => string | null
++// Find the URL of a source map using the bundler's API.
++// Shared via `globalThis` because this module is compiled both into the server
++// runtime bundles (which call `findSourceMapURLDEV`) and into `next/dist/server`
++// (where the dev server registers the implementation), and each copy has its own
++// module state.
++const bundlerFindSourceMapURLSymbol = Symbol.for(
++ 'next.server.bundlerFindSourceMapURL'
++)
++
++export function setBundlerFindSourceMapURLImplementation(
++ findSourceMapURLImplementation: FindSourceMapURL
++): void {
++ ;(globalThis as any)[bundlerFindSourceMapURLSymbol] =
++ findSourceMapURLImplementation
++}
++
++function bundlerFindSourceMapURL(scriptNameOrSourceURL: string): string | null {
++ const implementation: FindSourceMapURL | undefined = (globalThis as any)[
++ bundlerFindSourceMapURLSymbol
++ ]
++ return implementation === undefined
++ ? null
++ : implementation(scriptNameOrSourceURL)
++}
++
+ const invalidSourceMap = Symbol('invalid-source-map')
+ const sourceMapURLs = new LRUCache(
+ 512 * 1024 * 1024,
+@@ -172,6 +202,19 @@ const sourceMapURLs = new LRUCache(
+ export function findSourceMapURLDEV(
+ scriptNameOrSourceURL: string
+ ): string | null {
++ try {
++ const bundlerSourceMapURL = bundlerFindSourceMapURL(scriptNameOrSourceURL)
++ if (bundlerSourceMapURL !== null) {
++ return bundlerSourceMapURL
++ }
++ } catch (cause) {
++ console.error(
++ `${scriptNameOrSourceURL}: Failed to find the source map URL. Cause: ${cause}`
++ )
++ }
++
++ // No bundler implementation (e.g. Webpack): inline the source map Node.js
++ // knows as a `data:` URL.
+ let sourceMapURL = sourceMapURLs.get(scriptNameOrSourceURL)
+ if (sourceMapURL === undefined) {
+ let sourceMapPayload: ModernSourceMapPayload | undefined
+diff --git a/packages/next/src/server/patch-error-inspect.ts b/packages/next/src/server/patch-error-inspect.ts
+index be16e4727b..2aa0025d1e 100644
+--- a/packages/next/src/server/patch-error-inspect.ts
++++ b/packages/next/src/server/patch-error-inspect.ts
+@@ -181,7 +181,10 @@ function getSourcemappedFrameIfPossible(
+ let sourceMapConsumer: SyncSourceMapConsumer
+ let sourceMapPayload: ModernSourceMapPayload
+ if (sourceMapCacheEntry === undefined) {
+- let sourceURL = frame.file
++ // Fake frame scripts (`about://React/Server/file:///path/to/chunk.js?42`)
++ // have their positions padded to match the underlying chunk, so they
++ // resolve via the chunk's source map.
++ let sourceURL = devirtualizeReactServerURL(frame.file)
+ // e.g. "/Users/foo/APP/.next/server/chunks/ssr/[root-of-the-server]__2934a0._.js"
+ // or "C:\Users\foo\APP\.next\server\chunks\ssr\[root-of-the-server]__2934a0._.js"
+ // will be keyed by Node.js as "file:///APP/.next/server/chunks/ssr/[root-of-the-server]__2934a0._.js".
+@@ -189,8 +192,8 @@ function getSourcemappedFrameIfPossible(
+ //
+ // But frame.file might also be "webpack-internal:///(rsc)/./app/bad-sourcemap/page.js" or
+ // "" or "node:internal/process/task_queues" here
+- if (path.isAbsolute(frame.file)) {
+- sourceURL = url.pathToFileURL(frame.file).toString()
++ if (path.isAbsolute(sourceURL)) {
++ sourceURL = url.pathToFileURL(sourceURL).toString()
+ }
+ let maybeSourceMapPayload: ModernSourceMapPayload | undefined
+ try {
+@@ -228,10 +231,9 @@ function getSourcemappedFrameIfPossible(
+ // is sufficient to compute relative paths but is actually wrong (the
+ // chunk and sourcemap have different content hashes). We are using the
+ // node API to read the sourcemap and it doesn't give us access to the
+- // URI. Devirtualize `about://React/Server/file:///path/to/chunk.js?4` to
+- // `file:///path/to/chunk.js` so that relative `sources` in the source map
+- // resolve against the real chunk URL, not the virtual one.
+- const sourceMapURL = devirtualizeReactServerURL(sourceURL) + '.map'
++ // URI. `sourceURL` is already devirtualized so that relative `sources`
++ // resolve against the real chunk URL, not React's virtual one.
++ const sourceMapURL = sourceURL + '.map'
+ sourceMapConsumer = new SyncSourceMapConsumer(
+ sourceMapPayload,
+ // @ts-expect-error: our typings don't include this parameter but it is here.
diff --git a/nextjs-95946-file-sourcemaps/solution/solve.sh b/nextjs-95946-file-sourcemaps/solution/solve.sh
new file mode 100644
index 0000000000000000000000000000000000000000..b23b1455c5a01d637a3985c89514ac2b453ecec2
--- /dev/null
+++ b/nextjs-95946-file-sourcemaps/solution/solve.sh
@@ -0,0 +1,3 @@
+#!/bin/bash
+set -euo pipefail
+git -C /app apply --binary --whitespace=nowarn /solution/gold.patch
diff --git a/nextjs-95946-file-sourcemaps/tests/Dockerfile b/nextjs-95946-file-sourcemaps/tests/Dockerfile
new file mode 100644
index 0000000000000000000000000000000000000000..4d3094766db897cdab70c85cf0bc39ee0154a31c
--- /dev/null
+++ b/nextjs-95946-file-sourcemaps/tests/Dockerfile
@@ -0,0 +1,42 @@
+FROM ubuntu:24.04
+ENV DEBIAN_FRONTEND=noninteractive \
+ UV_LINK_MODE=copy \
+ UV_CACHE_DIR=/opt/uv-cache \
+ UV_PYTHON_INSTALL_DIR=/usr/local/share/uv/python \
+ UV_PYTHON_BIN_DIR=/usr/local/bin \
+ RUSTUP_HOME=/usr/local/rustup \
+ CARGO_HOME=/usr/local/cargo \
+ COREPACK_HOME=/opt/corepack \
+ PATH=/usr/local/go/bin:/usr/local/cargo/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin
+RUN apt-get update && apt-get install -y --no-install-recommends \
+ bash build-essential ca-certificates curl git jq passwd pkg-config procps unzip xz-utils \
+ && rm -rf /var/lib/apt/lists/*
+ENV PLAYWRIGHT_BROWSERS_PATH=/opt/playwright
+RUN mkdir -p "$PLAYWRIGHT_BROWSERS_PATH" && chmod 755 "$PLAYWRIGHT_BROWSERS_PATH" \
+ && arch="$(dpkg --print-architecture)" && case "$arch" in arm64) node_arch=arm64 ;; amd64) node_arch=x64 ;; *) exit 1 ;; esac \
+ && curl -fsSL "https://nodejs.org/dist/v22.14.0/node-v22.14.0-linux-${node_arch}.tar.xz" | tar -C /usr/local --strip-components=1 -xJ \
+ && mkdir -p /opt/corepack && chmod 755 /opt/corepack \
+ && corepack enable
+COPY repo.tar.gz /tmp/repo.tar.gz
+RUN mkdir -p /app && tar -xzf /tmp/repo.tar.gz -C /app && rm /tmp/repo.tar.gz \
+ && git -C /app init -q \
+ && git -C /app config user.email selfbench@local \
+ && git -C /app config user.name selfbench \
+ && git -C /app add -A \
+ && git -C /app commit -qm base
+RUN mkdir -p /opt/uv-cache && chmod 777 /opt/uv-cache \
+ && cd '/app/.' \
+ && bash -lc 'corepack enable && NEXT_SKIP_NATIVE_POSTINSTALL=0 pnpm install --frozen-lockfile && pnpm build && pnpm exec playwright install --with-deps chromium' \
+ && chmod -R a+rwX /opt/uv-cache
+
+RUN useradd --create-home --shell /bin/bash verifier \
+ && chown -R verifier:verifier /app /opt/uv-cache \
+ && mkdir -p /opt/selfbench \
+ && chmod 700 /opt/selfbench \
+ && mkdir -p /home/verifier/.cache/uv \
+ && chown -R verifier:verifier /home/verifier/.cache
+ENV UV_CACHE_DIR=/home/verifier/.cache/uv \
+ UV_NO_BUILD_ISOLATION=1
+COPY test.patch test.sh /tests/
+RUN chmod 700 /tests && chmod 600 /tests/test.patch && chmod +x /tests/test.sh
+WORKDIR /app
diff --git a/nextjs-95946-file-sourcemaps/tests/test.patch b/nextjs-95946-file-sourcemaps/tests/test.patch
new file mode 100644
index 0000000000000000000000000000000000000000..ae6221b7668454679bd2ec101ac9939e7de1fae1
--- /dev/null
+++ b/nextjs-95946-file-sourcemaps/tests/test.patch
@@ -0,0 +1,115 @@
+diff --git a/test/e2e/app-dir/server-source-maps/fake-frame-source-maps.test.ts b/test/e2e/app-dir/server-source-maps/fake-frame-source-maps.test.ts
+index be03cedc70..f59cd54945 100644
+--- a/test/e2e/app-dir/server-source-maps/fake-frame-source-maps.test.ts
++++ b/test/e2e/app-dir/server-source-maps/fake-frame-source-maps.test.ts
+@@ -229,6 +229,21 @@ describe('app-dir - server source maps - fake frame source maps', () => {
+ }).toEqual({ url: script.url, hasSourceMap: true })
+ }
+
++ if (isTurbopack) {
++ // The resolver silently falls back to inlining `data:` URLs, so a
++ // defect in the `file:` URL derivation keeps all behavior-based
++ // assertions green. Only this assertion catches it.
++ for (const script of fakeScripts) {
++ expect({
++ url: script.url,
++ sourceMapURL: script.sourceMapURL,
++ }).toEqual({
++ url: script.url,
++ sourceMapURL: expect.stringMatching(/^file:/),
++ })
++ }
++ }
++
+ // Resolve each source map like a debugger frontend and map the
+ // padded `_()` call position of each fake function back to its
+ // original source, like clicking the frame in a debugger would.
+@@ -282,6 +297,88 @@ describe('app-dir - server source maps - fake frame source maps', () => {
+ session.close()
+ }
+ })
++
++ it('fake stack frames from nested Flight requests are resolvable by an attached debugger', async () => {
++ // Rendering this page produces fake frame scripts whose frame
++ // filenames are `file:` URLs rather than file paths.
++ await next.render('/rsc-error-throw-cached')
++
++ const target = await findServerInspectorTarget()
++ const session = await CDPSession.connect(target.webSocketDebuggerUrl)
++ try {
++ const evalScripts: {
++ scriptId: string
++ url: string
++ sourceMapURL: string
++ }[] = []
++ session.onEvent = (method, params) => {
++ if (method === 'Debugger.scriptParsed' && params.hasSourceURL) {
++ evalScripts.push({
++ scriptId: params.scriptId,
++ url: params.url,
++ sourceMapURL: params.sourceMapURL ?? '',
++ })
++ }
++ }
++ await session.send('Debugger.enable', { maxScriptsCacheSize: 1 })
++
++ await retry(async () => {
++ expect(
++ evalScripts.filter((script) =>
++ script.url.startsWith('about://React/Cache/')
++ ).length
++ ).toBeGreaterThan(0)
++ })
++
++ // React emits a fake frame script under `about://React/` with a
++ // source map, or, when no source map could be found for it, under
++ // the frame's raw filename without one.
++ const fakeScripts = evalScripts.filter(
++ (script) =>
++ script.url.startsWith('about://React/') ||
++ (script.url.startsWith('file:') && script.sourceMapURL === '')
++ )
++ const mappedSources = new Set()
++ for (const script of fakeScripts) {
++ expect({
++ url: script.url,
++ hasSourceMap: script.sourceMapURL !== '',
++ }).toEqual({ url: script.url, hasSourceMap: true })
++
++ const { sourceMap, mapURL } = await resolveSourceMapLikeADebugger(
++ session,
++ script.url,
++ script.sourceMapURL
++ )
++ const { scriptSource } = await session.send(
++ 'Debugger.getScriptSource',
++ { scriptId: script.scriptId }
++ )
++ const callIndex = scriptSource.indexOf('_()')
++ if (callIndex === -1) continue
++ const line = scriptSource.slice(0, callIndex).split('\n').length
++ const column =
++ callIndex - (scriptSource.lastIndexOf('\n', callIndex) + 1)
++
++ const consumer = new SourceMap(sourceMap)
++ const original = consumer.findEntry(line - 1, column)
++ if (original.originalSource !== undefined) {
++ mappedSources.add(
++ mapURL === null
++ ? original.originalSource
++ : new URL(original.originalSource, mapURL).href
++ )
++ }
++ }
++
++ const testDirURL = url.pathToFileURL(fs.realpathSync(next.testDir))
++ expect([...mappedSources]).toContain(
++ `${testDirURL.href}/app/rsc-error-throw-cached/page.js`
++ )
++ } finally {
++ session.close()
++ }
++ })
+ } else {
+ it('server chunk source maps are resolvable by an attached debugger', async () => {
+ await next.render('/rsc-error-log')
diff --git a/nextjs-95946-file-sourcemaps/tests/test.sh b/nextjs-95946-file-sourcemaps/tests/test.sh
new file mode 100644
index 0000000000000000000000000000000000000000..b021c4146205395faf19341f6423c78ef283c45e
--- /dev/null
+++ b/nextjs-95946-file-sourcemaps/tests/test.sh
@@ -0,0 +1,98 @@
+#!/bin/bash
+set -uo pipefail
+mkdir -p /logs/verifier
+patch_applied=1
+fail_to_pass=0
+pass_to_pass=0
+deterministic=0
+setup_completed=0
+fail_to_pass_exit_code=-1
+fail_to_pass_repeat_exit_code=-1
+pass_to_pass_exit_code=-1
+verifier_cache=""
+
+kill_verifier_processes() { pkill -KILL -u "$(id -u verifier)" 2>/dev/null || true; }
+# Some toolchains fetch dependencies at test runtime (e.g. Next.js e2e installs),
+# so a single registry connection reset must not be misread as a dead test. Retry
+# only infrastructure-style failures with backoff; real assertion failures fail fast.
+run_verifier_command() {
+ local logfile
+ logfile="$(mktemp /tmp/selfbench-verifier-command-XXXXXX.log)"
+ local attempt=1
+ local status=1
+ while [ "$attempt" -le 3 ]; do
+ : > "$logfile"
+ runuser -u verifier -- env PATH="/usr/local/go/bin:/usr/local/cargo/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin" UV_CACHE_DIR="$verifier_cache" UV_NO_BUILD_ISOLATION=1 bash -lc "$1" >"$logfile" 2>&1
+ status=$?
+ if [ "$status" -eq 0 ]; then
+ break
+ fi
+ if [ "$attempt" -lt 3 ] && grep -qE 'ECONNRESET|ETIMEDOUT|ESOCKETTIMEDOUT|ENOTFOUND|EAI_AGAIN|META_FETCH_FAIL|FetchError|EPIPE|EPERM|registry\.npmjs' "$logfile"; then
+ sleep "$((10 * attempt))"
+ attempt=$((attempt + 1))
+ continue
+ fi
+ break
+ done
+ cat "$logfile"
+ rm -f "$logfile"
+ kill_verifier_processes
+ return "$status"
+}
+protect_held_out_path() {
+ local path="$1"
+ chown -R root:root -- "$path"
+ chmod -R a-w,go+rX -- "$path"
+}
+
+if [ ! -f /opt/selfbench/agent.patch ]; then
+ patch_applied=0
+elif [ -s /opt/selfbench/agent.patch ]; then
+ git -C /app apply --binary --whitespace=nowarn --exclude='test/e2e/app-dir/server-source-maps/fake-frame-source-maps.test.ts' --exclude='test/e2e/app-dir/server-source-maps/fake-frame-source-maps.test.ts/*' /opt/selfbench/agent.patch || patch_applied=0
+fi
+
+if [ "$patch_applied" -eq 1 ]; then setup_completed=1; fi
+
+if [ "$patch_applied" -eq 1 ] && [ "$setup_completed" -eq 1 ]; then
+ kill_verifier_processes
+ git -C /app restore --source=HEAD --staged --worktree -- 'test/e2e/app-dir/server-source-maps/fake-frame-source-maps.test.ts' 2>/dev/null || true
+ git -C /app clean -fd -- 'test/e2e/app-dir/server-source-maps/fake-frame-source-maps.test.ts' >/dev/null 2>&1 || true
+ git -C /app apply --binary --whitespace=nowarn /tests/test.patch || patch_applied=0
+ if [ "$patch_applied" -eq 1 ]; then
+ for protected_path in '/app/test/e2e/app-dir/server-source-maps/fake-frame-source-maps.test.ts'; do protect_held_out_path "$protected_path"; done
+ fi
+ rm -f /tests/test.patch
+fi
+
+if [ "$patch_applied" -eq 1 ] && [ "$setup_completed" -eq 1 ]; then
+ cd '/app/.'
+ verifier_cache="$(mktemp -d /tmp/selfbench-verifier-uv-XXXXXX)"
+ cp -a /opt/uv-cache/. "$verifier_cache"/
+ chown -R verifier:verifier "$verifier_cache"
+ if run_verifier_command 'pnpm build && pnpm test-dev-turbo '"'"'test/e2e/app-dir/server-source-maps/fake-frame-source-maps.test.ts'"'"''; then
+ fail_to_pass_exit_code=0
+ fail_to_pass=1
+ if run_verifier_command 'pnpm build && pnpm test-dev-turbo '"'"'test/e2e/app-dir/server-source-maps/fake-frame-source-maps.test.ts'"'"''; then
+ fail_to_pass_repeat_exit_code=0
+ deterministic=1
+ else
+ fail_to_pass_repeat_exit_code=$?
+ fi
+ else
+ fail_to_pass_exit_code=$?
+ fi
+ if run_verifier_command 'pnpm build && pnpm test-dev-turbo '"'"'test/e2e/app-dir/server-source-maps/server-source-maps.test.ts'"'"' '"'"'test/e2e/app-dir/server-source-maps/server-source-maps-edge.test.ts'"'"''; then
+ pass_to_pass_exit_code=0
+ pass_to_pass=1
+ else
+ pass_to_pass_exit_code=$?
+ fi
+ rm -rf "$verifier_cache"
+fi
+
+reward=0
+if [ "$patch_applied" -eq 1 ] && [ "$fail_to_pass" -eq 1 ] && [ "$pass_to_pass" -eq 1 ] && [ "$deterministic" -eq 1 ]; then reward=1; fi
+cat > /logs/verifier/reward.json <\` prevents the route from being prerendered, blocking the page load and leading to a slower user experience.\n\n` +
+ `Ways to fix this:\n` +
+ ` - [stream] Provide a placeholder with \`\` around the data access\n` +
+- ` https://nextjs.org/docs/messages/blocking-prerender-runtime#wrap-in-or-move-into-suspense\n` +
+- ` - [block] Set \`export const instant = false\` to allow a blocking route\n` +
+- ` https://nextjs.org/docs/messages/blocking-prerender-runtime#allow-blocking-route`
++ ` - [block] Set \`export const instant = false\` to allow a blocking route\n\n` +
++ `Learn more: https://nextjs.org/docs/messages/blocking-prerender-runtime`
+ )
+ }
+
+@@ -16,11 +15,9 @@ export function createDynamicBodyError(route: string): Error {
+ `\`fetch(...)\` or \`connection()\` accessed outside of \`\` prevents the route from being prerendered, blocking the page load and leading to a slower user experience.\n\n` +
+ `Ways to fix this:\n` +
+ ` - [stream] Provide a placeholder with \`\` around the data access\n` +
+- ` https://nextjs.org/docs/messages/blocking-prerender-dynamic#wrap-in-or-move-into-suspense\n` +
+ ` - [cache] Cache the data access with \`"use cache"\` (does not apply to \`connection()\`)\n` +
+- ` https://nextjs.org/docs/messages/blocking-prerender-dynamic#cache-the-component-or-data\n` +
+- ` - [block] Set \`export const instant = false\` to allow a blocking route\n` +
+- ` https://nextjs.org/docs/messages/blocking-prerender-dynamic#allow-blocking-route`
++ ` - [block] Set \`export const instant = false\` to allow a blocking route\n\n` +
++ `Learn more: https://nextjs.org/docs/messages/blocking-prerender-dynamic`
+ )
+ }
+
+@@ -30,9 +27,8 @@ export function createRuntimeBodyErrorInNavigation(route: string): Error {
+ `\`cookies()\`, \`headers()\`, \`params\`, or \`searchParams\` accessed outside of \`\` prevents the route from being prerendered or the navigation from being instant, leading to a slower user experience.\n\n` +
+ `Ways to fix this:\n` +
+ ` - [stream] Provide a placeholder with \`\` around the data access\n` +
+- ` https://nextjs.org/docs/messages/blocking-prerender-runtime#wrap-in-or-move-into-suspense\n` +
+- ` - [block] Set \`export const instant = false\` to allow a blocking route\n` +
+- ` https://nextjs.org/docs/messages/blocking-prerender-runtime#allow-blocking-route`
++ ` - [block] Set \`export const instant = false\` to allow a blocking route\n\n` +
++ `Learn more: https://nextjs.org/docs/messages/blocking-prerender-runtime`
+ )
+ }
+
+@@ -42,9 +38,8 @@ export function createLinkBodyErrorInNavigation(route: string): Error {
+ `\`params\` or \`searchParams\` accessed outside of \`\` may prevent the navigation from being instant, leading to a slower user experience.\n\n` +
+ `Ways to fix this:\n` +
+ ` - [stream] Provide a placeholder with \`\` around the data access\n` +
+- ` https://nextjs.org/docs/messages/instant-shell-url-data#wrap-in-or-move-into-suspense\n` +
+- ` - [block] Set \`export const instant = false\` to allow a blocking route\n` +
+- ` https://nextjs.org/docs/messages/instant-shell-url-data#allow-blocking-route`
++ ` - [block] Set \`export const instant = false\` to allow a blocking route\n\n` +
++ `Learn more: https://nextjs.org/docs/messages/instant-shell-url-data`
+ )
+ }
+
+@@ -54,11 +49,9 @@ export function createDynamicBodyErrorInNavigation(route: string): Error {
+ `\`fetch(...)\` or \`connection()\` accessed outside of \`\` prevents the route from being prerendered or the navigation from being instant, leading to a slower user experience.\n\n` +
+ `Ways to fix this:\n` +
+ ` - [stream] Provide a placeholder with \`\` around the data access\n` +
+- ` https://nextjs.org/docs/messages/blocking-prerender-dynamic#wrap-in-or-move-into-suspense\n` +
+ ` - [cache] Cache the data access with \`"use cache"\` (does not apply to \`connection()\`)\n` +
+- ` https://nextjs.org/docs/messages/blocking-prerender-dynamic#cache-the-component-or-data\n` +
+- ` - [block] Set \`export const instant = false\` to allow a blocking route\n` +
+- ` https://nextjs.org/docs/messages/blocking-prerender-dynamic#allow-blocking-route`
++ ` - [block] Set \`export const instant = false\` to allow a blocking route\n\n` +
++ `Learn more: https://nextjs.org/docs/messages/blocking-prerender-dynamic`
+ )
+ }
+
+@@ -73,11 +66,9 @@ export function createDynamicOrRuntimeBodyError(route: string): Error {
+ `\`fetch(...)\`, \`cookies()\`, \`headers()\`, \`params\`, \`searchParams\`, or \`connection()\` accessed outside of \`\` prevents the route from being prerendered, blocking the page load and leading to a slower user experience.\n\n` +
+ `Ways to fix this:\n` +
+ ` - [stream] Provide a placeholder with \`\` around the data access\n` +
+- ` https://nextjs.org/docs/messages/blocking-prerender-dynamic#wrap-in-or-move-into-suspense\n` +
+ ` - [cache] For uncached data (\`fetch\`, database calls): cache the access with \`"use cache"\` (does not apply to \`connection()\`)\n` +
+- ` https://nextjs.org/docs/messages/blocking-prerender-dynamic#cache-the-component-or-data\n` +
+- ` - [block] Set \`export const instant = false\` to allow a blocking route\n` +
+- ` https://nextjs.org/docs/messages/blocking-prerender-dynamic#allow-blocking-route`
++ ` - [block] Set \`export const instant = false\` to allow a blocking route\n\n` +
++ `Learn more: https://nextjs.org/docs/messages/blocking-prerender-dynamic`
+ )
+ }
+
+@@ -87,9 +78,8 @@ export function createLinkMetadataError(route: string): Error {
+ `This route's metadata is blocked, but the rest of its content can be prefetched. \`params\` or \`searchParams\` accessed in \`generateMetadata()\` prevent it from being prefetched.\n\n` +
+ `Ways to fix this:\n` +
+ ` - [static] Use a static metadata export instead of \`generateMetadata()\`\n` +
+- ` https://nextjs.org/docs/messages/blocking-prerender-metadata-runtime#use-static-metadata\n` +
+- ` - [dynamic] Render a marker component that calls \`await connection()\` inside \`\` on the page\n` +
+- ` https://nextjs.org/docs/messages/blocking-prerender-metadata-runtime#mark-the-route-as-dynamic`
++ ` - [dynamic] Render a marker component that calls \`await connection()\` inside \`\` on the page\n\n` +
++ `Learn more: https://nextjs.org/docs/messages/blocking-prerender-metadata-runtime`
+ )
+ }
+
+@@ -99,9 +89,8 @@ export function createRuntimeMetadataError(route: string): Error {
+ `This route's metadata is blocked, but the rest of its content can be prerendered. \`cookies()\`, \`headers()\`, \`params\`, or \`searchParams\` accessed in \`generateMetadata()\` cause it to run dynamically.\n\n` +
+ `Ways to fix this:\n` +
+ ` - [static] Use a static metadata export instead of \`generateMetadata()\`\n` +
+- ` https://nextjs.org/docs/messages/blocking-prerender-metadata-runtime#use-static-metadata\n` +
+- ` - [dynamic] Render a marker component that calls \`await connection()\` inside \`\` on the page\n` +
+- ` https://nextjs.org/docs/messages/blocking-prerender-metadata-runtime#mark-the-route-as-dynamic`
++ ` - [dynamic] Render a marker component that calls \`await connection()\` inside \`\` on the page\n\n` +
++ `Learn more: https://nextjs.org/docs/messages/blocking-prerender-metadata-runtime`
+ )
+ }
+
+@@ -111,9 +100,8 @@ export function createDynamicMetadataError(route: string): Error {
+ `This route's metadata is blocked, but the rest of its content can be prerendered. \`fetch(...)\` or \`connection()\` accessed in \`generateMetadata()\` cause it to run dynamically.\n\n` +
+ `Ways to fix this:\n` +
+ ` - [cache] Cache the metadata with \`"use cache"\` in \`generateMetadata()\` (does not apply to \`connection()\`)\n` +
+- ` https://nextjs.org/docs/messages/blocking-prerender-metadata-dynamic#cache-the-metadata\n` +
+- ` - [dynamic] Render a marker component that calls \`await connection()\` inside \`\` on the page\n` +
+- ` https://nextjs.org/docs/messages/blocking-prerender-metadata-dynamic#mark-the-route-as-dynamic`
++ ` - [dynamic] Render a marker component that calls \`await connection()\` inside \`\` on the page\n\n` +
++ `Learn more: https://nextjs.org/docs/messages/blocking-prerender-metadata-dynamic`
+ )
+ }
+
+@@ -123,9 +111,8 @@ export function createLinkViewportError(route: string): Error {
+ `\`params\` or \`searchParams\` in \`generateViewport()\` prevents the page from being prerendered, leading to a slower user experience.\n\n` +
+ `Ways to fix this:\n` +
+ ` - [static] Use a static viewport export instead of \`generateViewport()\`\n` +
+- ` https://nextjs.org/docs/messages/blocking-prerender-viewport-runtime#use-static-viewport\n` +
+- ` - [block] Set \`export const instant = false\` to allow a blocking route\n` +
+- ` https://nextjs.org/docs/messages/blocking-prerender-viewport-runtime#allow-blocking-route`
++ ` - [block] Set \`export const instant = false\` to allow a blocking route\n\n` +
++ `Learn more: https://nextjs.org/docs/messages/blocking-prerender-viewport-runtime`
+ )
+ }
+
+@@ -135,9 +122,8 @@ export function createRuntimeViewportError(route: string): Error {
+ `\`cookies()\`, \`headers()\`, \`params\`, or \`searchParams\` in \`generateViewport()\` prevents the page from being prerendered, leading to a slower user experience.\n\n` +
+ `Ways to fix this:\n` +
+ ` - [static] Use a static viewport export instead of \`generateViewport()\`\n` +
+- ` https://nextjs.org/docs/messages/blocking-prerender-viewport-runtime#use-static-viewport\n` +
+- ` - [block] Set \`export const instant = false\` to allow a blocking route\n` +
+- ` https://nextjs.org/docs/messages/blocking-prerender-viewport-runtime#allow-blocking-route`
++ ` - [block] Set \`export const instant = false\` to allow a blocking route\n\n` +
++ `Learn more: https://nextjs.org/docs/messages/blocking-prerender-viewport-runtime`
+ )
+ }
+
+@@ -147,9 +133,8 @@ export function createDynamicViewportError(route: string): Error {
+ `\`fetch(...)\` or \`connection()\` in \`generateViewport()\` prevents the page from being prerendered, leading to a slower user experience.\n\n` +
+ `Ways to fix this:\n` +
+ ` - [cache] Cache the viewport data with \`"use cache"\` in \`generateViewport()\` (does not apply to \`connection()\`)\n` +
+- ` https://nextjs.org/docs/messages/blocking-prerender-viewport-dynamic#cache-the-viewport-data\n` +
+- ` - [block] Set \`export const instant = false\` to allow a blocking route\n` +
+- ` https://nextjs.org/docs/messages/blocking-prerender-viewport-dynamic#allow-blocking-route`
++ ` - [block] Set \`export const instant = false\` to allow a blocking route\n\n` +
++ `Learn more: https://nextjs.org/docs/messages/blocking-prerender-viewport-dynamic`
+ )
+ }
+
+@@ -164,11 +149,9 @@ export function createDynamicOrRuntimeViewportError(route: string): Error {
+ `This prevents the page from being prerendered, leading to a slower user experience. Unlike metadata, viewport cannot be streamed behind \`\` because it affects the initial page load.\n\n` +
+ `Ways to fix this:\n` +
+ ` - [static] Use a static viewport export instead of \`generateViewport()\`\n` +
+- ` https://nextjs.org/docs/messages/blocking-prerender-viewport-runtime#use-static-viewport\n` +
+ ` - [cache] For uncached data (\`fetch\`, database calls): cache the viewport with \`"use cache"\` in \`generateViewport()\` (does not apply to \`connection()\`)\n` +
+- ` https://nextjs.org/docs/messages/blocking-prerender-viewport-dynamic#cache-the-viewport-data\n` +
+- ` - [block] Set \`export const instant = false\` to allow a blocking route\n` +
+- ` https://nextjs.org/docs/messages/blocking-prerender-viewport-dynamic#allow-blocking-route`
++ ` - [block] Set \`export const instant = false\` to allow a blocking route\n\n` +
++ `Learn more: https://nextjs.org/docs/messages/blocking-prerender-viewport-runtime`
+ )
+ }
+
+@@ -183,11 +166,9 @@ export function createDynamicOrRuntimeMetadataError(route: string): Error {
+ `This route's metadata is blocked, but the rest of its content can be prerendered.\n\n` +
+ `Ways to fix this:\n` +
+ ` - [static] Use a static metadata export instead of \`generateMetadata()\`\n` +
+- ` https://nextjs.org/docs/messages/blocking-prerender-metadata-runtime#use-static-metadata\n` +
+ ` - [cache] Cache the metadata with \`"use cache"\` in \`generateMetadata()\` (does not apply to \`connection()\`)\n` +
+- ` https://nextjs.org/docs/messages/blocking-prerender-metadata-dynamic#cache-the-metadata\n` +
+- ` - [dynamic] Render a marker component that calls \`await connection()\` inside \`\` on the page\n` +
+- ` https://nextjs.org/docs/messages/blocking-prerender-metadata-dynamic#mark-the-route-as-dynamic`
++ ` - [dynamic] Render a marker component that calls \`await connection()\` inside \`\` on the page\n\n` +
++ `Learn more: https://nextjs.org/docs/messages/blocking-prerender-metadata-runtime`
+ )
+ }
+
+diff --git a/packages/next/src/server/app-render/sync-io-messages.ts b/packages/next/src/server/app-render/sync-io-messages.ts
+index d65037c58d..b41ef8e909 100644
+--- a/packages/next/src/server/app-render/sync-io-messages.ts
++++ b/packages/next/src/server/app-render/sync-io-messages.ts
+@@ -18,18 +18,12 @@ const SYNC_IO_RUNTIME_DOCS: Record = {
+ crypto: 'https://nextjs.org/docs/messages/blocking-prerender-crypto',
+ }
+
+-function elapsedTimeBullet(type: SyncIOApiType, docsUrl: string): string {
++function elapsedTimeBullet(type: SyncIOApiType): string {
+ return type === 'time'
+- ? `\n - [measure] If the value is for telemetry, use a timing API such as \`performance.now()\`\n ${docsUrl}#for-telemetry-use-a-timing-api`
++ ? `\n - [measure] If the value is for telemetry, use a timing API such as \`performance.now()\``
+ : ''
+ }
+
+-const CACHE_ANCHOR: Record = {
+- random: '#cache-the-random-value',
+- time: '#cache-the-timestamp',
+- crypto: '#cache-the-generated-value',
+-}
+-
+ function createSyncIOErrorImpl(
+ route: string,
+ expression: string,
+@@ -40,10 +34,11 @@ function createSyncIOErrorImpl(
+ `Route "${route}": Next.js encountered the unstable value ${expression} while prerendering.\n\n` +
+ `This value can change between renders, so it must be either prerendered or computed later.\n\n` +
+ `Ways to fix this:\n` +
+- ` - [dynamic] Render at request time by adding a dynamic data access (e.g. \`await connection()\`) before this call\n ${docsUrl}#generate-on-every-request\n` +
+- ` - [cache] Prerender and cache the value with \`"use cache"\`\n ${docsUrl}${CACHE_ANCHOR[type]}\n` +
+- ` - [client] Render the value on the client with \`"use client"\`\n ${docsUrl}#render-on-the-client` +
+- elapsedTimeBullet(type, docsUrl)
++ ` - [dynamic] Render at request time by adding a dynamic data access (e.g. \`await connection()\`) before this call\n` +
++ ` - [cache] Prerender and cache the value with \`"use cache"\`\n` +
++ ` - [client] Render the value on the client with \`"use client"\`` +
++ elapsedTimeBullet(type) +
++ `\n\nLearn more: ${docsUrl}`
+ )
+ }
+
+@@ -78,8 +73,9 @@ export function createSyncIOClientError(
+ `Route "${route}": Next.js encountered the unstable value ${expression} in a Client Component.\n\n` +
+ `This value would be evaluated during the prerender, instead of recomputed on each visit.\n\n` +
+ `Ways to fix this:\n` +
+- ` - [stream] Wrap the Client Component in \`\`\n ${docsUrl}#wrap-in-or-move-into-suspense\n` +
+- ` - [defer] Move the read into a \`useEffect\` or event handler\n ${docsUrl}#move-into-effect-or-event-handler` +
+- elapsedTimeBullet(type, docsUrl)
++ ` - [stream] Wrap the Client Component in \`\`\n` +
++ ` - [defer] Move the read into a \`useEffect\` or event handler` +
++ elapsedTimeBullet(type) +
++ `\n\nLearn more: ${docsUrl}`
+ )
+ }
+diff --git a/packages/next/src/server/dynamic-rendering-utils.ts b/packages/next/src/server/dynamic-rendering-utils.ts
+index 4158512e7f..91dcb37339 100644
+--- a/packages/next/src/server/dynamic-rendering-utils.ts
++++ b/packages/next/src/server/dynamic-rendering-utils.ts
+@@ -42,9 +42,8 @@ export class ClientHookDynamicError extends Error {
+ `This blocks prerendering because the value is only available at runtime.\n\n` +
+ `Ways to fix this:\n` +
+ ` - [stream] Wrap the component in \`\` so the hook value streams in after prerendering\n` +
+- ` https://nextjs.org/docs/messages/blocking-prerender-client-hook#wrap-in-or-move-into-suspense\n` +
+- ` - [block] Set \`export const instant = false\` to allow a blocking route\n` +
+- ` https://nextjs.org/docs/messages/blocking-prerender-client-hook#allow-blocking-route`
++ ` - [block] Set \`export const instant = false\` to allow a blocking route\n\n` +
++ `Learn more: https://nextjs.org/docs/messages/blocking-prerender-client-hook`
+ )
+ }
+ }
+diff --git a/packages/next/src/shared/lib/instant-messages.ts b/packages/next/src/shared/lib/instant-messages.ts
+index b53b6a41ac..ce620c8738 100644
+--- a/packages/next/src/shared/lib/instant-messages.ts
++++ b/packages/next/src/shared/lib/instant-messages.ts
+@@ -11,9 +11,8 @@ export function createUnrenderedSegmentError(
+ `\n\n${label}:\n${missingFiles.map((p) => ` ${p}`).join('\n')}` +
+ `\n\nWays to fix this:` +
+ `\n - [render] Render the dropped segment` +
+- `\n https://nextjs.org/docs/messages/instant-unrendered-segment#render-the-dropped-segment` +
+ `\n - [ignore] Set \`export const instant = false\` to opt the dropped segment out of instant-navigation validation` +
+- `\n https://nextjs.org/docs/messages/instant-unrendered-segment#skip-validation-on-the-segment`
++ `\n\nLearn more: https://nextjs.org/docs/messages/instant-unrendered-segment`
+ }
+ return new Error(message)
+ }
+@@ -24,10 +23,8 @@ export function createLinkPrefetchPartialError(pathname: string): Error {
+ `This will lead to slower, more expensive prefetches.\n\n` +
+ `Ways to fix this:\n` +
+ ` - [upgrade] Opt into Partial Prefetching by exporting \`const prefetch = 'partial'\` from the page or layout, or by setting \`partialPrefetching: true\` in next.config to opt the whole app in\n` +
+- ` https://nextjs.org/docs/messages/instant-link-prefetch-partial#opt-into-partial-prefetching\n` +
+ ` - [disable] Remove \`prefetch={true}\` from the to use the default prefetch\n` +
+- ` https://nextjs.org/docs/messages/instant-link-prefetch-partial#use-the-default-prefetch\n` +
+- ` - [ignore] Set \`export const instant = false\` to opt the route out of instant-navigation validation\n` +
+- ` https://nextjs.org/docs/messages/instant-link-prefetch-partial#disable-validation-on-this-route`
++ ` - [ignore] Set \`export const instant = false\` to opt the route out of instant-navigation validation\n\n` +
++ `Learn more: https://nextjs.org/docs/messages/instant-link-prefetch-partial`
+ )
+ }
diff --git a/nextjs-95967-single-learn-more-links/solution/solve.sh b/nextjs-95967-single-learn-more-links/solution/solve.sh
new file mode 100644
index 0000000000000000000000000000000000000000..b23b1455c5a01d637a3985c89514ac2b453ecec2
--- /dev/null
+++ b/nextjs-95967-single-learn-more-links/solution/solve.sh
@@ -0,0 +1,3 @@
+#!/bin/bash
+set -euo pipefail
+git -C /app apply --binary --whitespace=nowarn /solution/gold.patch
diff --git a/nextjs-95967-single-learn-more-links/tests/Dockerfile b/nextjs-95967-single-learn-more-links/tests/Dockerfile
new file mode 100644
index 0000000000000000000000000000000000000000..80cb80920a7fe03f31f0c54cff60488cefbcf8c0
--- /dev/null
+++ b/nextjs-95967-single-learn-more-links/tests/Dockerfile
@@ -0,0 +1,42 @@
+FROM ubuntu:24.04
+ENV DEBIAN_FRONTEND=noninteractive \
+ UV_LINK_MODE=copy \
+ UV_CACHE_DIR=/opt/uv-cache \
+ UV_PYTHON_INSTALL_DIR=/usr/local/share/uv/python \
+ UV_PYTHON_BIN_DIR=/usr/local/bin \
+ RUSTUP_HOME=/usr/local/rustup \
+ CARGO_HOME=/usr/local/cargo \
+ COREPACK_HOME=/opt/corepack \
+ PATH=/usr/local/go/bin:/usr/local/cargo/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin
+RUN apt-get update && apt-get install -y --no-install-recommends \
+ bash build-essential ca-certificates curl git jq passwd pkg-config procps unzip xz-utils \
+ && rm -rf /var/lib/apt/lists/*
+ENV PLAYWRIGHT_BROWSERS_PATH=/opt/playwright
+RUN mkdir -p "$PLAYWRIGHT_BROWSERS_PATH" && chmod 755 "$PLAYWRIGHT_BROWSERS_PATH" \
+ && arch="$(dpkg --print-architecture)" && case "$arch" in arm64) node_arch=arm64 ;; amd64) node_arch=x64 ;; *) exit 1 ;; esac \
+ && curl -fsSL "https://nodejs.org/dist/v22.14.0/node-v22.14.0-linux-${node_arch}.tar.xz" | tar -C /usr/local --strip-components=1 -xJ \
+ && mkdir -p /opt/corepack && chmod 755 /opt/corepack \
+ && corepack enable
+COPY repo.tar.gz /tmp/repo.tar.gz
+RUN mkdir -p /app && tar -xzf /tmp/repo.tar.gz -C /app && rm /tmp/repo.tar.gz \
+ && git -C /app init -q \
+ && git -C /app config user.email selfbench@local \
+ && git -C /app config user.name selfbench \
+ && git -C /app add -A \
+ && git -C /app commit -qm base
+RUN mkdir -p /opt/uv-cache && chmod 777 /opt/uv-cache \
+ && cd '/app/.' \
+ && bash -lc 'corepack enable && corepack prepare pnpm@10.33.0 --activate && pnpm install --frozen-lockfile && pnpm build --filter=next' \
+ && chmod -R a+rwX /opt/uv-cache
+
+RUN useradd --create-home --shell /bin/bash verifier \
+ && chown -R verifier:verifier /app /opt/uv-cache \
+ && mkdir -p /opt/selfbench \
+ && chmod 700 /opt/selfbench \
+ && mkdir -p /home/verifier/.cache/uv \
+ && chown -R verifier:verifier /home/verifier/.cache
+ENV UV_CACHE_DIR=/home/verifier/.cache/uv \
+ UV_NO_BUILD_ISOLATION=1
+COPY test.patch test.sh /tests/
+RUN chmod 700 /tests && chmod 600 /tests/test.patch && chmod +x /tests/test.sh
+WORKDIR /app
diff --git a/nextjs-95967-single-learn-more-links/tests/test.patch b/nextjs-95967-single-learn-more-links/tests/test.patch
new file mode 100644
index 0000000000000000000000000000000000000000..ca5cccff46f6496a39cd46f9ad76c0e62d0c9aa5
--- /dev/null
+++ b/nextjs-95967-single-learn-more-links/tests/test.patch
@@ -0,0 +1,276 @@
+diff --git a/packages/next/src/next-devtools/dev-overlay/container/insight-console-messages.test.ts b/packages/next/src/next-devtools/dev-overlay/container/insight-console-messages.test.ts
+new file mode 100644
+index 00000000..5b889dba
+--- /dev/null
++++ b/packages/next/src/next-devtools/dev-overlay/container/insight-console-messages.test.ts
+@@ -0,0 +1,270 @@
++import {
++ createDynamicBodyError,
++ createDynamicBodyErrorInNavigation,
++ createDynamicMetadataError,
++ createDynamicOrRuntimeBodyError,
++ createDynamicOrRuntimeMetadataError,
++ createDynamicOrRuntimeViewportError,
++ createDynamicViewportError,
++ createLinkBodyErrorInNavigation,
++ createLinkMetadataError,
++ createLinkViewportError,
++ createRuntimeBodyError,
++ createRuntimeBodyErrorInNavigation,
++ createRuntimeMetadataError,
++ createRuntimeViewportError,
++} from '../../../server/app-render/blocking-route-messages'
++import {
++ createSyncIOClientError,
++ createSyncIOError,
++ createSyncIORuntimeError,
++ type SyncIOApiType,
++} from '../../../server/app-render/sync-io-messages'
++import { ClientHookDynamicError } from '../../../server/dynamic-rendering-utils'
++import {
++ createLinkPrefetchPartialError,
++ createUnrenderedSegmentError,
++} from '../../../shared/lib/instant-messages'
++import { getCards } from '../components/instant/instant-guidance-data'
++import { getBlockingRouteErrorDetails } from './errors'
++
++const ROUTE = '/insight-test'
++
++type MessageCase = {
++ name: string
++ error: () => Error
++ docs: string | string[]
++ labels: string[]
++ context?: string[]
++}
++
++function expectSingleLearnMoreLink({
++ error,
++ docs,
++ labels,
++ context = [ROUTE],
++}: MessageCase): void {
++ const message = error().message
++ const urls = message.match(/https:\/\/[^\s]+/g) ?? []
++ const allowedDocs = Array.isArray(docs) ? docs : [docs]
++ const renderedLabels = Array.from(
++ message.matchAll(/^\s*-\s*\[([a-z]+)\]/gm),
++ (match) => match[1]
++ )
++ const learnMoreLines = Array.from(
++ message.matchAll(/^Learn more: (https:\/\/[^\s]+)$/gm),
++ (match) => match[1]
++ )
++
++ expect(renderedLabels).toEqual(labels)
++ expect(learnMoreLines).toHaveLength(1)
++ expect(allowedDocs).toContain(learnMoreLines[0])
++ expect(urls).toEqual(learnMoreLines)
++ expect(learnMoreLines[0]).not.toContain('#')
++ expect(message).toMatch(/\n\nLearn more: https:\/\/[^\s]+\n?$/)
++ for (const value of context) {
++ expect(message).toContain(value)
++ }
++}
++
++const blockingRouteCases: MessageCase[] = [
++ {
++ name: 'runtime body',
++ error: () => createRuntimeBodyError(ROUTE),
++ docs: 'https://nextjs.org/docs/messages/blocking-prerender-runtime',
++ labels: ['stream', 'block'],
++ },
++ {
++ name: 'dynamic body',
++ error: () => createDynamicBodyError(ROUTE),
++ docs: 'https://nextjs.org/docs/messages/blocking-prerender-dynamic',
++ labels: ['stream', 'cache', 'block'],
++ },
++ {
++ name: 'runtime body during navigation',
++ error: () => createRuntimeBodyErrorInNavigation(ROUTE),
++ docs: 'https://nextjs.org/docs/messages/blocking-prerender-runtime',
++ labels: ['stream', 'block'],
++ },
++ {
++ name: 'URL body during navigation',
++ error: () => createLinkBodyErrorInNavigation(ROUTE),
++ docs: 'https://nextjs.org/docs/messages/instant-shell-url-data',
++ labels: ['stream', 'block'],
++ },
++ {
++ name: 'dynamic body during navigation',
++ error: () => createDynamicBodyErrorInNavigation(ROUTE),
++ docs: 'https://nextjs.org/docs/messages/blocking-prerender-dynamic',
++ labels: ['stream', 'cache', 'block'],
++ },
++ {
++ name: 'combined dynamic and runtime body',
++ error: () => createDynamicOrRuntimeBodyError(ROUTE),
++ docs: 'https://nextjs.org/docs/messages/blocking-prerender-dynamic',
++ labels: ['stream', 'cache', 'block'],
++ },
++ {
++ name: 'URL metadata',
++ error: () => createLinkMetadataError(ROUTE),
++ docs:
++ 'https://nextjs.org/docs/messages/blocking-prerender-metadata-runtime',
++ labels: ['static', 'dynamic'],
++ },
++ {
++ name: 'runtime metadata',
++ error: () => createRuntimeMetadataError(ROUTE),
++ docs:
++ 'https://nextjs.org/docs/messages/blocking-prerender-metadata-runtime',
++ labels: ['static', 'dynamic'],
++ },
++ {
++ name: 'dynamic metadata',
++ error: () => createDynamicMetadataError(ROUTE),
++ docs:
++ 'https://nextjs.org/docs/messages/blocking-prerender-metadata-dynamic',
++ labels: ['cache', 'dynamic'],
++ },
++ {
++ name: 'combined dynamic and runtime metadata',
++ error: () => createDynamicOrRuntimeMetadataError(ROUTE),
++ docs: [
++ 'https://nextjs.org/docs/messages/blocking-prerender-metadata-runtime',
++ 'https://nextjs.org/docs/messages/blocking-prerender-metadata-dynamic',
++ ],
++ labels: ['static', 'cache', 'dynamic'],
++ },
++ {
++ name: 'URL viewport',
++ error: () => createLinkViewportError(ROUTE),
++ docs:
++ 'https://nextjs.org/docs/messages/blocking-prerender-viewport-runtime',
++ labels: ['static', 'block'],
++ },
++ {
++ name: 'runtime viewport',
++ error: () => createRuntimeViewportError(ROUTE),
++ docs:
++ 'https://nextjs.org/docs/messages/blocking-prerender-viewport-runtime',
++ labels: ['static', 'block'],
++ },
++ {
++ name: 'dynamic viewport',
++ error: () => createDynamicViewportError(ROUTE),
++ docs:
++ 'https://nextjs.org/docs/messages/blocking-prerender-viewport-dynamic',
++ labels: ['cache', 'block'],
++ },
++ {
++ name: 'combined dynamic and runtime viewport',
++ error: () => createDynamicOrRuntimeViewportError(ROUTE),
++ docs: [
++ 'https://nextjs.org/docs/messages/blocking-prerender-viewport-runtime',
++ 'https://nextjs.org/docs/messages/blocking-prerender-viewport-dynamic',
++ ],
++ labels: ['static', 'cache', 'block'],
++ },
++]
++
++const syncIoTypes: SyncIOApiType[] = ['time', 'random', 'crypto']
++const syncIoDocs: Record = {
++ time: 'https://nextjs.org/docs/messages/blocking-prerender-current-time',
++ random: 'https://nextjs.org/docs/messages/blocking-prerender-random',
++ crypto: 'https://nextjs.org/docs/messages/blocking-prerender-crypto',
++}
++
++const syncIoCases: MessageCase[] = syncIoTypes.flatMap((type) => {
++ const measure = type === 'time' ? ['measure'] : []
++ return [
++ {
++ name: `${type} prerender`,
++ error: () => createSyncIOError(ROUTE, `${type}()`, type),
++ docs: syncIoDocs[type],
++ labels: ['dynamic', 'cache', 'client', ...measure],
++ context: [ROUTE, `${type}()`],
++ },
++ {
++ name: `${type} runtime prerender`,
++ error: () => createSyncIORuntimeError(ROUTE, `${type}()`, type),
++ docs: syncIoDocs[type],
++ labels: ['dynamic', 'cache', 'client', ...measure],
++ context: [ROUTE, `${type}()`],
++ },
++ {
++ name: `${type} client component`,
++ error: () => createSyncIOClientError(ROUTE, `${type}()`, type),
++ docs: `${syncIoDocs[type]}-client`,
++ labels: ['stream', 'defer', ...measure],
++ context: [ROUTE, `${type}()`],
++ },
++ ]
++})
++
++const instantCases: MessageCase[] = [
++ {
++ name: 'client hook',
++ error: () => new ClientHookDynamicError(ROUTE, 'useSearchParams()'),
++ docs: 'https://nextjs.org/docs/messages/blocking-prerender-client-hook',
++ labels: ['stream', 'block'],
++ context: [ROUTE, 'useSearchParams()'],
++ },
++ {
++ name: 'unrendered segment',
++ error: () =>
++ createUnrenderedSegmentError(ROUTE, [
++ 'app/@modal/default.tsx',
++ 'app/@sidebar/default.tsx',
++ ]),
++ docs: 'https://nextjs.org/docs/messages/instant-unrendered-segment',
++ labels: ['render', 'ignore'],
++ context: [
++ ROUTE,
++ 'app/@modal/default.tsx',
++ 'app/@sidebar/default.tsx',
++ ],
++ },
++ {
++ name: 'partial link prefetch',
++ error: () => createLinkPrefetchPartialError(ROUTE),
++ docs: 'https://nextjs.org/docs/messages/instant-link-prefetch-partial',
++ labels: ['upgrade', 'disable', 'ignore'],
++ },
++]
++
++describe('insight console guidance', () => {
++ it.each([...blockingRouteCases, ...syncIoCases, ...instantCases])(
++ '$name has one anchor-less Learn more link after its labeled fixes',
++ expectSingleLearnMoreLink
++ )
++
++ it.each(blockingRouteCases)(
++ '$name remains recognizable by the development overlay',
++ ({ error }) => {
++ expect(getBlockingRouteErrorDetails(error())).not.toBeNull()
++ }
++ )
++
++ it('preserves the unrendered-segment input list', () => {
++ const message = createUnrenderedSegmentError(ROUTE, [
++ 'app/@modal/default.tsx',
++ 'app/@sidebar/default.tsx',
++ ]).message
++ expect(message).toContain('app/@modal/default.tsx')
++ expect(message).toContain('app/@sidebar/default.tsx')
++ })
++
++ it('keeps per-fix links on development-overlay cards', () => {
++ for (const [kind, variant] of [
++ ['blocking-route', 'dynamic'],
++ ['metadata', 'runtime'],
++ ['viewport', 'dynamic'],
++ ['link-prefetch-partial', 'runtime'],
++ ] as const) {
++ const cards = getCards(kind, variant)
++ expect(cards.length).toBeGreaterThan(1)
++ for (const card of cards) {
++ expect(card.link).toMatch(/^https:\/\/nextjs\.org\/docs\/messages\/[^#]+#.+/)
++ }
++ }
++ })
++})
diff --git a/nextjs-95967-single-learn-more-links/tests/test.sh b/nextjs-95967-single-learn-more-links/tests/test.sh
new file mode 100644
index 0000000000000000000000000000000000000000..b7472b76223341cfcd0142e3dfce6f4142572b7a
--- /dev/null
+++ b/nextjs-95967-single-learn-more-links/tests/test.sh
@@ -0,0 +1,98 @@
+#!/bin/bash
+set -uo pipefail
+mkdir -p /logs/verifier
+patch_applied=1
+fail_to_pass=0
+pass_to_pass=0
+deterministic=0
+setup_completed=0
+fail_to_pass_exit_code=-1
+fail_to_pass_repeat_exit_code=-1
+pass_to_pass_exit_code=-1
+verifier_cache=""
+
+kill_verifier_processes() { pkill -KILL -u "$(id -u verifier)" 2>/dev/null || true; }
+# Some toolchains fetch dependencies at test runtime (e.g. Next.js e2e installs),
+# so a single registry connection reset must not be misread as a dead test. Retry
+# only infrastructure-style failures with backoff; real assertion failures fail fast.
+run_verifier_command() {
+ local logfile
+ logfile="$(mktemp /tmp/selfbench-verifier-command-XXXXXX.log)"
+ local attempt=1
+ local status=1
+ while [ "$attempt" -le 3 ]; do
+ : > "$logfile"
+ runuser -u verifier -- env PATH="/usr/local/go/bin:/usr/local/cargo/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin" UV_CACHE_DIR="$verifier_cache" UV_NO_BUILD_ISOLATION=1 bash -lc "$1" >"$logfile" 2>&1
+ status=$?
+ if [ "$status" -eq 0 ]; then
+ break
+ fi
+ if [ "$attempt" -lt 3 ] && grep -qE 'ECONNRESET|ETIMEDOUT|ESOCKETTIMEDOUT|ENOTFOUND|EAI_AGAIN|META_FETCH_FAIL|FetchError|EPIPE|EPERM|registry\.npmjs' "$logfile"; then
+ sleep "$((10 * attempt))"
+ attempt=$((attempt + 1))
+ continue
+ fi
+ break
+ done
+ cat "$logfile"
+ rm -f "$logfile"
+ kill_verifier_processes
+ return "$status"
+}
+protect_held_out_path() {
+ local path="$1"
+ chown -R root:root -- "$path"
+ chmod -R a-w,go+rX -- "$path"
+}
+
+if [ ! -f /opt/selfbench/agent.patch ]; then
+ patch_applied=0
+elif [ -s /opt/selfbench/agent.patch ]; then
+ git -C /app apply --binary --whitespace=nowarn --exclude='packages/next/src/next-devtools/dev-overlay/container/insight-console-messages.test.ts' --exclude='packages/next/src/next-devtools/dev-overlay/container/insight-console-messages.test.ts/*' /opt/selfbench/agent.patch || patch_applied=0
+fi
+
+if [ "$patch_applied" -eq 1 ]; then setup_completed=1; fi
+
+if [ "$patch_applied" -eq 1 ] && [ "$setup_completed" -eq 1 ]; then
+ kill_verifier_processes
+ git -C /app restore --source=HEAD --staged --worktree -- 'packages/next/src/next-devtools/dev-overlay/container/insight-console-messages.test.ts' 2>/dev/null || true
+ git -C /app clean -fd -- 'packages/next/src/next-devtools/dev-overlay/container/insight-console-messages.test.ts' >/dev/null 2>&1 || true
+ git -C /app apply --binary --whitespace=nowarn /tests/test.patch || patch_applied=0
+ if [ "$patch_applied" -eq 1 ]; then
+ for protected_path in '/app/packages/next/src/next-devtools/dev-overlay/container/insight-console-messages.test.ts'; do protect_held_out_path "$protected_path"; done
+ fi
+ rm -f /tests/test.patch
+fi
+
+if [ "$patch_applied" -eq 1 ] && [ "$setup_completed" -eq 1 ]; then
+ cd '/app/.'
+ verifier_cache="$(mktemp -d /tmp/selfbench-verifier-uv-XXXXXX)"
+ cp -a /opt/uv-cache/. "$verifier_cache"/
+ chown -R verifier:verifier "$verifier_cache"
+ if run_verifier_command 'pnpm test-webpack '"'"'packages/next/src/next-devtools/dev-overlay/container/insight-console-messages.test.ts'"'"''; then
+ fail_to_pass_exit_code=0
+ fail_to_pass=1
+ if run_verifier_command 'pnpm test-webpack '"'"'packages/next/src/next-devtools/dev-overlay/container/insight-console-messages.test.ts'"'"''; then
+ fail_to_pass_repeat_exit_code=0
+ deterministic=1
+ else
+ fail_to_pass_repeat_exit_code=$?
+ fi
+ else
+ fail_to_pass_exit_code=$?
+ fi
+ if run_verifier_command 'pnpm test-webpack '"'"'packages/next/src/next-devtools/dev-overlay/container/errors.test.ts'"'"' '"'"'packages/next/src/shared/lib/deep-freeze.test.ts'"'"''; then
+ pass_to_pass_exit_code=0
+ pass_to_pass=1
+ else
+ pass_to_pass_exit_code=$?
+ fi
+ rm -rf "$verifier_cache"
+fi
+
+reward=0
+if [ "$patch_applied" -eq 1 ] && [ "$fail_to_pass" -eq 1 ] && [ "$pass_to_pass" -eq 1 ] && [ "$deterministic" -eq 1 ]; then reward=1; fi
+cat > /logs/verifier/reward.json <()
+@@ -1495,6 +1503,16 @@ export async function createHotReloaderTurbopack(
+ }
+ },
+
++ getServerComponentsHmrRefreshHash() {
++ // The current server-components generation. Only the change subscription
++ // (an actual recompile) advances `hmrHash`; reloads and config
++ // invalidations don't, so the value stays stable across requests until a
++ // real edit. Returned unconditionally (`"0"` before the first edit) so
++ // `"use cache"` keys are present and consistent for every request,
++ // mirroring webpack's always-present `stats.hash`.
++ return String(hmrHash)
++ },
++
+ sendToLegacyClients(action) {
+ const payload = JSON.stringify(action)
+
+@@ -1641,7 +1659,6 @@ export async function createHotReloaderTurbopack(
+ await clearAllModuleContexts()
+ this.send({
+ type: HMR_MESSAGE_SENT_TO_BROWSER.SERVER_COMPONENT_CHANGES,
+- hash: String(++hmrHash),
+ })
+ }
+ },
+@@ -1922,7 +1939,10 @@ export async function createHotReloaderTurbopack(
+
+ sendToClient(client, {
+ type: HMR_MESSAGE_SENT_TO_BROWSER.BUILT,
+- hash: String(++hmrHash),
++ // Report the current version without advancing it: a completed
++ // compilation is not itself an edit, and this hash is not
++ // consumed by the Turbopack client.
++ hash: String(hmrHash),
+ errors: [...clientErrors.values()],
+ warnings: [],
+ })
+@@ -1981,7 +2001,6 @@ export async function createHotReloaderTurbopack(
+ // Tell browsers to refetch RSC (soft refresh, not full page reload)
+ hotReloader.send({
+ type: HMR_MESSAGE_SENT_TO_BROWSER.SERVER_COMPONENT_CHANGES,
+- hash: String(++hmrHash),
+ })
+ },
+ })
+diff --git a/packages/next/src/server/dev/hot-reloader-types.ts b/packages/next/src/server/dev/hot-reloader-types.ts
+index 04334c6f49..2e2855605d 100644
+--- a/packages/next/src/server/dev/hot-reloader-types.ts
++++ b/packages/next/src/server/dev/hot-reloader-types.ts
+@@ -117,7 +117,6 @@ export interface ReloadPageMessage {
+
+ export interface ServerComponentChangesMessage {
+ type: HMR_MESSAGE_SENT_TO_BROWSER.SERVER_COMPONENT_CHANGES
+- hash: string
+ }
+
+ /**
+@@ -259,6 +258,13 @@ export interface NextJsHotReloaderInterface {
+ * and App Router clients that don't have Cache Components enabled.
+ */
+ sendToLegacyClients(action: HmrMessageSentToBrowser): void
++ /**
++ * The hash of the most recent server component change, or `undefined` if no
++ * server component change has occurred yet. In dev, this is included in `"use
++ * cache"` cache keys so that cached entries are revalidated after an edit,
++ * for every client, regardless of whether it runs the HMR client.
++ */
++ getServerComponentsHmrRefreshHash(): string | undefined
+ setCacheStatus(status: ServerCacheStatus, htmlRequestId: string): void
+ setReactDebugChannel(
+ debugChannel: ReactDebugChannelForBrowser,
+diff --git a/packages/next/src/server/dev/hot-reloader-webpack.ts b/packages/next/src/server/dev/hot-reloader-webpack.ts
+index 063ebe195a..3f687776c7 100644
+--- a/packages/next/src/server/dev/hot-reloader-webpack.ts
++++ b/packages/next/src/server/dev/hot-reloader-webpack.ts
+@@ -241,6 +241,7 @@ export default class HotReloaderWebpack implements NextJsHotReloaderInterface {
+ private serverError: Error | null = null
+ private hmrServerError: Error | null = null
+ private serverPrevDocumentHash: string | null
++ private serverComponentsHmrRefreshHash: string | undefined
+ private serverChunkNames?: Set
+ private prevChunkNames?: Set
+ private onDemandEntries?: ReturnType
+@@ -431,14 +432,18 @@ export default class HotReloaderWebpack implements NextJsHotReloaderInterface {
+ }
+
+ protected async refreshServerComponents(hash: string): Promise {
++ this.serverComponentsHmrRefreshHash = hash
+ this.send({
+ type: HMR_MESSAGE_SENT_TO_BROWSER.SERVER_COMPONENT_CHANGES,
+- hash,
+ // TODO: granular reloading of changes
+ // entrypoints: serverComponentChanges,
+ })
+ }
+
++ public getServerComponentsHmrRefreshHash(): string | undefined {
++ return this.serverComponentsHmrRefreshHash
++ }
++
+ public onHMR(
+ req: IncomingMessage,
+ _socket: Duplex,
+diff --git a/packages/next/src/server/dev/next-dev-server.ts b/packages/next/src/server/dev/next-dev-server.ts
+index 5f40da7ef9..54fa3aaf96 100644
+--- a/packages/next/src/server/dev/next-dev-server.ts
++++ b/packages/next/src/server/dev/next-dev-server.ts
+@@ -231,6 +231,10 @@ export default class DevServer extends Server {
+ return this.serverComponentsHmrCache
+ }
+
++ protected override getServerComponentsHmrRefreshHash(): string | undefined {
++ return this.bundlerService.getServerComponentsHmrRefreshHash()
++ }
++
+ protected getRouteMatchers(): RouteMatcherManager {
+ const { pagesDir, appDir } = findPagesDir(this.dir)
+
+diff --git a/packages/next/src/server/dev/turbopack-utils.ts b/packages/next/src/server/dev/turbopack-utils.ts
+index 25155df83f..7aa2900da5 100644
+--- a/packages/next/src/server/dev/turbopack-utils.ts
++++ b/packages/next/src/server/dev/turbopack-utils.ts
+@@ -408,6 +408,34 @@ export async function handleRouteType({
+ const writtenEndpoint = await route.endpoint.writeToDisk()
+ hooks?.handleWrittenEndpoint(key, writtenEndpoint, false)
+
++ if (dev) {
++ // Advance the hot-reloader's HMR refresh hash whenever this route
++ // handler is recompiled, so its `"use cache"` entries are invalidated
++ // after an edit. Subscribing runs `subscribeToClientChanges`, which
++ // bumps the `hmrHash` counter on each change; that counter is returned
++ // by `getServerComponentsHmrRefreshHash` and folded into cache keys by
++ // `getHmrRefreshHash`. Unlike app pages there is no RSC for a connected
++ // browser to refetch, so `createMessage` returns nothing; the
++ // subscription exists only to advance the hash.
++ hooks?.subscribeToChanges(
++ key,
++ /** includeIssues= */ true,
++ route.endpoint,
++ () => undefined,
++ (error) => {
++ // This subscription only advances the refresh hash, so there is
++ // nothing to send the browser when it fails. `subscribeToChanges`
++ // drops the subscription on error and re-creates it the next time
++ // this route is ensured, so just log it.
++ console.error(
++ new Error(`Error in the "${page}" app-route HMR subscription`, {
++ cause: error,
++ })
++ )
++ }
++ )
++ }
++
+ const type = writtenEndpoint.type
+
+ manifestLoader.loadAppPathsManifest(page)
+diff --git a/packages/next/src/server/dev/use-cache-probe-worker.ts b/packages/next/src/server/dev/use-cache-probe-worker.ts
+index c77c7c8901..a29a26bcb4 100644
+--- a/packages/next/src/server/dev/use-cache-probe-worker.ts
++++ b/packages/next/src/server/dev/use-cache-probe-worker.ts
+@@ -167,6 +167,7 @@ export async function probeUseCache(msg: ProbeMessage): Promise {
+ previewProps: undefined,
+ isHmrRefresh: msg.request.isHmrRefresh,
+ serverComponentsHmrCache: undefined,
++ hmrRefreshHash: msg.request.hmrRefreshHash,
+ fallbackParams: null,
+ })
+
+diff --git a/packages/next/src/server/lib/dev-bundler-service.ts b/packages/next/src/server/lib/dev-bundler-service.ts
+index c1e963d0f6..f284e79b12 100644
+--- a/packages/next/src/server/lib/dev-bundler-service.ts
++++ b/packages/next/src/server/lib/dev-bundler-service.ts
+@@ -64,6 +64,10 @@ export class DevBundlerService {
+ return await this.bundler.hotReloader.ensurePage(definition)
+ }
+
++ public getServerComponentsHmrRefreshHash(): string | undefined {
++ return this.bundler.hotReloader.getServerComponentsHmrRefreshHash()
++ }
++
+ public logErrorWithOriginalStack =
+ this.bundler.logErrorWithOriginalStack.bind(this.bundler)
+
+diff --git a/packages/next/src/server/request-meta.ts b/packages/next/src/server/request-meta.ts
+index db02b9abdd..0521765ea2 100644
+--- a/packages/next/src/server/request-meta.ts
++++ b/packages/next/src/server/request-meta.ts
+@@ -114,6 +114,14 @@ export interface RequestMeta {
+ */
+ serverComponentsHmrCache?: ServerComponentsHmrCache
+
++ /**
++ * The hash of the most recent server component change (dev only), set by the
++ * router-server from the hot-reloader. Included in `"use cache"` cache keys
++ * so that cached entries are revalidated after an edit, for every client,
++ * regardless of whether it runs the HMR client.
++ */
++ hmrRefreshHash?: string
++
+ /**
+ * Equals the segment path that was used for the prefetch RSC request.
+ */
+diff --git a/packages/next/src/server/route-modules/app-route/module.ts b/packages/next/src/server/route-modules/app-route/module.ts
+index d87306003e..5bcc998eac 100644
+--- a/packages/next/src/server/route-modules/app-route/module.ts
++++ b/packages/next/src/server/route-modules/app-route/module.ts
+@@ -805,7 +805,8 @@ export class AppRouteRouteModule extends RouteModule<
+ req.nextUrl,
+ implicitTags,
+ undefined,
+- context.previewProps
++ context.previewProps,
++ context.renderOpts.hmrRefreshHash
+ )
+
+ const workStore = createWorkStore(staticGenerationContext)
+diff --git a/packages/next/src/server/use-cache/use-cache-probe-globals.ts b/packages/next/src/server/use-cache/use-cache-probe-globals.ts
+index 272e71d1a7..1f3b3a5f30 100644
+--- a/packages/next/src/server/use-cache/use-cache-probe-globals.ts
++++ b/packages/next/src/server/use-cache/use-cache-probe-globals.ts
+@@ -24,6 +24,7 @@ export type UseCacheProbeRequestSnapshot = {
+ rootParams: Params
+ isDraftMode: boolean
+ isHmrRefresh: boolean
++ hmrRefreshHash: string | undefined
+ }
+
+ /**
+diff --git a/packages/next/src/server/use-cache/use-cache-probe-scheduler.ts b/packages/next/src/server/use-cache/use-cache-probe-scheduler.ts
+index f8733b7e8f..dbed303bda 100644
+--- a/packages/next/src/server/use-cache/use-cache-probe-scheduler.ts
++++ b/packages/next/src/server/use-cache/use-cache-probe-scheduler.ts
+@@ -115,6 +115,7 @@ export function setupProbeScheduler(
+ rootParams: outerRequestStore.rootParams ?? {},
+ isDraftMode: workStore.isDraftMode ?? false,
+ isHmrRefresh: outerRequestStore.isHmrRefresh ?? false,
++ hmrRefreshHash: outerRequestStore.hmrRefreshHash,
+ },
+ timeoutMs: probeInternalTimeoutMs,
+ }).then(
+diff --git a/packages/next/src/server/use-cache/use-cache-wrapper.ts b/packages/next/src/server/use-cache/use-cache-wrapper.ts
+index 2bebc96297..f549de8b8d 100644
+--- a/packages/next/src/server/use-cache/use-cache-wrapper.ts
++++ b/packages/next/src/server/use-cache/use-cache-wrapper.ts
+@@ -74,10 +74,7 @@ import {
+ } from './handlers'
+ import type { CacheReadWriteHandler } from './tiered-cache-handler'
+ import { cloneCacheEntry } from './clone-cache-entry'
+-import {
+- NEXT_HMR_REFRESH_HASH_COOKIE,
+- NEXT_INSTANT_TEST_COOKIE,
+-} from '../../client/components/app-router-headers'
++import { NEXT_INSTANT_TEST_COOKIE } from '../../client/components/app-router-headers'
+ import type { ReadonlyRequestCookies } from '../web/spec-extension/adapters/request-cookies'
+ import type { ReadonlyHeaders } from '../web/spec-extension/adapters/headers'
+ import {
+@@ -366,10 +363,8 @@ function computeRootParamsCacheKeySuffix(
+ // Next-internal cookies that must not vary the private cache key, since they're
+ // not part of the application's own cookie state. The instant-navigation cookie
+ // toggles while a navigation lock is held, so including it would force spurious
+-// misses. The HMR refresh hash is already part of the cache key (see
+-// `cacheKeyParts`), so including its cookie too would just be redundant.
++// misses.
+ const COOKIES_EXCLUDED_FROM_PRIVATE_CACHE_KEY = new Set([
+- NEXT_HMR_REFRESH_HASH_COOKIE,
+ NEXT_INSTANT_TEST_COOKIE,
+ ])
+
+diff --git a/packages/next/src/server/web/adapter.ts b/packages/next/src/server/web/adapter.ts
+index 38c960b804..c9c2a43ac3 100644
+--- a/packages/next/src/server/web/adapter.ts
++++ b/packages/next/src/server/web/adapter.ts
+@@ -313,7 +313,10 @@ export async function adapter(
+ request.nextUrl,
+ implicitTags,
+ onUpdateCookies,
+- previewProps
++ previewProps,
++ // Edge route handlers can't use `"use cache"`, so there's no HMR
++ // refresh hash to thread through here.
++ undefined
+ )
+
+ const workStore = createWorkStore({
diff --git a/nextjs-96022-dev-use-cache-invalidation/solution/solve.sh b/nextjs-96022-dev-use-cache-invalidation/solution/solve.sh
new file mode 100644
index 0000000000000000000000000000000000000000..b23b1455c5a01d637a3985c89514ac2b453ecec2
--- /dev/null
+++ b/nextjs-96022-dev-use-cache-invalidation/solution/solve.sh
@@ -0,0 +1,3 @@
+#!/bin/bash
+set -euo pipefail
+git -C /app apply --binary --whitespace=nowarn /solution/gold.patch
diff --git a/nextjs-96022-dev-use-cache-invalidation/tests/Dockerfile b/nextjs-96022-dev-use-cache-invalidation/tests/Dockerfile
new file mode 100644
index 0000000000000000000000000000000000000000..6d305bb8a8c16799736860e2145f46dc5aa67c7d
--- /dev/null
+++ b/nextjs-96022-dev-use-cache-invalidation/tests/Dockerfile
@@ -0,0 +1,42 @@
+FROM ubuntu:24.04
+ENV DEBIAN_FRONTEND=noninteractive \
+ UV_LINK_MODE=copy \
+ UV_CACHE_DIR=/opt/uv-cache \
+ UV_PYTHON_INSTALL_DIR=/usr/local/share/uv/python \
+ UV_PYTHON_BIN_DIR=/usr/local/bin \
+ RUSTUP_HOME=/usr/local/rustup \
+ CARGO_HOME=/usr/local/cargo \
+ COREPACK_HOME=/opt/corepack \
+ PATH=/usr/local/go/bin:/usr/local/cargo/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin
+RUN apt-get update && apt-get install -y --no-install-recommends \
+ bash build-essential ca-certificates curl git jq passwd pkg-config procps unzip xz-utils \
+ && rm -rf /var/lib/apt/lists/*
+ENV PLAYWRIGHT_BROWSERS_PATH=/opt/playwright
+RUN mkdir -p "$PLAYWRIGHT_BROWSERS_PATH" && chmod 755 "$PLAYWRIGHT_BROWSERS_PATH" \
+ && arch="$(dpkg --print-architecture)" && case "$arch" in arm64) node_arch=arm64 ;; amd64) node_arch=x64 ;; *) exit 1 ;; esac \
+ && curl -fsSL "https://nodejs.org/dist/v22.14.0/node-v22.14.0-linux-${node_arch}.tar.xz" | tar -C /usr/local --strip-components=1 -xJ \
+ && mkdir -p /opt/corepack && chmod 755 /opt/corepack \
+ && corepack enable
+COPY repo.tar.gz /tmp/repo.tar.gz
+RUN mkdir -p /app && tar -xzf /tmp/repo.tar.gz -C /app && rm /tmp/repo.tar.gz \
+ && git -C /app init -q \
+ && git -C /app config user.email selfbench@local \
+ && git -C /app config user.name selfbench \
+ && git -C /app add -A \
+ && git -C /app commit -qm base
+RUN mkdir -p /opt/uv-cache && chmod 777 /opt/uv-cache \
+ && cd '/app/.' \
+ && bash -lc 'corepack enable && corepack install --global pnpm@10.33.0 && NEXT_SKIP_NATIVE_POSTINSTALL=0 pnpm install --frozen-lockfile && TURBO_TASKS_AVAILABLE_PARALLELISM=4 ANALYZE=1 pnpm build && pnpm exec playwright install --with-deps chromium && chmod -R a+rwX packages/next' \
+ && chmod -R a+rwX /opt/uv-cache
+
+RUN useradd --create-home --shell /bin/bash verifier \
+ && chown -R verifier:verifier /app /opt/uv-cache \
+ && mkdir -p /opt/selfbench \
+ && chmod 700 /opt/selfbench \
+ && mkdir -p /home/verifier/.cache/uv \
+ && chown -R verifier:verifier /home/verifier/.cache
+ENV UV_CACHE_DIR=/home/verifier/.cache/uv \
+ UV_NO_BUILD_ISOLATION=1
+COPY test.patch test.sh /tests/
+RUN chmod 700 /tests && chmod 600 /tests/test.patch && chmod +x /tests/test.sh
+WORKDIR /app
diff --git a/nextjs-96022-dev-use-cache-invalidation/tests/test.patch b/nextjs-96022-dev-use-cache-invalidation/tests/test.patch
new file mode 100644
index 0000000000000000000000000000000000000000..5cd68d81b3465790cd1bebd9f6f6349416446a47
--- /dev/null
+++ b/nextjs-96022-dev-use-cache-invalidation/tests/test.patch
@@ -0,0 +1,61 @@
+diff --git a/test/e2e/app-dir/use-cache-dev/use-cache-dev.test.ts b/test/e2e/app-dir/use-cache-dev/use-cache-dev.test.ts
+index da4e0a22..ca835118 100644
+--- a/test/e2e/app-dir/use-cache-dev/use-cache-dev.test.ts
++++ b/test/e2e/app-dir/use-cache-dev/use-cache-dev.test.ts
+@@ -108,15 +108,11 @@ describe('use-cache-dev', () => {
+ )
+ })
+
+- // These two currently fail in both Turbopack and Webpack. Dev "use cache"
+- // invalidation relies on the __next_hmr_refresh_hash__ cookie that the
+- // browser HMR client sets after an edit; a client that fetches directly
+- // (curl, a plain fetch, a second device) never sends that cookie, so the
+- // "use cache" key does not change across the edit and the stale entry is
+- // reused. Change these to `it` once editing a file invalidates cached data
+- // for requests that do not carry the cookie, covering both route handlers
+- // and pages.
+- it.failing(
++ // Regression coverage for requesters that don't run the browser HMR client.
++ // A direct requester never receives browser-authored refresh state, but it
++ // must still observe a new cache generation after the server recompiles an
++ // edited page or route handler.
++ it(
+ 'should update cached data used by a route handler after editing a file',
+ async () => {
+ const initialData = await next
+@@ -160,10 +156,20 @@ describe('use-cache-dev', () => {
+ // random value due to a cache miss.
+ expect(newData.text).toBe('bar')
+ expect(newData.mathRandom).not.toBe(initialData.mathRandom)
++
++ // Once the edited module has compiled, ordinary warm requests should
++ // keep reusing its new cache entry rather than advancing the cache key
++ // for development bookkeeping.
++ const warmData = await next
++ .fetch('/api/cached')
++ .then((res) => res.json())
++
++ expect(warmData.text).toBe('bar')
++ expect(warmData.mathRandom).toBe(newData.mathRandom)
+ }
+ )
+
+- it.failing(
++ it(
+ 'should update cached data used by a page fetched without a cookie after editing a file',
+ async () => {
+ // `next.render$` fetches directly, without the browser HMR client, so
+@@ -202,6 +208,13 @@ describe('use-cache-dev', () => {
+ // random value due to a cache miss.
+ expect($('#text').text()).toBe('bar')
+ expect($('#mathRandom').text()).not.toBe(initialMathRandom)
++
++ // The post-edit value should remain cached on another direct request.
++ const editedMathRandom = $('#mathRandom').text()
++ $ = await next.render$('/cached-page')
++
++ expect($('#text').text()).toBe('bar')
++ expect($('#mathRandom').text()).toBe(editedMathRandom)
+ }
+ )
+
diff --git a/nextjs-96022-dev-use-cache-invalidation/tests/test.sh b/nextjs-96022-dev-use-cache-invalidation/tests/test.sh
new file mode 100644
index 0000000000000000000000000000000000000000..c70725d2197d041ac085ab0a750d72db306c3a43
--- /dev/null
+++ b/nextjs-96022-dev-use-cache-invalidation/tests/test.sh
@@ -0,0 +1,98 @@
+#!/bin/bash
+set -uo pipefail
+mkdir -p /logs/verifier
+patch_applied=1
+fail_to_pass=0
+pass_to_pass=0
+deterministic=0
+setup_completed=0
+fail_to_pass_exit_code=-1
+fail_to_pass_repeat_exit_code=-1
+pass_to_pass_exit_code=-1
+verifier_cache=""
+
+kill_verifier_processes() { pkill -KILL -u "$(id -u verifier)" 2>/dev/null || true; }
+# Some toolchains fetch dependencies at test runtime (e.g. Next.js e2e installs),
+# so a single registry connection reset must not be misread as a dead test. Retry
+# only infrastructure-style failures with backoff; real assertion failures fail fast.
+run_verifier_command() {
+ local logfile
+ logfile="$(mktemp /tmp/selfbench-verifier-command-XXXXXX.log)"
+ local attempt=1
+ local status=1
+ while [ "$attempt" -le 3 ]; do
+ : > "$logfile"
+ runuser -u verifier -- env PATH="/usr/local/go/bin:/usr/local/cargo/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin" UV_CACHE_DIR="$verifier_cache" UV_NO_BUILD_ISOLATION=1 bash -lc "$1" >"$logfile" 2>&1
+ status=$?
+ if [ "$status" -eq 0 ]; then
+ break
+ fi
+ if [ "$attempt" -lt 3 ] && grep -qE 'ECONNRESET|ETIMEDOUT|ESOCKETTIMEDOUT|ENOTFOUND|EAI_AGAIN|META_FETCH_FAIL|FetchError|EPIPE|EPERM|registry\.npmjs' "$logfile"; then
+ sleep "$((10 * attempt))"
+ attempt=$((attempt + 1))
+ continue
+ fi
+ break
+ done
+ cat "$logfile"
+ rm -f "$logfile"
+ kill_verifier_processes
+ return "$status"
+}
+protect_held_out_path() {
+ local path="$1"
+ chown -R root:root -- "$path"
+ chmod -R a-w,go+rX -- "$path"
+}
+
+if [ ! -f /opt/selfbench/agent.patch ]; then
+ patch_applied=0
+elif [ -s /opt/selfbench/agent.patch ]; then
+ git -C /app apply --binary --whitespace=nowarn --exclude='test/e2e/app-dir/use-cache-dev/use-cache-dev.test.ts' --exclude='test/e2e/app-dir/use-cache-dev/use-cache-dev.test.ts/*' /opt/selfbench/agent.patch || patch_applied=0
+fi
+
+if [ "$patch_applied" -eq 1 ]; then setup_completed=1; fi
+
+if [ "$patch_applied" -eq 1 ] && [ "$setup_completed" -eq 1 ]; then
+ kill_verifier_processes
+ git -C /app restore --source=HEAD --staged --worktree -- 'test/e2e/app-dir/use-cache-dev/use-cache-dev.test.ts' 2>/dev/null || true
+ git -C /app clean -fd -- 'test/e2e/app-dir/use-cache-dev/use-cache-dev.test.ts' >/dev/null 2>&1 || true
+ git -C /app apply --binary --whitespace=nowarn /tests/test.patch || patch_applied=0
+ if [ "$patch_applied" -eq 1 ]; then
+ for protected_path in '/app/test/e2e/app-dir/use-cache-dev/use-cache-dev.test.ts'; do protect_held_out_path "$protected_path"; done
+ fi
+ rm -f /tests/test.patch
+fi
+
+if [ "$patch_applied" -eq 1 ] && [ "$setup_completed" -eq 1 ]; then
+ cd '/app/.'
+ verifier_cache="$(mktemp -d /tmp/selfbench-verifier-uv-XXXXXX)"
+ cp -a /opt/uv-cache/. "$verifier_cache"/
+ chown -R verifier:verifier "$verifier_cache"
+ if run_verifier_command 'git diff --name-only -z -- packages/next | while IFS= read -r -d '"'"''"'"' file; do if [ -f "$file" ] && [ ! -w "$file" ]; then cp -- "$file" "$file.selfbench-tmp" && mv -- "$file.selfbench-tmp" "$file"; fi; done && TURBO_TASKS_AVAILABLE_PARALLELISM=4 pnpm build && pnpm test-dev-turbo '"'"'test/e2e/app-dir/use-cache-dev/use-cache-dev.test.ts'"'"''; then
+ fail_to_pass_exit_code=0
+ fail_to_pass=1
+ if run_verifier_command 'git diff --name-only -z -- packages/next | while IFS= read -r -d '"'"''"'"' file; do if [ -f "$file" ] && [ ! -w "$file" ]; then cp -- "$file" "$file.selfbench-tmp" && mv -- "$file.selfbench-tmp" "$file"; fi; done && TURBO_TASKS_AVAILABLE_PARALLELISM=4 pnpm build && pnpm test-dev-turbo '"'"'test/e2e/app-dir/use-cache-dev/use-cache-dev.test.ts'"'"''; then
+ fail_to_pass_repeat_exit_code=0
+ deterministic=1
+ else
+ fail_to_pass_repeat_exit_code=$?
+ fi
+ else
+ fail_to_pass_exit_code=$?
+ fi
+ if run_verifier_command 'git diff --name-only -z -- packages/next | while IFS= read -r -d '"'"''"'"' file; do if [ -f "$file" ] && [ ! -w "$file" ]; then cp -- "$file" "$file.selfbench-tmp" && mv -- "$file.selfbench-tmp" "$file"; fi; done && TURBO_TASKS_AVAILABLE_PARALLELISM=4 pnpm build && pnpm test-dev-turbo '"'"'test/development/app-dir/basic/basic.test.ts'"'"' '"'"'test/development/app-dir/multiple-compiles-single-route/multiple-compiles-single-route.test.ts'"'"''; then
+ pass_to_pass_exit_code=0
+ pass_to_pass=1
+ else
+ pass_to_pass_exit_code=$?
+ fi
+ rm -rf "$verifier_cache"
+fi
+
+reward=0
+if [ "$patch_applied" -eq 1 ] && [ "$fail_to_pass" -eq 1 ] && [ "$pass_to_pass" -eq 1 ] && [ "$deterministic" -eq 1 ]; then reward=1; fi
+cat > /logs/verifier/reward.json <(
+ maxSize,
+- (entry) => entry.size
++ (entry, cacheKey) => entry.size + cacheKey.length
+ )
+ const pendingSets = new Map>()
+
+diff --git a/packages/next/src/server/lib/incremental-cache/memory-cache.external.ts b/packages/next/src/server/lib/incremental-cache/memory-cache.external.ts
+index e446656409..d9f66ba850 100644
+--- a/packages/next/src/server/lib/incremental-cache/memory-cache.external.ts
++++ b/packages/next/src/server/lib/incremental-cache/memory-cache.external.ts
+@@ -24,30 +24,37 @@ function getSegmentDataSize(segmentData: Map | undefined) {
+
+ export function getMemoryCache(maxMemoryCacheSize: number) {
+ if (!memoryCache) {
+- memoryCache = new LRUCache(maxMemoryCacheSize, function length({ value }) {
++ memoryCache = new LRUCache(maxMemoryCacheSize, function length(
++ { value },
++ cacheKey
++ ) {
++ let valueSize: number
++
+ if (!value) {
+- return 25
++ valueSize = 25
+ } else if (value.kind === CachedRouteKind.REDIRECT) {
+- return JSON.stringify(value.props).length
++ valueSize = JSON.stringify(value.props).length
+ } else if (value.kind === CachedRouteKind.IMAGE) {
+ throw new Error('invariant image should not be incremental-cache')
+ } else if (value.kind === CachedRouteKind.FETCH) {
+- return JSON.stringify(value.data || '').length
++ valueSize = JSON.stringify(value.data || '').length
+ } else if (value.kind === CachedRouteKind.APP_ROUTE) {
+- return value.body.length
+- }
+- // rough estimate of size of cache value
+- if (value.kind === CachedRouteKind.APP_PAGE) {
+- return Math.max(
++ valueSize = value.body.length
++ } else if (value.kind === CachedRouteKind.APP_PAGE) {
++ // rough estimate of size of cache value
++ valueSize = Math.max(
+ 1,
+ value.html.length +
+ getBufferSize(value.rscData) +
+ (value.postponed?.length || 0) +
+ getSegmentDataSize(value.segmentData)
+ )
++ } else {
++ valueSize =
++ value.html.length + (JSON.stringify(value.pageData)?.length || 0)
+ }
+
+- return value.html.length + (JSON.stringify(value.pageData)?.length || 0)
++ return cacheKey.length + valueSize
+ })
+ }
+
+diff --git a/packages/next/src/server/lib/source-maps.ts b/packages/next/src/server/lib/source-maps.ts
+index af2969c03e..654de4126e 100644
+--- a/packages/next/src/server/lib/source-maps.ts
++++ b/packages/next/src/server/lib/source-maps.ts
+@@ -215,13 +215,13 @@ function bundlerFindSourceMapURL(scriptNameOrSourceURL: string): string | null {
+ const invalidSourceMap = Symbol('invalid-source-map')
+ const sourceMapURLs = new LRUCache(
+ 512 * 1024 * 1024,
+- (url) =>
+- url === invalidSourceMap
+- ? // Ideally we'd account for key length. So we just guestimate a small source map
+- // so that we don't create a huge cache with empty source maps.
++ (url, sourceURL) =>
++ sourceURL.length +
++ (url === invalidSourceMap
++ ? // Guestimate a small source map so invalid entries don't fill the cache.
+ 8 * 1024
+ : // these URLs contain only ASCII characters so .length is equal to Buffer.byteLength
+- url.length
++ url.length)
+ )
+ export function findSourceMapURLDEV(
+ scriptNameOrSourceURL: string
diff --git a/nextjs-byte-budgeted-lru-keys/solution/solve.sh b/nextjs-byte-budgeted-lru-keys/solution/solve.sh
new file mode 100644
index 0000000000000000000000000000000000000000..b23b1455c5a01d637a3985c89514ac2b453ecec2
--- /dev/null
+++ b/nextjs-byte-budgeted-lru-keys/solution/solve.sh
@@ -0,0 +1,3 @@
+#!/bin/bash
+set -euo pipefail
+git -C /app apply --binary --whitespace=nowarn /solution/gold.patch
diff --git a/nextjs-byte-budgeted-lru-keys/tests/Dockerfile b/nextjs-byte-budgeted-lru-keys/tests/Dockerfile
new file mode 100644
index 0000000000000000000000000000000000000000..6935ad83ca6c323529f66717ee83fc533edfb26d
--- /dev/null
+++ b/nextjs-byte-budgeted-lru-keys/tests/Dockerfile
@@ -0,0 +1,42 @@
+FROM ubuntu:24.04
+ENV DEBIAN_FRONTEND=noninteractive \
+ UV_LINK_MODE=copy \
+ UV_CACHE_DIR=/opt/uv-cache \
+ UV_PYTHON_INSTALL_DIR=/usr/local/share/uv/python \
+ UV_PYTHON_BIN_DIR=/usr/local/bin \
+ RUSTUP_HOME=/usr/local/rustup \
+ CARGO_HOME=/usr/local/cargo \
+ COREPACK_HOME=/opt/corepack \
+ PATH=/usr/local/go/bin:/usr/local/cargo/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin
+RUN apt-get update && apt-get install -y --no-install-recommends \
+ bash build-essential ca-certificates curl git jq passwd pkg-config procps unzip xz-utils \
+ && rm -rf /var/lib/apt/lists/*
+ENV PLAYWRIGHT_BROWSERS_PATH=/opt/playwright
+RUN mkdir -p "$PLAYWRIGHT_BROWSERS_PATH" && chmod 755 "$PLAYWRIGHT_BROWSERS_PATH" \
+ && arch="$(dpkg --print-architecture)" && case "$arch" in arm64) node_arch=arm64 ;; amd64) node_arch=x64 ;; *) exit 1 ;; esac \
+ && curl -fsSL "https://nodejs.org/dist/v22.14.0/node-v22.14.0-linux-${node_arch}.tar.xz" | tar -C /usr/local --strip-components=1 -xJ \
+ && mkdir -p /opt/corepack && chmod 755 /opt/corepack \
+ && corepack enable
+COPY repo.tar.gz /tmp/repo.tar.gz
+RUN mkdir -p /app && tar -xzf /tmp/repo.tar.gz -C /app && rm /tmp/repo.tar.gz \
+ && git -C /app init -q \
+ && git -C /app config user.email selfbench@local \
+ && git -C /app config user.name selfbench \
+ && git -C /app add -A \
+ && git -C /app commit -qm base
+RUN mkdir -p /opt/uv-cache && chmod 777 /opt/uv-cache \
+ && cd '/app/.' \
+ && bash -lc 'corepack prepare pnpm@10.33.0 --activate && mkdir -p .selfbench-bin && corepack enable --install-directory "$PWD/.selfbench-bin" && PATH="$PWD/.selfbench-bin:$PATH" NEXT_TELEMETRY_DISABLED=1 pnpm install --frozen-lockfile && PATH="$PWD/.selfbench-bin:$PATH" NEXT_TELEMETRY_DISABLED=1 ANALYZE=1 pnpm build' \
+ && chmod -R a+rwX /opt/uv-cache
+
+RUN useradd --create-home --shell /bin/bash verifier \
+ && chown -R verifier:verifier /app /opt/uv-cache \
+ && mkdir -p /opt/selfbench \
+ && chmod 700 /opt/selfbench \
+ && mkdir -p /home/verifier/.cache/uv \
+ && chown -R verifier:verifier /home/verifier/.cache
+ENV UV_CACHE_DIR=/home/verifier/.cache/uv \
+ UV_NO_BUILD_ISOLATION=1
+COPY test.patch test.sh /tests/
+RUN chmod 700 /tests && chmod 600 /tests/test.patch && chmod +x /tests/test.sh
+WORKDIR /app
diff --git a/nextjs-byte-budgeted-lru-keys/tests/test.patch b/nextjs-byte-budgeted-lru-keys/tests/test.patch
new file mode 100644
index 0000000000000000000000000000000000000000..2806679886c4ac628927931483e3f928cbbdab18
--- /dev/null
+++ b/nextjs-byte-budgeted-lru-keys/tests/test.patch
@@ -0,0 +1,243 @@
+diff --git a/packages/next/src/server/lib/byte-budgeted-cache-keys.test.ts b/packages/next/src/server/lib/byte-budgeted-cache-keys.test.ts
+new file mode 100644
+index 0000000000..4cb91c9136
+--- /dev/null
++++ b/packages/next/src/server/lib/byte-budgeted-cache-keys.test.ts
+@@ -0,0 +1,237 @@
++import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs'
++import type { SourceMap } from 'module'
++import { tmpdir } from 'os'
++import { join } from 'path'
++import DevServer from 'next/dist/server/dev/next-dev-server'
++import { defaultConfig } from 'next/dist/server/config-shared'
++import type { CacheEntry } from './cache-handlers/types'
++import { createDefaultCacheHandler } from './cache-handlers/default'
++import { getMemoryCache } from './incremental-cache/memory-cache.external'
++
++function cacheEntry(body: string): CacheEntry {
++ return {
++ value: new ReadableStream({
++ start(controller) {
++ controller.enqueue(new TextEncoder().encode(body))
++ controller.close()
++ },
++ }),
++ tags: [],
++ stale: 60,
++ timestamp: Date.now(),
++ expire: 60,
++ revalidate: 60,
++ }
++}
++
++class TestDevServer extends DevServer {
++ readStaticPaths(pathname: string) {
++ return this.getStaticPaths({
++ pathname,
++ urlPathname: pathname,
++ requestHeaders: {},
++ page: '/[slug]',
++ isAppPath: false,
++ })
++ }
++
++ hmrCache() {
++ return this.getServerComponentsHmrCache()
++ }
++}
++
++describe('byte-budgeted server caches', () => {
++ it('charges incremental-cache keys against the memory budget', () => {
++ const cache = getMemoryCache(64)
++ const key = `/api/data?${'p'.repeat(80)}`
++ const warning = jest.spyOn(console, 'warn').mockImplementation()
++
++ cache?.set(key, {
++ value: { kind: 'FETCH', data: { body: 'ok' } },
++ lastModified: 1,
++ } as any)
++
++ warning.mockRestore()
++ expect(cache?.get(key)).toBeUndefined()
++ })
++
++ it('charges use-cache keys against the default handler budget', async () => {
++ const handler = createDefaultCacheHandler(16)
++ const key = `cache-${'k'.repeat(32)}`
++ const warning = jest.spyOn(console, 'warn').mockImplementation()
++
++ await handler.set(key, Promise.resolve(cacheEntry('x')))
++
++ warning.mockRestore()
++ expect(await handler.get(key, [])).toBeUndefined()
++ })
++
++ it('charges route keys against the development static paths budget', async () => {
++ const dir = mkdtempSync(join(tmpdir(), 'next-static-paths-cache-'))
++ mkdirSync(join(dir, 'pages'))
++ mkdirSync(join(dir, '.next', 'server', 'pages'), { recursive: true })
++ writeFileSync(
++ join(dir, '.next', 'prerender-manifest.json'),
++ JSON.stringify({
++ version: 4,
++ routes: {},
++ dynamicRoutes: {},
++ notFoundRoutes: [],
++ preview: {
++ previewModeId: 'a'.repeat(32),
++ previewModeSigningKey: 'b'.repeat(64),
++ previewModeEncryptionKey: 'c'.repeat(32),
++ },
++ })
++ )
++ writeFileSync(join(dir, '.next', 'build-manifest.json'), '{}')
++ writeFileSync(join(dir, '.next', 'react-loadable-manifest.json'), '{}')
++ writeFileSync(
++ join(dir, '.next', 'server', 'pages-manifest.json'),
++ JSON.stringify({
++ '/_document': 'pages/_document.js',
++ '/_app': 'pages/_app.js',
++ '/[slug]': 'pages/[slug].js',
++ })
++ )
++ writeFileSync(
++ join(dir, '.next', 'server', 'pages', '_document.js'),
++ 'module.exports={default:()=>null}'
++ )
++ writeFileSync(
++ join(dir, '.next', 'server', 'pages', '_app.js'),
++ 'module.exports={default:()=>null}'
++ )
++ const counter = join(dir, 'counter')
++ writeFileSync(counter, '0')
++ writeFileSync(
++ join(dir, '.next', 'server', 'pages', '[slug].js'),
++ `const fs=require('fs');const p=${JSON.stringify(
++ counter
++ )};module.exports={default:()=>null,getStaticProps:async()=>({props:{}}),getStaticPaths:async()=>{const n=+fs.readFileSync(p,'utf8')+1;fs.writeFileSync(p,String(n));return {paths:['/generated-'+n],fallback:false}}}`
++ )
++
++ try {
++ const server = new TestDevServer({
++ dir,
++ conf: {
++ ...defaultConfig,
++ experimental: {
++ ...defaultConfig.experimental,
++ instantInsights: { validationLevel: 'warning' },
++ useCacheTimeout: 50,
++ turbopackMemoryEvictionMode: 'auto',
++ },
++ },
++ bundlerService: {
++ getServerComponentsHmrRefreshHash: () => '',
++ sendHmrMessage: jest.fn(),
++ } as any,
++ startServerSpan: undefined as any,
++ })
++ const parameterName = 'p'.repeat(3 * 1024 * 1024)
++ const first = `/[${parameterName}a]`
++ const second = `/[${parameterName}b]`
++
++ await server.readStaticPaths(first)
++ await server.readStaticPaths(second)
++ const refreshed = await server.readStaticPaths(first)
++
++ for (let i = 0; i < 100 && Number(readFileSync(counter)) < 3; i++) {
++ await new Promise((resolve) => setTimeout(resolve, 10))
++ }
++ await new Promise((resolve) => setTimeout(resolve, 100))
++ expect(refreshed.staticPaths).toEqual(['/generated-3'])
++ } finally {
++ rmSync(dir, { recursive: true, force: true })
++ }
++ })
++
++ it('charges module keys against the development HMR cache budget', () => {
++ const dir = mkdtempSync(join(tmpdir(), 'next-dev-cache-'))
++ mkdirSync(join(dir, 'pages'))
++ mkdirSync(join(dir, '.next'))
++ writeFileSync(
++ join(dir, '.next', 'prerender-manifest.json'),
++ JSON.stringify({
++ version: 4,
++ routes: {},
++ dynamicRoutes: {},
++ notFoundRoutes: [],
++ preview: {
++ previewModeId: 'a'.repeat(32),
++ previewModeSigningKey: 'b'.repeat(64),
++ previewModeEncryptionKey: 'c'.repeat(32),
++ },
++ })
++ )
++
++ try {
++ const server = new TestDevServer({
++ dir,
++ conf: {
++ ...defaultConfig,
++ experimental: {
++ ...defaultConfig.experimental,
++ serverComponentsHmrCache: true,
++ instantInsights: { validationLevel: 'warning' },
++ useCacheTimeout: 50,
++ turbopackMemoryEvictionMode: 'auto',
++ },
++ },
++ bundlerService: {
++ getServerComponentsHmrRefreshHash: () => '',
++ sendHmrMessage: jest.fn(),
++ } as any,
++ startServerSpan: undefined as any,
++ })
++ const cache = server.hmrCache()
++ const prefix = 'm'.repeat(30 * 1024 * 1024)
++ const first = `${prefix}-first`
++ const second = `${prefix}-second`
++
++ cache!.set(first, ['first'] as any)
++ cache!.set(second, ['second'] as any)
++
++ expect(cache!.get(first)).toBeUndefined()
++ expect(cache!.get(second)).toEqual(['second'])
++ } finally {
++ rmSync(dir, { recursive: true, force: true })
++ }
++ })
++
++ it('eventually revisits old source-map misses when URL keys fill the budget', () => {
++ jest.resetModules()
++ const nodeModule = jest.requireActual('module')
++ const available = new Map()
++ const findSourceMap = jest
++ .spyOn(nodeModule, 'findSourceMap')
++ .mockImplementation((sourceURL) => available.get(sourceURL))
++
++ let sourceMaps!: typeof import('./source-maps')
++ jest.isolateModules(() => {
++ sourceMaps = require('./source-maps')
++ })
++
++ const original = 'server-entry.js'
++ expect(sourceMaps.findSourceMapURLDEV(original)).toBeNull()
++
++ for (let i = 0; i < 65_535; i++) {
++ sourceMaps.findSourceMapURLDEV(`chunk-${i}-${'x'.repeat(96)}`)
++ }
++
++ available.set(original, {
++ payload: {
++ version: 3,
++ file: original,
++ sources: ['server-entry.ts'],
++ names: [],
++ mappings: '',
++ },
++ } as SourceMap)
++
++ const refreshed = sourceMaps.findSourceMapURLDEV(original)
++ findSourceMap.mockRestore()
++ expect(refreshed).toMatch(/^data:application\/json;base64,/)
++ })
++})
diff --git a/nextjs-byte-budgeted-lru-keys/tests/test.sh b/nextjs-byte-budgeted-lru-keys/tests/test.sh
new file mode 100644
index 0000000000000000000000000000000000000000..f335044a27bb894dec71c23e3f549b6d1b193cbe
--- /dev/null
+++ b/nextjs-byte-budgeted-lru-keys/tests/test.sh
@@ -0,0 +1,98 @@
+#!/bin/bash
+set -uo pipefail
+mkdir -p /logs/verifier
+patch_applied=1
+fail_to_pass=0
+pass_to_pass=0
+deterministic=0
+setup_completed=0
+fail_to_pass_exit_code=-1
+fail_to_pass_repeat_exit_code=-1
+pass_to_pass_exit_code=-1
+verifier_cache=""
+
+kill_verifier_processes() { pkill -KILL -u "$(id -u verifier)" 2>/dev/null || true; }
+# Some toolchains fetch dependencies at test runtime (e.g. Next.js e2e installs),
+# so a single registry connection reset must not be misread as a dead test. Retry
+# only infrastructure-style failures with backoff; real assertion failures fail fast.
+run_verifier_command() {
+ local logfile
+ logfile="$(mktemp /tmp/selfbench-verifier-command-XXXXXX.log)"
+ local attempt=1
+ local status=1
+ while [ "$attempt" -le 3 ]; do
+ : > "$logfile"
+ runuser -u verifier -- env PATH="/usr/local/go/bin:/usr/local/cargo/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin" UV_CACHE_DIR="$verifier_cache" UV_NO_BUILD_ISOLATION=1 bash -lc "$1" >"$logfile" 2>&1
+ status=$?
+ if [ "$status" -eq 0 ]; then
+ break
+ fi
+ if [ "$attempt" -lt 3 ] && grep -qE 'ECONNRESET|ETIMEDOUT|ESOCKETTIMEDOUT|ENOTFOUND|EAI_AGAIN|META_FETCH_FAIL|FetchError|EPIPE|EPERM|registry\.npmjs' "$logfile"; then
+ sleep "$((10 * attempt))"
+ attempt=$((attempt + 1))
+ continue
+ fi
+ break
+ done
+ cat "$logfile"
+ rm -f "$logfile"
+ kill_verifier_processes
+ return "$status"
+}
+protect_held_out_path() {
+ local path="$1"
+ chown -R root:root -- "$path"
+ chmod -R a-w,go+rX -- "$path"
+}
+
+if [ ! -f /opt/selfbench/agent.patch ]; then
+ patch_applied=0
+elif [ -s /opt/selfbench/agent.patch ]; then
+ git -C /app apply --binary --whitespace=nowarn --exclude='packages/next/src/server/lib/byte-budgeted-cache-keys.test.ts' --exclude='packages/next/src/server/lib/byte-budgeted-cache-keys.test.ts/*' /opt/selfbench/agent.patch || patch_applied=0
+fi
+
+if [ "$patch_applied" -eq 1 ]; then setup_completed=1; fi
+
+if [ "$patch_applied" -eq 1 ] && [ "$setup_completed" -eq 1 ]; then
+ kill_verifier_processes
+ git -C /app restore --source=HEAD --staged --worktree -- 'packages/next/src/server/lib/byte-budgeted-cache-keys.test.ts' 2>/dev/null || true
+ git -C /app clean -fd -- 'packages/next/src/server/lib/byte-budgeted-cache-keys.test.ts' >/dev/null 2>&1 || true
+ git -C /app apply --binary --whitespace=nowarn /tests/test.patch || patch_applied=0
+ if [ "$patch_applied" -eq 1 ]; then
+ for protected_path in '/app/packages/next/src/server/lib/byte-budgeted-cache-keys.test.ts'; do protect_held_out_path "$protected_path"; done
+ fi
+ rm -f /tests/test.patch
+fi
+
+if [ "$patch_applied" -eq 1 ] && [ "$setup_completed" -eq 1 ]; then
+ cd '/app/.'
+ verifier_cache="$(mktemp -d /tmp/selfbench-verifier-uv-XXXXXX)"
+ cp -a /opt/uv-cache/. "$verifier_cache"/
+ chown -R verifier:verifier "$verifier_cache"
+ if run_verifier_command 'PATH="$PWD/.selfbench-bin:$PATH" NEXT_TELEMETRY_DISABLED=1 ANALYZE=1 pnpm build && PATH="$PWD/.selfbench-bin:$PATH" NEXT_TELEMETRY_DISABLED=1 pnpm test '"'"'packages/next/src/server/lib/byte-budgeted-cache-keys.test.ts'"'"''; then
+ fail_to_pass_exit_code=0
+ fail_to_pass=1
+ if run_verifier_command 'PATH="$PWD/.selfbench-bin:$PATH" NEXT_TELEMETRY_DISABLED=1 ANALYZE=1 pnpm build && PATH="$PWD/.selfbench-bin:$PATH" NEXT_TELEMETRY_DISABLED=1 pnpm test '"'"'packages/next/src/server/lib/byte-budgeted-cache-keys.test.ts'"'"''; then
+ fail_to_pass_repeat_exit_code=0
+ deterministic=1
+ else
+ fail_to_pass_repeat_exit_code=$?
+ fi
+ else
+ fail_to_pass_exit_code=$?
+ fi
+ if run_verifier_command 'true'; then
+ pass_to_pass_exit_code=0
+ pass_to_pass=1
+ else
+ pass_to_pass_exit_code=$?
+ fi
+ rm -rf "$verifier_cache"
+fi
+
+reward=0
+if [ "$patch_applied" -eq 1 ] && [ "$fail_to_pass" -eq 1 ] && [ "$pass_to_pass" -eq 1 ] && [ "$deterministic" -eq 1 ]; then reward=1; fi
+cat > /logs/verifier/reward.json <
++ ({
++ version: 4,
++ routes: {},
++ dynamicRoutes: {},
++ notFoundRoutes: [],
++ preview: {
++ previewModeId: 'id',
++ previewModeSigningKey: 'key',
++ previewModeEncryptionKey: 'key',
++ },
++ }) as any,
++ })
++}
++
++describe('IncrementalCache.generateCacheKey', () => {
++ const cache = createCache()
++ const url = 'https://example.com/api'
++
++ it('distinguishes binary bodies that UTF-8 decoding would collapse', async () => {
++ // 0xff and 0xfe both decode to U+FFFD as UTF-8; the key must tell them
++ // apart by their raw bytes.
++ const a = await cache.generateCacheKey(url, {
++ body: new Uint8Array([0xff]),
++ })
++ const b = await cache.generateCacheKey(url, {
++ body: new Uint8Array([0xfe]),
++ })
++ expect(a).not.toBe(b)
++ })
++
++ it('distinguishes a string body from its UTF-8 encoded bytes', async () => {
++ // A string and the bytes it encodes to are different request shapes.
++ const a = await cache.generateCacheKey(url, { body: 'hello' })
++ const b = await cache.generateCacheKey(url, {
++ body: new TextEncoder().encode('hello'),
++ })
++ expect(a).not.toBe(b)
++ })
++
++ it('uses the selected bytes of arbitrary ArrayBuffer views', async () => {
++ const backing = new Uint8Array([9, 1, 2, 3, 9])
++ const dataView = new DataView(backing.buffer, 1, 3)
++ const typedView = new Uint8Array([1, 2, 3])
++
++ const a = await cache.generateCacheKey(url, { body: dataView })
++ const b = await cache.generateCacheKey(url, { body: typedView })
++ expect(a).toBe(b)
++ })
++
++ it('distinguishes URLSearchParams, FormData, and string bodies', async () => {
++ const form = new FormData()
++ form.append('x', 'a')
++
++ const formKey = await cache.generateCacheKey(url, { body: form })
++ const paramsKey = await cache.generateCacheKey(url, {
++ body: new URLSearchParams([['x', 'a']]),
++ })
++ const stringKey = await cache.generateCacheKey(url, { body: 'x=a' })
++
++ expect(new Set([formKey, paramsKey, stringKey]).size).toBe(3)
++ })
++
++ it('distinguishes a Blob from its raw content bytes', async () => {
++ const bytes = new Uint8Array([1, 2, 3])
++ const blobKey = await cache.generateCacheKey(url, {
++ body: new Blob([bytes]),
++ })
++ const bytesKey = await cache.generateCacheKey(url, { body: bytes })
++
++ expect(blobKey).not.toBe(bytesKey)
++ })
++
++ it('is deterministic for identical bodies', async () => {
++ const a = await cache.generateCacheKey(url, {
++ body: new Uint8Array([1, 2, 3]),
++ })
++ const b = await cache.generateCacheKey(url, {
++ body: new Uint8Array([1, 2, 3]),
++ })
++ expect(a).toBe(b)
++ })
++
++ it('does not collide FormData multi-values with a comma-joined string', async () => {
++ // The two values ['a', 'b'] must not hash the same as the single 'a,b'.
++ const multi = new FormData()
++ multi.append('x', 'a')
++ multi.append('x', 'b')
++
++ const joined = new FormData()
++ joined.append('x', 'a,b')
++
++ const a = await cache.generateCacheKey(url, { body: multi })
++ const b = await cache.generateCacheKey(url, { body: joined })
++ expect(a).not.toBe(b)
++ })
++
++ it('distinguishes blobs that differ only by content type', async () => {
++ const bytes = new Uint8Array([1, 2, 3])
++ const a = await cache.generateCacheKey(url, {
++ body: new Blob([bytes], { type: 'text/plain' }),
++ })
++ const b = await cache.generateCacheKey(url, {
++ body: new Blob([bytes], { type: 'application/json' }),
++ })
++ expect(a).not.toBe(b)
++ })
++
++ it('distinguishes ArrayBuffers', async () => {
++ const a = await cache.generateCacheKey(url, {
++ body: new Uint8Array([1, 2, 3, 4]).buffer,
++ })
++ const b = await cache.generateCacheKey(url, {
++ body: new Uint8Array([1, 2, 3]).buffer,
++ })
++ expect(a).not.toBe(b)
++ })
++
++ it('produces the same key for identical bytes in different typed arrays', async () => {
++ const uint8View = new Uint8Array([1, 2, 3, 4])
++ const uint16View = new Uint16Array(
++ uint8View.buffer,
++ uint8View.byteOffset,
++ uint8View.byteLength / 2
++ )
++ const a = await cache.generateCacheKey(url, {
++ body: uint8View,
++ })
++ const b = await cache.generateCacheKey(url, {
++ body: uint16View,
++ })
++ expect(a).toBe(b)
++ })
++
++ it('does not collide FormData with differently interleaved values', async () => {
++ const a = new FormData()
++ a.append('x', 'a')
++ a.append('x', 'b')
++ a.append('y', 'a')
++
++ const b = new FormData()
++ b.append('x', 'a')
++ b.append('y', 'a')
++ b.append('x', 'b')
++
++ const keyA = await cache.generateCacheKey(url, { body: a })
++ const keyB = await cache.generateCacheKey(url, { body: b })
++ expect(keyA).not.toBe(keyB)
++ })
++
++ it('does not collide FormData whose value forges quoted entry delimiters', async () => {
++ // User values may resemble framing text and must remain data.
++ const a = new FormData()
++ a.append('x', 'a"key:"y"str:"b')
++
++ const b = new FormData()
++ b.append('x', 'a')
++ b.append('y', 'b')
++
++ const keyA = await cache.generateCacheKey(url, { body: a })
++ const keyB = await cache.generateCacheKey(url, { body: b })
++ expect(keyA).not.toBe(keyB)
++ })
++
++ it('does not collide FormData whose value spans an entry boundary', async () => {
++ // One value may contain text resembling a complete following entry.
++ const a = new FormData()
++ a.append('x', 'akey:ystr:b')
++
++ const b = new FormData()
++ b.append('x', 'a')
++ b.append('y', 'b')
++
++ const keyA = await cache.generateCacheKey(url, { body: a })
++ const keyB = await cache.generateCacheKey(url, { body: b })
++ expect(keyA).not.toBe(keyB)
++ })
++
++ it('does not collide FormData files that differ only by name/type split', async () => {
++ // File name and content type are separate fetch-relevant metadata.
++ const bytes = new Uint8Array([1, 2, 3])
++
++ const a = new FormData()
++ a.append('f', new Blob([bytes], { type: 'c' }), 'ab')
++
++ const b = new FormData()
++ b.append('f', new Blob([bytes], { type: 'bc' }), 'a')
++
++ const keyA = await cache.generateCacheKey(url, { body: a })
++ const keyB = await cache.generateCacheKey(url, { body: b })
++ expect(keyA).not.toBe(keyB)
++ })
++
++ it('does not collide a file whose content forges a following entry', async () => {
++ // File bytes may resemble framing for a following field.
++ const enc = new TextEncoder()
++
++ const a = new FormData()
++ a.append('f', new Blob([enc.encode('AAAkey:1kstr:1v')], { type: '' }), 'n')
++
++ const b = new FormData()
++ b.append('f', new Blob([enc.encode('AAA')], { type: '' }), 'n')
++ b.append('k', 'v')
++
++ const keyA = await cache.generateCacheKey(url, { body: a })
++ const keyB = await cache.generateCacheKey(url, { body: b })
++ expect(keyA).not.toBe(keyB)
++ })
++
++ it('does not collide blobs that differ only by type/content split', async () => {
++ // Blob content types and bytes must be framed as separate values.
++ const enc = new TextEncoder()
++
++ const a = new Blob([enc.encode('y')], { type: 'bytes:x' })
++ const b = new Blob([enc.encode('xbytes:y')], { type: '' })
++
++ const keyA = await cache.generateCacheKey(url, { body: a })
++ const keyB = await cache.generateCacheKey(url, { body: b })
++ expect(keyA).not.toBe(keyB)
++ })
++
++ it('does not collide a FormData value whose length digits absorb a forged entry', async () => {
++ // Length digits adjacent to user data must not make framing ambiguous.
++ const a = new FormData()
++ a.append('x', 'key:1astr:0')
++
++ const b = new FormData()
++ b.append('x', '1')
++ b.append('a', '')
++
++ const keyA = await cache.generateCacheKey(url, { body: a })
++ const keyB = await cache.generateCacheKey(url, { body: b })
++ expect(keyA).not.toBe(keyB)
++ })
++
++ it('does not collide blobs whose type-length digits absorb the content', async () => {
++ // Type lengths and content beginning with digits remain distinct.
++ const enc = new TextEncoder()
++ const a = new Blob([new Uint8Array(0)], { type: 'bytes:aaaaa' })
++ const b = new Blob([enc.encode('aaaaabytes:')], { type: '1' })
++
++ const keyA = await cache.generateCacheKey(url, { body: a })
++ const keyB = await cache.generateCacheKey(url, { body: b })
++ expect(keyA).not.toBe(keyB)
++ })
++})
diff --git a/nextjs-byte-exact-binary-fetch-cache-keys/tests/test.sh b/nextjs-byte-exact-binary-fetch-cache-keys/tests/test.sh
new file mode 100644
index 0000000000000000000000000000000000000000..91514c7cb7900076407c698a5f6136a7d6465e28
--- /dev/null
+++ b/nextjs-byte-exact-binary-fetch-cache-keys/tests/test.sh
@@ -0,0 +1,98 @@
+#!/bin/bash
+set -uo pipefail
+mkdir -p /logs/verifier
+patch_applied=1
+fail_to_pass=0
+pass_to_pass=0
+deterministic=0
+setup_completed=0
+fail_to_pass_exit_code=-1
+fail_to_pass_repeat_exit_code=-1
+pass_to_pass_exit_code=-1
+verifier_cache=""
+
+kill_verifier_processes() { pkill -KILL -u "$(id -u verifier)" 2>/dev/null || true; }
+# Some toolchains fetch dependencies at test runtime (e.g. Next.js e2e installs),
+# so a single registry connection reset must not be misread as a dead test. Retry
+# only infrastructure-style failures with backoff; real assertion failures fail fast.
+run_verifier_command() {
+ local logfile
+ logfile="$(mktemp /tmp/selfbench-verifier-command-XXXXXX.log)"
+ local attempt=1
+ local status=1
+ while [ "$attempt" -le 3 ]; do
+ : > "$logfile"
+ runuser -u verifier -- env PATH="/usr/local/go/bin:/usr/local/cargo/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin" UV_CACHE_DIR="$verifier_cache" UV_NO_BUILD_ISOLATION=1 bash -lc "$1" >"$logfile" 2>&1
+ status=$?
+ if [ "$status" -eq 0 ]; then
+ break
+ fi
+ if [ "$attempt" -lt 3 ] && grep -qE 'ECONNRESET|ETIMEDOUT|ESOCKETTIMEDOUT|ENOTFOUND|EAI_AGAIN|META_FETCH_FAIL|FetchError|EPIPE|EPERM|registry\.npmjs' "$logfile"; then
+ sleep "$((10 * attempt))"
+ attempt=$((attempt + 1))
+ continue
+ fi
+ break
+ done
+ cat "$logfile"
+ rm -f "$logfile"
+ kill_verifier_processes
+ return "$status"
+}
+protect_held_out_path() {
+ local path="$1"
+ chown -R root:root -- "$path"
+ chmod -R a-w,go+rX -- "$path"
+}
+
+if [ ! -f /opt/selfbench/agent.patch ]; then
+ patch_applied=0
+elif [ -s /opt/selfbench/agent.patch ]; then
+ git -C /app apply --binary --whitespace=nowarn --exclude='test/unit/incremental-cache/generate-cache-key.test.ts' --exclude='test/unit/incremental-cache/generate-cache-key.test.ts/*' /opt/selfbench/agent.patch || patch_applied=0
+fi
+
+if [ "$patch_applied" -eq 1 ]; then setup_completed=1; fi
+
+if [ "$patch_applied" -eq 1 ] && [ "$setup_completed" -eq 1 ]; then
+ kill_verifier_processes
+ git -C /app restore --source=HEAD --staged --worktree -- 'test/unit/incremental-cache/generate-cache-key.test.ts' 2>/dev/null || true
+ git -C /app clean -fd -- 'test/unit/incremental-cache/generate-cache-key.test.ts' >/dev/null 2>&1 || true
+ git -C /app apply --binary --whitespace=nowarn /tests/test.patch || patch_applied=0
+ if [ "$patch_applied" -eq 1 ]; then
+ for protected_path in '/app/test/unit/incremental-cache/generate-cache-key.test.ts'; do protect_held_out_path "$protected_path"; done
+ fi
+ rm -f /tests/test.patch
+fi
+
+if [ "$patch_applied" -eq 1 ] && [ "$setup_completed" -eq 1 ]; then
+ cd '/app/.'
+ verifier_cache="$(mktemp -d /tmp/selfbench-verifier-uv-XXXXXX)"
+ cp -a /opt/uv-cache/. "$verifier_cache"/
+ chown -R verifier:verifier "$verifier_cache"
+ if run_verifier_command 'pnpm test-webpack '"'"'test/unit/incremental-cache/generate-cache-key.test.ts'"'"''; then
+ fail_to_pass_exit_code=0
+ fail_to_pass=1
+ if run_verifier_command 'pnpm test-webpack '"'"'test/unit/incremental-cache/generate-cache-key.test.ts'"'"''; then
+ fail_to_pass_repeat_exit_code=0
+ deterministic=1
+ else
+ fail_to_pass_repeat_exit_code=$?
+ fi
+ else
+ fail_to_pass_exit_code=$?
+ fi
+ if run_verifier_command 'pnpm test-webpack '"'"'test/unit/incremental-cache/file-system-cache.test.ts'"'"' '"'"'test/unit/stream-utils/uint8array-helpers.test.ts'"'"''; then
+ pass_to_pass_exit_code=0
+ pass_to_pass=1
+ else
+ pass_to_pass_exit_code=$?
+ fi
+ rm -rf "$verifier_cache"
+fi
+
+reward=0
+if [ "$patch_applied" -eq 1 ] && [ "$fail_to_pass" -eq 1 ] && [ "$pass_to_pass" -eq 1 ] && [ "$deterministic" -eq 1 ]; then reward=1; fi
+cat > /logs/verifier/reward.json <
+ /**
+ * Development-only. Puts a fast built-in in-memory `front` handler in front of
+ * a slower or persistent user-configured `backing` handler. Its only job is to
+- * guarantee that warm reads resolve in a microtask (so they aren't counted as
++ * guarantee that cache hits resolve in a microtask (so they aren't counted as
+ * cache misses at a staged-render boundary, which would otherwise surface a
+ * cold cache indicator), while keeping the front in sync with the backing.
+ *
+@@ -76,9 +76,9 @@ export function createTieredCacheHandler(
+ const frontEntry = await front.get(cacheKey, softTags)
+
+ if (frontEntry) {
+- // Warm hit: serve immediately (in a microtask). A background reconcile
++ // Cache hit: serve immediately (in a microtask). A background reconcile
+ // keeps the front in sync with the backing for the next read;
+- // reconciles for the same key are serialized, so concurrent warm reads
++ // reconciles for the same key are serialized, so concurrent cache hits
+ // don't hit the backing in parallel.
+ scheduleBackgroundSync(cacheKey, () =>
+ reconcileFrontFromBacking(
+@@ -104,7 +104,7 @@ export function createTieredCacheHandler(
+ }
+
+ // Mirror this freshly read backing entry into the front so the next read
+- // is warm. The mirror is serialized per key: if a sync is already
++ // hits it. The mirror is serialized per key: if a sync is already
+ // running, this chains after it, so the front converges to this read even
+ // if the backing changed since that sync started.
+ const [servedEntry, mirroredEntry] = cloneCacheEntry(backingEntry)
+@@ -130,9 +130,9 @@ export function createTieredCacheHandler(
+ }
+
+ /**
+- * After serving a warm front hit, consult the backing and mirror a newer entry
+- * into the front for the next read. Runs in the background; failures are
+- * non-fatal.
++ * After serving a cache hit from the front, consult the backing and mirror a
++ * newer entry into the front for the next read. Runs in the background;
++ * failures are non-fatal.
+ */
+ async function reconcileFrontFromBacking(
+ front: CacheHandler,
+@@ -186,17 +186,18 @@ async function mirrorIntoFront(
+
+ /**
+ * Build an already-expired copy of an entry, used to evict it from the front
+- * handler (which has no per-key delete) once the backing no longer has it. In
+- * dev the default handler treats an entry as missing once `now > timestamp +
+- * expire * 1000`, so `expire: 0` against the original (past) timestamp makes
+- * the next read a miss. The value is never read once the entry is expired, but
+- * it must carry at least one byte because the built-in LRU cache refuses to
+- * store size-0 entries.
++ * handler (which has no per-key delete) once the backing no longer has it. The
++ * default handler treats a negative `expire` as an eviction sentinel and
++ * reports the entry as missing on the next read. A negative `expire` is used
++ * rather than `0` because the dev front handler enforces a minimum retention,
++ * so a `0` `expire` would be kept alive by that minimum instead of evicted. The
++ * value is never read once the entry is evicted, but it must carry at least one
++ * byte because the built-in LRU cache refuses to store size-0 entries.
+ */
+ function toExpiredEntry(entry: CacheEntry): CacheEntry {
+ return {
+ ...entry,
+- expire: 0,
++ expire: -1,
+ value: new ReadableStream({
+ start(controller) {
+ controller.enqueue(new Uint8Array(1))
+diff --git a/packages/next/src/server/use-cache/use-cache-wrapper.ts b/packages/next/src/server/use-cache/use-cache-wrapper.ts
+index 9dfddda9d4..3ca4a061e8 100644
+--- a/packages/next/src/server/use-cache/use-cache-wrapper.ts
++++ b/packages/next/src/server/use-cache/use-cache-wrapper.ts
+@@ -1092,12 +1092,17 @@ async function collectResult(
+ // `MIN_PRERENDERABLE_EXPIRE` (5 minutes) caps how long an entry lingers in
+ // the dedicated in-memory private handler. It is the shortest `expire` that
+ // isn't treated as dynamic; a smaller `expire` would exclude the entry from
+- // prerenders. The size-0 case (`cacheMaxMemorySize: 0`) deliberately does NOT
+- // force this: it keeps its resolved cache life so that the cache entry can be
+- // considered prerenderable instead of being misread as a dynamic hole, and a
+- // separate dev revalidation (see the cache-hit path below) keeps its reloads
+- // showing a fresh value. Custom kinds keep their real cache life too, since
+- // their backing handler owns it.
++ // prerenders. Two other cases deliberately do NOT force this and keep their
++ // resolved cache life, relying instead on the dev handler's minimum retention
++ // and a dev revalidation (see the cache-hit path below) to keep reloads fast
++ // and fresh. The size-0 case (`cacheMaxMemorySize: 0`) keeps its life so the
++ // entry can be considered prerenderable instead of being misread as a dynamic
++ // hole. An explicit short-`expire` public cache (e.g. `cacheLife({ expire: 0
++ // })`) keeps its life so it stays correctly excluded from static prerenders
++ // via its real `expire` while a reload still hits the cache; forcing
++ // `revalidate: 0` here would instead corrupt the cache life propagated to an
++ // enclosing cache and trigger the nested-dynamic error. A cache backed by a
++ // custom handler keeps its real cache life too, since that handler owns it.
+ const forceDynamicCacheLifeInDev = isPrivateCacheInDev
+
+ // If cacheLife() was used to set an explicit revalidate/expire/stale time we
+@@ -1640,7 +1645,7 @@ export async function cache(
+ if (isPrivate) {
+ // Private caches normally go to the Resume Data Cache (RDC), not a cache
+ // handler. In development we additionally persist them in a dedicated
+- // built-in in-memory handler so that warm reloads are fast.
++ // built-in in-memory handler so that reloads are fast.
+ if (process.env.__NEXT_DEV_SERVER) {
+ cacheHandler = getPrivateCacheHandler()
+ }
+@@ -1652,7 +1657,7 @@ export async function cache(
+
+ // In development, a user-configured (custom) handler may be slow or
+ // remote, so we read through a tiered handler that puts a built-in
+- // in-memory front in front of it to keep warm reads microtask-fast.
++ // in-memory front in front of it to keep cache hits microtask-fast.
+ // Built-in handlers (the default handler, and its size-0 replacement) are
+ // already in-memory and used directly.
+ if (process.env.__NEXT_DEV_SERVER && isCustomCacheHandler(kind)) {
+@@ -2188,7 +2193,7 @@ export async function cache(
+
+ let stream: undefined | ReadableStream = undefined
+
+- // Set when a short-lived warm hit ends its cache read up front (dev only) so
++ // Set when a short-lived cache hit ends its cache read up front (dev only) so
+ // the static-shell boundary doesn't count it as a phantom miss. Once set, the
+ // cache signal read is balanced, so serving must use a plain stream and skip
+ // any trailing cacheSignal.endRead() call.
+@@ -2945,7 +2950,19 @@ export async function cache(
+
+ if (
+ entry === undefined ||
+- currentTime > entry.timestamp + entry.expire * 1000 ||
++ // In dev, the built-in default handler retains a short-`expire` entry
++ // for at least `MIN_PRERENDERABLE_EXPIRE`, both when used directly
++ // and when fronting a custom cache handler. Apply that same minimum
++ // here so the retained entry is served and re-warmed in the
++ // background (below), rather than blocking to regenerate it on every
++ // read. The entry's real `expire` is untouched, so staging still
++ // treats it as dynamic.
++ currentTime >
++ entry.timestamp +
++ (process.env.__NEXT_DEV_SERVER
++ ? Math.max(entry.expire, MIN_PRERENDERABLE_EXPIRE)
++ : entry.expire) *
++ 1000 ||
+ (workStore.isStaticGeneration &&
+ currentTime > entry.timestamp + entry.revalidate * 1000)
+ ) {
+@@ -3134,19 +3151,24 @@ export async function cache(
+
+ // Trigger a background revalidation when the entry is stale (past its
+ // `revalidate`), so the next read gets a fresh value without blocking
+- // this one. In development with the in-memory cache disabled
+- // (`cacheMaxMemorySize: 0`), built-in entries keep their resolved
+- // (potentially non-dynamic) cache life, so an entry read back from
+- // the dev in-memory cache is normally still fresh and wouldn't
+- // revalidate on its own; revalidate those on every dynamic request
+- // render too, so each reload still shows a fresh value.
++ // this one. Development additionally re-warms on every dynamic
++ // request render in two cases where the dev in-memory entry would
++ // otherwise read back as fresh, so a subsequent reload still shows a
++ // fresh value. The first is with the in-memory cache disabled
++ // (`cacheMaxMemorySize: 0`), where built-in entries keep their
++ // resolved (potentially non-dynamic) cache life. The second is a
++ // short-`expire` entry (an explicit dynamic or client-only cache,
++ // e.g. `cacheLife({ expire: 0 })`), which is retained for at least
++ // `MIN_PRERENDERABLE_EXPIRE` so it is served from the cache; this
++ // also covers custom handlers, re-executing and writing through to
++ // the backing.
+ let shouldTriggerBackgroundRevalidation =
+ currentTime > entry.timestamp + entry.revalidate * 1000
+ if (
+ !shouldTriggerBackgroundRevalidation &&
+ process.env.__NEXT_DEV_SERVER &&
+- isMemoryCacheDisabled() &&
+- !isCustomCacheHandler(kind)
++ (entry.expire < MIN_PRERENDERABLE_EXPIRE ||
++ (isMemoryCacheDisabled() && !isCustomCacheHandler(kind)))
+ ) {
+ switch (workUnitStore.type) {
+ case 'request':
diff --git a/nextjs-cache-short-expire-dev/solution/solve.sh b/nextjs-cache-short-expire-dev/solution/solve.sh
new file mode 100644
index 0000000000000000000000000000000000000000..b23b1455c5a01d637a3985c89514ac2b453ecec2
--- /dev/null
+++ b/nextjs-cache-short-expire-dev/solution/solve.sh
@@ -0,0 +1,3 @@
+#!/bin/bash
+set -euo pipefail
+git -C /app apply --binary --whitespace=nowarn /solution/gold.patch
diff --git a/nextjs-cache-short-expire-dev/tests/Dockerfile b/nextjs-cache-short-expire-dev/tests/Dockerfile
new file mode 100644
index 0000000000000000000000000000000000000000..cebc134b40f55703b8b59227f5737edd0e8b4e16
--- /dev/null
+++ b/nextjs-cache-short-expire-dev/tests/Dockerfile
@@ -0,0 +1,42 @@
+FROM ubuntu:24.04
+ENV DEBIAN_FRONTEND=noninteractive \
+ UV_LINK_MODE=copy \
+ UV_CACHE_DIR=/opt/uv-cache \
+ UV_PYTHON_INSTALL_DIR=/usr/local/share/uv/python \
+ UV_PYTHON_BIN_DIR=/usr/local/bin \
+ RUSTUP_HOME=/usr/local/rustup \
+ CARGO_HOME=/usr/local/cargo \
+ COREPACK_HOME=/opt/corepack \
+ PATH=/usr/local/go/bin:/usr/local/cargo/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin
+RUN apt-get update && apt-get install -y --no-install-recommends \
+ bash build-essential ca-certificates curl git jq passwd pkg-config procps unzip xz-utils \
+ && rm -rf /var/lib/apt/lists/*
+ENV PLAYWRIGHT_BROWSERS_PATH=/opt/playwright
+RUN mkdir -p "$PLAYWRIGHT_BROWSERS_PATH" && chmod 755 "$PLAYWRIGHT_BROWSERS_PATH" \
+ && arch="$(dpkg --print-architecture)" && case "$arch" in arm64) node_arch=arm64 ;; amd64) node_arch=x64 ;; *) exit 1 ;; esac \
+ && curl -fsSL "https://nodejs.org/dist/v22.14.0/node-v22.14.0-linux-${node_arch}.tar.xz" | tar -C /usr/local --strip-components=1 -xJ \
+ && mkdir -p /opt/corepack && chmod 755 /opt/corepack \
+ && corepack enable
+COPY repo.tar.gz /tmp/repo.tar.gz
+RUN mkdir -p /app && tar -xzf /tmp/repo.tar.gz -C /app && rm /tmp/repo.tar.gz \
+ && git -C /app init -q \
+ && git -C /app config user.email selfbench@local \
+ && git -C /app config user.name selfbench \
+ && git -C /app add -A \
+ && git -C /app commit -qm base
+RUN mkdir -p /opt/uv-cache && chmod 777 /opt/uv-cache \
+ && cd '/app/.' \
+ && bash -lc 'corepack enable && pnpm install --frozen-lockfile && ANALYZE=1 pnpm build && pnpm exec playwright install --with-deps chromium' \
+ && chmod -R a+rwX /opt/uv-cache
+
+RUN useradd --create-home --shell /bin/bash verifier \
+ && chown -R verifier:verifier /app /opt/uv-cache \
+ && mkdir -p /opt/selfbench \
+ && chmod 700 /opt/selfbench \
+ && mkdir -p /home/verifier/.cache/uv \
+ && chown -R verifier:verifier /home/verifier/.cache
+ENV UV_CACHE_DIR=/home/verifier/.cache/uv \
+ UV_NO_BUILD_ISOLATION=1
+COPY test.patch test.sh /tests/
+RUN chmod 700 /tests && chmod 600 /tests/test.patch && chmod +x /tests/test.sh
+WORKDIR /app
diff --git a/nextjs-cache-short-expire-dev/tests/test.patch b/nextjs-cache-short-expire-dev/tests/test.patch
new file mode 100644
index 0000000000000000000000000000000000000000..f37ad7c3be1f2e005c8164c647513ea07e071d55
--- /dev/null
+++ b/nextjs-cache-short-expire-dev/tests/test.patch
@@ -0,0 +1,246 @@
+diff --git a/test/development/app-dir/cache-components-dev-streaming/app/page.tsx b/test/development/app-dir/cache-components-dev-streaming/app/page.tsx
+index a5d1524c73..4f3c15dfb9 100644
+--- a/test/development/app-dir/cache-components-dev-streaming/app/page.tsx
++++ b/test/development/app-dir/cache-components-dev-streaming/app/page.tsx
+@@ -14,6 +14,11 @@ export default function Page() {
+ /use-cache-private-runtime-prefetch
+
+
++
++
++ /use-cache-expire-zero/nav
++
++
+
+
+ /partial-prefetching/session-data
+diff --git a/test/development/app-dir/cache-components-dev-streaming/app/use-cache-expire-zero/[slug]/page.tsx b/test/development/app-dir/cache-components-dev-streaming/app/use-cache-expire-zero/[slug]/page.tsx
+new file mode 100644
+index 0000000000..cdf45502d4
+--- /dev/null
++++ b/test/development/app-dir/cache-components-dev-streaming/app/use-cache-expire-zero/[slug]/page.tsx
+@@ -0,0 +1,43 @@
++import { Suspense } from 'react'
++import { setTimeout } from 'timers/promises'
++import { cacheLife } from 'next/cache'
++
++export const prefetch = 'allow-runtime'
++
++// A distinct slug per test keys a separate cache entry (so the first request
++// for each slug is a genuine cold miss), while both tests share this one
++// runtime-prefetchable page. Declaring the slugs also keeps `params` statically
++// known, so the page shell doesn't depend on dynamic params. In development
++// this does not pre-fill the cache.
++export function generateStaticParams() {
++ return [{ slug: 'nav' }, { slug: 'reload' }]
++}
++
++async function getExpireZeroValue(slug: string) {
++ 'use cache'
++ // An explicit short `expire` opts this public cache into a dynamic,
++ // client-only life: excluded from the static shell, but included in the
++ // runtime prefetch. The slug keys the entry; the value itself is just a
++ // timestamp.
++ cacheLife({ expire: 0 })
++ await setTimeout(1500)
++ return new Date().toISOString()
++}
++
++async function ExpireZeroCached({ slug }: Promise<{ slug: string }>) {
++ const value = await getExpireZeroValue(slug)
++
++ return
}>
++ slug)} />
++
++ )
++}
+diff --git a/test/development/app-dir/cache-components-dev-streaming/cache-components-dev-streaming.test.ts b/test/development/app-dir/cache-components-dev-streaming/cache-components-dev-streaming.test.ts
+index 2f649898b1..b8c3b0eb1a 100644
+--- a/test/development/app-dir/cache-components-dev-streaming/cache-components-dev-streaming.test.ts
++++ b/test/development/app-dir/cache-components-dev-streaming/cache-components-dev-streaming.test.ts
+@@ -189,6 +189,91 @@ describe('cache-components-dev-streaming', () => {
+ })
+ })
+
++ it('shows the short-expire-cache fallback on a cold client navigation but not on a warm one', async () => {
++ // A public `'use cache'` with an explicit short `expire` (`cacheLife({
++ // expire: 0 })`) is a runtime-prefetch route here, so its cached content
++ // belongs to the runtime shell stage. On a warm navigation the dev minimum
++ // retention keeps the entry available, and the client defers revealing the
++ // response until the shell has flushed, so the content arrives with the
++ // shell and the fallback isn't shown - just like a private cache.
++ const browser = await next.browser('/')
++
++ // Cold navigation: the cache misses and fills in the background, so the
++ // fallback is shown until the content streams in.
++ await browser.elementByCss('a[href="/use-cache-expire-zero/nav"]').click()
++ expect(await browser.elementByCss('#expire-zero-fallback').text()).toBe(
++ 'Loading...'
++ )
++ expect(await browser.elementByCss('#expire-zero').text()).toBeDateString()
++
++ // Wait for the background write to settle so the next navigation hits the
++ // warm entry instead of racing a pending write.
++ await waitFor(2000)
++
++ // Hard-reload home so the warm navigation below starts from a fresh page.
++ await browser.loadPage(new URL('/', next.url).href)
++
++ // Warm navigation: record whether the fallback ever enters the DOM. It
++ // shouldn't, since the retained entry is delivered with the shell. (The
++ // client-side reveal race that this delivery relies on is covered by the
++ // private-cache test above, so we don't repeat its stress loop here.)
++ const fallbackObserver = observeNodeAppearances(browser, [
++ 'expire-zero-fallback',
++ ])
++
++ await fallbackObserver.observe()
++
++ await browser.elementByCss('a[href="/use-cache-expire-zero/nav"]').click()
++ expect(await browser.elementByCss('#expire-zero').text()).toBeDateString()
++
++ const appearanceCounts = await fallbackObserver.getResult()
++ expect(appearanceCounts).toEqual({
++ 'expire-zero-fallback': 0,
++ })
++ })
++
++ it('serves a short-expire cache warm on reload and converges to a fresh value', async () => {
++ const browser = await next.browser('/use-cache-expire-zero/reload', {
++ waitHydration: false,
++ // Do not wait for "load"; inspect the page as it streams in.
++ waitUntil: 'commit',
++ })
++
++ // Cold load: the cache misses, so the fallback streams first, and the
++ // generated value streams in once generation completes. The value is a
++ // dynamic hole (real `expire: 0`), so it streams in after the shell.
++ expect(
++ await browser
++ .elementByCss('#expire-zero-fallback', { waitUntil: false })
++ .text()
++ ).toBe('Loading...')
++ const coldValue = await browser
++ .elementByCss('#expire-zero', { waitUntil: false })
++ .text()
++ expect(coldValue).toBeDateString()
++
++ // Warm reload: the dev minimum retention keeps the short-expire entry, so
++ // the reload serves the previously cached value fast instead of
++ // regenerating it. A background revalidation regenerates a fresh entry for
++ // the next reload (asserted below). We wait for the streamed-in element
++ // without waiting for "load", so no retry is needed.
++ await browser.refresh({ waitUntil: 'commit' })
++ expect(
++ await browser.elementByCss('#expire-zero', { waitUntil: false }).text()
++ ).toBe(coldValue)
++
++ // That warm reload re-warmed a fresh entry in the background, so a later
++ // reload converges to the new value. Read after "load" here (a plain
++ // refresh) since we want the settled value, not the streaming inspection
++ // above.
++ await retry(async () => {
++ await browser.refresh()
++ expect(await browser.elementById('expire-zero').text()).not.toBe(
++ coldValue
++ )
++ })
++ })
++
+ // The following are smoke tests that Cache Components validation still
+ // surfaces errors for both cold-cache renders (validated via a separate
+ // warm-cache render) and warm-cache renders (validated via the streamed
+diff --git a/test/development/app-dir/use-cache-custom-handler-dev/app/expire-zero/page.tsx b/test/development/app-dir/use-cache-custom-handler-dev/app/expire-zero/page.tsx
+new file mode 100644
+index 0000000000..e7d5b06820
+--- /dev/null
++++ b/test/development/app-dir/use-cache-custom-handler-dev/app/expire-zero/page.tsx
+@@ -0,0 +1,36 @@
++import { Suspense } from 'react'
++import { setTimeout } from 'timers/promises'
++import { cacheLife } from 'next/cache'
++
++// A public `'use cache'` routed through the custom (slow) handler, with an
++// explicit short `expire`. In dev the built-in front handler applies a minimum
++// retention, so a cache hit still resolves from the front in a microtask
++// instead of paying the backing's latency on every read.
++async function getCachedValue() {
++ 'use cache'
++ // `expire: 0` gives a short, dynamic (client-only) cache life, excluded from
++ // static prerenders. Reusing it across client navigations would require
++ // opting the route into runtime prefetching (`prefetch = 'allow-runtime'`) so
++ // Cached Navigations embeds it into the client router cache; this fixture
++ // doesn't, since the test only exercises the dev front handler serving it
++ // warm on reloads.
++ cacheLife({ expire: 0 })
++ await setTimeout(1000)
++ return new Date().toISOString()
++}
++
++async function CachedValue() {
++ const value = await getCachedValue()
++
++ return
{value}
++}
++
++export default function Page() {
++ return (
++
++ Loading...}>
++
++
++
++ )
++}
+diff --git a/test/development/app-dir/use-cache-custom-handler-dev/use-cache-custom-handler-dev.test.ts b/test/development/app-dir/use-cache-custom-handler-dev/use-cache-custom-handler-dev.test.ts
+index f7a8508129..197060fa4a 100644
+--- a/test/development/app-dir/use-cache-custom-handler-dev/use-cache-custom-handler-dev.test.ts
++++ b/test/development/app-dir/use-cache-custom-handler-dev/use-cache-custom-handler-dev.test.ts
+@@ -40,6 +40,38 @@ describe('use-cache-custom-handler-dev', () => {
+ expect(await browser.hasElementByCss('[data-cold-cache-badge]')).toBe(false)
+ })
+
++ it('serves a short-expire value warm through a custom handler and re-warms it on each reload', async () => {
++ const browser = await next.browser('/expire-zero', {
++ waitHydration: false,
++ // Do not wait for "load"; inspect the page as it streams in.
++ waitUntil: 'commit',
++ })
++
++ // Cold load: the custom handler misses, the value generates and is written
++ // through to both the backing handler and the dev-only in-memory front. We
++ // wait for the streamed-in element without waiting for "load".
++ const coldValue = await browser
++ .elementByCss('#value', { waitUntil: false })
++ .text()
++ expect(coldValue).toBeDateString()
++
++ // Warm reload: served fast from the front, whose minimum retention keeps
++ // the short-`expire` entry. The custom handler's slow `get` isn't on the
++ // critical path, and the short `expire` no longer evicts the front entry on
++ // every read, so the same cached value shows.
++ await browser.refresh({ waitUntil: 'commit' })
++ expect(
++ await browser.elementByCss('#value', { waitUntil: false }).text()
++ ).toBe(coldValue)
++
++ // Each warm reload re-executes the cache function and writes through to the
++ // backing, so reloads converge to a fresh value.
++ await retry(async () => {
++ await browser.refresh()
++ expect(await browser.elementById('value').text()).not.toBe(coldValue)
++ })
++ })
++
+ it('stops serving a front-cached entry after the backing cache is purged out-of-band', async () => {
+ const browser = await next.browser('/purged')
+
diff --git a/nextjs-cache-short-expire-dev/tests/test.sh b/nextjs-cache-short-expire-dev/tests/test.sh
new file mode 100644
index 0000000000000000000000000000000000000000..b3c45e7cf4987374ff37136f1730c4164998cf2d
--- /dev/null
+++ b/nextjs-cache-short-expire-dev/tests/test.sh
@@ -0,0 +1,98 @@
+#!/bin/bash
+set -uo pipefail
+mkdir -p /logs/verifier
+patch_applied=1
+fail_to_pass=0
+pass_to_pass=0
+deterministic=0
+setup_completed=0
+fail_to_pass_exit_code=-1
+fail_to_pass_repeat_exit_code=-1
+pass_to_pass_exit_code=-1
+verifier_cache=""
+
+kill_verifier_processes() { pkill -KILL -u "$(id -u verifier)" 2>/dev/null || true; }
+# Some toolchains fetch dependencies at test runtime (e.g. Next.js e2e installs),
+# so a single registry connection reset must not be misread as a dead test. Retry
+# only infrastructure-style failures with backoff; real assertion failures fail fast.
+run_verifier_command() {
+ local logfile
+ logfile="$(mktemp /tmp/selfbench-verifier-command-XXXXXX.log)"
+ local attempt=1
+ local status=1
+ while [ "$attempt" -le 3 ]; do
+ : > "$logfile"
+ runuser -u verifier -- env PATH="/usr/local/go/bin:/usr/local/cargo/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin" UV_CACHE_DIR="$verifier_cache" UV_NO_BUILD_ISOLATION=1 bash -lc "$1" >"$logfile" 2>&1
+ status=$?
+ if [ "$status" -eq 0 ]; then
+ break
+ fi
+ if [ "$attempt" -lt 3 ] && grep -qE 'ECONNRESET|ETIMEDOUT|ESOCKETTIMEDOUT|ENOTFOUND|EAI_AGAIN|META_FETCH_FAIL|FetchError|EPIPE|EPERM|registry\.npmjs' "$logfile"; then
+ sleep "$((10 * attempt))"
+ attempt=$((attempt + 1))
+ continue
+ fi
+ break
+ done
+ cat "$logfile"
+ rm -f "$logfile"
+ kill_verifier_processes
+ return "$status"
+}
+protect_held_out_path() {
+ local path="$1"
+ chown -R root:root -- "$path"
+ chmod -R a-w,go+rX -- "$path"
+}
+
+if [ ! -f /opt/selfbench/agent.patch ]; then
+ patch_applied=0
+elif [ -s /opt/selfbench/agent.patch ]; then
+ git -C /app apply --binary --whitespace=nowarn --exclude='test/development/app-dir/cache-components-dev-streaming/cache-components-dev-streaming.test.ts' --exclude='test/development/app-dir/cache-components-dev-streaming/cache-components-dev-streaming.test.ts/*' --exclude='test/development/app-dir/use-cache-custom-handler-dev/use-cache-custom-handler-dev.test.ts' --exclude='test/development/app-dir/use-cache-custom-handler-dev/use-cache-custom-handler-dev.test.ts/*' /opt/selfbench/agent.patch || patch_applied=0
+fi
+
+if [ "$patch_applied" -eq 1 ]; then setup_completed=1; fi
+
+if [ "$patch_applied" -eq 1 ] && [ "$setup_completed" -eq 1 ]; then
+ kill_verifier_processes
+ git -C /app restore --source=HEAD --staged --worktree -- 'test/development/app-dir/cache-components-dev-streaming/cache-components-dev-streaming.test.ts' 'test/development/app-dir/use-cache-custom-handler-dev/use-cache-custom-handler-dev.test.ts' 2>/dev/null || true
+ git -C /app clean -fd -- 'test/development/app-dir/cache-components-dev-streaming/cache-components-dev-streaming.test.ts' 'test/development/app-dir/use-cache-custom-handler-dev/use-cache-custom-handler-dev.test.ts' >/dev/null 2>&1 || true
+ git -C /app apply --binary --whitespace=nowarn /tests/test.patch || patch_applied=0
+ if [ "$patch_applied" -eq 1 ]; then
+ for protected_path in '/app/test/development/app-dir/cache-components-dev-streaming/cache-components-dev-streaming.test.ts' '/app/test/development/app-dir/use-cache-custom-handler-dev/use-cache-custom-handler-dev.test.ts'; do protect_held_out_path "$protected_path"; done
+ fi
+ rm -f /tests/test.patch
+fi
+
+if [ "$patch_applied" -eq 1 ] && [ "$setup_completed" -eq 1 ]; then
+ cd '/app/.'
+ verifier_cache="$(mktemp -d /tmp/selfbench-verifier-uv-XXXXXX)"
+ cp -a /opt/uv-cache/. "$verifier_cache"/
+ chown -R verifier:verifier "$verifier_cache"
+ if run_verifier_command 'ANALYZE=1 pnpm build && pnpm test-dev '"'"'test/development/app-dir/cache-components-dev-streaming/cache-components-dev-streaming.test.ts'"'"' '"'"'test/development/app-dir/use-cache-custom-handler-dev/use-cache-custom-handler-dev.test.ts'"'"''; then
+ fail_to_pass_exit_code=0
+ fail_to_pass=1
+ if run_verifier_command 'ANALYZE=1 pnpm build && pnpm test-dev '"'"'test/development/app-dir/cache-components-dev-streaming/cache-components-dev-streaming.test.ts'"'"' '"'"'test/development/app-dir/use-cache-custom-handler-dev/use-cache-custom-handler-dev.test.ts'"'"''; then
+ fail_to_pass_repeat_exit_code=0
+ deterministic=1
+ else
+ fail_to_pass_repeat_exit_code=$?
+ fi
+ else
+ fail_to_pass_exit_code=$?
+ fi
+ if run_verifier_command 'ANALYZE=1 pnpm build && pnpm test-dev '"'"'test/development/app-dir/use-cache-size-zero/use-cache-size-zero.test.ts'"'"' '"'"'test/development/app-dir/basic/basic.test.ts'"'"''; then
+ pass_to_pass_exit_code=0
+ pass_to_pass=1
+ else
+ pass_to_pass_exit_code=$?
+ fi
+ rm -rf "$verifier_cache"
+fi
+
+reward=0
+if [ "$patch_applied" -eq 1 ] && [ "$fail_to_pass" -eq 1 ] && [ "$pass_to_pass" -eq 1 ] && [ "$deterministic" -eq 1 ]; then reward=1; fi
+cat > /logs/verifier/reward.json < {
++ const isTailwindTemplate = [
++ 'app-tw',
++ 'app-tw-empty',
++ 'default-tw',
++ 'default-tw-empty',
++ ].includes(template)
++
+ projectFilesShouldExist({
+ cwd,
+ projectName,
+ files: getProjectSetting({ template, mode, setting: 'files', srcDir }),
+ })
+
+- // Tailwind templates share the same files (tailwind.config.mjs, postcss.config.mjs)
+- if (
+- !['app-tw', 'app-tw-empty', 'default-tw', 'default-tw-empty'].includes(
+- template
+- )
+- ) {
++ // Tailwind templates share the same files across JavaScript and TypeScript.
++ if (!isTailwindTemplate) {
+ projectFilesShouldNotExist({
+ cwd,
+ projectName,
+@@ -165,6 +168,14 @@ export const shouldBeTemplateProject = ({
+ })
+ }
+
++ if (isTailwindTemplate && !process.env.NEXT_RSPACK) {
++ projectFilesShouldNotExist({
++ cwd,
++ projectName,
++ files: ['postcss.config.mjs'],
++ })
++ }
++
+ projectDepsShouldBe({
+ type: 'dependencies',
+ cwd,
+diff --git a/test/production/create-next-app/templates/app.test.ts b/test/production/create-next-app/templates/app.test.ts
+index f52d05fa..9593db13 100644
+--- a/test/production/create-next-app/templates/app.test.ts
++++ b/test/production/create-next-app/templates/app.test.ts
+@@ -1,4 +1,7 @@
++import { readFileSync } from 'fs'
++import { join } from 'path'
+ import {
++ projectFilesShouldExist,
+ projectShouldHaveNoGitChanges,
+ resolveNextTgzFilename,
+ shouldBeTemplateProject,
+@@ -145,7 +148,49 @@ describe('create-next-app --app (App Router)', () => {
+ await tryNextDev({
+ cwd,
+ projectName,
++ tailwind: true,
+ })
++
++ // The non-Turbopack path must keep its PostCSS integration.
++ if (!process.env.NEXT_RSPACK) {
++ const rspackProjectName = 'app-tw-rspack'
++ const rspackResult = await run(
++ [
++ rspackProjectName,
++ '--ts',
++ '--app',
++ '--tailwind',
++ '--rspack',
++ '--skip-install',
++ '--no-eslint',
++ '--no-biome',
++ '--no-src-dir',
++ '--no-import-alias',
++ '--no-react-compiler',
++ '--no-agents-md',
++ ],
++ nextTgzFilename,
++ { cwd }
++ )
++
++ expect(rspackResult.exitCode).toBe(0)
++ projectFilesShouldExist({
++ cwd,
++ projectName: rspackProjectName,
++ files: ['postcss.config.mjs'],
++ })
++ const rspackRoot = join(cwd, rspackProjectName)
++ const rspackPackage = JSON.parse(
++ readFileSync(join(rspackRoot, 'package.json'), 'utf8')
++ )
++ expect(rspackPackage.devDependencies).toHaveProperty(
++ '@tailwindcss/postcss'
++ )
++ expect(rspackPackage.devDependencies).toHaveProperty('tailwindcss')
++ expect(rspackPackage.devDependencies).not.toHaveProperty(
++ '@tailwindcss/turbopack'
++ )
++ }
+ })
+ })
+
+diff --git a/test/production/create-next-app/utils.ts b/test/production/create-next-app/utils.ts
+index 73a46770..39411d8a 100644
+--- a/test/production/create-next-app/utils.ts
++++ b/test/production/create-next-app/utils.ts
+@@ -2,6 +2,7 @@ import execa from 'execa'
+ import { join } from 'path'
+ import { spawn } from 'child_process'
+ import { fetchViaHTTP, findPort, killApp } from 'next-test-utils'
++import webdriver from 'next-webdriver'
+ import {
+ resolveTestPkgPaths,
+ serializeTestPkgPathsEnv,
+@@ -9,6 +10,15 @@ import {
+
+ export const CNA_PATH = require.resolve('create-next-app/dist/index.js')
+
++// Run create-next-app from TypeScript source so the test exercises the current
++// checkout. The verifier applies candidate changes after its build fixtures are
++// prepared, so invoking dist/index.js here would test a stale pre-patch bundle.
++const CNA_SOURCE_PATH = join(
++ __dirname,
++ '../../../packages/create-next-app/index.ts'
++)
++const TSX_CLI_PATH = require.resolve('tsx/cli')
++
+ /**
+ * Resolves the path to the packed `next` tarball. Uses NEXT_TEST_PKG_PATHS
+ * when available (set by run-tests.js), otherwise finds packed.tgz files
+@@ -49,7 +59,7 @@ export const run = async (
+ env?: Record
+ }
+ ) => {
+- return execa('node', [CNA_PATH].concat(args), {
++ return execa('node', [TSX_CLI_PATH, CNA_SOURCE_PATH].concat(args), {
+ // tests with options.reject false are expected to exit(1) so don't inherit
+ stdio: options.reject === false ? 'pipe' : 'inherit',
+ ...options,
+@@ -84,12 +94,14 @@ export async function tryNextDev({
+ isApp = true,
+ isApi = false,
+ isEmpty = false,
++ tailwind = false,
+ }: {
+ cwd: string
+ projectName: string
+ isApp?: boolean
+ isApi?: boolean
+ isEmpty?: boolean
++ tailwind?: boolean
+ }) {
+ // The caller wraps this in `useTempDir`, so `cwd` (and the CNA project
+ // inside it) is already an isolated temp directory that gets removed
+@@ -129,6 +141,8 @@ export async function tryNextDev({
+ // headroom so these tests aren't flaky on loaded CI machines.
+ const startServerTimeout = 60_000
+
++ let browser: Awaited> | undefined
++
+ try {
+ await new Promise((resolve, reject) => {
+ const onTimeout = setTimeout(() => {
+@@ -164,6 +178,17 @@ export async function tryNextDev({
+ })
+ })
+
++ // The webpack test matrix forces generated apps to build with webpack,
++ // but create-next-app only exposes Turbopack and Rspack as bundler choices.
++ // Only assert rendered Tailwind styles when the generated bundler matches
++ // the test bundler.
++ if (tailwind && !process.env.IS_WEBPACK_TEST) {
++ browser = await webdriver(port, '/')
++ expect(await browser.elementByCss('main').getComputedCss('display')).toBe(
++ 'flex'
++ )
++ }
++
+ const res = await fetchViaHTTP(port, '/')
+ if (isEmpty || isApi) {
+ expect(await res.text()).toContain('Hello world!')
+@@ -190,6 +215,7 @@ export async function tryNextDev({
+ expect(apiRes.status).toBe(200)
+ }
+ } finally {
++ await browser?.close()
+ await killApp(server).catch(() => {})
+ }
+ }
diff --git a/nextjs-cna-tailwind-turbopack/tests/test.sh b/nextjs-cna-tailwind-turbopack/tests/test.sh
new file mode 100644
index 0000000000000000000000000000000000000000..81b88846a61b6ccafa6a50f520f130f5642ce0a0
--- /dev/null
+++ b/nextjs-cna-tailwind-turbopack/tests/test.sh
@@ -0,0 +1,98 @@
+#!/bin/bash
+set -uo pipefail
+mkdir -p /logs/verifier
+patch_applied=1
+fail_to_pass=0
+pass_to_pass=0
+deterministic=0
+setup_completed=0
+fail_to_pass_exit_code=-1
+fail_to_pass_repeat_exit_code=-1
+pass_to_pass_exit_code=-1
+verifier_cache=""
+
+kill_verifier_processes() { pkill -KILL -u "$(id -u verifier)" 2>/dev/null || true; }
+# Some toolchains fetch dependencies at test runtime (e.g. Next.js e2e installs),
+# so a single registry connection reset must not be misread as a dead test. Retry
+# only infrastructure-style failures with backoff; real assertion failures fail fast.
+run_verifier_command() {
+ local logfile
+ logfile="$(mktemp /tmp/selfbench-verifier-command-XXXXXX.log)"
+ local attempt=1
+ local status=1
+ while [ "$attempt" -le 3 ]; do
+ : > "$logfile"
+ runuser -u verifier -- env PATH="/usr/local/go/bin:/usr/local/cargo/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin" UV_CACHE_DIR="$verifier_cache" UV_NO_BUILD_ISOLATION=1 bash -lc "$1" >"$logfile" 2>&1
+ status=$?
+ if [ "$status" -eq 0 ]; then
+ break
+ fi
+ if [ "$attempt" -lt 3 ] && grep -qE 'ECONNRESET|ETIMEDOUT|ESOCKETTIMEDOUT|ENOTFOUND|EAI_AGAIN|META_FETCH_FAIL|FetchError|EPIPE|EPERM|registry\.npmjs' "$logfile"; then
+ sleep "$((10 * attempt))"
+ attempt=$((attempt + 1))
+ continue
+ fi
+ break
+ done
+ cat "$logfile"
+ rm -f "$logfile"
+ kill_verifier_processes
+ return "$status"
+}
+protect_held_out_path() {
+ local path="$1"
+ chown -R root:root -- "$path"
+ chmod -R a-w,go+rX -- "$path"
+}
+
+if [ ! -f /opt/selfbench/agent.patch ]; then
+ patch_applied=0
+elif [ -s /opt/selfbench/agent.patch ]; then
+ git -C /app apply --binary --whitespace=nowarn --exclude='test/production/create-next-app/templates/app.test.ts' --exclude='test/production/create-next-app/templates/app.test.ts/*' --exclude='test/production/create-next-app/eslint-config.test.ts' --exclude='test/production/create-next-app/eslint-config.test.ts/*' /opt/selfbench/agent.patch || patch_applied=0
+fi
+
+if [ "$patch_applied" -eq 1 ]; then setup_completed=1; fi
+
+if [ "$patch_applied" -eq 1 ] && [ "$setup_completed" -eq 1 ]; then
+ kill_verifier_processes
+ git -C /app restore --source=HEAD --staged --worktree -- 'test/production/create-next-app/templates/app.test.ts' 'test/production/create-next-app/eslint-config.test.ts' 2>/dev/null || true
+ git -C /app clean -fd -- 'test/production/create-next-app/templates/app.test.ts' 'test/production/create-next-app/eslint-config.test.ts' >/dev/null 2>&1 || true
+ git -C /app apply --binary --whitespace=nowarn /tests/test.patch || patch_applied=0
+ if [ "$patch_applied" -eq 1 ]; then
+ for protected_path in '/app/test/production/create-next-app/templates/app.test.ts' '/app/test/production/create-next-app/eslint-config.test.ts'; do protect_held_out_path "$protected_path"; done
+ fi
+ rm -f /tests/test.patch
+fi
+
+if [ "$patch_applied" -eq 1 ] && [ "$setup_completed" -eq 1 ]; then
+ cd '/app/.'
+ verifier_cache="$(mktemp -d /tmp/selfbench-verifier-uv-XXXXXX)"
+ cp -a /opt/uv-cache/. "$verifier_cache"/
+ chown -R verifier:verifier "$verifier_cache"
+ if run_verifier_command 'NEXT_TEST_NATIVE_DIR="$PWD/node_modules/@next/swc-linux-x64-gnu" pnpm test-start-turbo '"'"'test/production/create-next-app/templates/app.test.ts'"'"' -t '"'"'should create TailwindCSS project with --tailwind flag|should generate eslint.config.mjs for TypeScript project with ESLint'"'"''; then
+ fail_to_pass_exit_code=0
+ fail_to_pass=1
+ if run_verifier_command 'NEXT_TEST_NATIVE_DIR="$PWD/node_modules/@next/swc-linux-x64-gnu" pnpm test-start-turbo '"'"'test/production/create-next-app/templates/app.test.ts'"'"' -t '"'"'should create TailwindCSS project with --tailwind flag|should generate eslint.config.mjs for TypeScript project with ESLint'"'"''; then
+ fail_to_pass_repeat_exit_code=0
+ deterministic=1
+ else
+ fail_to_pass_repeat_exit_code=$?
+ fi
+ else
+ fail_to_pass_exit_code=$?
+ fi
+ if run_verifier_command 'NEXT_TEST_NATIVE_DIR="$PWD/node_modules/@next/swc-linux-x64-gnu" pnpm test-start-turbo '"'"'test/production/create-next-app/eslint-config.test.ts'"'"' -t '"'"'should create TailwindCSS project with --tailwind flag|should generate eslint.config.mjs for TypeScript project with ESLint'"'"''; then
+ pass_to_pass_exit_code=0
+ pass_to_pass=1
+ else
+ pass_to_pass_exit_code=$?
+ fi
+ rm -rf "$verifier_cache"
+fi
+
+reward=0
+if [ "$patch_applied" -eq 1 ] && [ "$fail_to_pass" -eq 1 ] && [ "$pass_to_pass" -eq 1 ] && [ "$deterministic" -eq 1 ]; then reward=1; fi
+cat > /logs/verifier/reward.json < = {}
+ ): Promise {
+ const isCompileMode = experimentalBuildMode === 'compile'
+@@ -977,7 +978,6 @@ export default async function build(
+ NextBuildContext.reactProductionProfiling = reactProductionProfiling
+ NextBuildContext.noMangling = noMangling
+ NextBuildContext.debugPrerender = debugPrerender
+- NextBuildContext.debugBuildPaths = debugBuildPaths
+
+ await nextBuildSpan.traceAsyncFn(async () => {
+ // attempt to load global env values so they are available in next.config.js
+@@ -1018,6 +1018,19 @@ export default async function build(
+ )
+ loadedConfig = config
+
++ // Resolve selective build paths now that the page extensions are known.
++ const debugBuildPaths = debugBuildPathsPatterns
++ ? await (async () => {
++ const resolved = await resolveBuildPaths(
++ debugBuildPathsPatterns,
++ dir,
++ config.pageExtensions
++ )
++ return { app: resolved.appPaths, pages: resolved.pagePaths }
++ })()
++ : undefined
++ NextBuildContext.debugBuildPaths = debugBuildPaths
++
+ // Validate deploymentId if provided
+ if (config.deploymentId !== undefined) {
+ if (typeof config.deploymentId !== 'string') {
+diff --git a/packages/next/src/cli/next-build.ts b/packages/next/src/cli/next-build.ts
+index bc2ac3537e3cfa4b75301538f7a8ed2f8626c480..a0e3cdcdb3f41814f80e511c82cad7d4a5533822 100755
+--- a/packages/next/src/cli/next-build.ts
++++ b/packages/next/src/cli/next-build.ts
+@@ -11,10 +11,7 @@ import { getProjectDir } from '../lib/get-project-dir'
+ import { enableMemoryDebuggingMode } from '../lib/memory/startup'
+ import { disableMemoryDebuggingMode } from '../lib/memory/shutdown'
+ import { Bundler, parseBundlerArgs } from '../lib/bundler'
+-import {
+- resolveBuildPaths,
+- parseBuildPathsInput,
+-} from '../lib/resolve-build-paths'
++import { parseBuildPathsInput } from '../lib/resolve-build-paths'
+
+ export type NextBuildOptions = {
+ experimentalAnalyze?: boolean
+@@ -104,24 +101,13 @@ const nextBuild = async (options: NextBuildOptions, directory?: string) => {
+ printAndExit(`> No such directory exists as the project root: ${dir}`)
+ }
+
+- // Resolve selective build paths
+- let resolvedBuildPaths: { app: string[]; pages: string[] } | undefined
++ let debugBuildPathsPatterns: string[] | undefined
+
+ if (debugBuildPaths) {
+- try {
+- const patterns = parseBuildPathsInput(debugBuildPaths)
+-
+- if (patterns.length > 0) {
+- const resolved = await resolveBuildPaths(patterns, dir)
+- resolvedBuildPaths = {
+- app: resolved.appPaths,
+- pages: resolved.pagePaths,
+- }
+- }
+- } catch (err) {
+- printAndExit(
+- `Failed to resolve build paths: ${isError(err) ? err.message : String(err)}`
+- )
++ const patterns = parseBuildPathsInput(debugBuildPaths)
++
++ if (patterns.length > 0) {
++ debugBuildPathsPatterns = patterns
+ }
+ }
+
+@@ -145,7 +131,7 @@ const nextBuild = async (options: NextBuildOptions, directory?: string) => {
+ bundler,
+ experimentalBuildMode,
+ traceUploadUrl,
+- resolvedBuildPaths,
++ debugBuildPathsPatterns,
+ enabledFeatures
+ )
+ .catch((err) => {
+diff --git a/packages/next/src/lib/resolve-build-paths.ts b/packages/next/src/lib/resolve-build-paths.ts
+index 9ffb4c70b7bc044c7eb58fe652b79625afe264e1..b8759df8a0b7d7a85bc19c238c9095e86ed929ad 100644
+--- a/packages/next/src/lib/resolve-build-paths.ts
++++ b/packages/next/src/lib/resolve-build-paths.ts
+@@ -4,6 +4,8 @@ import * as Log from '../build/output/log'
+ import path from 'path'
+ import fs from 'fs'
+ import isError from './is-error'
++import { createValidFileMatcher } from '../server/lib/find-page-file'
++import type { PageExtensions } from '../build/page-extensions-type'
+
+ const glob = promisify(globOriginal)
+
+@@ -35,10 +37,12 @@ function escapeBrackets(pattern: string): string {
+ */
+ export async function resolveBuildPaths(
+ patterns: string[],
+- projectDir: string
++ projectDir: string,
++ pageExtensions: PageExtensions
+ ): Promise {
+ const appPaths: Set = new Set()
+ const pagePaths: Set = new Set()
++ const validFileMatcher = createValidFileMatcher(pageExtensions, undefined)
+
+ // Detect whether the project keeps its routes under `src/` so we can accept
+ // patterns written with or without that prefix (e.g. both `app/foo/page.tsx`
+@@ -89,7 +93,7 @@ export async function resolveBuildPaths(
+
+ for (const file of matches) {
+ if (!fs.statSync(path.join(projectDir, file)).isDirectory()) {
+- categorizeAndAddPath(file, appPaths, pagePaths)
++ categorizeAndAddPath(file, appPaths, pagePaths, validFileMatcher)
+ }
+ }
+ } catch (error) {
+@@ -128,7 +132,7 @@ function addSrcPrefixIfNeeded(
+
+ /**
+ * Categorizes a file path to either app or pages router based on its prefix.
+- * For app router, only route-defining files (page.*, route.*) are included.
++ * For app router, only route-defining files are included.
+ *
+ * Accepts both top-level (`app/...`, `pages/...`) and src-prefixed
+ * (`src/app/...`, `src/pages/...`) project structures.
+@@ -142,7 +146,8 @@ function addSrcPrefixIfNeeded(
+ function categorizeAndAddPath(
+ filePath: string,
+ appPaths: Set,
+- pagePaths: Set
++ pagePaths: Set,
++ validFileMatcher: ReturnType
+ ): void {
+ let normalized = filePath.replace(/\\/g, '/')
+
+@@ -151,9 +156,9 @@ function categorizeAndAddPath(
+ }
+
+ if (normalized.startsWith('app/')) {
+- // Only include route-defining files (page.* or route.*)
+- if (/\/(page|route)\.[^/]+$/.test(normalized)) {
+- appPaths.add('/' + normalized.slice(4))
++ const appRelativePath = '/' + normalized.slice(4)
++ if (validFileMatcher.isAppRouterPage(appRelativePath)) {
++ appPaths.add(appRelativePath)
+ }
+ } else if (normalized.startsWith('pages/')) {
+ pagePaths.add('/' + normalized.slice(6))
diff --git a/nextjs-debug-build-paths-metadata/solution/solve.sh b/nextjs-debug-build-paths-metadata/solution/solve.sh
new file mode 100644
index 0000000000000000000000000000000000000000..b23b1455c5a01d637a3985c89514ac2b453ecec2
--- /dev/null
+++ b/nextjs-debug-build-paths-metadata/solution/solve.sh
@@ -0,0 +1,3 @@
+#!/bin/bash
+set -euo pipefail
+git -C /app apply --binary --whitespace=nowarn /solution/gold.patch
diff --git a/nextjs-debug-build-paths-metadata/tests/Dockerfile b/nextjs-debug-build-paths-metadata/tests/Dockerfile
new file mode 100644
index 0000000000000000000000000000000000000000..dfe1584980495892ac74a9a85e157b20addb6d5b
--- /dev/null
+++ b/nextjs-debug-build-paths-metadata/tests/Dockerfile
@@ -0,0 +1,42 @@
+FROM ubuntu:24.04
+ENV DEBIAN_FRONTEND=noninteractive \
+ UV_LINK_MODE=copy \
+ UV_CACHE_DIR=/opt/uv-cache \
+ UV_PYTHON_INSTALL_DIR=/usr/local/share/uv/python \
+ UV_PYTHON_BIN_DIR=/usr/local/bin \
+ RUSTUP_HOME=/usr/local/rustup \
+ CARGO_HOME=/usr/local/cargo \
+ COREPACK_HOME=/opt/corepack \
+ PATH=/usr/local/go/bin:/usr/local/cargo/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin
+RUN apt-get update && apt-get install -y --no-install-recommends \
+ bash build-essential ca-certificates curl git jq passwd pkg-config procps unzip xz-utils \
+ && rm -rf /var/lib/apt/lists/*
+ENV PLAYWRIGHT_BROWSERS_PATH=/opt/playwright
+RUN mkdir -p "$PLAYWRIGHT_BROWSERS_PATH" && chmod 755 "$PLAYWRIGHT_BROWSERS_PATH" \
+ && arch="$(dpkg --print-architecture)" && case "$arch" in arm64) node_arch=arm64 ;; amd64) node_arch=x64 ;; *) exit 1 ;; esac \
+ && curl -fsSL "https://nodejs.org/dist/v22.14.0/node-v22.14.0-linux-${node_arch}.tar.xz" | tar -C /usr/local --strip-components=1 -xJ \
+ && mkdir -p /opt/corepack && chmod 755 /opt/corepack \
+ && corepack enable
+COPY repo.tar.gz /tmp/repo.tar.gz
+RUN mkdir -p /app && tar -xzf /tmp/repo.tar.gz -C /app && rm /tmp/repo.tar.gz \
+ && git -C /app init -q \
+ && git -C /app config user.email selfbench@local \
+ && git -C /app config user.name selfbench \
+ && git -C /app add -A \
+ && git -C /app commit -qm base
+RUN mkdir -p /opt/uv-cache && chmod 777 /opt/uv-cache \
+ && cd '/app/.' \
+ && bash -lc 'corepack enable && NEXT_SKIP_NATIVE_POSTINSTALL=0 pnpm install --frozen-lockfile && pnpm build' \
+ && chmod -R a+rwX /opt/uv-cache
+
+RUN useradd --create-home --shell /bin/bash verifier \
+ && chown -R verifier:verifier /app /opt/uv-cache \
+ && mkdir -p /opt/selfbench \
+ && chmod 700 /opt/selfbench \
+ && mkdir -p /home/verifier/.cache/uv \
+ && chown -R verifier:verifier /home/verifier/.cache
+ENV UV_CACHE_DIR=/home/verifier/.cache/uv \
+ UV_NO_BUILD_ISOLATION=1
+COPY test.patch test.sh /tests/
+RUN chmod 700 /tests && chmod 600 /tests/test.patch && chmod +x /tests/test.sh
+WORKDIR /app
diff --git a/nextjs-debug-build-paths-metadata/tests/test.patch b/nextjs-debug-build-paths-metadata/tests/test.patch
new file mode 100644
index 0000000000000000000000000000000000000000..fb7123491300513a8d384f205fe70aa60b3d330d
--- /dev/null
+++ b/nextjs-debug-build-paths-metadata/tests/test.patch
@@ -0,0 +1,96 @@
+diff --git a/test/production/debug-build-path/fixtures/default/app/robots.metadata.ts b/test/production/debug-build-path/fixtures/default/app/robots.metadata.ts
+new file mode 100644
+index 0000000000000000000000000000000000000000..309e3e197d231f2a9ea60926a67b9c6456c65b56
+--- /dev/null
++++ b/test/production/debug-build-path/fixtures/default/app/robots.metadata.ts
+@@ -0,0 +1,8 @@
++export default function robots() {
++ return {
++ rules: {
++ userAgent: '*',
++ allow: '/',
++ },
++ }
++}
+diff --git a/test/production/debug-build-path/fixtures/default/app/sitemap.metadata.ts b/test/production/debug-build-path/fixtures/default/app/sitemap.metadata.ts
+new file mode 100644
+index 0000000000000000000000000000000000000000..7d37bfe091ebf1a2c2cbc1d9e32ea654acbb39c8
+--- /dev/null
++++ b/test/production/debug-build-path/fixtures/default/app/sitemap.metadata.ts
+@@ -0,0 +1,3 @@
++export default function sitemap() {
++ return [{ url: 'https://example.com' }]
++}
+diff --git a/test/production/debug-build-path/fixtures/default/next.config.js b/test/production/debug-build-path/fixtures/default/next.config.js
+index 767719fc4fba59345ae29e29159c9aff270f5819..af7a39f7888845358a628ac3f0e2e2a2130754de 100644
+--- a/test/production/debug-build-path/fixtures/default/next.config.js
++++ b/test/production/debug-build-path/fixtures/default/next.config.js
+@@ -1,4 +1,6 @@
+ /** @type {import('next').NextConfig} */
+-const nextConfig = {}
++const nextConfig = {
++ pageExtensions: ['metadata.ts', 'js', 'jsx', 'ts', 'tsx'],
++}
+
+ module.exports = nextConfig
+diff --git a/test/production/debug-build-path/metadata-routes.test.ts b/test/production/debug-build-path/metadata-routes.test.ts
+new file mode 100644
+index 0000000000000000000000000000000000000000..eb06963fafb3fc74463da0c1a352da5628d0a884
+--- /dev/null
++++ b/test/production/debug-build-path/metadata-routes.test.ts
+@@ -0,0 +1,26 @@
++import path from 'path'
++import { nextTestSetup } from 'e2e-utils'
++
++describe('debug-build-paths metadata routes', () => {
++ const { next } = nextTestSetup({
++ files: path.join(__dirname, 'fixtures/default'),
++ skipStart: true,
++ env: {
++ __NEXT_PRIVATE_DETERMINISTIC_BUILD_OUTPUT: '1',
++ },
++ })
++
++ it('selectively builds App Router metadata routes', async () => {
++ const result = await next.build({
++ args: [
++ '--debug-build-paths',
++ 'app/robots.metadata.ts,app/sitemap.metadata.ts',
++ ],
++ })
++
++ expect(result.exitCode).toBe(0)
++ expect(result.cliOutput).toContain('/robots.txt')
++ expect(result.cliOutput).toContain('/sitemap.xml')
++ expect(result.cliOutput).not.toContain('/about')
++ })
++})
+diff --git a/test/production/debug-build-path/page-route.test.ts b/test/production/debug-build-path/page-route.test.ts
+new file mode 100644
+index 0000000000000000000000000000000000000000..6febe039083cf070a099aae81574fb70a18a7ee1
+--- /dev/null
++++ b/test/production/debug-build-path/page-route.test.ts
+@@ -0,0 +1,23 @@
++import path from 'path'
++import { nextTestSetup } from 'e2e-utils'
++
++describe('debug-build-paths page route regression', () => {
++ const { next } = nextTestSetup({
++ files: path.join(__dirname, 'fixtures/default'),
++ skipStart: true,
++ env: {
++ __NEXT_PRIVATE_DETERMINISTIC_BUILD_OUTPUT: '1',
++ },
++ })
++
++ it('continues to selectively build a regular App Router page', async () => {
++ const result = await next.build({
++ args: ['--debug-build-paths', 'app/about/page.tsx'],
++ })
++
++ expect(result.exitCode).toBe(0)
++ expect(result.cliOutput).toContain('/about')
++ expect(result.cliOutput).not.toContain('/robots.txt')
++ expect(result.cliOutput).not.toContain('/sitemap.xml')
++ })
++})
diff --git a/nextjs-debug-build-paths-metadata/tests/test.sh b/nextjs-debug-build-paths-metadata/tests/test.sh
new file mode 100644
index 0000000000000000000000000000000000000000..a1649816a523c886074d7a59c344a8aa8e66bbe3
--- /dev/null
+++ b/nextjs-debug-build-paths-metadata/tests/test.sh
@@ -0,0 +1,98 @@
+#!/bin/bash
+set -uo pipefail
+mkdir -p /logs/verifier
+patch_applied=1
+fail_to_pass=0
+pass_to_pass=0
+deterministic=0
+setup_completed=0
+fail_to_pass_exit_code=-1
+fail_to_pass_repeat_exit_code=-1
+pass_to_pass_exit_code=-1
+verifier_cache=""
+
+kill_verifier_processes() { pkill -KILL -u "$(id -u verifier)" 2>/dev/null || true; }
+# Some toolchains fetch dependencies at test runtime (e.g. Next.js e2e installs),
+# so a single registry connection reset must not be misread as a dead test. Retry
+# only infrastructure-style failures with backoff; real assertion failures fail fast.
+run_verifier_command() {
+ local logfile
+ logfile="$(mktemp /tmp/selfbench-verifier-command-XXXXXX.log)"
+ local attempt=1
+ local status=1
+ while [ "$attempt" -le 3 ]; do
+ : > "$logfile"
+ runuser -u verifier -- env PATH="/usr/local/go/bin:/usr/local/cargo/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin" UV_CACHE_DIR="$verifier_cache" UV_NO_BUILD_ISOLATION=1 bash -lc "$1" >"$logfile" 2>&1
+ status=$?
+ if [ "$status" -eq 0 ]; then
+ break
+ fi
+ if [ "$attempt" -lt 3 ] && grep -qE 'ECONNRESET|ETIMEDOUT|ESOCKETTIMEDOUT|ENOTFOUND|EAI_AGAIN|META_FETCH_FAIL|FetchError|EPIPE|EPERM|registry\.npmjs' "$logfile"; then
+ sleep "$((10 * attempt))"
+ attempt=$((attempt + 1))
+ continue
+ fi
+ break
+ done
+ cat "$logfile"
+ rm -f "$logfile"
+ kill_verifier_processes
+ return "$status"
+}
+protect_held_out_path() {
+ local path="$1"
+ chown -R root:root -- "$path"
+ chmod -R a-w,go+rX -- "$path"
+}
+
+if [ ! -f /opt/selfbench/agent.patch ]; then
+ patch_applied=0
+elif [ -s /opt/selfbench/agent.patch ]; then
+ git -C /app apply --binary --whitespace=nowarn --exclude='test/production/debug-build-path/metadata-routes.test.ts' --exclude='test/production/debug-build-path/metadata-routes.test.ts/*' --exclude='test/production/debug-build-path/page-route.test.ts' --exclude='test/production/debug-build-path/page-route.test.ts/*' /opt/selfbench/agent.patch || patch_applied=0
+fi
+
+if [ "$patch_applied" -eq 1 ]; then setup_completed=1; fi
+
+if [ "$patch_applied" -eq 1 ] && [ "$setup_completed" -eq 1 ]; then
+ kill_verifier_processes
+ git -C /app restore --source=HEAD --staged --worktree -- 'test/production/debug-build-path/metadata-routes.test.ts' 'test/production/debug-build-path/page-route.test.ts' 2>/dev/null || true
+ git -C /app clean -fd -- 'test/production/debug-build-path/metadata-routes.test.ts' 'test/production/debug-build-path/page-route.test.ts' >/dev/null 2>&1 || true
+ git -C /app apply --binary --whitespace=nowarn /tests/test.patch || patch_applied=0
+ if [ "$patch_applied" -eq 1 ]; then
+ for protected_path in '/app/test/production/debug-build-path/metadata-routes.test.ts' '/app/test/production/debug-build-path/page-route.test.ts'; do protect_held_out_path "$protected_path"; done
+ fi
+ rm -f /tests/test.patch
+fi
+
+if [ "$patch_applied" -eq 1 ] && [ "$setup_completed" -eq 1 ]; then
+ cd '/app/.'
+ verifier_cache="$(mktemp -d /tmp/selfbench-verifier-uv-XXXXXX)"
+ cp -a /opt/uv-cache/. "$verifier_cache"/
+ chown -R verifier:verifier "$verifier_cache"
+ if run_verifier_command 'pnpm build && NEXT_SKIP_ISOLATE=1 pnpm test-start-webpack '"'"'test/production/debug-build-path/metadata-routes.test.ts'"'"''; then
+ fail_to_pass_exit_code=0
+ fail_to_pass=1
+ if run_verifier_command 'pnpm build && NEXT_SKIP_ISOLATE=1 pnpm test-start-webpack '"'"'test/production/debug-build-path/metadata-routes.test.ts'"'"''; then
+ fail_to_pass_repeat_exit_code=0
+ deterministic=1
+ else
+ fail_to_pass_repeat_exit_code=$?
+ fi
+ else
+ fail_to_pass_exit_code=$?
+ fi
+ if run_verifier_command 'pnpm build && NEXT_SKIP_ISOLATE=1 pnpm test-start-webpack '"'"'test/production/debug-build-path/page-route.test.ts'"'"''; then
+ pass_to_pass_exit_code=0
+ pass_to_pass=1
+ else
+ pass_to_pass_exit_code=$?
+ fi
+ rm -rf "$verifier_cache"
+fi
+
+reward=0
+if [ "$patch_applied" -eq 1 ] && [ "$fail_to_pass" -eq 1 ] && [ "$pass_to_pass" -eq 1 ] && [ "$deterministic" -eq 1 ]; then reward=1; fi
+cat > /logs/verifier/reward.json < (
+- match urlencoding::decode(&token.original_file)? {
+- Cow::Borrowed(_) => token.original_file,
+- Cow::Owned(original_file) => RcStr::from(original_file),
+- },
++ // Still percent-encoded, like the URIs it's compared against.
++ token.original_file,
+ // JS stack frames are 1-indexed, source map tokens are 0-indexed
+ Some(token.original_line + 1),
+ Some(token.original_column + 1),
+@@ -2361,36 +2359,51 @@ async fn project_trace_source_operation(
+ }
+ };
+
++ // Turns a percent-encoded URI fragment back into a path for output.
++ fn decode_uri_fragment(value: &str) -> Result {
++ Ok(match urlencoding::decode(value)? {
++ Cow::Borrowed(borrowed) => RcStr::from(borrowed),
++ Cow::Owned(owned) => RcStr::from(owned),
++ })
++ }
++
+ let project_root_uri =
+ uri_from_file(container.project().project_root_path().owned().await?, None).await? + "/";
++ // Relative paths are computed on decoded inputs: they come from
++ // different encoders that disagree on characters like `[` vs `%5B`.
++ let current_directory_path = decode_uri_fragment(¤t_directory_file_url)?;
+ let (file, original_file) =
+ if let Some(source_file) = original_file.strip_prefix(&project_root_uri) {
+ // Client code uses file://
+ (
+ RcStr::from(
+- get_relative_path_to(¤t_directory_file_url, &original_file)
+- // TODO(sokra) remove this to include a ./ here to make it a relative path
+- .trim_start_matches("./"),
++ get_relative_path_to(
++ ¤t_directory_path,
++ &decode_uri_fragment(&original_file)?,
++ )
++ // TODO(sokra) remove this to include a ./ here to make it a relative path
++ .trim_start_matches("./"),
+ ),
+- Some(RcStr::from(source_file)),
++ Some(decode_uri_fragment(source_file)?),
+ )
+ } else if let Some(source_file) = original_file.strip_prefix(&*SOURCE_MAP_PREFIX_PROJECT) {
+ // Server code uses turbopack:///[project]
+ // TODO should this also be file://?
++ let source_file = decode_uri_fragment(source_file)?;
+ (
+ RcStr::from(
+ get_relative_path_to(
+- ¤t_directory_file_url,
+- &format!("{project_root_uri}{source_file}"),
++ ¤t_directory_path,
++ &format!("{}{}", decode_uri_fragment(&project_root_uri)?, source_file),
+ )
+ // TODO(sokra) remove this to include a ./ here to make it a relative path
+ .trim_start_matches("./"),
+ ),
+- Some(RcStr::from(source_file)),
++ Some(source_file),
+ )
+ } else if let Some(source_file) = original_file.strip_prefix(&*SOURCE_MAP_PREFIX) {
+ // TODO(veil): Should the protocol be preserved?
+- (RcStr::from(source_file), None)
++ (decode_uri_fragment(source_file)?, None)
+ } else {
+ bail!(
+ "Original file ({}) outside project ({})",
+diff --git a/packages/next/src/server/dev/middleware-turbopack.ts b/packages/next/src/server/dev/middleware-turbopack.ts
+index d733e77aa41ac46c297d1e5c4f154f4dec14815b..5de99c4d43dc9732ce0256718cca887f5fe5c7f4 100644
+--- a/packages/next/src/server/dev/middleware-turbopack.ts
++++ b/packages/next/src/server/dev/middleware-turbopack.ts
+@@ -130,7 +130,16 @@ function parseFile(fileParam: string | null): string | undefined {
+ return undefined
+ }
+
+- return devirtualizeReactServerURL(fileParam)
++ const file = devirtualizeReactServerURL(fileParam)
++ // React virtualizes filenames as `'file://' + path`, which is malformed
++ // for paths that need percent-encoding (e.g. a space in the project path)
++ // and then fails both Turbopack's `traceSource` and Node.js' source map
++ // cache lookups. Re-encode through WHATWG URL parsing.
++ // TODO(veil): Revisit if React's virtualization round-trips losslessly.
++ if (file.startsWith('file://') && URL.canParse(file)) {
++ return new URL(file).href
++ }
++ return file
+ }
+
+ function createStackFrames(
diff --git a/nextjs-dev-overlay-encoded-paths/solution/solve.sh b/nextjs-dev-overlay-encoded-paths/solution/solve.sh
new file mode 100644
index 0000000000000000000000000000000000000000..b23b1455c5a01d637a3985c89514ac2b453ecec2
--- /dev/null
+++ b/nextjs-dev-overlay-encoded-paths/solution/solve.sh
@@ -0,0 +1,3 @@
+#!/bin/bash
+set -euo pipefail
+git -C /app apply --binary --whitespace=nowarn /solution/gold.patch
diff --git a/nextjs-dev-overlay-encoded-paths/tests/Dockerfile b/nextjs-dev-overlay-encoded-paths/tests/Dockerfile
new file mode 100644
index 0000000000000000000000000000000000000000..71b3414d677d6a424cd89a512e08543bffb5a0ee
--- /dev/null
+++ b/nextjs-dev-overlay-encoded-paths/tests/Dockerfile
@@ -0,0 +1,43 @@
+FROM ubuntu:24.04
+ENV DEBIAN_FRONTEND=noninteractive \
+ UV_LINK_MODE=copy \
+ UV_CACHE_DIR=/opt/uv-cache \
+ UV_PYTHON_INSTALL_DIR=/usr/local/share/uv/python \
+ UV_PYTHON_BIN_DIR=/usr/local/bin \
+ RUSTUP_HOME=/usr/local/rustup \
+ CARGO_HOME=/usr/local/cargo \
+ COREPACK_HOME=/opt/corepack \
+ PATH=/usr/local/go/bin:/usr/local/cargo/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin
+RUN apt-get update && apt-get install -y --no-install-recommends \
+ bash build-essential ca-certificates curl git jq passwd pkg-config procps unzip xz-utils \
+ && rm -rf /var/lib/apt/lists/*
+ENV PLAYWRIGHT_BROWSERS_PATH=/opt/playwright
+RUN mkdir -p "$PLAYWRIGHT_BROWSERS_PATH" && chmod 755 "$PLAYWRIGHT_BROWSERS_PATH" \
+ && arch="$(dpkg --print-architecture)" && case "$arch" in arm64) node_arch=arm64 ;; amd64) node_arch=x64 ;; *) exit 1 ;; esac \
+ && curl -fsSL "https://nodejs.org/dist/v22.14.0/node-v22.14.0-linux-${node_arch}.tar.xz" | tar -C /usr/local --strip-components=1 -xJ \
+ && mkdir -p /opt/corepack && chmod 755 /opt/corepack \
+ && corepack enable
+RUN curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | env RUSTUP_HOME=/usr/local/rustup CARGO_HOME=/usr/local/cargo sh -s -- -y --no-modify-path --profile minimal --default-toolchain 1.90.0
+COPY repo.tar.gz /tmp/repo.tar.gz
+RUN mkdir -p /app && tar -xzf /tmp/repo.tar.gz -C /app && rm /tmp/repo.tar.gz \
+ && git -C /app init -q \
+ && git -C /app config user.email selfbench@local \
+ && git -C /app config user.name selfbench \
+ && git -C /app add -A \
+ && git -C /app commit -qm base
+RUN mkdir -p /opt/uv-cache && chmod 777 /opt/uv-cache \
+ && cd '/app/.' \
+ && bash -lc 'corepack enable && corepack prepare pnpm@10.33.0 --activate && pnpm install --frozen-lockfile && pnpm build && pnpm --dir packages/next-swc build-native && pnpm exec playwright install --with-deps chromium' \
+ && chmod -R a+rwX /opt/uv-cache
+
+RUN useradd --create-home --shell /bin/bash verifier \
+ && chown -R verifier:verifier /app /opt/uv-cache \
+ && mkdir -p /opt/selfbench \
+ && chmod 700 /opt/selfbench \
+ && mkdir -p /home/verifier/.cache/uv \
+ && chown -R verifier:verifier /home/verifier/.cache
+ENV UV_CACHE_DIR=/home/verifier/.cache/uv \
+ UV_NO_BUILD_ISOLATION=1
+COPY test.patch test.sh /tests/
+RUN chmod 700 /tests && chmod 600 /tests/test.patch && chmod +x /tests/test.sh
+WORKDIR /app
diff --git a/nextjs-dev-overlay-encoded-paths/tests/test.patch b/nextjs-dev-overlay-encoded-paths/tests/test.patch
new file mode 100644
index 0000000000000000000000000000000000000000..133c427ef9f88cba128e05ec4dce45c80af8f0bc
--- /dev/null
+++ b/nextjs-dev-overlay-encoded-paths/tests/test.patch
@@ -0,0 +1,119 @@
+diff --git a/test/development/app-dir/special-project-paths/fixtures/app/layout.js b/test/development/app-dir/special-project-paths/fixtures/app/layout.js
+new file mode 100644
+index 0000000000000000000000000000000000000000..803f17d863c8ad887c14588aab3487e473367b41
+--- /dev/null
++++ b/test/development/app-dir/special-project-paths/fixtures/app/layout.js
+@@ -0,0 +1,7 @@
++export default function RootLayout({ children }) {
++ return (
++
++ {children}
++
++ )
++}
+diff --git a/test/development/app-dir/special-project-paths/fixtures/app/ssr-throw/Thrower.js b/test/development/app-dir/special-project-paths/fixtures/app/ssr-throw/Thrower.js
+new file mode 100644
+index 0000000000000000000000000000000000000000..140fa61e8ba3c0d722afbabe5ba1d69de79bf0f2
+--- /dev/null
++++ b/test/development/app-dir/special-project-paths/fixtures/app/ssr-throw/Thrower.js
+@@ -0,0 +1,10 @@
++'use client'
++
++function throwError() {
++ throw new Error('ssr-throw')
++}
++
++export function Thrower() {
++ throwError()
++ return null
++}
+diff --git a/test/development/app-dir/special-project-paths/fixtures/app/ssr-throw/page.js b/test/development/app-dir/special-project-paths/fixtures/app/ssr-throw/page.js
+new file mode 100644
+index 0000000000000000000000000000000000000000..d5d6f5cad684f2e81f3c796e9a7e0ede72c95637
+--- /dev/null
++++ b/test/development/app-dir/special-project-paths/fixtures/app/ssr-throw/page.js
+@@ -0,0 +1,5 @@
++import { Thrower } from './Thrower'
++
++export default function Page() {
++ return
++}
+diff --git a/test/development/app-dir/special-project-paths/fixtures/next.config.js b/test/development/app-dir/special-project-paths/fixtures/next.config.js
+new file mode 100644
+index 0000000000000000000000000000000000000000..4ba52ba2c8df6758685c8f65f490306b5c44eb76
+--- /dev/null
++++ b/test/development/app-dir/special-project-paths/fixtures/next.config.js
+@@ -0,0 +1 @@
++module.exports = {}
+diff --git a/test/development/app-dir/special-project-paths/special-project-paths.test.ts b/test/development/app-dir/special-project-paths/special-project-paths.test.ts
+new file mode 100644
+index 0000000000000000000000000000000000000000..4f5399aff3c8c153fa06a243c81ad8ea6c6ff89d
+--- /dev/null
++++ b/test/development/app-dir/special-project-paths/special-project-paths.test.ts
+@@ -0,0 +1,66 @@
++import * as path from 'path'
++import { nextTestSetup } from 'e2e-utils'
++import stripAnsi from 'strip-ansi'
++import { getRedboxSource, retry } from 'next-test-utils'
++
++function setup(subDir: string) {
++ return nextTestSetup({
++ files: path.join(__dirname, 'fixtures'),
++ subDir,
++ })
++}
++
++async function assertSymbolicatedSSRError(
++ next: ReturnType['next']
++) {
++ const outputIndex = next.cliOutput.length
++ const browser = await next.browser('/ssr-throw')
++
++ await retry(() => {
++ expect(next.cliOutput.slice(outputIndex)).toContain('Error: ssr-throw')
++ })
++
++ const cliOutput = stripAnsi(next.cliOutput.slice(outputIndex))
++ expect(cliOutput).toContain('at throwError (app/ssr-throw/Thrower.js:4:9)')
++ expect(cliOutput).toContain('at Thrower (app/ssr-throw/Thrower.js:8:3)')
++ expect(cliOutput).toContain("throw new Error('ssr-throw')")
++
++ let redboxSource: string | null = null
++ await retry(async () => {
++ redboxSource = await getRedboxSource(browser)
++ expect(redboxSource).not.toBeNull()
++ })
++ expect(redboxSource).toContain('app/ssr-throw/Thrower.js (4:9) @ throwError')
++ expect(redboxSource).toContain("throw new Error('ssr-throw')")
++}
++
++// Symbolication must work in project directories whose absolute path
++// contains characters that need percent-encoding in URLs.
++describe('special project paths', () => {
++ describe('in "space dir"', () => {
++ const { skipped, next } = setup('space dir')
++ if (skipped) return
++
++ it('symbolicates thrown SSR errors', async () => {
++ await assertSymbolicatedSSRError(next)
++ })
++ })
++
++ describe('in "ünïcode-dir"', () => {
++ const { skipped, next } = setup('ünïcode-dir')
++ if (skipped) return
++
++ it('symbolicates thrown SSR errors', async () => {
++ await assertSymbolicatedSSRError(next)
++ })
++ })
++
++ describe('in "bracket [dir]"', () => {
++ const { skipped, next } = setup('bracket [dir]')
++ if (skipped) return
++
++ it('symbolicates thrown SSR errors', async () => {
++ await assertSymbolicatedSSRError(next)
++ })
++ })
++})
diff --git a/nextjs-dev-overlay-encoded-paths/tests/test.sh b/nextjs-dev-overlay-encoded-paths/tests/test.sh
new file mode 100644
index 0000000000000000000000000000000000000000..7332ab57cf057eb886b395cb374d2747c10be92d
--- /dev/null
+++ b/nextjs-dev-overlay-encoded-paths/tests/test.sh
@@ -0,0 +1,98 @@
+#!/bin/bash
+set -uo pipefail
+mkdir -p /logs/verifier
+patch_applied=1
+fail_to_pass=0
+pass_to_pass=0
+deterministic=0
+setup_completed=0
+fail_to_pass_exit_code=-1
+fail_to_pass_repeat_exit_code=-1
+pass_to_pass_exit_code=-1
+verifier_cache=""
+
+kill_verifier_processes() { pkill -KILL -u "$(id -u verifier)" 2>/dev/null || true; }
+# Some toolchains fetch dependencies at test runtime (e.g. Next.js e2e installs),
+# so a single registry connection reset must not be misread as a dead test. Retry
+# only infrastructure-style failures with backoff; real assertion failures fail fast.
+run_verifier_command() {
+ local logfile
+ logfile="$(mktemp /tmp/selfbench-verifier-command-XXXXXX.log)"
+ local attempt=1
+ local status=1
+ while [ "$attempt" -le 3 ]; do
+ : > "$logfile"
+ runuser -u verifier -- env PATH="/usr/local/go/bin:/usr/local/cargo/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin" UV_CACHE_DIR="$verifier_cache" UV_NO_BUILD_ISOLATION=1 bash -lc "$1" >"$logfile" 2>&1
+ status=$?
+ if [ "$status" -eq 0 ]; then
+ break
+ fi
+ if [ "$attempt" -lt 3 ] && grep -qE 'ECONNRESET|ETIMEDOUT|ESOCKETTIMEDOUT|ENOTFOUND|EAI_AGAIN|META_FETCH_FAIL|FetchError|EPIPE|EPERM|registry\.npmjs' "$logfile"; then
+ sleep "$((10 * attempt))"
+ attempt=$((attempt + 1))
+ continue
+ fi
+ break
+ done
+ cat "$logfile"
+ rm -f "$logfile"
+ kill_verifier_processes
+ return "$status"
+}
+protect_held_out_path() {
+ local path="$1"
+ chown -R root:root -- "$path"
+ chmod -R a-w,go+rX -- "$path"
+}
+
+if [ ! -f /opt/selfbench/agent.patch ]; then
+ patch_applied=0
+elif [ -s /opt/selfbench/agent.patch ]; then
+ git -C /app apply --binary --whitespace=nowarn --exclude='test/development/app-dir/special-project-paths/special-project-paths.test.ts' --exclude='test/development/app-dir/special-project-paths/special-project-paths.test.ts/*' /opt/selfbench/agent.patch || patch_applied=0
+fi
+
+if [ "$patch_applied" -eq 1 ]; then setup_completed=1; fi
+
+if [ "$patch_applied" -eq 1 ] && [ "$setup_completed" -eq 1 ]; then
+ kill_verifier_processes
+ git -C /app restore --source=HEAD --staged --worktree -- 'test/development/app-dir/special-project-paths/special-project-paths.test.ts' 2>/dev/null || true
+ git -C /app clean -fd -- 'test/development/app-dir/special-project-paths/special-project-paths.test.ts' >/dev/null 2>&1 || true
+ git -C /app apply --binary --whitespace=nowarn /tests/test.patch || patch_applied=0
+ if [ "$patch_applied" -eq 1 ]; then
+ for protected_path in '/app/test/development/app-dir/special-project-paths/special-project-paths.test.ts'; do protect_held_out_path "$protected_path"; done
+ fi
+ rm -f /tests/test.patch
+fi
+
+if [ "$patch_applied" -eq 1 ] && [ "$setup_completed" -eq 1 ]; then
+ cd '/app/.'
+ verifier_cache="$(mktemp -d /tmp/selfbench-verifier-uv-XXXXXX)"
+ cp -a /opt/uv-cache/. "$verifier_cache"/
+ chown -R verifier:verifier "$verifier_cache"
+ if run_verifier_command 'pnpm build && pnpm --dir packages/next-swc build-native && pnpm test-dev-turbo '"'"'test/development/app-dir/special-project-paths/special-project-paths.test.ts'"'"''; then
+ fail_to_pass_exit_code=0
+ fail_to_pass=1
+ if run_verifier_command 'pnpm build && pnpm --dir packages/next-swc build-native && pnpm test-dev-turbo '"'"'test/development/app-dir/special-project-paths/special-project-paths.test.ts'"'"''; then
+ fail_to_pass_repeat_exit_code=0
+ deterministic=1
+ else
+ fail_to_pass_repeat_exit_code=$?
+ fi
+ else
+ fail_to_pass_exit_code=$?
+ fi
+ if run_verifier_command 'true'; then
+ pass_to_pass_exit_code=0
+ pass_to_pass=1
+ else
+ pass_to_pass_exit_code=$?
+ fi
+ rm -rf "$verifier_cache"
+fi
+
+reward=0
+if [ "$patch_applied" -eq 1 ] && [ "$fail_to_pass" -eq 1 ] && [ "$pass_to_pass" -eq 1 ] && [ "$deterministic" -eq 1 ]; then reward=1; fi
+cat > /logs/verifier/reward.json < {
+- const tracer = originalGetTracer.apply(provider, args)
+- if (WeakTracers.has(tracer)) {
+- return tracer
+- }
+- const originalStartSpan = tracer.startSpan
+- tracer.startSpan = (...startSpanArgs) => {
+- return workUnitAsyncStorage.exit(() =>
+- originalStartSpan.apply(tracer, startSpanArgs)
+- )
++ return instrumentTracerForCacheComponents(
++ originalGetTracer.apply(provider, args)
++ )
++ }
++
++ // Tracers acquired before registration can use getDelegateTracer() from the
++ // proxy provider to get a tracer from the registered provider, bypassing the
++ // getTracer() patch above. This can be problematic when third-party
++ // instrumentation creates spans that call dynamic APIs like Math.random(),
++ // causing a prerendering error. Therefore, patch getDelegateTracer() to apply
++ // the same tracer instrumentation as getTracer().
++ if (isProxyTracerProvider(provider)) {
++ const originalGetDelegateTracer = provider.getDelegateTracer.bind(provider)
++ provider.getDelegateTracer = (...args) => {
++ const tracer = originalGetDelegateTracer(...args)
++ return tracer === undefined
++ ? undefined
++ : instrumentTracerForCacheComponents(tracer)
+ }
++ }
++}
+
+- const originalStartActiveSpan = tracer.startActiveSpan
+- // @ts-ignore TS doesn't recognize the overloads correctly
+- tracer.startActiveSpan = (...startActiveSpanArgs: any[]) => {
+- const workUnitStore = workUnitAsyncStorage.getStore()
+- if (!workUnitStore) {
+- // @ts-ignore TS doesn't recognize the overloads correctly
+- return originalStartActiveSpan.apply(tracer, startActiveSpanArgs)
+- }
++function instrumentTracerForCacheComponents(tracer: Tracer): Tracer {
++ if (WeakTracers.has(tracer)) {
++ return tracer
++ }
++ const originalStartSpan = tracer.startSpan
++ tracer.startSpan = (...startSpanArgs) => {
++ return workUnitAsyncStorage.exit(() =>
++ originalStartSpan.apply(tracer, startSpanArgs)
++ )
++ }
+
+- let fnIdx: number = 0
+- if (
+- startActiveSpanArgs.length === 2 &&
+- typeof startActiveSpanArgs[1] === 'function'
+- ) {
+- fnIdx = 1
+- } else if (
+- startActiveSpanArgs.length === 3 &&
+- typeof startActiveSpanArgs[2] === 'function'
+- ) {
+- fnIdx = 2
+- } else if (
+- startActiveSpanArgs.length > 3 &&
+- typeof startActiveSpanArgs[3] === 'function'
+- ) {
+- fnIdx = 3
+- }
++ const originalStartActiveSpan = tracer.startActiveSpan
++ // @ts-ignore TS doesn't recognize the overloads correctly
++ tracer.startActiveSpan = (...startActiveSpanArgs: any[]) => {
++ const workUnitStore = workUnitAsyncStorage.getStore()
++ if (!workUnitStore) {
++ // @ts-ignore TS doesn't recognize the overloads correctly
++ return originalStartActiveSpan.apply(tracer, startActiveSpanArgs)
++ }
+
+- if (fnIdx) {
+- const originalFn = startActiveSpanArgs[fnIdx]
+- if (isUseCacheFunction(originalFn)) {
+- console.error(
+- 'A Cache Function (`use cache`) was passed to startActiveSpan which means it will receive a Span argument with a possibly random ID on every invocation leading to cache misses. Provide a wrapping function around the Cache Function that does not forward the Span argument to avoid this issue.'
+- )
+- }
+- startActiveSpanArgs[fnIdx] = withWorkUnitContext(
+- workUnitStore,
+- originalFn
++ let fnIdx: number = 0
++ if (
++ startActiveSpanArgs.length === 2 &&
++ typeof startActiveSpanArgs[1] === 'function'
++ ) {
++ fnIdx = 1
++ } else if (
++ startActiveSpanArgs.length === 3 &&
++ typeof startActiveSpanArgs[2] === 'function'
++ ) {
++ fnIdx = 2
++ } else if (
++ startActiveSpanArgs.length > 3 &&
++ typeof startActiveSpanArgs[3] === 'function'
++ ) {
++ fnIdx = 3
++ }
++
++ if (fnIdx) {
++ const originalFn = startActiveSpanArgs[fnIdx]
++ if (isUseCacheFunction(originalFn)) {
++ console.error(
++ 'A Cache Function (`use cache`) was passed to startActiveSpan which means it will receive a Span argument with a possibly random ID on every invocation leading to cache misses. Provide a wrapping function around the Cache Function that does not forward the Span argument to avoid this issue.'
+ )
+ }
+-
+- return workUnitAsyncStorage.exit(() => {
+- // @ts-ignore TS doesn't recognize the overloads correctly
+- return originalStartActiveSpan.apply(tracer, startActiveSpanArgs)
+- })
++ startActiveSpanArgs[fnIdx] = withWorkUnitContext(
++ workUnitStore,
++ originalFn
++ )
+ }
+
+- WeakTracers.add(tracer)
+- return tracer
++ return workUnitAsyncStorage.exit(() => {
++ // @ts-ignore TS doesn't recognize the overloads correctly
++ return originalStartActiveSpan.apply(tracer, startActiveSpanArgs)
++ })
+ }
++
++ WeakTracers.add(tracer)
++ return tracer
+ }
+
+ const WeakTracers = new WeakSet()
diff --git a/nextjs-early-otel-proxy-tracers/solution/solve.sh b/nextjs-early-otel-proxy-tracers/solution/solve.sh
new file mode 100644
index 0000000000000000000000000000000000000000..b23b1455c5a01d637a3985c89514ac2b453ecec2
--- /dev/null
+++ b/nextjs-early-otel-proxy-tracers/solution/solve.sh
@@ -0,0 +1,3 @@
+#!/bin/bash
+set -euo pipefail
+git -C /app apply --binary --whitespace=nowarn /solution/gold.patch
diff --git a/nextjs-early-otel-proxy-tracers/tests/Dockerfile b/nextjs-early-otel-proxy-tracers/tests/Dockerfile
new file mode 100644
index 0000000000000000000000000000000000000000..81e249ceb76ad970bf76970c9e958e1eed759918
--- /dev/null
+++ b/nextjs-early-otel-proxy-tracers/tests/Dockerfile
@@ -0,0 +1,42 @@
+FROM ubuntu:24.04
+ENV DEBIAN_FRONTEND=noninteractive \
+ UV_LINK_MODE=copy \
+ UV_CACHE_DIR=/opt/uv-cache \
+ UV_PYTHON_INSTALL_DIR=/usr/local/share/uv/python \
+ UV_PYTHON_BIN_DIR=/usr/local/bin \
+ RUSTUP_HOME=/usr/local/rustup \
+ CARGO_HOME=/usr/local/cargo \
+ COREPACK_HOME=/opt/corepack \
+ PATH=/usr/local/go/bin:/usr/local/cargo/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin
+RUN apt-get update && apt-get install -y --no-install-recommends \
+ bash build-essential ca-certificates curl git jq passwd pkg-config procps unzip xz-utils \
+ && rm -rf /var/lib/apt/lists/*
+ENV PLAYWRIGHT_BROWSERS_PATH=/opt/playwright
+RUN mkdir -p "$PLAYWRIGHT_BROWSERS_PATH" && chmod 755 "$PLAYWRIGHT_BROWSERS_PATH" \
+ && arch="$(dpkg --print-architecture)" && case "$arch" in arm64) node_arch=arm64 ;; amd64) node_arch=x64 ;; *) exit 1 ;; esac \
+ && curl -fsSL "https://nodejs.org/dist/v22.14.0/node-v22.14.0-linux-${node_arch}.tar.xz" | tar -C /usr/local --strip-components=1 -xJ \
+ && mkdir -p /opt/corepack && chmod 755 /opt/corepack \
+ && corepack enable
+COPY repo.tar.gz /tmp/repo.tar.gz
+RUN mkdir -p /app && tar -xzf /tmp/repo.tar.gz -C /app && rm /tmp/repo.tar.gz \
+ && git -C /app init -q \
+ && git -C /app config user.email selfbench@local \
+ && git -C /app config user.name selfbench \
+ && git -C /app add -A \
+ && git -C /app commit -qm base
+RUN mkdir -p /opt/uv-cache && chmod 777 /opt/uv-cache \
+ && cd '/app/.' \
+ && bash -lc 'corepack enable && corepack prepare pnpm@10.33.0 --activate && pnpm install --frozen-lockfile && pnpm exec playwright install --with-deps chromium && NEXT_TELEMETRY_DISABLED=1 pnpm build' \
+ && chmod -R a+rwX /opt/uv-cache
+
+RUN useradd --create-home --shell /bin/bash verifier \
+ && chown -R verifier:verifier /app /opt/uv-cache \
+ && mkdir -p /opt/selfbench \
+ && chmod 700 /opt/selfbench \
+ && mkdir -p /home/verifier/.cache/uv \
+ && chown -R verifier:verifier /home/verifier/.cache
+ENV UV_CACHE_DIR=/home/verifier/.cache/uv \
+ UV_NO_BUILD_ISOLATION=1
+COPY test.patch test.sh /tests/
+RUN chmod 700 /tests && chmod 600 /tests/test.patch && chmod +x /tests/test.sh
+WORKDIR /app
diff --git a/nextjs-early-otel-proxy-tracers/tests/test.patch b/nextjs-early-otel-proxy-tracers/tests/test.patch
new file mode 100644
index 0000000000000000000000000000000000000000..2c78e9bd1a79a7a9234608e9b21f6b56430e3415
--- /dev/null
+++ b/nextjs-early-otel-proxy-tracers/tests/test.patch
@@ -0,0 +1,157 @@
+diff --git a/test/e2e/app-dir/cache-components-allow-otel-spans/app/[slug]/early-span/page.tsx b/test/e2e/app-dir/cache-components-allow-otel-spans/app/[slug]/early-span/page.tsx
+new file mode 100644
+index 0000000000..6e63ee216c
+--- /dev/null
++++ b/test/e2e/app-dir/cache-components-allow-otel-spans/app/[slug]/early-span/page.tsx
+@@ -0,0 +1,18 @@
++import { TracedComponentEarlyTracerSpan } from '../../traced-work'
++
++export function generateStaticParams() {
++ return [{ slug: 'prerendered' }]
++}
++
++export default async function Page({
++ params,
++}: {
++ params: Promise<{ slug: string }>
++}) {
++ const { slug } = await params
++ if (slug === 'prerendered') {
++ return null
++ }
++
++ return
++}
+diff --git a/test/e2e/app-dir/cache-components-allow-otel-spans/app/traced-work.tsx b/test/e2e/app-dir/cache-components-allow-otel-spans/app/traced-work.tsx
+index 067d6cf484..9c614ed403 100644
+--- a/test/e2e/app-dir/cache-components-allow-otel-spans/app/traced-work.tsx
++++ b/test/e2e/app-dir/cache-components-allow-otel-spans/app/traced-work.tsx
+@@ -1,4 +1,4 @@
+-import { type Span, trace, context } from '@opentelemetry/api'
++import { type Span, type Tracer, trace, context } from '@opentelemetry/api'
+ import { Suspense } from 'react'
+
+ async function asyncWork() {
+@@ -173,6 +173,45 @@ export const TracedComponentActiveSpan = withActiveSpan(async function (
+ )
+ })
+
++type TestGlobal = typeof globalThis & {
++ __nextTestEarlyTracer?: Tracer
++}
++
++export async function TracedComponentEarlyTracerSpan() {
++ const tracer = (globalThis as TestGlobal).__nextTestEarlyTracer
++ if (!tracer) {
++ throw new Error(
++ 'Expected instrumentation to register the early tracer before rendering'
++ )
++ }
++
++ const span = tracer.startSpan('span-early-manual-span')
++ const ctx = trace.setSpan(context.active(), span)
++
++ return context.with(ctx, async () => {
++ async function Inner() {
++ const result = await asyncWork()
++ return {result}
++ }
++ return (
++
++
(Manual Span) Tracer acquired before provider registration
}>
++
++
++
++ )
++}
++
++// A module-level cache keyed on the identity of the headers object (like
++// `dedupe()` from the Flags SDK, or any per-request memoization that treats
++// the headers object as "the request"), gating its data on `connection()` so
++// it only produces data during actual navigations, never during (runtime)
++// prefetches.
++//
++// A request can be rendered by multiple passes with different semantics for
++// `connection()`: the prospective and final prerenders of a runtime prefetch,
++// or a navigation's dynamic render and the runtime prerender that is spawned
++// from it to refresh the client's prefetch cache. In prerenders the
++// connection() promise hangs and is rejected when the pass is aborted; during
++// navigations it resolves. Each render pass resolves `await headers()` to a
++// distinct object, which scopes identity-keyed memoization like this cache to
++// a single pass: a promise created under one pass's semantics is never
++// consumed by another pass.
++const requestDataCache = new WeakMap